diff --git a/cmd/kube-apiserver/app/server.go b/cmd/kube-apiserver/app/server.go index 680e6b02884..c12a5506edb 100644 --- a/cmd/kube-apiserver/app/server.go +++ b/cmd/kube-apiserver/app/server.go @@ -253,7 +253,7 @@ func Run(s *options.ServerRunOptions) error { if err != nil { glog.Errorf("Failed to create clientset: %v", err) } - sharedInformers := informers.NewSharedInformerFactory(client, 10*time.Minute) + sharedInformers := informers.NewSharedInformerFactory(nil, client, 10*time.Minute) authorizationConfig := authorizer.AuthorizationConfig{ PolicyFile: s.GenericServerRunOptions.AuthorizationPolicyFile, diff --git a/cmd/kube-controller-manager/app/BUILD b/cmd/kube-controller-manager/app/BUILD index e92a609333a..719537f92f0 100644 --- a/cmd/kube-controller-manager/app/BUILD +++ b/cmd/kube-controller-manager/app/BUILD @@ -21,11 +21,12 @@ go_library( "//cmd/kube-controller-manager/app/options:go_default_library", "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/apis/batch:go_default_library", "//pkg/apis/componentconfig:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/leaderelection:go_default_library", "//pkg/client/leaderelection/resourcelock:go_default_library", "//pkg/client/record:go_default_library", diff --git a/cmd/kube-controller-manager/app/controllermanager.go b/cmd/kube-controller-manager/app/controllermanager.go index 17a87feb6b6..1e021edbafb 100644 --- a/cmd/kube-controller-manager/app/controllermanager.go +++ b/cmd/kube-controller-manager/app/controllermanager.go @@ -34,10 +34,11 @@ import ( "k8s.io/kubernetes/cmd/kube-controller-manager/app/options" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/apis/batch" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/leaderelection" "k8s.io/kubernetes/pkg/client/leaderelection/resourcelock" "k8s.io/kubernetes/pkg/client/record" @@ -159,8 +160,8 @@ func Run(s *options.CMServer) error { eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(glog.Infof) - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) - recorder := eventBroadcaster.NewRecorder(api.EventSource{Component: "controller-manager"}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.Core().Events("")}) + recorder := eventBroadcaster.NewRecorder(v1.EventSource{Component: "controller-manager"}) run := func(stop <-chan struct{}) { rootClientBuilder := controller.SimpleControllerClientBuilder{ @@ -194,7 +195,7 @@ func Run(s *options.CMServer) error { // TODO: enable other lock types rl := resourcelock.EndpointsLock{ - EndpointsMeta: api.ObjectMeta{ + EndpointsMeta: v1.ObjectMeta{ Namespace: "kube-system", Name: "kube-controller-manager", }, @@ -225,7 +226,7 @@ func StartControllers(s *options.CMServer, kubeconfig *restclient.Config, rootCl return rootClientBuilder.ClientOrDie(serviceAccountName) } discoveryClient := client("controller-discovery").Discovery() - sharedInformers := informers.NewSharedInformerFactory(client("shared-informers"), ResyncPeriod(s)()) + sharedInformers := informers.NewSharedInformerFactory(client("shared-informers"), nil, ResyncPeriod(s)()) // always start the SA token controller first using a full-power client, since it needs to mint tokens for the rest if len(s.ServiceAccountKeyFile) > 0 { @@ -392,7 +393,7 @@ func StartControllers(s *options.CMServer, kubeconfig *restclient.Config, rootCl return gvr, nil } } - namespaceController := namespacecontroller.NewNamespaceController(namespaceKubeClient, namespaceClientPool, gvrFn, s.NamespaceSyncPeriod.Duration, api.FinalizerKubernetes) + namespaceController := namespacecontroller.NewNamespaceController(namespaceKubeClient, namespaceClientPool, gvrFn, s.NamespaceSyncPeriod.Duration, v1.FinalizerKubernetes) go namespaceController.Run(int(s.ConcurrentNamespaceSyncs), wait.NeverStop) time.Sleep(wait.Jitter(s.ControllerStartInterval.Duration, ControllerStartJitter)) diff --git a/cmd/kube-dns/app/BUILD b/cmd/kube-dns/app/BUILD index 5afe7ea4fca..a3fd5992bf7 100644 --- a/cmd/kube-dns/app/BUILD +++ b/cmd/kube-dns/app/BUILD @@ -17,7 +17,7 @@ go_library( deps = [ "//cmd/kube-dns/app/options:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/unversioned/clientcmd:go_default_library", "//pkg/dns:go_default_library", diff --git a/cmd/kube-dns/app/server.go b/cmd/kube-dns/app/server.go index a369719e2d4..fab3bb0b698 100644 --- a/cmd/kube-dns/app/server.go +++ b/cmd/kube-dns/app/server.go @@ -30,7 +30,7 @@ import ( "k8s.io/kubernetes/cmd/kube-dns/app/options" "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" kclientcmd "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" kdns "k8s.io/kubernetes/pkg/dns" diff --git a/cmd/kube-proxy/app/BUILD b/cmd/kube-proxy/app/BUILD index 099c65de1dd..2ae19aae860 100644 --- a/cmd/kube-proxy/app/BUILD +++ b/cmd/kube-proxy/app/BUILD @@ -20,6 +20,7 @@ go_library( deps = [ "//cmd/kube-proxy/app/options:go_default_library", "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", "//pkg/client/record:go_default_library", diff --git a/cmd/kube-proxy/app/server.go b/cmd/kube-proxy/app/server.go index d079adff163..207e5494ce7 100644 --- a/cmd/kube-proxy/app/server.go +++ b/cmd/kube-proxy/app/server.go @@ -30,6 +30,7 @@ import ( "k8s.io/kubernetes/cmd/kube-proxy/app/options" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" "k8s.io/kubernetes/pkg/client/record" @@ -205,7 +206,7 @@ func NewProxyServerDefault(config *options.ProxyServerConfig) (*ProxyServer, err // Create event recorder hostname := nodeutil.GetHostname(config.HostnameOverride) eventBroadcaster := record.NewBroadcaster() - recorder := eventBroadcaster.NewRecorder(api.EventSource{Component: "kube-proxy", Host: hostname}) + recorder := eventBroadcaster.NewRecorder(v1.EventSource{Component: "kube-proxy", Host: hostname}) var proxier proxy.ProxyProvider var endpointsHandler proxyconfig.EndpointsConfigHandler @@ -468,7 +469,7 @@ func getNodeIP(client clientset.Interface, hostname string) net.IP { glog.Warningf("Failed to retrieve node info: %v", err) return nil } - nodeIP, err = nodeutil.GetNodeHostIP(node) + nodeIP, err = nodeutil.InternalGetNodeHostIP(node) if err != nil { glog.Warningf("Failed to retrieve node IP: %v", err) return nil diff --git a/cmd/kubeadm/app/master/BUILD b/cmd/kubeadm/app/master/BUILD index 2961f2bb200..a8f3aaa7f1f 100644 --- a/cmd/kubeadm/app/master/BUILD +++ b/cmd/kubeadm/app/master/BUILD @@ -32,8 +32,8 @@ go_library( "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", "//pkg/api/v1:go_default_library", - "//pkg/apis/extensions:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/unversioned/clientcmd:go_default_library", "//pkg/client/unversioned/clientcmd/api:go_default_library", "//pkg/kubectl/cmd/util:go_default_library", diff --git a/cmd/kubeadm/app/master/addons.go b/cmd/kubeadm/app/master/addons.go index 26aaa1f2e9d..ff165bbd169 100644 --- a/cmd/kubeadm/app/master/addons.go +++ b/cmd/kubeadm/app/master/addons.go @@ -25,21 +25,23 @@ import ( "k8s.io/kubernetes/cmd/kubeadm/app/images" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" ipallocator "k8s.io/kubernetes/pkg/registry/core/service/ipallocator" "k8s.io/kubernetes/pkg/util/intstr" ) -func createKubeProxyPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { +func createKubeProxyPodSpec(cfg *kubeadmapi.MasterConfiguration) v1.PodSpec { privilegedTrue := true - return api.PodSpec{ - SecurityContext: &api.PodSecurityContext{HostNetwork: true}, - Containers: []api.Container{{ + return v1.PodSpec{ + HostNetwork: true, + SecurityContext: &v1.PodSecurityContext{}, + Containers: []v1.Container{{ Name: kubeProxy, Image: images.GetCoreImage(images.KubeProxyImage, cfg, kubeadmapi.GlobalEnvParams.HyperkubeImage), Command: append(getProxyCommand(cfg), "--kubeconfig=/run/kubeconfig"), - SecurityContext: &api.SecurityContext{Privileged: &privilegedTrue}, - VolumeMounts: []api.VolumeMount{ + SecurityContext: &v1.SecurityContext{Privileged: &privilegedTrue}, + VolumeMounts: []v1.VolumeMount{ { Name: "dbus", MountPath: "/var/run/dbus", @@ -62,33 +64,33 @@ func createKubeProxyPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { }, }, }}, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: "kubeconfig", - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: path.Join(kubeadmapi.GlobalEnvParams.KubernetesDir, "kubelet.conf")}, + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{Path: path.Join(kubeadmapi.GlobalEnvParams.KubernetesDir, "kubelet.conf")}, }, }, { Name: "dbus", - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/var/run/dbus"}, + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{Path: "/var/run/dbus"}, }, }, }, } } -func createKubeDNSPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { +func createKubeDNSPodSpec(cfg *kubeadmapi.MasterConfiguration) v1.PodSpec { - dnsPodResources := api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("100m"), - api.ResourceName(api.ResourceMemory): resource.MustParse("170Mi"), + dnsPodResources := v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("100m"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("170Mi"), } - healthzPodResources := api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10m"), - api.ResourceName(api.ResourceMemory): resource.MustParse("50Mi"), + healthzPodResources := v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10m"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("50Mi"), } kubeDNSPort := int32(10053) @@ -101,13 +103,13 @@ func createKubeDNSPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { nslookup, kubeDNSPort, ) - return api.PodSpec{ - Containers: []api.Container{ + return v1.PodSpec{ + Containers: []v1.Container{ // DNS server { Name: "kube-dns", Image: images.GetAddonImage(images.KubeDNSImage), - Resources: api.ResourceRequirements{ + Resources: v1.ResourceRequirements{ Limits: dnsPodResources, Requests: dnsPodResources, }, @@ -116,12 +118,12 @@ func createKubeDNSPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { fmt.Sprintf("--dns-port=%d", kubeDNSPort), // TODO __PILLAR__FEDERATIONS__DOMAIN__MAP__ }, - LivenessProbe: &api.Probe{ - Handler: api.Handler{ - HTTPGet: &api.HTTPGetAction{ + LivenessProbe: &v1.Probe{ + Handler: v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Path: "/healthz", Port: intstr.FromInt(8080), - Scheme: api.URISchemeHTTP, + Scheme: v1.URISchemeHTTP, }, }, InitialDelaySeconds: 60, @@ -131,27 +133,27 @@ func createKubeDNSPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { }, // # we poll on pod startup for the Kubernetes master service and // # only setup the /readiness HTTP server once that's available. - ReadinessProbe: &api.Probe{ - Handler: api.Handler{ - HTTPGet: &api.HTTPGetAction{ + ReadinessProbe: &v1.Probe{ + Handler: v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Path: "/readiness", Port: intstr.FromInt(8081), - Scheme: api.URISchemeHTTP, + Scheme: v1.URISchemeHTTP, }, }, InitialDelaySeconds: 30, TimeoutSeconds: 5, }, - Ports: []api.ContainerPort{ + Ports: []v1.ContainerPort{ { ContainerPort: kubeDNSPort, Name: "dns-local", - Protocol: api.ProtocolUDP, + Protocol: v1.ProtocolUDP, }, { ContainerPort: kubeDNSPort, Name: "dns-tcp-local", - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, }, }, @@ -159,7 +161,7 @@ func createKubeDNSPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { { Name: "dnsmasq", Image: images.GetAddonImage(images.KubeDNSmasqImage), - Resources: api.ResourceRequirements{ + Resources: v1.ResourceRequirements{ Limits: dnsPodResources, Requests: dnsPodResources, }, @@ -168,16 +170,16 @@ func createKubeDNSPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { "--no-resolv", fmt.Sprintf("--server=127.0.0.1#%d", kubeDNSPort), }, - Ports: []api.ContainerPort{ + Ports: []v1.ContainerPort{ { ContainerPort: dnsmasqPort, Name: "dns", - Protocol: api.ProtocolUDP, + Protocol: v1.ProtocolUDP, }, { ContainerPort: dnsmasqPort, Name: "dns-tcp", - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, }, }, @@ -185,7 +187,7 @@ func createKubeDNSPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { { Name: "healthz", Image: images.GetAddonImage(images.KubeExechealthzImage), - Resources: api.ResourceRequirements{ + Resources: v1.ResourceRequirements{ Limits: healthzPodResources, Requests: healthzPodResources, }, @@ -194,18 +196,18 @@ func createKubeDNSPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { "-port=8080", "-quiet", }, - Ports: []api.ContainerPort{{ + Ports: []v1.ContainerPort{{ ContainerPort: 8080, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }}, }, }, - DNSPolicy: api.DNSDefault, + DNSPolicy: v1.DNSDefault, } } -func createKubeDNSServiceSpec(cfg *kubeadmapi.MasterConfiguration) (*api.ServiceSpec, error) { +func createKubeDNSServiceSpec(cfg *kubeadmapi.MasterConfiguration) (*v1.ServiceSpec, error) { _, n, err := net.ParseCIDR(cfg.Networking.ServiceSubnet) if err != nil { return nil, fmt.Errorf("could not parse %q: %v", cfg.Networking.ServiceSubnet, err) @@ -215,11 +217,11 @@ func createKubeDNSServiceSpec(cfg *kubeadmapi.MasterConfiguration) (*api.Service return nil, fmt.Errorf("unable to allocate IP address for kube-dns addon from the given CIDR (%q) [%v]", cfg.Networking.ServiceSubnet, err) } - svc := &api.ServiceSpec{ + svc := &v1.ServiceSpec{ Selector: map[string]string{"name": "kube-dns"}, - Ports: []api.ServicePort{ - {Name: "dns", Port: 53, Protocol: api.ProtocolUDP}, - {Name: "dns-tcp", Port: 53, Protocol: api.ProtocolTCP}, + Ports: []v1.ServicePort{ + {Name: "dns", Port: 53, Protocol: v1.ProtocolUDP}, + {Name: "dns-tcp", Port: 53, Protocol: v1.ProtocolTCP}, }, ClusterIP: ip.String(), } diff --git a/cmd/kubeadm/app/master/apiclient.go b/cmd/kubeadm/app/master/apiclient.go index b790a9c1cdb..8966f33c1dd 100644 --- a/cmd/kubeadm/app/master/apiclient.go +++ b/cmd/kubeadm/app/master/apiclient.go @@ -26,8 +26,9 @@ import ( "k8s.io/kubernetes/pkg/api" apierrs "k8s.io/kubernetes/pkg/api/errors" unversionedapi "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/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" "k8s.io/kubernetes/pkg/util/wait" @@ -55,7 +56,7 @@ func CreateClientAndWaitForAPI(adminConfig *clientcmdapi.Config) (*clientset.Cli start := time.Now() wait.PollInfinite(apiCallRetryInterval, func() (bool, error) { - cs, err := client.ComponentStatuses().List(api.ListOptions{}) + cs, err := client.ComponentStatuses().List(v1.ListOptions{}) if err != nil { return false, nil } @@ -66,7 +67,7 @@ func CreateClientAndWaitForAPI(adminConfig *clientcmdapi.Config) (*clientset.Cli } for _, item := range cs.Items { for _, condition := range item.Conditions { - if condition.Type != api.ComponentHealthy { + if condition.Type != v1.ComponentHealthy { fmt.Printf(" control plane component %q is still unhealthy: %#v\n", item.ObjectMeta.Name, item.Conditions) return false, nil } @@ -80,7 +81,7 @@ func CreateClientAndWaitForAPI(adminConfig *clientcmdapi.Config) (*clientset.Cli fmt.Println(" waiting for at least one node to register and become ready") start = time.Now() wait.PollInfinite(apiCallRetryInterval, func() (bool, error) { - nodeList, err := client.Nodes().List(api.ListOptions{}) + nodeList, err := client.Nodes().List(v1.ListOptions{}) if err != nil { fmt.Println(" temporarily unable to list nodes (will retry)") return false, nil @@ -89,7 +90,7 @@ func CreateClientAndWaitForAPI(adminConfig *clientcmdapi.Config) (*clientset.Cli return false, nil } n := &nodeList.Items[0] - if !api.IsNodeReady(n) { + if !v1.IsNodeReady(n) { fmt.Println(" first node has registered, but is not ready yet") return false, nil } @@ -110,24 +111,24 @@ func standardLabels(n string) map[string]string { } } -func NewDaemonSet(daemonName string, podSpec api.PodSpec) *extensions.DaemonSet { +func NewDaemonSet(daemonName string, podSpec v1.PodSpec) *extensions.DaemonSet { l := standardLabels(daemonName) return &extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: daemonName}, + ObjectMeta: v1.ObjectMeta{Name: daemonName}, Spec: extensions.DaemonSetSpec{ Selector: &unversionedapi.LabelSelector{MatchLabels: l}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{Labels: l}, + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{Labels: l}, Spec: podSpec, }, }, } } -func NewService(serviceName string, spec api.ServiceSpec) *api.Service { +func NewService(serviceName string, spec v1.ServiceSpec) *v1.Service { l := standardLabels(serviceName) - return &api.Service{ - ObjectMeta: api.ObjectMeta{ + return &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: serviceName, Labels: l, }, @@ -135,15 +136,15 @@ func NewService(serviceName string, spec api.ServiceSpec) *api.Service { } } -func NewDeployment(deploymentName string, replicas int32, podSpec api.PodSpec) *extensions.Deployment { +func NewDeployment(deploymentName string, replicas int32, podSpec v1.PodSpec) *extensions.Deployment { l := standardLabels(deploymentName) return &extensions.Deployment{ - ObjectMeta: api.ObjectMeta{Name: deploymentName}, + ObjectMeta: v1.ObjectMeta{Name: deploymentName}, Spec: extensions.DeploymentSpec{ - Replicas: replicas, + Replicas: &replicas, Selector: &unversionedapi.LabelSelector{MatchLabels: l}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{Labels: l}, + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{Labels: l}, Spec: podSpec, }, }, @@ -152,8 +153,8 @@ func NewDeployment(deploymentName string, replicas int32, podSpec api.PodSpec) * // It's safe to do this for alpha, as we don't have HA and there is no way we can get // more then one node here (TODO(phase1+) use os.Hostname) -func findMyself(client *clientset.Clientset) (*api.Node, error) { - nodeList, err := client.Nodes().List(api.ListOptions{}) +func findMyself(client *clientset.Clientset) (*v1.Node, error) { + nodeList, err := client.Nodes().List(v1.ListOptions{}) if err != nil { return nil, fmt.Errorf("unable to list nodes [%v]", err) } @@ -173,8 +174,8 @@ func attemptToUpdateMasterRoleLabelsAndTaints(client *clientset.Clientset, sched n.ObjectMeta.Labels[unversionedapi.NodeLabelKubeadmAlphaRole] = unversionedapi.NodeLabelRoleMaster if !schedulable { - taintsAnnotation, _ := json.Marshal([]api.Taint{{Key: "dedicated", Value: "master", Effect: "NoSchedule"}}) - n.ObjectMeta.Annotations[api.TaintsAnnotationKey] = string(taintsAnnotation) + taintsAnnotation, _ := json.Marshal([]v1.Taint{{Key: "dedicated", Value: "master", Effect: "NoSchedule"}}) + n.ObjectMeta.Annotations[v1.TaintsAnnotationKey] = string(taintsAnnotation) } if _, err := client.Nodes().Update(n); err != nil { @@ -199,50 +200,51 @@ func UpdateMasterRoleLabelsAndTaints(client *clientset.Clientset, schedulable bo return nil } -func SetMasterTaintTolerations(meta *api.ObjectMeta) { - tolerationsAnnotation, _ := json.Marshal([]api.Toleration{{Key: "dedicated", Value: "master", Effect: "NoSchedule"}}) +func SetMasterTaintTolerations(meta *v1.ObjectMeta) { + tolerationsAnnotation, _ := json.Marshal([]v1.Toleration{{Key: "dedicated", Value: "master", Effect: "NoSchedule"}}) if meta.Annotations == nil { meta.Annotations = map[string]string{} } - meta.Annotations[api.TolerationsAnnotationKey] = string(tolerationsAnnotation) + meta.Annotations[v1.TolerationsAnnotationKey] = string(tolerationsAnnotation) } -// SetNodeAffinity is a basic helper to set meta.Annotations[api.AffinityAnnotationKey] for one or more api.NodeSelectorRequirement(s) -func SetNodeAffinity(meta *api.ObjectMeta, expr ...api.NodeSelectorRequirement) { - nodeAffinity := &api.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &api.NodeSelector{ - NodeSelectorTerms: []api.NodeSelectorTerm{{MatchExpressions: expr}}, +// SetNodeAffinity is a basic helper to set meta.Annotations[v1.AffinityAnnotationKey] for one or more v1.NodeSelectorRequirement(s) +func SetNodeAffinity(meta *v1.ObjectMeta, expr ...v1.NodeSelectorRequirement) { + nodeAffinity := &v1.NodeAffinity{ + RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{ + NodeSelectorTerms: []v1.NodeSelectorTerm{{MatchExpressions: expr}}, }, } - affinityAnnotation, _ := json.Marshal(api.Affinity{NodeAffinity: nodeAffinity}) + affinityAnnotation, _ := json.Marshal(v1.Affinity{NodeAffinity: nodeAffinity}) if meta.Annotations == nil { meta.Annotations = map[string]string{} } - meta.Annotations[api.AffinityAnnotationKey] = string(affinityAnnotation) + meta.Annotations[v1.AffinityAnnotationKey] = string(affinityAnnotation) } -// MasterNodeAffinity returns api.NodeSelectorRequirement to be used with SetNodeAffinity to set affinity to master node -func MasterNodeAffinity() api.NodeSelectorRequirement { - return api.NodeSelectorRequirement{ +// MasterNodeAffinity returns v1.NodeSelectorRequirement to be used with SetNodeAffinity to set affinity to master node +func MasterNodeAffinity() v1.NodeSelectorRequirement { + return v1.NodeSelectorRequirement{ Key: unversionedapi.NodeLabelKubeadmAlphaRole, - Operator: api.NodeSelectorOpIn, + Operator: v1.NodeSelectorOpIn, Values: []string{unversionedapi.NodeLabelRoleMaster}, } } -// NativeArchitectureNodeAffinity returns api.NodeSelectorRequirement to be used with SetNodeAffinity to nodes with CPU architecture +// NativeArchitectureNodeAffinity returns v1.NodeSelectorRequirement to be used with SetNodeAffinity to nodes with CPU architecture // the same as master node -func NativeArchitectureNodeAffinity() api.NodeSelectorRequirement { - return api.NodeSelectorRequirement{ - Key: "beta.kubernetes.io/arch", Operator: api.NodeSelectorOpIn, Values: []string{runtime.GOARCH}, +func NativeArchitectureNodeAffinity() v1.NodeSelectorRequirement { + return v1.NodeSelectorRequirement{ + Key: "beta.kubernetes.io/arch", Operator: v1.NodeSelectorOpIn, Values: []string{runtime.GOARCH}, } } func createDummyDeployment(client *clientset.Clientset) { fmt.Println(" attempting a test deployment") - dummyDeployment := NewDeployment("dummy", 1, api.PodSpec{ - SecurityContext: &api.PodSecurityContext{HostNetwork: true}, - Containers: []api.Container{{ + dummyDeployment := NewDeployment("dummy", 1, v1.PodSpec{ + HostNetwork: true, + SecurityContext: &v1.PodSecurityContext{}, + Containers: []v1.Container{{ Name: "dummy", Image: images.GetAddonImage("pause"), }}, @@ -271,7 +273,7 @@ func createDummyDeployment(client *clientset.Clientset) { fmt.Println(" test deployment succeeded") - if err := client.Extensions().Deployments(api.NamespaceSystem).Delete("dummy", &api.DeleteOptions{}); err != nil { + if err := client.Extensions().Deployments(api.NamespaceSystem).Delete("dummy", &v1.DeleteOptions{}); err != nil { fmt.Printf(" failed to delete test deployment [%v] (will ignore)", err) } } diff --git a/cmd/kubeadm/app/master/discovery.go b/cmd/kubeadm/app/master/discovery.go index 2c2c5b88eef..87c24cd04c7 100644 --- a/cmd/kubeadm/app/master/discovery.go +++ b/cmd/kubeadm/app/master/discovery.go @@ -25,15 +25,16 @@ import ( kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" kubeadmapiext "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1alpha1" "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" certutil "k8s.io/kubernetes/pkg/util/cert" "k8s.io/kubernetes/pkg/util/wait" ) type kubeDiscovery struct { Deployment *extensions.Deployment - Secret *api.Secret + Secret *v1.Secret } const ( @@ -61,29 +62,30 @@ func encodeKubeDiscoverySecretData(cfg *kubeadmapi.MasterConfiguration, caCert * return data } -func newKubeDiscoveryPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { - return api.PodSpec{ +func newKubeDiscoveryPodSpec(cfg *kubeadmapi.MasterConfiguration) v1.PodSpec { + return v1.PodSpec{ // We have to use host network namespace, as `HostPort`/`HostIP` are Docker's // buisness and CNI support isn't quite there yet (except for kubenet) // (see https://github.com/kubernetes/kubernetes/issues/31307) // TODO update this when #31307 is resolved - SecurityContext: &api.PodSecurityContext{HostNetwork: true}, - Containers: []api.Container{{ + HostNetwork: true, + SecurityContext: &v1.PodSecurityContext{}, + Containers: []v1.Container{{ Name: kubeDiscoveryName, Image: kubeadmapi.GlobalEnvParams.DiscoveryImage, Command: []string{"/usr/local/bin/kube-discovery"}, - VolumeMounts: []api.VolumeMount{{ + VolumeMounts: []v1.VolumeMount{{ Name: kubeDiscoverySecretName, MountPath: "/tmp/secret", // TODO use a shared constant ReadOnly: true, }}, - Ports: []api.ContainerPort{ + Ports: []v1.ContainerPort{ // TODO when CNI issue (#31307) is resolved, we should consider adding // `HostIP: s.API.AdvertiseAddrs[0]`, if there is only one address` {Name: "http", ContainerPort: kubeadmapiext.DefaultDiscoveryBindPort, HostPort: cfg.Discovery.BindPort}, }, - SecurityContext: &api.SecurityContext{ - SELinuxOptions: &api.SELinuxOptions{ + SecurityContext: &v1.SecurityContext{ + SELinuxOptions: &v1.SELinuxOptions{ // TODO: This implies our discovery container is not being restricted by // SELinux. This is not optimal and would be nice to adjust in future // so it can read /tmp/secret, but for now this avoids recommending @@ -92,10 +94,10 @@ func newKubeDiscoveryPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { }, }, }}, - Volumes: []api.Volume{{ + Volumes: []v1.Volume{{ Name: kubeDiscoverySecretName, - VolumeSource: api.VolumeSource{ - Secret: &api.SecretVolumeSource{SecretName: kubeDiscoverySecretName}, + VolumeSource: v1.VolumeSource{ + Secret: &v1.SecretVolumeSource{SecretName: kubeDiscoverySecretName}, }}, }, } @@ -104,9 +106,9 @@ func newKubeDiscoveryPodSpec(cfg *kubeadmapi.MasterConfiguration) api.PodSpec { func newKubeDiscovery(cfg *kubeadmapi.MasterConfiguration, caCert *x509.Certificate) kubeDiscovery { kd := kubeDiscovery{ Deployment: NewDeployment(kubeDiscoveryName, 1, newKubeDiscoveryPodSpec(cfg)), - Secret: &api.Secret{ - ObjectMeta: api.ObjectMeta{Name: kubeDiscoverySecretName}, - Type: api.SecretTypeOpaque, + Secret: &v1.Secret{ + ObjectMeta: v1.ObjectMeta{Name: kubeDiscoverySecretName}, + Type: v1.SecretTypeOpaque, Data: encodeKubeDiscoverySecretData(cfg, caCert), }, } diff --git a/cmd/kubeadm/app/node/BUILD b/cmd/kubeadm/app/node/BUILD index d0f47aab7c5..75ae162bdf3 100644 --- a/cmd/kubeadm/app/node/BUILD +++ b/cmd/kubeadm/app/node/BUILD @@ -22,8 +22,8 @@ go_library( "//cmd/kubeadm/app/apis/kubeadm:go_default_library", "//cmd/kubeadm/app/util:go_default_library", "//pkg/apis/certificates:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/certificates/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/certificates/v1alpha1:go_default_library", "//pkg/client/unversioned/clientcmd:go_default_library", "//pkg/client/unversioned/clientcmd/api:go_default_library", "//pkg/kubelet/util/csr:go_default_library", diff --git a/cmd/kubeadm/app/node/bootstrap.go b/cmd/kubeadm/app/node/bootstrap.go index 6af284c3efa..808b361ec09 100644 --- a/cmd/kubeadm/app/node/bootstrap.go +++ b/cmd/kubeadm/app/node/bootstrap.go @@ -25,8 +25,8 @@ import ( kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util" "k8s.io/kubernetes/pkg/apis/certificates" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - certclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + certclient "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/certificates/v1alpha1" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/wait" @@ -34,7 +34,7 @@ import ( // ConnectionDetails represents a master API endpoint connection type ConnectionDetails struct { - CertClient *certclient.CertificatesClient + CertClient *certclient.CertificatesV1alpha1Client Endpoint string CACert []byte NodeName types.NodeName @@ -82,7 +82,7 @@ func EstablishMasterConnection(s *kubeadmapi.NodeConfiguration, clusterInfo *kub // connection established, stop all wait threads close(stopChan) result <- &ConnectionDetails{ - CertClient: clientSet.CertificatesClient, + CertClient: clientSet.CertificatesV1alpha1Client, Endpoint: apiEndpoint, CACert: caCert, NodeName: nodeName, diff --git a/cmd/kubelet/app/BUILD b/cmd/kubelet/app/BUILD index 731f63ef85a..b681156b224 100644 --- a/cmd/kubelet/app/BUILD +++ b/cmd/kubelet/app/BUILD @@ -23,6 +23,7 @@ go_library( deps = [ "//cmd/kubelet/app/options:go_default_library", "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/componentconfig:go_default_library", "//pkg/apis/componentconfig/v1alpha1:go_default_library", "//pkg/auth/authenticator:go_default_library", @@ -31,11 +32,11 @@ go_library( "//pkg/auth/group:go_default_library", "//pkg/capabilities:go_default_library", "//pkg/client/chaosclient:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/authentication/internalversion:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/authorization/internalversion:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/certificates/internalversion:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/authentication/v1beta1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/authorization/v1beta1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/certificates/v1alpha1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/unversioned/auth:go_default_library", diff --git a/cmd/kubelet/app/auth.go b/cmd/kubelet/app/auth.go index 53100c9aa15..aa2a496e8da 100644 --- a/cmd/kubelet/app/auth.go +++ b/cmd/kubelet/app/auth.go @@ -26,9 +26,9 @@ import ( "k8s.io/kubernetes/pkg/auth/authenticator/bearertoken" "k8s.io/kubernetes/pkg/auth/authorizer" "k8s.io/kubernetes/pkg/auth/group" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - authenticationclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/authentication/internalversion" - authorizationclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/authorization/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + authenticationclient "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/authentication/v1beta1" + authorizationclient "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/authorization/v1beta1" alwaysallowauthorizer "k8s.io/kubernetes/pkg/genericapiserver/authorizer" "k8s.io/kubernetes/pkg/kubelet/server" "k8s.io/kubernetes/pkg/types" @@ -40,7 +40,7 @@ import ( webhooksar "k8s.io/kubernetes/plugin/pkg/auth/authorizer/webhook" ) -func buildAuth(nodeName types.NodeName, client internalclientset.Interface, config componentconfig.KubeletConfiguration) (server.AuthInterface, error) { +func buildAuth(nodeName types.NodeName, client clientset.Interface, config componentconfig.KubeletConfiguration) (server.AuthInterface, error) { // Get clients, if provided var ( tokenClient authenticationclient.TokenReviewInterface diff --git a/cmd/kubelet/app/bootstrap.go b/cmd/kubelet/app/bootstrap.go index e1d1593e207..b0569a03178 100644 --- a/cmd/kubelet/app/bootstrap.go +++ b/cmd/kubelet/app/bootstrap.go @@ -25,7 +25,7 @@ import ( "github.com/golang/glog" - unversionedcertificates "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/internalversion" + unversionedcertificates "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/certificates/v1alpha1" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" diff --git a/cmd/kubelet/app/server.go b/cmd/kubelet/app/server.go index 86f2a32ca2a..df98b4bb871 100644 --- a/cmd/kubelet/app/server.go +++ b/cmd/kubelet/app/server.go @@ -38,12 +38,13 @@ import ( "k8s.io/kubernetes/cmd/kubelet/app/options" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" componentconfigv1alpha1 "k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1" "k8s.io/kubernetes/pkg/capabilities" "k8s.io/kubernetes/pkg/client/chaosclient" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/restclient" clientauth "k8s.io/kubernetes/pkg/client/unversioned/auth" @@ -170,7 +171,7 @@ func getRemoteKubeletConfig(s *options.KubeletServer, kubeDeps *kubelet.KubeletD return "", err } - configmap, err := func() (*api.ConfigMap, error) { + configmap, err := func() (*v1.ConfigMap, error) { var nodename types.NodeName hostname := nodeutil.GetHostname(s.HostnameOverride) @@ -186,14 +187,14 @@ func getRemoteKubeletConfig(s *options.KubeletServer, kubeDeps *kubelet.KubeletD return nil, err } // look for kubelet- configmap from "kube-system" - configmap, err := kubeClient.CoreClient.ConfigMaps("kube-system").Get(fmt.Sprintf("kubelet-%s", nodename)) + configmap, err := kubeClient.CoreV1Client.ConfigMaps("kube-system").Get(fmt.Sprintf("kubelet-%s", nodename)) if err != nil { return nil, err } return configmap, nil } // No cloud provider yet, so can't get the nodename via Cloud.Instances().CurrentNodeName(hostname), try just using the hostname - configmap, err := kubeClient.CoreClient.ConfigMaps("kube-system").Get(fmt.Sprintf("kubelet-%s", hostname)) + configmap, err := kubeClient.CoreV1Client.ConfigMaps("kube-system").Get(fmt.Sprintf("kubelet-%s", hostname)) if err != nil { return nil, fmt.Errorf("cloud provider was nil, and attempt to use hostname to find config resulted in: %v", err) } @@ -660,11 +661,11 @@ func RunKubelet(kubeCfg *componentconfig.KubeletConfiguration, kubeDeps *kubelet } eventBroadcaster := record.NewBroadcaster() - kubeDeps.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: "kubelet", Host: string(nodeName)}) + kubeDeps.Recorder = eventBroadcaster.NewRecorder(v1.EventSource{Component: "kubelet", Host: string(nodeName)}) eventBroadcaster.StartLogging(glog.V(3).Infof) if kubeDeps.EventClient != nil { glog.V(4).Infof("Sending events to api server.") - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeDeps.EventClient.Events("")}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeDeps.EventClient.Events("")}) } else { glog.Warning("No api server defined - no events will be sent to API server.") } diff --git a/cmd/kubemark/BUILD b/cmd/kubemark/BUILD index 22e193b836d..35b39b97ed0 100644 --- a/cmd/kubemark/BUILD +++ b/cmd/kubemark/BUILD @@ -15,8 +15,9 @@ go_binary( srcs = ["hollow-node.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/metrics/prometheus:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/restclient:go_default_library", diff --git a/cmd/kubemark/hollow-node.go b/cmd/kubemark/hollow-node.go index 6bf3fce3061..d341739e40d 100644 --- a/cmd/kubemark/hollow-node.go +++ b/cmd/kubemark/hollow-node.go @@ -19,8 +19,9 @@ package main import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" _ "k8s.io/kubernetes/pkg/client/metrics/prometheus" // for client metric registration "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/restclient" @@ -96,10 +97,14 @@ func main() { glog.Fatalf("Failed to create a ClientConfig: %v. Exiting.", err) } - clientset, err := internalclientset.NewForConfig(clientConfig) + clientset, err := clientset.NewForConfig(clientConfig) if err != nil { glog.Fatalf("Failed to create a ClientSet: %v. Exiting.", err) } + internalClientset, err := internalclientset.NewForConfig(clientConfig) + if err != nil { + glog.Fatalf("Failed to create an internal ClientSet: %v. Exiting.", err) + } if config.Morph == "kubelet" { cadvisorInterface := new(cadvisortest.Fake) @@ -124,7 +129,7 @@ func main() { if config.Morph == "proxy" { eventBroadcaster := record.NewBroadcaster() - recorder := eventBroadcaster.NewRecorder(api.EventSource{Component: "kube-proxy", Host: config.NodeName}) + recorder := eventBroadcaster.NewRecorder(v1.EventSource{Component: "kube-proxy", Host: config.NodeName}) iptInterface := fakeiptables.NewFake() @@ -134,7 +139,7 @@ func main() { endpointsConfig := proxyconfig.NewEndpointsConfig() endpointsConfig.RegisterHandler(&kubemark.FakeProxyHandler{}) - hollowProxy := kubemark.NewHollowProxyOrDie(config.NodeName, clientset, endpointsConfig, serviceConfig, iptInterface, eventBroadcaster, recorder) + hollowProxy := kubemark.NewHollowProxyOrDie(config.NodeName, internalClientset, endpointsConfig, serviceConfig, iptInterface, eventBroadcaster, recorder) hollowProxy.Run() } } diff --git a/federation/cmd/federation-apiserver/app/server.go b/federation/cmd/federation-apiserver/app/server.go index aff83f4ed84..0345b2964a0 100644 --- a/federation/cmd/federation-apiserver/app/server.go +++ b/federation/cmd/federation-apiserver/app/server.go @@ -143,7 +143,7 @@ func Run(s *options.ServerRunOptions) error { if err != nil { glog.Errorf("Failed to create clientset: %v", err) } - sharedInformers := informers.NewSharedInformerFactory(client, 10*time.Minute) + sharedInformers := informers.NewSharedInformerFactory(nil, client, 10*time.Minute) authorizationConfig := authorizer.AuthorizationConfig{ PolicyFile: s.GenericServerRunOptions.AuthorizationPolicyFile, diff --git a/federation/pkg/federation-controller/cluster/clustercontroller.go b/federation/pkg/federation-controller/cluster/clustercontroller.go index aa0bb38f7df..51bb855a54b 100644 --- a/federation/pkg/federation-controller/cluster/clustercontroller.go +++ b/federation/pkg/federation-controller/cluster/clustercontroller.go @@ -24,8 +24,6 @@ import ( federation_v1beta1 "k8s.io/kubernetes/federation/apis/federation/v1beta1" cluster_cache "k8s.io/kubernetes/federation/client/cache" federationclientset "k8s.io/kubernetes/federation/client/clientset_generated/federation_release_1_5" - "k8s.io/kubernetes/federation/pkg/federation-controller/util" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/controller" @@ -66,13 +64,11 @@ func NewclusterController(federationClient federationclientset.Interface, cluste } cc.clusterStore.Store, cc.clusterController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return cc.federationClient.Federation().Clusters().List(versionedOptions) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return cc.federationClient.Federation().Clusters().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return cc.federationClient.Federation().Clusters().Watch(versionedOptions) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return cc.federationClient.Federation().Clusters().Watch(options) }, }, &federation_v1beta1.Cluster{}, diff --git a/federation/pkg/federation-controller/configmap/configmap_controller.go b/federation/pkg/federation-controller/configmap/configmap_controller.go index e0a9a26e6db..1c952945e8e 100644 --- a/federation/pkg/federation-controller/configmap/configmap_controller.go +++ b/federation/pkg/federation-controller/configmap/configmap_controller.go @@ -79,7 +79,7 @@ type ConfigMapController struct { func NewConfigMapController(client federationclientset.Interface) *ConfigMapController { broadcaster := record.NewBroadcaster() broadcaster.StartRecordingToSink(eventsink.NewFederatedEventSink(client)) - recorder := broadcaster.NewRecorder(api.EventSource{Component: "federated-configmaps-controller"}) + recorder := broadcaster.NewRecorder(api_v1.EventSource{Component: "federated-configmaps-controller"}) configmapcontroller := &ConfigMapController{ federatedApiClient: client, @@ -98,13 +98,11 @@ func NewConfigMapController(client federationclientset.Interface) *ConfigMapCont // Start informer on federated API servers on configmaps that should be federated. configmapcontroller.configmapInformerStore, configmapcontroller.configmapInformerController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return client.Core().ConfigMaps(api_v1.NamespaceAll).List(versionedOptions) + ListFunc: func(options api_v1.ListOptions) (pkg_runtime.Object, error) { + return client.Core().ConfigMaps(api_v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return client.Core().ConfigMaps(api_v1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options api_v1.ListOptions) (watch.Interface, error) { + return client.Core().ConfigMaps(api_v1.NamespaceAll).Watch(options) }, }, &api_v1.ConfigMap{}, @@ -117,13 +115,11 @@ func NewConfigMapController(client federationclientset.Interface) *ConfigMapCont func(cluster *federation_api.Cluster, targetClient kubeclientset.Interface) (cache.Store, cache.ControllerInterface) { return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Core().ConfigMaps(api_v1.NamespaceAll).List(versionedOptions) + ListFunc: func(options api_v1.ListOptions) (pkg_runtime.Object, error) { + return targetClient.Core().ConfigMaps(api_v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Core().ConfigMaps(api_v1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options api_v1.ListOptions) (watch.Interface, error) { + return targetClient.Core().ConfigMaps(api_v1.NamespaceAll).Watch(options) }, }, &api_v1.ConfigMap{}, diff --git a/federation/pkg/federation-controller/daemonset/daemonset_controller.go b/federation/pkg/federation-controller/daemonset/daemonset_controller.go index 73cf015e11b..b4e02f14a0b 100644 --- a/federation/pkg/federation-controller/daemonset/daemonset_controller.go +++ b/federation/pkg/federation-controller/daemonset/daemonset_controller.go @@ -87,7 +87,7 @@ type DaemonSetController struct { func NewDaemonSetController(client federationclientset.Interface) *DaemonSetController { broadcaster := record.NewBroadcaster() broadcaster.StartRecordingToSink(eventsink.NewFederatedEventSink(client)) - recorder := broadcaster.NewRecorder(api.EventSource{Component: "federated-daemonset-controller"}) + recorder := broadcaster.NewRecorder(api_v1.EventSource{Component: "federated-daemonset-controller"}) daemonsetcontroller := &DaemonSetController{ federatedApiClient: client, @@ -106,13 +106,11 @@ func NewDaemonSetController(client federationclientset.Interface) *DaemonSetCont // Start informer in federated API servers on daemonsets that should be federated. daemonsetcontroller.daemonsetInformerStore, daemonsetcontroller.daemonsetInformerController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return client.Extensions().DaemonSets(api_v1.NamespaceAll).List(versionedOptions) + ListFunc: func(options api_v1.ListOptions) (pkg_runtime.Object, error) { + return client.Extensions().DaemonSets(api_v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return client.Extensions().DaemonSets(api_v1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options api_v1.ListOptions) (watch.Interface, error) { + return client.Extensions().DaemonSets(api_v1.NamespaceAll).Watch(options) }, }, &extensionsv1.DaemonSet{}, @@ -125,13 +123,11 @@ func NewDaemonSetController(client federationclientset.Interface) *DaemonSetCont func(cluster *federation_api.Cluster, targetClient kubeclientset.Interface) (cache.Store, cache.ControllerInterface) { return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Extensions().DaemonSets(api_v1.NamespaceAll).List(versionedOptions) + ListFunc: func(options api_v1.ListOptions) (pkg_runtime.Object, error) { + return targetClient.Extensions().DaemonSets(api_v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Extensions().DaemonSets(api_v1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options api_v1.ListOptions) (watch.Interface, error) { + return targetClient.Extensions().DaemonSets(api_v1.NamespaceAll).Watch(options) }, }, &extensionsv1.DaemonSet{}, diff --git a/federation/pkg/federation-controller/deployment/deploymentcontroller.go b/federation/pkg/federation-controller/deployment/deploymentcontroller.go index 0f791ad64dd..e2981c5c87f 100644 --- a/federation/pkg/federation-controller/deployment/deploymentcontroller.go +++ b/federation/pkg/federation-controller/deployment/deploymentcontroller.go @@ -104,7 +104,7 @@ type DeploymentController struct { func NewDeploymentController(federationClient fedclientset.Interface) *DeploymentController { broadcaster := record.NewBroadcaster() broadcaster.StartRecordingToSink(eventsink.NewFederatedEventSink(federationClient)) - recorder := broadcaster.NewRecorder(api.EventSource{Component: "federated-deployment-controller"}) + recorder := broadcaster.NewRecorder(apiv1.EventSource{Component: "federated-deployment-controller"}) fdc := &DeploymentController{ fedClient: federationClient, @@ -123,13 +123,11 @@ func NewDeploymentController(federationClient fedclientset.Interface) *Deploymen deploymentFedInformerFactory := func(cluster *fedv1.Cluster, clientset kubeclientset.Interface) (cache.Store, cache.ControllerInterface) { return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return clientset.Extensions().Deployments(apiv1.NamespaceAll).List(versionedOptions) + ListFunc: func(options apiv1.ListOptions) (runtime.Object, error) { + return clientset.Extensions().Deployments(apiv1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return clientset.Extensions().Deployments(apiv1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options apiv1.ListOptions) (watch.Interface, error) { + return clientset.Extensions().Deployments(apiv1.NamespaceAll).Watch(options) }, }, &extensionsv1.Deployment{}, @@ -152,13 +150,11 @@ func NewDeploymentController(federationClient fedclientset.Interface) *Deploymen podFedInformerFactory := func(cluster *fedv1.Cluster, clientset kubeclientset.Interface) (cache.Store, cache.ControllerInterface) { return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return clientset.Core().Pods(apiv1.NamespaceAll).List(versionedOptions) + ListFunc: func(options apiv1.ListOptions) (runtime.Object, error) { + return clientset.Core().Pods(apiv1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return clientset.Core().Pods(apiv1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options apiv1.ListOptions) (watch.Interface, error) { + return clientset.Core().Pods(apiv1.NamespaceAll).Watch(options) }, }, &apiv1.Pod{}, @@ -174,13 +170,11 @@ func NewDeploymentController(federationClient fedclientset.Interface) *Deploymen fdc.deploymentStore, fdc.deploymentController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return fdc.fedClient.Extensions().Deployments(apiv1.NamespaceAll).List(versionedOptions) + ListFunc: func(options apiv1.ListOptions) (runtime.Object, error) { + return fdc.fedClient.Extensions().Deployments(apiv1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return fdc.fedClient.Extensions().Deployments(apiv1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options apiv1.ListOptions) (watch.Interface, error) { + return fdc.fedClient.Extensions().Deployments(apiv1.NamespaceAll).Watch(options) }, }, &extensionsv1.Deployment{}, diff --git a/federation/pkg/federation-controller/ingress/ingress_controller.go b/federation/pkg/federation-controller/ingress/ingress_controller.go index 6a8a614976c..4b25c08ea9b 100644 --- a/federation/pkg/federation-controller/ingress/ingress_controller.go +++ b/federation/pkg/federation-controller/ingress/ingress_controller.go @@ -108,7 +108,7 @@ func NewIngressController(client federationclientset.Interface) *IngressControll glog.V(4).Infof("->NewIngressController V(4)") broadcaster := record.NewBroadcaster() broadcaster.StartRecordingToSink(eventsink.NewFederatedEventSink(client)) - recorder := broadcaster.NewRecorder(api.EventSource{Component: "federated-ingress-controller"}) + recorder := broadcaster.NewRecorder(v1.EventSource{Component: "federated-ingress-controller"}) ic := &IngressController{ federatedApiClient: client, ingressReviewDelay: time.Second * 10, @@ -129,13 +129,11 @@ func NewIngressController(client federationclientset.Interface) *IngressControll // Start informer in federated API servers on ingresses that should be federated. ic.ingressInformerStore, ic.ingressInformerController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return client.Extensions().Ingresses(api.NamespaceAll).List(versionedOptions) + ListFunc: func(options v1.ListOptions) (pkg_runtime.Object, error) { + return client.Extensions().Ingresses(api.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return client.Extensions().Ingresses(api.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return client.Extensions().Ingresses(api.NamespaceAll).Watch(options) }, }, &extensions_v1beta1.Ingress{}, @@ -152,13 +150,11 @@ func NewIngressController(client federationclientset.Interface) *IngressControll func(cluster *federation_api.Cluster, targetClient kubeclientset.Interface) (cache.Store, cache.ControllerInterface) { return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Extensions().Ingresses(api.NamespaceAll).List(versionedOptions) + ListFunc: func(options v1.ListOptions) (pkg_runtime.Object, error) { + return targetClient.Extensions().Ingresses(api.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Extensions().Ingresses(api.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return targetClient.Extensions().Ingresses(api.NamespaceAll).Watch(options) }, }, &extensions_v1beta1.Ingress{}, @@ -187,19 +183,17 @@ func NewIngressController(client federationclientset.Interface) *IngressControll glog.V(4).Infof("Returning new informer for cluster %q", cluster.Name) return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (pkg_runtime.Object, error) { if targetClient == nil { glog.Errorf("Internal error: targetClient is nil") } - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Core().ConfigMaps(uidConfigMapNamespace).List(versionedOptions) // we only want to list one by name - unfortunately Kubernetes don't have a selector for that. + return targetClient.Core().ConfigMaps(uidConfigMapNamespace).List(options) // we only want to list one by name - unfortunately Kubernetes don't have a selector for that. }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if targetClient == nil { glog.Errorf("Internal error: targetClient is nil") } - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Core().ConfigMaps(uidConfigMapNamespace).Watch(versionedOptions) // as above + return targetClient.Core().ConfigMaps(uidConfigMapNamespace).Watch(options) // as above }, }, &v1.ConfigMap{}, diff --git a/federation/pkg/federation-controller/namespace/namespace_controller.go b/federation/pkg/federation-controller/namespace/namespace_controller.go index 07a1c3731f9..cab9f579451 100644 --- a/federation/pkg/federation-controller/namespace/namespace_controller.go +++ b/federation/pkg/federation-controller/namespace/namespace_controller.go @@ -84,7 +84,7 @@ type NamespaceController struct { func NewNamespaceController(client federationclientset.Interface) *NamespaceController { broadcaster := record.NewBroadcaster() broadcaster.StartRecordingToSink(eventsink.NewFederatedEventSink(client)) - recorder := broadcaster.NewRecorder(api.EventSource{Component: "federated-namespace-controller"}) + recorder := broadcaster.NewRecorder(api_v1.EventSource{Component: "federated-namespace-controller"}) nc := &NamespaceController{ federatedApiClient: client, @@ -103,13 +103,11 @@ func NewNamespaceController(client federationclientset.Interface) *NamespaceCont // Start informer in federated API servers on namespaces that should be federated. nc.namespaceInformerStore, nc.namespaceInformerController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return client.Core().Namespaces().List(versionedOptions) + ListFunc: func(options api_v1.ListOptions) (runtime.Object, error) { + return client.Core().Namespaces().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return client.Core().Namespaces().Watch(versionedOptions) + WatchFunc: func(options api_v1.ListOptions) (watch.Interface, error) { + return client.Core().Namespaces().Watch(options) }, }, &api_v1.Namespace{}, @@ -122,13 +120,11 @@ func NewNamespaceController(client federationclientset.Interface) *NamespaceCont func(cluster *federation_api.Cluster, targetClient kubeclientset.Interface) (cache.Store, cache.ControllerInterface) { return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Core().Namespaces().List(versionedOptions) + ListFunc: func(options api_v1.ListOptions) (runtime.Object, error) { + return targetClient.Core().Namespaces().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Core().Namespaces().Watch(versionedOptions) + WatchFunc: func(options api_v1.ListOptions) (watch.Interface, error) { + return targetClient.Core().Namespaces().Watch(options) }, }, &api_v1.Namespace{}, diff --git a/federation/pkg/federation-controller/replicaset/replicasetcontroller.go b/federation/pkg/federation-controller/replicaset/replicasetcontroller.go index aa66cb85c58..5929ca7e088 100644 --- a/federation/pkg/federation-controller/replicaset/replicasetcontroller.go +++ b/federation/pkg/federation-controller/replicaset/replicasetcontroller.go @@ -106,7 +106,7 @@ type ReplicaSetController struct { func NewReplicaSetController(federationClient fedclientset.Interface) *ReplicaSetController { broadcaster := record.NewBroadcaster() broadcaster.StartRecordingToSink(eventsink.NewFederatedEventSink(federationClient)) - recorder := broadcaster.NewRecorder(api.EventSource{Component: "federated-replicaset-controller"}) + recorder := broadcaster.NewRecorder(apiv1.EventSource{Component: "federated-replicaset-controller"}) frsc := &ReplicaSetController{ fedClient: federationClient, @@ -125,13 +125,11 @@ func NewReplicaSetController(federationClient fedclientset.Interface) *ReplicaSe replicaSetFedInformerFactory := func(cluster *fedv1.Cluster, clientset kubeclientset.Interface) (cache.Store, cache.ControllerInterface) { return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return clientset.Extensions().ReplicaSets(apiv1.NamespaceAll).List(versionedOptions) + ListFunc: func(options apiv1.ListOptions) (runtime.Object, error) { + return clientset.Extensions().ReplicaSets(apiv1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return clientset.Extensions().ReplicaSets(apiv1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options apiv1.ListOptions) (watch.Interface, error) { + return clientset.Extensions().ReplicaSets(apiv1.NamespaceAll).Watch(options) }, }, &extensionsv1.ReplicaSet{}, @@ -154,13 +152,11 @@ func NewReplicaSetController(federationClient fedclientset.Interface) *ReplicaSe podFedInformerFactory := func(cluster *fedv1.Cluster, clientset kubeclientset.Interface) (cache.Store, cache.ControllerInterface) { return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return clientset.Core().Pods(apiv1.NamespaceAll).List(versionedOptions) + ListFunc: func(options apiv1.ListOptions) (runtime.Object, error) { + return clientset.Core().Pods(apiv1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return clientset.Core().Pods(apiv1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options apiv1.ListOptions) (watch.Interface, error) { + return clientset.Core().Pods(apiv1.NamespaceAll).Watch(options) }, }, &apiv1.Pod{}, @@ -176,13 +172,11 @@ func NewReplicaSetController(federationClient fedclientset.Interface) *ReplicaSe frsc.replicaSetStore.Indexer, frsc.replicaSetController = cache.NewIndexerInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return frsc.fedClient.Extensions().ReplicaSets(apiv1.NamespaceAll).List(versionedOptions) + ListFunc: func(options apiv1.ListOptions) (runtime.Object, error) { + return frsc.fedClient.Extensions().ReplicaSets(apiv1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := fedutil.VersionizeV1ListOptions(options) - return frsc.fedClient.Extensions().ReplicaSets(apiv1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options apiv1.ListOptions) (watch.Interface, error) { + return frsc.fedClient.Extensions().ReplicaSets(apiv1.NamespaceAll).Watch(options) }, }, &extensionsv1.ReplicaSet{}, diff --git a/federation/pkg/federation-controller/secret/secret_controller.go b/federation/pkg/federation-controller/secret/secret_controller.go index 593cb9cc374..413fb2debca 100644 --- a/federation/pkg/federation-controller/secret/secret_controller.go +++ b/federation/pkg/federation-controller/secret/secret_controller.go @@ -85,7 +85,7 @@ type SecretController struct { func NewSecretController(client federationclientset.Interface) *SecretController { broadcaster := record.NewBroadcaster() broadcaster.StartRecordingToSink(eventsink.NewFederatedEventSink(client)) - recorder := broadcaster.NewRecorder(api.EventSource{Component: "federated-secrets-controller"}) + recorder := broadcaster.NewRecorder(api_v1.EventSource{Component: "federated-secrets-controller"}) secretcontroller := &SecretController{ federatedApiClient: client, @@ -104,13 +104,11 @@ func NewSecretController(client federationclientset.Interface) *SecretController // Start informer in federated API servers on secrets that should be federated. secretcontroller.secretInformerStore, secretcontroller.secretInformerController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return client.Core().Secrets(api_v1.NamespaceAll).List(versionedOptions) + ListFunc: func(options api_v1.ListOptions) (pkg_runtime.Object, error) { + return client.Core().Secrets(api_v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return client.Core().Secrets(api_v1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options api_v1.ListOptions) (watch.Interface, error) { + return client.Core().Secrets(api_v1.NamespaceAll).Watch(options) }, }, &api_v1.Secret{}, @@ -123,13 +121,11 @@ func NewSecretController(client federationclientset.Interface) *SecretController func(cluster *federation_api.Cluster, targetClient kubeclientset.Interface) (cache.Store, cache.ControllerInterface) { return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Core().Secrets(api_v1.NamespaceAll).List(versionedOptions) + ListFunc: func(options api_v1.ListOptions) (pkg_runtime.Object, error) { + return targetClient.Core().Secrets(api_v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return targetClient.Core().Secrets(api_v1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options api_v1.ListOptions) (watch.Interface, error) { + return targetClient.Core().Secrets(api_v1.NamespaceAll).Watch(options) }, }, &api_v1.Secret{}, diff --git a/federation/pkg/federation-controller/service/BUILD b/federation/pkg/federation-controller/service/BUILD index 2abff8ce857..e429e663da7 100644 --- a/federation/pkg/federation-controller/service/BUILD +++ b/federation/pkg/federation-controller/service/BUILD @@ -28,7 +28,6 @@ go_library( "//federation/pkg/dnsprovider:go_default_library", "//federation/pkg/dnsprovider/rrstype:go_default_library", "//federation/pkg/federation-controller/util:go_default_library", - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", diff --git a/federation/pkg/federation-controller/service/cluster_helper.go b/federation/pkg/federation-controller/service/cluster_helper.go index f9a524ab8f1..2f0f73c6030 100644 --- a/federation/pkg/federation-controller/service/cluster_helper.go +++ b/federation/pkg/federation-controller/service/cluster_helper.go @@ -20,7 +20,6 @@ import ( "sync" v1beta1 "k8s.io/kubernetes/federation/apis/federation/v1beta1" - "k8s.io/kubernetes/pkg/api" v1 "k8s.io/kubernetes/pkg/api/v1" cache "k8s.io/kubernetes/pkg/client/cache" kubeclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" @@ -92,13 +91,11 @@ func (cc *clusterClientCache) startClusterLW(cluster *v1beta1.Cluster, clusterNa } cachedClusterClient.endpointStore.Store, cachedClusterClient.endpointController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return clientset.Core().Endpoints(v1.NamespaceAll).List(versionedOptions) + ListFunc: func(options v1.ListOptions) (pkg_runtime.Object, error) { + return clientset.Core().Endpoints(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return clientset.Core().Endpoints(v1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return clientset.Core().Endpoints(v1.NamespaceAll).Watch(options) }, }, &v1.Endpoints{}, @@ -118,13 +115,11 @@ func (cc *clusterClientCache) startClusterLW(cluster *v1beta1.Cluster, clusterNa cachedClusterClient.serviceStore.Indexer, cachedClusterClient.serviceController = cache.NewIndexerInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return clientset.Core().Services(v1.NamespaceAll).List(versionedOptions) + ListFunc: func(options v1.ListOptions) (pkg_runtime.Object, error) { + return clientset.Core().Services(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return clientset.Core().Services(v1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return clientset.Core().Services(v1.NamespaceAll).Watch(options) }, }, &v1.Service{}, diff --git a/federation/pkg/federation-controller/service/dns.go b/federation/pkg/federation-controller/service/dns.go index 4e50df14e7e..6f27ac6aba7 100644 --- a/federation/pkg/federation-controller/service/dns.go +++ b/federation/pkg/federation-controller/service/dns.go @@ -22,9 +22,10 @@ import ( "github.com/golang/glog" + "strings" + "k8s.io/kubernetes/federation/pkg/dnsprovider" "k8s.io/kubernetes/federation/pkg/dnsprovider/rrstype" - "strings" ) const ( diff --git a/federation/pkg/federation-controller/service/dns_test.go b/federation/pkg/federation-controller/service/dns_test.go index 72a3a1475d4..4380d4c6071 100644 --- a/federation/pkg/federation-controller/service/dns_test.go +++ b/federation/pkg/federation-controller/service/dns_test.go @@ -21,12 +21,13 @@ import ( "testing" "fmt" + "reflect" + "sort" + "k8s.io/kubernetes/federation/apis/federation/v1beta1" "k8s.io/kubernetes/federation/pkg/dnsprovider/providers/google/clouddns" // Only for unit testing purposes. "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/sets" - "reflect" - "sort" ) func TestServiceController_ensureDnsRecords(t *testing.T) { diff --git a/federation/pkg/federation-controller/service/servicecontroller.go b/federation/pkg/federation-controller/service/servicecontroller.go index e4716c8db39..73214ccb9a8 100644 --- a/federation/pkg/federation-controller/service/servicecontroller.go +++ b/federation/pkg/federation-controller/service/servicecontroller.go @@ -28,8 +28,6 @@ import ( federationcache "k8s.io/kubernetes/federation/client/cache" fedclientset "k8s.io/kubernetes/federation/client/clientset_generated/federation_release_1_5" "k8s.io/kubernetes/federation/pkg/dnsprovider" - "k8s.io/kubernetes/federation/pkg/federation-controller/util" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" v1 "k8s.io/kubernetes/pkg/api/v1" cache "k8s.io/kubernetes/pkg/client/cache" @@ -145,7 +143,7 @@ func New(federationClient fedclientset.Interface, dns dnsprovider.Interface, broadcaster := record.NewBroadcaster() // federationClient event is not supported yet // broadcaster.StartRecordingToSink(&unversioned_core.EventSinkImpl{Interface: kubeClient.Core().Events("")}) - recorder := broadcaster.NewRecorder(api.EventSource{Component: UserAgentName}) + recorder := broadcaster.NewRecorder(v1.EventSource{Component: UserAgentName}) s := &ServiceController{ dns: dns, @@ -166,13 +164,11 @@ func New(federationClient fedclientset.Interface, dns dnsprovider.Interface, } s.serviceStore.Indexer, s.serviceController = cache.NewIndexerInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return s.federationClient.Core().Services(v1.NamespaceAll).List(versionedOptions) + ListFunc: func(options v1.ListOptions) (pkg_runtime.Object, error) { + return s.federationClient.Core().Services(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return s.federationClient.Core().Services(v1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return s.federationClient.Core().Services(v1.NamespaceAll).Watch(options) }, }, &v1.Service{}, @@ -191,13 +187,11 @@ func New(federationClient fedclientset.Interface, dns dnsprovider.Interface, ) s.clusterStore.Store, s.clusterController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return s.federationClient.Federation().Clusters().List(versionedOptions) + ListFunc: func(options v1.ListOptions) (pkg_runtime.Object, error) { + return s.federationClient.Federation().Clusters().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := util.VersionizeV1ListOptions(options) - return s.federationClient.Federation().Clusters().Watch(versionedOptions) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return s.federationClient.Federation().Clusters().Watch(options) }, }, &v1beta1.Cluster{}, diff --git a/federation/pkg/federation-controller/util/BUILD b/federation/pkg/federation-controller/util/BUILD index 442f3bd5c23..9ee677814da 100644 --- a/federation/pkg/federation-controller/util/BUILD +++ b/federation/pkg/federation-controller/util/BUILD @@ -60,7 +60,6 @@ go_test( deps = [ "//federation/apis/federation/v1beta1:go_default_library", "//federation/client/clientset_generated/federation_release_1_5/fake:go_default_library", - "//pkg/api:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/client/clientset_generated/release_1_5:go_default_library", diff --git a/federation/pkg/federation-controller/util/eventsink/BUILD b/federation/pkg/federation-controller/util/eventsink/BUILD index 060465adb79..e27514b5895 100644 --- a/federation/pkg/federation-controller/util/eventsink/BUILD +++ b/federation/pkg/federation-controller/util/eventsink/BUILD @@ -30,7 +30,6 @@ go_test( deps = [ "//federation/client/clientset_generated/federation_release_1_5/fake:go_default_library", "//federation/pkg/federation-controller/util/test:go_default_library", - "//pkg/api:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/runtime:go_default_library", diff --git a/federation/pkg/federation-controller/util/eventsink/eventsink.go b/federation/pkg/federation-controller/util/eventsink/eventsink.go index e19cdf12297..5d1ae3e9f25 100644 --- a/federation/pkg/federation-controller/util/eventsink/eventsink.go +++ b/federation/pkg/federation-controller/util/eventsink/eventsink.go @@ -37,36 +37,14 @@ func NewFederatedEventSink(clientset fedclientset.Interface) *FederatedEventSink } } -func (fes *FederatedEventSink) Create(event *api.Event) (*api.Event, error) { - return fes.executeOperation(event, func(eventV1 *api_v1.Event) (*api_v1.Event, error) { - return fes.clientset.Core().Events(event.Namespace).Create(eventV1) - }) +func (fes *FederatedEventSink) Create(event *api_v1.Event) (*api_v1.Event, error) { + return fes.clientset.Core().Events(event.Namespace).Create(event) } -func (fes *FederatedEventSink) Update(event *api.Event) (*api.Event, error) { - return fes.executeOperation(event, func(eventV1 *api_v1.Event) (*api_v1.Event, error) { - return fes.clientset.Core().Events(event.Namespace).Update(eventV1) - }) +func (fes *FederatedEventSink) Update(event *api_v1.Event) (*api_v1.Event, error) { + return fes.clientset.Core().Events(event.Namespace).Update(event) } -func (fes *FederatedEventSink) Patch(event *api.Event, data []byte) (*api.Event, error) { - return fes.executeOperation(event, func(eventV1 *api_v1.Event) (*api_v1.Event, error) { - return fes.clientset.Core().Events(event.Namespace).Patch(event.Name, api.StrategicMergePatchType, data) - }) -} - -func (fes *FederatedEventSink) executeOperation(event *api.Event, operation func(*api_v1.Event) (*api_v1.Event, error)) (*api.Event, error) { - var versionedEvent api_v1.Event - if err := api.Scheme.Convert(event, &versionedEvent, nil); err != nil { - return nil, err - } - versionedEventPtr, err := operation(&versionedEvent) - if err != nil { - return nil, err - } - var unversionedEvent api.Event - if err := api.Scheme.Convert(versionedEventPtr, &unversionedEvent, nil); err != nil { - return nil, err - } - return &unversionedEvent, nil +func (fes *FederatedEventSink) Patch(event *api_v1.Event, data []byte) (*api_v1.Event, error) { + return fes.clientset.Core().Events(event.Namespace).Patch(event.Name, api.StrategicMergePatchType, data) } diff --git a/federation/pkg/federation-controller/util/eventsink/eventsink_test.go b/federation/pkg/federation-controller/util/eventsink/eventsink_test.go index d7912d25054..858dbc0bda3 100644 --- a/federation/pkg/federation-controller/util/eventsink/eventsink_test.go +++ b/federation/pkg/federation-controller/util/eventsink/eventsink_test.go @@ -21,7 +21,6 @@ import ( fake_fedclientset "k8s.io/kubernetes/federation/client/clientset_generated/federation_release_1_5/fake" . "k8s.io/kubernetes/federation/pkg/federation-controller/util/test" - api "k8s.io/kubernetes/pkg/api" api_v1 "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/runtime" @@ -46,8 +45,8 @@ func TestEventSink(t *testing.T) { return true, obj, nil }) - event := api.Event{ - ObjectMeta: api.ObjectMeta{ + event := api_v1.Event{ + ObjectMeta: api_v1.ObjectMeta{ Name: "bzium", Namespace: "ns", }, diff --git a/federation/pkg/federation-controller/util/federated_informer.go b/federation/pkg/federation-controller/util/federated_informer.go index 23478bc34f6..dd57ca7626a 100644 --- a/federation/pkg/federation-controller/util/federated_informer.go +++ b/federation/pkg/federation-controller/util/federated_informer.go @@ -24,7 +24,6 @@ import ( federation_api "k8s.io/kubernetes/federation/apis/federation/v1beta1" federationclientset "k8s.io/kubernetes/federation/client/clientset_generated/federation_release_1_5" - api "k8s.io/kubernetes/pkg/api" api_v1 "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" kubeclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" @@ -161,13 +160,11 @@ func NewFederatedInformer( federatedInformer.clusterInformer.store, federatedInformer.clusterInformer.controller = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - versionedOptions := VersionizeV1ListOptions(options) - return federationClient.Federation().Clusters().List(versionedOptions) + ListFunc: func(options api_v1.ListOptions) (pkg_runtime.Object, error) { + return federationClient.Federation().Clusters().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := VersionizeV1ListOptions(options) - return federationClient.Federation().Clusters().Watch(versionedOptions) + WatchFunc: func(options api_v1.ListOptions) (watch.Interface, error) { + return federationClient.Federation().Clusters().Watch(options) }, }, &federation_api.Cluster{}, diff --git a/federation/pkg/federation-controller/util/federated_informer_test.go b/federation/pkg/federation-controller/util/federated_informer_test.go index 320547ae8a2..88d984ad4cd 100644 --- a/federation/pkg/federation-controller/util/federated_informer_test.go +++ b/federation/pkg/federation-controller/util/federated_informer_test.go @@ -22,7 +22,6 @@ import ( federation_api "k8s.io/kubernetes/federation/apis/federation/v1beta1" fakefederationclientset "k8s.io/kubernetes/federation/client/clientset_generated/federation_release_1_5/fake" - api "k8s.io/kubernetes/pkg/api" api_v1 "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" kubeclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" @@ -81,13 +80,11 @@ func TestFederatedInformer(t *testing.T) { targetInformerFactory := func(cluster *federation_api.Cluster, clientset kubeclientset.Interface) (cache.Store, cache.ControllerInterface) { return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - versionedOptions := VersionizeV1ListOptions(options) - return clientset.Core().Services(api_v1.NamespaceAll).List(versionedOptions) + ListFunc: func(options api_v1.ListOptions) (runtime.Object, error) { + return clientset.Core().Services(api_v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - versionedOptions := VersionizeV1ListOptions(options) - return clientset.Core().Services(api_v1.NamespaceAll).Watch(versionedOptions) + WatchFunc: func(options api_v1.ListOptions) (watch.Interface, error) { + return clientset.Core().Services(api_v1.NamespaceAll).Watch(options) }, }, &api_v1.Service{}, diff --git a/hack/.linted_packages b/hack/.linted_packages index 43b247ae11f..d1c0d0a70a0 100644 --- a/hack/.linted_packages +++ b/hack/.linted_packages @@ -64,6 +64,7 @@ pkg/api/meta pkg/api/resource pkg/api/service pkg/api/v1 +pkg/api/v1/service pkg/apimachinery pkg/apis/abac/v0 pkg/apis/apps/install @@ -88,6 +89,7 @@ pkg/apiserver/audit pkg/apiserver/openapi pkg/auth/authenticator pkg/auth/authorizer/union +pkg/client/conditions pkg/client/listers/apps/internalversion pkg/client/listers/apps/v1alpha1 pkg/client/listers/apps/v1beta1 diff --git a/hack/make-rules/test-cmd.sh b/hack/make-rules/test-cmd.sh index 893225e38e4..94f33895fa0 100755 --- a/hack/make-rules/test-cmd.sh +++ b/hack/make-rules/test-cmd.sh @@ -2313,8 +2313,9 @@ __EOF__ kubectl-with-retry rollout resume deployment nginx "${kube_flags[@]}" # The resumed deployment can now be rolled back kubectl rollout undo deployment nginx "${kube_flags[@]}" - # Check that the new replica set (nginx-618515232) has all old revisions stored in an annotation - kubectl get rs nginx-618515232 -o yaml | grep "deployment.kubernetes.io/revision-history: 1,3" + # Check that the new replica set has all old revisions stored in an annotation + newrs="$(kubectl describe deployment nginx | grep NewReplicaSet | awk '{print $2}')" + kubectl get rs "${newrs}" -o yaml | grep "deployment.kubernetes.io/revision-history: 1,3" # Check that trying to watch the status of a superseded revision returns an error ! kubectl rollout status deployment/nginx --revision=3 cat hack/testdata/deployment-revision1.yaml | $SED "s/name: nginx$/name: nginx2/" | kubectl create -f - "${kube_flags[@]}" diff --git a/pkg/api/pod/BUILD b/pkg/api/pod/BUILD index fa654640607..1b9c35f6b39 100644 --- a/pkg/api/pod/BUILD +++ b/pkg/api/pod/BUILD @@ -14,19 +14,4 @@ go_library( name = "go_default_library", srcs = ["util.go"], tags = ["automanaged"], - deps = [ - "//pkg/api:go_default_library", - "//pkg/util/intstr:go_default_library", - ], -) - -go_test( - name = "go_default_test", - srcs = ["util_test.go"], - library = "go_default_library", - tags = ["automanaged"], - deps = [ - "//pkg/api:go_default_library", - "//pkg/util/intstr:go_default_library", - ], ) diff --git a/pkg/api/pod/util.go b/pkg/api/pod/util.go index dfc12db6088..0675a50e225 100644 --- a/pkg/api/pod/util.go +++ b/pkg/api/pod/util.go @@ -16,13 +16,6 @@ limitations under the License. package pod -import ( - "fmt" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/util/intstr" -) - const ( // TODO: to be de!eted after v1.3 is released. PodSpec has a dedicated Hostname field. // The annotation value is a string specifying the hostname to be used for the pod e.g 'my-webserver-1' @@ -36,26 +29,3 @@ const ( // .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 -// match is found, fail. -func FindPort(pod *api.Pod, svcPort *api.ServicePort) (int, error) { - portName := svcPort.TargetPort - switch portName.Type { - case intstr.String: - name := portName.StrVal - for _, container := range pod.Spec.Containers { - for _, port := range container.Ports { - if port.Name == name && port.Protocol == svcPort.Protocol { - return int(port.ContainerPort), nil - } - } - } - case intstr.Int: - return portName.IntValue(), nil - } - - return 0, fmt.Errorf("no suitable port for manifest: %s", pod.UID) -} diff --git a/pkg/api/service/annotations.go b/pkg/api/service/annotations.go index 4b45549983b..42fd68b7593 100644 --- a/pkg/api/service/annotations.go +++ b/pkg/api/service/annotations.go @@ -97,15 +97,3 @@ func GetServiceHealthCheckNodePort(service *api.Service) int32 { } return 0 } - -// GetServiceHealthCheckPathPort Return the path and nodePort programmed into the Cloud LB Health Check -func GetServiceHealthCheckPathPort(service *api.Service) (string, int32) { - if !NeedsHealthCheck(service) { - return "", 0 - } - port := GetServiceHealthCheckNodePort(service) - if port == 0 { - return "", 0 - } - return "/healthz", port -} diff --git a/pkg/api/testing/BUILD b/pkg/api/testing/BUILD index ce3c2e9a0e2..7e9c6052d89 100644 --- a/pkg/api/testing/BUILD +++ b/pkg/api/testing/BUILD @@ -24,6 +24,7 @@ go_library( "//pkg/api/resource:go_default_library", "//pkg/api/testapi:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/autoscaling:go_default_library", "//pkg/apis/batch:go_default_library", "//pkg/apis/extensions:go_default_library", diff --git a/pkg/api/testing/pod_specs.go b/pkg/api/testing/pod_specs.go index d54606b300e..87300a3da73 100644 --- a/pkg/api/testing/pod_specs.go +++ b/pkg/api/testing/pod_specs.go @@ -18,6 +18,7 @@ package testing import ( "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) // DeepEqualSafePodSpec returns a PodSpec which is ready to be used with api.Semantic.DeepEqual @@ -30,3 +31,14 @@ func DeepEqualSafePodSpec() api.PodSpec { SecurityContext: &api.PodSecurityContext{}, } } + +// V1DeepEqualSafePodSpec returns a PodSpec which is ready to be used with api.Semantic.DeepEqual +func V1DeepEqualSafePodSpec() v1.PodSpec { + grace := int64(30) + return v1.PodSpec{ + RestartPolicy: v1.RestartPolicyAlways, + DNSPolicy: v1.DNSClusterFirst, + TerminationGracePeriodSeconds: &grace, + SecurityContext: &v1.PodSecurityContext{}, + } +} diff --git a/pkg/api/v1/BUILD b/pkg/api/v1/BUILD index 812ae84bdc8..3e46586fdfe 100644 --- a/pkg/api/v1/BUILD +++ b/pkg/api/v1/BUILD @@ -16,10 +16,13 @@ go_library( "conversion.go", "defaults.go", "doc.go", + "generate.go", "generated.pb.go", "helpers.go", "meta.go", + "ref.go", "register.go", + "resource_helpers.go", "types.generated.go", "types.go", "types_swagger_doc_generated.go", @@ -36,11 +39,16 @@ go_library( "//pkg/api/unversioned:go_default_library", "//pkg/apis/extensions:go_default_library", "//pkg/conversion:go_default_library", + "//pkg/fields:go_default_library", + "//pkg/labels:go_default_library", "//pkg/runtime:go_default_library", + "//pkg/selection:go_default_library", "//pkg/types:go_default_library", "//pkg/util:go_default_library", "//pkg/util/intstr:go_default_library", "//pkg/util/parsers:go_default_library", + "//pkg/util/rand:go_default_library", + "//pkg/util/sets:go_default_library", "//pkg/util/validation/field:go_default_library", "//pkg/watch/versioned:go_default_library", "//vendor:github.com/gogo/protobuf/proto", @@ -70,3 +78,19 @@ go_test( "//pkg/util/validation/field:go_default_library", ], ) + +go_test( + name = "go_default_test", + srcs = [ + "helpers_test.go", + "resource_helpers_test.go", + ], + library = "go_default_library", + tags = ["automanaged"], + deps = [ + "//pkg/api:go_default_library", + "//pkg/api/resource:go_default_library", + "//pkg/api/unversioned:go_default_library", + "//pkg/labels:go_default_library", + ], +) diff --git a/pkg/api/v1/endpoints/BUILD b/pkg/api/v1/endpoints/BUILD new file mode 100644 index 00000000000..f7c43219029 --- /dev/null +++ b/pkg/api/v1/endpoints/BUILD @@ -0,0 +1,34 @@ +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +load( + "@io_bazel_rules_go//go:def.bzl", + "go_binary", + "go_library", + "go_test", + "cgo_library", +) + +go_library( + name = "go_default_library", + srcs = ["util.go"], + tags = ["automanaged"], + deps = [ + "//pkg/api/v1:go_default_library", + "//pkg/types:go_default_library", + "//pkg/util/hash:go_default_library", + ], +) + +go_test( + name = "go_default_test", + srcs = ["util_test.go"], + library = "go_default_library", + tags = ["automanaged"], + deps = [ + "//pkg/api/v1:go_default_library", + "//pkg/types:go_default_library", + "//vendor:github.com/davecgh/go-spew/spew", + ], +) diff --git a/pkg/api/v1/endpoints/util.go b/pkg/api/v1/endpoints/util.go new file mode 100644 index 00000000000..c81999f370f --- /dev/null +++ b/pkg/api/v1/endpoints/util.go @@ -0,0 +1,238 @@ +/* +Copyright 2015 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package endpoints + +import ( + "bytes" + "crypto/md5" + "encoding/hex" + "hash" + "sort" + + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/types" + hashutil "k8s.io/kubernetes/pkg/util/hash" +) + +const ( + // TODO: to be deleted after v1.3 is released + // 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" +) + +// TODO: to be deleted after v1.3 is released +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 +// form for things like comparison. The result is a newly allocated slice. +func RepackSubsets(subsets []v1.EndpointSubset) []v1.EndpointSubset { + // First map each unique port definition to the sets of hosts that + // offer it. + allAddrs := map[addressKey]*v1.EndpointAddress{} + portToAddrReadyMap := map[v1.EndpointPort]addressSet{} + for i := range subsets { + for _, port := range subsets[i].Ports { + for k := range subsets[i].Addresses { + mapAddressByPort(&subsets[i].Addresses[k], port, true, allAddrs, portToAddrReadyMap) + } + for k := range subsets[i].NotReadyAddresses { + mapAddressByPort(&subsets[i].NotReadyAddresses[k], port, false, allAddrs, portToAddrReadyMap) + } + } + } + + // Next, map the sets of hosts to the sets of ports they offer. + // Go does not allow maps or slices as keys to maps, so we have + // to synthesize an artificial key and do a sort of 2-part + // associative entity. + type keyString string + keyToAddrReadyMap := map[keyString]addressSet{} + addrReadyMapKeyToPorts := map[keyString][]v1.EndpointPort{} + for port, addrs := range portToAddrReadyMap { + key := keyString(hashAddresses(addrs)) + keyToAddrReadyMap[key] = addrs + addrReadyMapKeyToPorts[key] = append(addrReadyMapKeyToPorts[key], port) + } + + // Next, build the N-to-M association the API wants. + final := []v1.EndpointSubset{} + for key, ports := range addrReadyMapKeyToPorts { + var readyAddrs, notReadyAddrs []v1.EndpointAddress + for addr, ready := range keyToAddrReadyMap[key] { + if ready { + readyAddrs = append(readyAddrs, *addr) + } else { + notReadyAddrs = append(notReadyAddrs, *addr) + } + } + final = append(final, v1.EndpointSubset{Addresses: readyAddrs, NotReadyAddresses: notReadyAddrs, Ports: ports}) + } + + // Finally, sort it. + return SortSubsets(final) +} + +// The sets of hosts must be de-duped, using IP+UID as the key. +type addressKey struct { + ip string + uid types.UID +} + +// mapAddressByPort adds an address into a map by its ports, registering the address with a unique pointer, and preserving +// any existing ready state. +func mapAddressByPort(addr *v1.EndpointAddress, port v1.EndpointPort, ready bool, allAddrs map[addressKey]*v1.EndpointAddress, portToAddrReadyMap map[v1.EndpointPort]addressSet) *v1.EndpointAddress { + // use addressKey to distinguish between two endpoints that are identical addresses + // but may have come from different hosts, for attribution. For instance, Mesos + // assigns pods the node IP, but the pods are distinct. + key := addressKey{ip: addr.IP} + if addr.TargetRef != nil { + key.uid = addr.TargetRef.UID + } + + // Accumulate the address. The full EndpointAddress structure is preserved for use when + // we rebuild the subsets so that the final TargetRef has all of the necessary data. + existingAddress := allAddrs[key] + if existingAddress == nil { + // Make a copy so we don't write to the + // input args of this function. + existingAddress = &v1.EndpointAddress{} + *existingAddress = *addr + allAddrs[key] = existingAddress + } + + // Remember that this port maps to this address. + if _, found := portToAddrReadyMap[port]; !found { + portToAddrReadyMap[port] = addressSet{} + } + // if we have not yet recorded this port for this address, or if the previous + // state was ready, write the current ready state. not ready always trumps + // ready. + if wasReady, found := portToAddrReadyMap[port][existingAddress]; !found || wasReady { + portToAddrReadyMap[port][existingAddress] = ready + } + return existingAddress +} + +type addressSet map[*v1.EndpointAddress]bool + +type addrReady struct { + addr *v1.EndpointAddress + ready bool +} + +func hashAddresses(addrs addressSet) string { + // Flatten the list of addresses into a string so it can be used as a + // map key. Unfortunately, DeepHashObject is implemented in terms of + // spew, and spew does not handle non-primitive map keys well. So + // first we collapse it into a slice, sort the slice, then hash that. + slice := make([]addrReady, 0, len(addrs)) + for k, ready := range addrs { + slice = append(slice, addrReady{k, ready}) + } + sort.Sort(addrsReady(slice)) + hasher := md5.New() + hashutil.DeepHashObject(hasher, slice) + return hex.EncodeToString(hasher.Sum(nil)[0:]) +} + +func lessAddrReady(a, b addrReady) bool { + // ready is not significant to hashing since we can't have duplicate addresses + return LessEndpointAddress(a.addr, b.addr) +} + +type addrsReady []addrReady + +func (sl addrsReady) Len() int { return len(sl) } +func (sl addrsReady) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] } +func (sl addrsReady) Less(i, j int) bool { + return lessAddrReady(sl[i], sl[j]) +} + +func LessEndpointAddress(a, b *v1.EndpointAddress) bool { + ipComparison := bytes.Compare([]byte(a.IP), []byte(b.IP)) + if ipComparison != 0 { + return ipComparison < 0 + } + if b.TargetRef == nil { + return false + } + if a.TargetRef == nil { + return true + } + return a.TargetRef.UID < b.TargetRef.UID +} + +type addrPtrsByIpAndUID []*v1.EndpointAddress + +func (sl addrPtrsByIpAndUID) Len() int { return len(sl) } +func (sl addrPtrsByIpAndUID) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] } +func (sl addrPtrsByIpAndUID) Less(i, j int) bool { + return LessEndpointAddress(sl[i], sl[j]) +} + +// SortSubsets sorts an array of EndpointSubset objects in place. For ease of +// use it returns the input slice. +func SortSubsets(subsets []v1.EndpointSubset) []v1.EndpointSubset { + for i := range subsets { + ss := &subsets[i] + sort.Sort(addrsByIpAndUID(ss.Addresses)) + sort.Sort(addrsByIpAndUID(ss.NotReadyAddresses)) + sort.Sort(portsByHash(ss.Ports)) + } + sort.Sort(subsetsByHash(subsets)) + return subsets +} + +func hashObject(hasher hash.Hash, obj interface{}) []byte { + hashutil.DeepHashObject(hasher, obj) + return hasher.Sum(nil) +} + +type subsetsByHash []v1.EndpointSubset + +func (sl subsetsByHash) Len() int { return len(sl) } +func (sl subsetsByHash) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] } +func (sl subsetsByHash) Less(i, j int) bool { + hasher := md5.New() + h1 := hashObject(hasher, sl[i]) + h2 := hashObject(hasher, sl[j]) + return bytes.Compare(h1, h2) < 0 +} + +type addrsByIpAndUID []v1.EndpointAddress + +func (sl addrsByIpAndUID) Len() int { return len(sl) } +func (sl addrsByIpAndUID) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] } +func (sl addrsByIpAndUID) Less(i, j int) bool { + return LessEndpointAddress(&sl[i], &sl[j]) +} + +type portsByHash []v1.EndpointPort + +func (sl portsByHash) Len() int { return len(sl) } +func (sl portsByHash) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] } +func (sl portsByHash) Less(i, j int) bool { + hasher := md5.New() + h1 := hashObject(hasher, sl[i]) + h2 := hashObject(hasher, sl[j]) + return bytes.Compare(h1, h2) < 0 +} diff --git a/pkg/api/v1/endpoints/util_test.go b/pkg/api/v1/endpoints/util_test.go new file mode 100644 index 00000000000..e73a948650c --- /dev/null +++ b/pkg/api/v1/endpoints/util_test.go @@ -0,0 +1,464 @@ +/* +Copyright 2015 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package endpoints + +import ( + "reflect" + "testing" + + "github.com/davecgh/go-spew/spew" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/types" +) + +func podRef(uid string) *v1.ObjectReference { + ref := v1.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 := v1.ObjectReference{Name: "foo"} + barObjRef := v1.ObjectReference{Name: "bar"} + + testCases := []struct { + name string + given []v1.EndpointSubset + expect []v1.EndpointSubset + }{ + { + name: "empty everything", + given: []v1.EndpointSubset{{Addresses: []v1.EndpointAddress{}, Ports: []v1.EndpointPort{}}}, + expect: []v1.EndpointSubset{}, + }, { + name: "empty addresses", + given: []v1.EndpointSubset{{Addresses: []v1.EndpointAddress{}, Ports: []v1.EndpointPort{{Port: 111}}}}, + expect: []v1.EndpointSubset{}, + }, { + name: "empty ports", + given: []v1.EndpointSubset{{Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, Ports: []v1.EndpointPort{}}}, + expect: []v1.EndpointSubset{}, + }, { + name: "empty ports", + given: []v1.EndpointSubset{{NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, Ports: []v1.EndpointPort{}}}, + expect: []v1.EndpointSubset{}, + }, { + name: "one set, one ip, one port", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, one ip, one port (IPv6)", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "beef::1:2:3:4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "beef::1:2:3:4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, one notReady ip, one port", + given: []v1.EndpointSubset{{ + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, one ip, one UID, one port", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, one notReady ip, one UID, one port", + given: []v1.EndpointSubset{{ + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, one ip, empty UID, one port", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, one notReady ip, empty UID, one port", + given: []v1.EndpointSubset{{ + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, two ips, one port", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}, {IP: "5.6.7.8"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}, {IP: "5.6.7.8"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, two mixed ips, one port", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + NotReadyAddresses: []v1.EndpointAddress{{IP: "5.6.7.8"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + NotReadyAddresses: []v1.EndpointAddress{{IP: "5.6.7.8"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, two duplicate ips, one port, notReady is covered by ready", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, one ip, two ports", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}, {Port: 222}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}, {Port: 222}}, + }}, + }, { + name: "one set, dup ips, one port", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}, {IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, dup ips, one port (IPv6)", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "beef::1"}, {IP: "beef::1"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "beef::1"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, dup ips with target-refs, one port", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{ + {IP: "1.2.3.4", TargetRef: &fooObjRef}, + {IP: "1.2.3.4", TargetRef: &barObjRef}, + }, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: &fooObjRef}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, dup mixed ips with target-refs, one port", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{ + {IP: "1.2.3.4", TargetRef: &fooObjRef}, + }, + NotReadyAddresses: []v1.EndpointAddress{ + {IP: "1.2.3.4", TargetRef: &barObjRef}, + }, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + // finding the same address twice is considered an error on input, only the first address+port + // reference is preserved + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: &fooObjRef}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "one set, one ip, dup ports", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}, {Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "two sets, dup ip, dup port", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "two sets, dup mixed ip, dup port", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "two sets, dup ip, two ports", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 222}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}, {Port: 222}}, + }}, + }, { + name: "two sets, dup ip, dup uids, two ports", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 222}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}, {Port: 222}}, + }}, + }, { + name: "two sets, dup mixed ip, dup uids, two ports", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 222}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 222}}, + }}, + }, { + name: "two sets, two ips, dup port", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "5.6.7.8"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}, {IP: "5.6.7.8"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "two set, dup ip, two uids, dup ports", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-2")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{ + {IP: "1.2.3.4", TargetRef: podRef("uid-1")}, + {IP: "1.2.3.4", TargetRef: podRef("uid-2")}, + }, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "two set, dup ip, with and without uid, dup ports", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-2")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{ + {IP: "1.2.3.4"}, + {IP: "1.2.3.4", TargetRef: podRef("uid-2")}, + }, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "two sets, two ips, two dup ip with uid, dup port, wrong order", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "5.6.7.8"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "5.6.7.8", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.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: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "two sets, two mixed ips, two dup ip with uid, dup port, wrong order, ends up with split addresses", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "5.6.7.8"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + NotReadyAddresses: []v1.EndpointAddress{{IP: "5.6.7.8", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{ + {IP: "5.6.7.8"}, + }, + NotReadyAddresses: []v1.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: []v1.EndpointPort{{Port: 111}}, + }}, + }, { + name: "two sets, two ips, two ports", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "5.6.7.8"}}, + Ports: []v1.EndpointPort{{Port: 222}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "5.6.7.8"}}, + Ports: []v1.EndpointPort{{Port: 222}}, + }}, + }, { + name: "four sets, three ips, three ports, jumbled", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.5"}}, + Ports: []v1.EndpointPort{{Port: 222}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.6"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.5"}}, + Ports: []v1.EndpointPort{{Port: 333}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}, {IP: "1.2.3.6"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.5"}}, + Ports: []v1.EndpointPort{{Port: 222}, {Port: 333}}, + }}, + }, { + name: "four sets, three mixed ips, three ports, jumbled", + given: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.5"}}, + Ports: []v1.EndpointPort{{Port: 222}}, + }, { + Addresses: []v1.EndpointAddress{{IP: "1.2.3.6"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.5"}}, + Ports: []v1.EndpointPort{{Port: 333}}, + }}, + expect: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}, {IP: "1.2.3.6"}}, + Ports: []v1.EndpointPort{{Port: 111}}, + }, { + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.5"}}, + Ports: []v1.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/pkg/api/v1/generate.go b/pkg/api/v1/generate.go new file mode 100644 index 00000000000..b6d1b347eba --- /dev/null +++ b/pkg/api/v1/generate.go @@ -0,0 +1,64 @@ +/* +Copyright 2014 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "fmt" + + utilrand "k8s.io/kubernetes/pkg/util/rand" +) + +// NameGenerator generates names for objects. Some backends may have more information +// available to guide selection of new names and this interface hides those details. +type NameGenerator interface { + // GenerateName generates a valid name from the base name, adding a random suffix to the + // the base. If base is valid, the returned name must also be valid. The generator is + // responsible for knowing the maximum valid name length. + GenerateName(base string) string +} + +// GenerateName will resolve the object name of the provided ObjectMeta to a generated version if +// necessary. It expects that validation for ObjectMeta has already completed (that Base is a +// valid name) and that the NameGenerator generates a name that is also valid. +func GenerateName(u NameGenerator, meta *ObjectMeta) { + if len(meta.GenerateName) == 0 || len(meta.Name) != 0 { + return + } + meta.Name = u.GenerateName(meta.GenerateName) +} + +// simpleNameGenerator generates random names. +type simpleNameGenerator struct{} + +// SimpleNameGenerator is a generator that returns the name plus a random suffix of five alphanumerics +// when a name is requested. The string is guaranteed to not exceed the length of a standard Kubernetes +// name (63 characters) +var SimpleNameGenerator NameGenerator = simpleNameGenerator{} + +const ( + // TODO: make this flexible for non-core resources with alternate naming rules. + maxNameLength = 63 + randomLength = 5 + maxGeneratedNameLength = maxNameLength - randomLength +) + +func (simpleNameGenerator) GenerateName(base string) string { + if len(base) > maxGeneratedNameLength { + base = base[:maxGeneratedNameLength] + } + return fmt.Sprintf("%s%s", base, utilrand.String(randomLength)) +} diff --git a/pkg/api/v1/generated.pb.go b/pkg/api/v1/generated.pb.go index 109c0c1bd8d..401f2aa85a8 100644 --- a/pkg/api/v1/generated.pb.go +++ b/pkg/api/v1/generated.pb.go @@ -101,6 +101,7 @@ limitations under the License. NodeDaemonEndpoints NodeList NodeProxyOptions + NodeResources NodeSelector NodeSelectorRequirement NodeSelectorTerm @@ -173,6 +174,7 @@ limitations under the License. ServiceProxyOptions ServiceSpec ServiceStatus + Sysctl TCPSocketAction Taint Toleration @@ -521,350 +523,358 @@ func (m *NodeProxyOptions) Reset() { *m = NodeProxyOptions{} func (*NodeProxyOptions) ProtoMessage() {} func (*NodeProxyOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{75} } +func (m *NodeResources) Reset() { *m = NodeResources{} } +func (*NodeResources) ProtoMessage() {} +func (*NodeResources) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{76} } + func (m *NodeSelector) Reset() { *m = NodeSelector{} } func (*NodeSelector) ProtoMessage() {} -func (*NodeSelector) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{76} } +func (*NodeSelector) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{77} } func (m *NodeSelectorRequirement) Reset() { *m = NodeSelectorRequirement{} } func (*NodeSelectorRequirement) ProtoMessage() {} func (*NodeSelectorRequirement) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{77} + return fileDescriptorGenerated, []int{78} } func (m *NodeSelectorTerm) Reset() { *m = NodeSelectorTerm{} } func (*NodeSelectorTerm) ProtoMessage() {} -func (*NodeSelectorTerm) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{78} } +func (*NodeSelectorTerm) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{79} } func (m *NodeSpec) Reset() { *m = NodeSpec{} } func (*NodeSpec) ProtoMessage() {} -func (*NodeSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{79} } +func (*NodeSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{80} } func (m *NodeStatus) Reset() { *m = NodeStatus{} } func (*NodeStatus) ProtoMessage() {} -func (*NodeStatus) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{80} } +func (*NodeStatus) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{81} } func (m *NodeSystemInfo) Reset() { *m = NodeSystemInfo{} } func (*NodeSystemInfo) ProtoMessage() {} -func (*NodeSystemInfo) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{81} } +func (*NodeSystemInfo) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{82} } func (m *ObjectFieldSelector) Reset() { *m = ObjectFieldSelector{} } func (*ObjectFieldSelector) ProtoMessage() {} -func (*ObjectFieldSelector) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{82} } +func (*ObjectFieldSelector) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{83} } func (m *ObjectMeta) Reset() { *m = ObjectMeta{} } func (*ObjectMeta) ProtoMessage() {} -func (*ObjectMeta) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{83} } +func (*ObjectMeta) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{84} } func (m *ObjectReference) Reset() { *m = ObjectReference{} } func (*ObjectReference) ProtoMessage() {} -func (*ObjectReference) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{84} } +func (*ObjectReference) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{85} } func (m *OwnerReference) Reset() { *m = OwnerReference{} } func (*OwnerReference) ProtoMessage() {} -func (*OwnerReference) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{85} } +func (*OwnerReference) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{86} } func (m *PersistentVolume) Reset() { *m = PersistentVolume{} } func (*PersistentVolume) ProtoMessage() {} -func (*PersistentVolume) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{86} } +func (*PersistentVolume) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{87} } func (m *PersistentVolumeClaim) Reset() { *m = PersistentVolumeClaim{} } func (*PersistentVolumeClaim) ProtoMessage() {} -func (*PersistentVolumeClaim) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{87} } +func (*PersistentVolumeClaim) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{88} } func (m *PersistentVolumeClaimList) Reset() { *m = PersistentVolumeClaimList{} } func (*PersistentVolumeClaimList) ProtoMessage() {} func (*PersistentVolumeClaimList) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{88} + return fileDescriptorGenerated, []int{89} } func (m *PersistentVolumeClaimSpec) Reset() { *m = PersistentVolumeClaimSpec{} } func (*PersistentVolumeClaimSpec) ProtoMessage() {} func (*PersistentVolumeClaimSpec) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{89} + return fileDescriptorGenerated, []int{90} } func (m *PersistentVolumeClaimStatus) Reset() { *m = PersistentVolumeClaimStatus{} } func (*PersistentVolumeClaimStatus) ProtoMessage() {} func (*PersistentVolumeClaimStatus) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{90} + return fileDescriptorGenerated, []int{91} } func (m *PersistentVolumeClaimVolumeSource) Reset() { *m = PersistentVolumeClaimVolumeSource{} } func (*PersistentVolumeClaimVolumeSource) ProtoMessage() {} func (*PersistentVolumeClaimVolumeSource) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{91} + return fileDescriptorGenerated, []int{92} } func (m *PersistentVolumeList) Reset() { *m = PersistentVolumeList{} } func (*PersistentVolumeList) ProtoMessage() {} -func (*PersistentVolumeList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{92} } +func (*PersistentVolumeList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{93} } func (m *PersistentVolumeSource) Reset() { *m = PersistentVolumeSource{} } func (*PersistentVolumeSource) ProtoMessage() {} -func (*PersistentVolumeSource) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{93} } +func (*PersistentVolumeSource) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{94} } func (m *PersistentVolumeSpec) Reset() { *m = PersistentVolumeSpec{} } func (*PersistentVolumeSpec) ProtoMessage() {} -func (*PersistentVolumeSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{94} } +func (*PersistentVolumeSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{95} } func (m *PersistentVolumeStatus) Reset() { *m = PersistentVolumeStatus{} } func (*PersistentVolumeStatus) ProtoMessage() {} -func (*PersistentVolumeStatus) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{95} } +func (*PersistentVolumeStatus) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{96} } func (m *PhotonPersistentDiskVolumeSource) Reset() { *m = PhotonPersistentDiskVolumeSource{} } func (*PhotonPersistentDiskVolumeSource) ProtoMessage() {} func (*PhotonPersistentDiskVolumeSource) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{96} + return fileDescriptorGenerated, []int{97} } func (m *Pod) Reset() { *m = Pod{} } func (*Pod) ProtoMessage() {} -func (*Pod) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{97} } +func (*Pod) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{98} } func (m *PodAffinity) Reset() { *m = PodAffinity{} } func (*PodAffinity) ProtoMessage() {} -func (*PodAffinity) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{98} } +func (*PodAffinity) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{99} } func (m *PodAffinityTerm) Reset() { *m = PodAffinityTerm{} } func (*PodAffinityTerm) ProtoMessage() {} -func (*PodAffinityTerm) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{99} } +func (*PodAffinityTerm) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{100} } func (m *PodAntiAffinity) Reset() { *m = PodAntiAffinity{} } func (*PodAntiAffinity) ProtoMessage() {} -func (*PodAntiAffinity) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{100} } +func (*PodAntiAffinity) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{101} } func (m *PodAttachOptions) Reset() { *m = PodAttachOptions{} } func (*PodAttachOptions) ProtoMessage() {} -func (*PodAttachOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{101} } +func (*PodAttachOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{102} } func (m *PodCondition) Reset() { *m = PodCondition{} } func (*PodCondition) ProtoMessage() {} -func (*PodCondition) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{102} } +func (*PodCondition) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{103} } func (m *PodExecOptions) Reset() { *m = PodExecOptions{} } func (*PodExecOptions) ProtoMessage() {} -func (*PodExecOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{103} } +func (*PodExecOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{104} } func (m *PodList) Reset() { *m = PodList{} } func (*PodList) ProtoMessage() {} -func (*PodList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{104} } +func (*PodList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{105} } func (m *PodLogOptions) Reset() { *m = PodLogOptions{} } func (*PodLogOptions) ProtoMessage() {} -func (*PodLogOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{105} } +func (*PodLogOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{106} } func (m *PodProxyOptions) Reset() { *m = PodProxyOptions{} } func (*PodProxyOptions) ProtoMessage() {} -func (*PodProxyOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{106} } +func (*PodProxyOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{107} } func (m *PodSecurityContext) Reset() { *m = PodSecurityContext{} } func (*PodSecurityContext) ProtoMessage() {} -func (*PodSecurityContext) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{107} } +func (*PodSecurityContext) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{108} } func (m *PodSignature) Reset() { *m = PodSignature{} } func (*PodSignature) ProtoMessage() {} -func (*PodSignature) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{108} } +func (*PodSignature) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{109} } func (m *PodSpec) Reset() { *m = PodSpec{} } func (*PodSpec) ProtoMessage() {} -func (*PodSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{109} } +func (*PodSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{110} } func (m *PodStatus) Reset() { *m = PodStatus{} } func (*PodStatus) ProtoMessage() {} -func (*PodStatus) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{110} } +func (*PodStatus) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{111} } func (m *PodStatusResult) Reset() { *m = PodStatusResult{} } func (*PodStatusResult) ProtoMessage() {} -func (*PodStatusResult) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{111} } +func (*PodStatusResult) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{112} } func (m *PodTemplate) Reset() { *m = PodTemplate{} } func (*PodTemplate) ProtoMessage() {} -func (*PodTemplate) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{112} } +func (*PodTemplate) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{113} } func (m *PodTemplateList) Reset() { *m = PodTemplateList{} } func (*PodTemplateList) ProtoMessage() {} -func (*PodTemplateList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{113} } +func (*PodTemplateList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{114} } func (m *PodTemplateSpec) Reset() { *m = PodTemplateSpec{} } func (*PodTemplateSpec) ProtoMessage() {} -func (*PodTemplateSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{114} } +func (*PodTemplateSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{115} } func (m *Preconditions) Reset() { *m = Preconditions{} } func (*Preconditions) ProtoMessage() {} -func (*Preconditions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{115} } +func (*Preconditions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{116} } func (m *PreferAvoidPodsEntry) Reset() { *m = PreferAvoidPodsEntry{} } func (*PreferAvoidPodsEntry) ProtoMessage() {} -func (*PreferAvoidPodsEntry) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{116} } +func (*PreferAvoidPodsEntry) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{117} } func (m *PreferredSchedulingTerm) Reset() { *m = PreferredSchedulingTerm{} } func (*PreferredSchedulingTerm) ProtoMessage() {} func (*PreferredSchedulingTerm) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{117} + return fileDescriptorGenerated, []int{118} } func (m *Probe) Reset() { *m = Probe{} } func (*Probe) ProtoMessage() {} -func (*Probe) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{118} } +func (*Probe) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{119} } func (m *QuobyteVolumeSource) Reset() { *m = QuobyteVolumeSource{} } func (*QuobyteVolumeSource) ProtoMessage() {} -func (*QuobyteVolumeSource) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{119} } +func (*QuobyteVolumeSource) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{120} } func (m *RBDVolumeSource) Reset() { *m = RBDVolumeSource{} } func (*RBDVolumeSource) ProtoMessage() {} -func (*RBDVolumeSource) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{120} } +func (*RBDVolumeSource) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{121} } func (m *RangeAllocation) Reset() { *m = RangeAllocation{} } func (*RangeAllocation) ProtoMessage() {} -func (*RangeAllocation) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{121} } +func (*RangeAllocation) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{122} } func (m *ReplicationController) Reset() { *m = ReplicationController{} } func (*ReplicationController) ProtoMessage() {} -func (*ReplicationController) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{122} } +func (*ReplicationController) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{123} } func (m *ReplicationControllerCondition) Reset() { *m = ReplicationControllerCondition{} } func (*ReplicationControllerCondition) ProtoMessage() {} func (*ReplicationControllerCondition) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{123} + return fileDescriptorGenerated, []int{124} } func (m *ReplicationControllerList) Reset() { *m = ReplicationControllerList{} } func (*ReplicationControllerList) ProtoMessage() {} func (*ReplicationControllerList) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{124} + return fileDescriptorGenerated, []int{125} } func (m *ReplicationControllerSpec) Reset() { *m = ReplicationControllerSpec{} } func (*ReplicationControllerSpec) ProtoMessage() {} func (*ReplicationControllerSpec) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{125} + return fileDescriptorGenerated, []int{126} } func (m *ReplicationControllerStatus) Reset() { *m = ReplicationControllerStatus{} } func (*ReplicationControllerStatus) ProtoMessage() {} func (*ReplicationControllerStatus) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{126} + return fileDescriptorGenerated, []int{127} } func (m *ResourceFieldSelector) Reset() { *m = ResourceFieldSelector{} } func (*ResourceFieldSelector) ProtoMessage() {} -func (*ResourceFieldSelector) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{127} } +func (*ResourceFieldSelector) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{128} } func (m *ResourceQuota) Reset() { *m = ResourceQuota{} } func (*ResourceQuota) ProtoMessage() {} -func (*ResourceQuota) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{128} } +func (*ResourceQuota) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{129} } func (m *ResourceQuotaList) Reset() { *m = ResourceQuotaList{} } func (*ResourceQuotaList) ProtoMessage() {} -func (*ResourceQuotaList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{129} } +func (*ResourceQuotaList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{130} } func (m *ResourceQuotaSpec) Reset() { *m = ResourceQuotaSpec{} } func (*ResourceQuotaSpec) ProtoMessage() {} -func (*ResourceQuotaSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{130} } +func (*ResourceQuotaSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{131} } func (m *ResourceQuotaStatus) Reset() { *m = ResourceQuotaStatus{} } func (*ResourceQuotaStatus) ProtoMessage() {} -func (*ResourceQuotaStatus) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{131} } +func (*ResourceQuotaStatus) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{132} } func (m *ResourceRequirements) Reset() { *m = ResourceRequirements{} } func (*ResourceRequirements) ProtoMessage() {} -func (*ResourceRequirements) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{132} } +func (*ResourceRequirements) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{133} } func (m *SELinuxOptions) Reset() { *m = SELinuxOptions{} } func (*SELinuxOptions) ProtoMessage() {} -func (*SELinuxOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{133} } +func (*SELinuxOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{134} } func (m *Secret) Reset() { *m = Secret{} } func (*Secret) ProtoMessage() {} -func (*Secret) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{134} } +func (*Secret) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{135} } func (m *SecretKeySelector) Reset() { *m = SecretKeySelector{} } func (*SecretKeySelector) ProtoMessage() {} -func (*SecretKeySelector) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{135} } +func (*SecretKeySelector) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{136} } func (m *SecretList) Reset() { *m = SecretList{} } func (*SecretList) ProtoMessage() {} -func (*SecretList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{136} } +func (*SecretList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{137} } func (m *SecretVolumeSource) Reset() { *m = SecretVolumeSource{} } func (*SecretVolumeSource) ProtoMessage() {} -func (*SecretVolumeSource) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{137} } +func (*SecretVolumeSource) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{138} } func (m *SecurityContext) Reset() { *m = SecurityContext{} } func (*SecurityContext) ProtoMessage() {} -func (*SecurityContext) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{138} } +func (*SecurityContext) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{139} } func (m *SerializedReference) Reset() { *m = SerializedReference{} } func (*SerializedReference) ProtoMessage() {} -func (*SerializedReference) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{139} } +func (*SerializedReference) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{140} } func (m *Service) Reset() { *m = Service{} } func (*Service) ProtoMessage() {} -func (*Service) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{140} } +func (*Service) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{141} } func (m *ServiceAccount) Reset() { *m = ServiceAccount{} } func (*ServiceAccount) ProtoMessage() {} -func (*ServiceAccount) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{141} } +func (*ServiceAccount) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{142} } func (m *ServiceAccountList) Reset() { *m = ServiceAccountList{} } func (*ServiceAccountList) ProtoMessage() {} -func (*ServiceAccountList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{142} } +func (*ServiceAccountList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{143} } func (m *ServiceList) Reset() { *m = ServiceList{} } func (*ServiceList) ProtoMessage() {} -func (*ServiceList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{143} } +func (*ServiceList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{144} } func (m *ServicePort) Reset() { *m = ServicePort{} } func (*ServicePort) ProtoMessage() {} -func (*ServicePort) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{144} } +func (*ServicePort) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{145} } func (m *ServiceProxyOptions) Reset() { *m = ServiceProxyOptions{} } func (*ServiceProxyOptions) ProtoMessage() {} -func (*ServiceProxyOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{145} } +func (*ServiceProxyOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{146} } func (m *ServiceSpec) Reset() { *m = ServiceSpec{} } func (*ServiceSpec) ProtoMessage() {} -func (*ServiceSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{146} } +func (*ServiceSpec) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{147} } func (m *ServiceStatus) Reset() { *m = ServiceStatus{} } func (*ServiceStatus) ProtoMessage() {} -func (*ServiceStatus) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{147} } +func (*ServiceStatus) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{148} } + +func (m *Sysctl) Reset() { *m = Sysctl{} } +func (*Sysctl) ProtoMessage() {} +func (*Sysctl) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{149} } func (m *TCPSocketAction) Reset() { *m = TCPSocketAction{} } func (*TCPSocketAction) ProtoMessage() {} -func (*TCPSocketAction) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{148} } +func (*TCPSocketAction) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{150} } func (m *Taint) Reset() { *m = Taint{} } func (*Taint) ProtoMessage() {} -func (*Taint) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{149} } +func (*Taint) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{151} } func (m *Toleration) Reset() { *m = Toleration{} } func (*Toleration) ProtoMessage() {} -func (*Toleration) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{150} } +func (*Toleration) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{152} } func (m *Volume) Reset() { *m = Volume{} } func (*Volume) ProtoMessage() {} -func (*Volume) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{151} } +func (*Volume) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{153} } func (m *VolumeMount) Reset() { *m = VolumeMount{} } func (*VolumeMount) ProtoMessage() {} -func (*VolumeMount) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{152} } +func (*VolumeMount) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{154} } func (m *VolumeSource) Reset() { *m = VolumeSource{} } func (*VolumeSource) ProtoMessage() {} -func (*VolumeSource) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{153} } +func (*VolumeSource) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{155} } func (m *VsphereVirtualDiskVolumeSource) Reset() { *m = VsphereVirtualDiskVolumeSource{} } func (*VsphereVirtualDiskVolumeSource) ProtoMessage() {} func (*VsphereVirtualDiskVolumeSource) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{154} + return fileDescriptorGenerated, []int{156} } func (m *WeightedPodAffinityTerm) Reset() { *m = WeightedPodAffinityTerm{} } func (*WeightedPodAffinityTerm) ProtoMessage() {} func (*WeightedPodAffinityTerm) Descriptor() ([]byte, []int) { - return fileDescriptorGenerated, []int{155} + return fileDescriptorGenerated, []int{157} } func init() { @@ -944,6 +954,7 @@ func init() { proto.RegisterType((*NodeDaemonEndpoints)(nil), "k8s.io.kubernetes.pkg.api.v1.NodeDaemonEndpoints") proto.RegisterType((*NodeList)(nil), "k8s.io.kubernetes.pkg.api.v1.NodeList") proto.RegisterType((*NodeProxyOptions)(nil), "k8s.io.kubernetes.pkg.api.v1.NodeProxyOptions") + proto.RegisterType((*NodeResources)(nil), "k8s.io.kubernetes.pkg.api.v1.NodeResources") proto.RegisterType((*NodeSelector)(nil), "k8s.io.kubernetes.pkg.api.v1.NodeSelector") proto.RegisterType((*NodeSelectorRequirement)(nil), "k8s.io.kubernetes.pkg.api.v1.NodeSelectorRequirement") proto.RegisterType((*NodeSelectorTerm)(nil), "k8s.io.kubernetes.pkg.api.v1.NodeSelectorTerm") @@ -1016,6 +1027,7 @@ func init() { proto.RegisterType((*ServiceProxyOptions)(nil), "k8s.io.kubernetes.pkg.api.v1.ServiceProxyOptions") proto.RegisterType((*ServiceSpec)(nil), "k8s.io.kubernetes.pkg.api.v1.ServiceSpec") proto.RegisterType((*ServiceStatus)(nil), "k8s.io.kubernetes.pkg.api.v1.ServiceStatus") + proto.RegisterType((*Sysctl)(nil), "k8s.io.kubernetes.pkg.api.v1.Sysctl") proto.RegisterType((*TCPSocketAction)(nil), "k8s.io.kubernetes.pkg.api.v1.TCPSocketAction") proto.RegisterType((*Taint)(nil), "k8s.io.kubernetes.pkg.api.v1.Taint") proto.RegisterType((*Toleration)(nil), "k8s.io.kubernetes.pkg.api.v1.Toleration") @@ -4129,6 +4141,46 @@ func (m *NodeProxyOptions) MarshalTo(data []byte) (int, error) { return i, nil } +func (m *NodeResources) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *NodeResources) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Capacity) > 0 { + for k := range m.Capacity { + data[i] = 0xa + i++ + v := m.Capacity[k] + msgSize := (&v).Size() + mapSize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + msgSize + sovGenerated(uint64(msgSize)) + i = encodeVarintGenerated(data, i, uint64(mapSize)) + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(len(k))) + i += copy(data[i:], k) + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64((&v).Size())) + n71, err := (&v).MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n71 + } + } + return i, nil +} + func (m *NodeSelector) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) @@ -4298,11 +4350,11 @@ func (m *NodeStatus) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n71, err := (&v).MarshalTo(data[i:]) + n72, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n71 + i += n72 } } if len(m.Allocatable) > 0 { @@ -4320,11 +4372,11 @@ func (m *NodeStatus) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n72, err := (&v).MarshalTo(data[i:]) + n73, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n72 + i += n73 } } data[i] = 0x1a @@ -4358,19 +4410,19 @@ func (m *NodeStatus) MarshalTo(data []byte) (int, error) { data[i] = 0x32 i++ i = encodeVarintGenerated(data, i, uint64(m.DaemonEndpoints.Size())) - n73, err := m.DaemonEndpoints.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n73 - data[i] = 0x3a - i++ - i = encodeVarintGenerated(data, i, uint64(m.NodeInfo.Size())) - n74, err := m.NodeInfo.MarshalTo(data[i:]) + n74, err := m.DaemonEndpoints.MarshalTo(data[i:]) if err != nil { return 0, err } i += n74 + data[i] = 0x3a + i++ + i = encodeVarintGenerated(data, i, uint64(m.NodeInfo.Size())) + n75, err := m.NodeInfo.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n75 if len(m.Images) > 0 { for _, msg := range m.Images { data[i] = 0x42 @@ -4542,20 +4594,20 @@ func (m *ObjectMeta) MarshalTo(data []byte) (int, error) { data[i] = 0x42 i++ i = encodeVarintGenerated(data, i, uint64(m.CreationTimestamp.Size())) - n75, err := m.CreationTimestamp.MarshalTo(data[i:]) + n76, err := m.CreationTimestamp.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n75 + i += n76 if m.DeletionTimestamp != nil { data[i] = 0x4a i++ i = encodeVarintGenerated(data, i, uint64(m.DeletionTimestamp.Size())) - n76, err := m.DeletionTimestamp.MarshalTo(data[i:]) + n77, err := m.DeletionTimestamp.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n76 + i += n77 } if m.DeletionGracePeriodSeconds != nil { data[i] = 0x50 @@ -4738,27 +4790,27 @@ func (m *PersistentVolume) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n77, err := m.ObjectMeta.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n77 - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) - n78, err := m.Spec.MarshalTo(data[i:]) + n78, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } i += n78 - data[i] = 0x1a + data[i] = 0x12 i++ - i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) - n79, err := m.Status.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) + n79, err := m.Spec.MarshalTo(data[i:]) if err != nil { return 0, err } i += n79 + data[i] = 0x1a + i++ + i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) + n80, err := m.Status.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n80 return i, nil } @@ -4780,27 +4832,27 @@ func (m *PersistentVolumeClaim) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n80, err := m.ObjectMeta.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n80 - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) - n81, err := m.Spec.MarshalTo(data[i:]) + n81, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } i += n81 - data[i] = 0x1a + data[i] = 0x12 i++ - i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) - n82, err := m.Status.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) + n82, err := m.Spec.MarshalTo(data[i:]) if err != nil { return 0, err } i += n82 + data[i] = 0x1a + i++ + i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) + n83, err := m.Status.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n83 return i, nil } @@ -4822,11 +4874,11 @@ func (m *PersistentVolumeClaimList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n83, err := m.ListMeta.MarshalTo(data[i:]) + n84, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n83 + i += n84 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -4875,11 +4927,11 @@ func (m *PersistentVolumeClaimSpec) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.Resources.Size())) - n84, err := m.Resources.MarshalTo(data[i:]) + n85, err := m.Resources.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n84 + i += n85 data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(len(m.VolumeName))) @@ -4888,11 +4940,11 @@ func (m *PersistentVolumeClaimSpec) MarshalTo(data []byte) (int, error) { data[i] = 0x22 i++ i = encodeVarintGenerated(data, i, uint64(m.Selector.Size())) - n85, err := m.Selector.MarshalTo(data[i:]) + n86, err := m.Selector.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n85 + i += n86 } return i, nil } @@ -4946,11 +4998,11 @@ func (m *PersistentVolumeClaimStatus) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n86, err := (&v).MarshalTo(data[i:]) + n87, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n86 + i += n87 } } return i, nil @@ -5004,11 +5056,11 @@ func (m *PersistentVolumeList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n87, err := m.ListMeta.MarshalTo(data[i:]) + n88, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n87 + i += n88 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -5043,163 +5095,163 @@ func (m *PersistentVolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.GCEPersistentDisk.Size())) - n88, err := m.GCEPersistentDisk.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n88 - } - if m.AWSElasticBlockStore != nil { - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.AWSElasticBlockStore.Size())) - n89, err := m.AWSElasticBlockStore.MarshalTo(data[i:]) + n89, err := m.GCEPersistentDisk.MarshalTo(data[i:]) if err != nil { return 0, err } i += n89 } - if m.HostPath != nil { - data[i] = 0x1a + if m.AWSElasticBlockStore != nil { + data[i] = 0x12 i++ - i = encodeVarintGenerated(data, i, uint64(m.HostPath.Size())) - n90, err := m.HostPath.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.AWSElasticBlockStore.Size())) + n90, err := m.AWSElasticBlockStore.MarshalTo(data[i:]) if err != nil { return 0, err } i += n90 } - if m.Glusterfs != nil { - data[i] = 0x22 + if m.HostPath != nil { + data[i] = 0x1a i++ - i = encodeVarintGenerated(data, i, uint64(m.Glusterfs.Size())) - n91, err := m.Glusterfs.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.HostPath.Size())) + n91, err := m.HostPath.MarshalTo(data[i:]) if err != nil { return 0, err } i += n91 } - if m.NFS != nil { - data[i] = 0x2a + if m.Glusterfs != nil { + data[i] = 0x22 i++ - i = encodeVarintGenerated(data, i, uint64(m.NFS.Size())) - n92, err := m.NFS.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Glusterfs.Size())) + n92, err := m.Glusterfs.MarshalTo(data[i:]) if err != nil { return 0, err } i += n92 } - if m.RBD != nil { - data[i] = 0x32 + if m.NFS != nil { + data[i] = 0x2a i++ - i = encodeVarintGenerated(data, i, uint64(m.RBD.Size())) - n93, err := m.RBD.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.NFS.Size())) + n93, err := m.NFS.MarshalTo(data[i:]) if err != nil { return 0, err } i += n93 } - if m.ISCSI != nil { - data[i] = 0x3a + if m.RBD != nil { + data[i] = 0x32 i++ - i = encodeVarintGenerated(data, i, uint64(m.ISCSI.Size())) - n94, err := m.ISCSI.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.RBD.Size())) + n94, err := m.RBD.MarshalTo(data[i:]) if err != nil { return 0, err } i += n94 } - if m.Cinder != nil { - data[i] = 0x42 + if m.ISCSI != nil { + data[i] = 0x3a i++ - i = encodeVarintGenerated(data, i, uint64(m.Cinder.Size())) - n95, err := m.Cinder.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.ISCSI.Size())) + n95, err := m.ISCSI.MarshalTo(data[i:]) if err != nil { return 0, err } i += n95 } - if m.CephFS != nil { - data[i] = 0x4a + if m.Cinder != nil { + data[i] = 0x42 i++ - i = encodeVarintGenerated(data, i, uint64(m.CephFS.Size())) - n96, err := m.CephFS.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Cinder.Size())) + n96, err := m.Cinder.MarshalTo(data[i:]) if err != nil { return 0, err } i += n96 } - if m.FC != nil { - data[i] = 0x52 + if m.CephFS != nil { + data[i] = 0x4a i++ - i = encodeVarintGenerated(data, i, uint64(m.FC.Size())) - n97, err := m.FC.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.CephFS.Size())) + n97, err := m.CephFS.MarshalTo(data[i:]) if err != nil { return 0, err } i += n97 } - if m.Flocker != nil { - data[i] = 0x5a + if m.FC != nil { + data[i] = 0x52 i++ - i = encodeVarintGenerated(data, i, uint64(m.Flocker.Size())) - n98, err := m.Flocker.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.FC.Size())) + n98, err := m.FC.MarshalTo(data[i:]) if err != nil { return 0, err } i += n98 } - if m.FlexVolume != nil { - data[i] = 0x62 + if m.Flocker != nil { + data[i] = 0x5a i++ - i = encodeVarintGenerated(data, i, uint64(m.FlexVolume.Size())) - n99, err := m.FlexVolume.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Flocker.Size())) + n99, err := m.Flocker.MarshalTo(data[i:]) if err != nil { return 0, err } i += n99 } - if m.AzureFile != nil { - data[i] = 0x6a + if m.FlexVolume != nil { + data[i] = 0x62 i++ - i = encodeVarintGenerated(data, i, uint64(m.AzureFile.Size())) - n100, err := m.AzureFile.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.FlexVolume.Size())) + n100, err := m.FlexVolume.MarshalTo(data[i:]) if err != nil { return 0, err } i += n100 } - if m.VsphereVolume != nil { - data[i] = 0x72 + if m.AzureFile != nil { + data[i] = 0x6a i++ - i = encodeVarintGenerated(data, i, uint64(m.VsphereVolume.Size())) - n101, err := m.VsphereVolume.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.AzureFile.Size())) + n101, err := m.AzureFile.MarshalTo(data[i:]) if err != nil { return 0, err } i += n101 } - if m.Quobyte != nil { - data[i] = 0x7a + if m.VsphereVolume != nil { + data[i] = 0x72 i++ - i = encodeVarintGenerated(data, i, uint64(m.Quobyte.Size())) - n102, err := m.Quobyte.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.VsphereVolume.Size())) + n102, err := m.VsphereVolume.MarshalTo(data[i:]) if err != nil { return 0, err } i += n102 } + if m.Quobyte != nil { + data[i] = 0x7a + i++ + i = encodeVarintGenerated(data, i, uint64(m.Quobyte.Size())) + n103, err := m.Quobyte.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n103 + } if m.AzureDisk != nil { data[i] = 0x82 i++ data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.AzureDisk.Size())) - n103, err := m.AzureDisk.MarshalTo(data[i:]) + n104, err := m.AzureDisk.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n103 + i += n104 } if m.PhotonPersistentDisk != nil { data[i] = 0x8a @@ -5207,11 +5259,11 @@ func (m *PersistentVolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.PhotonPersistentDisk.Size())) - n104, err := m.PhotonPersistentDisk.MarshalTo(data[i:]) + n105, err := m.PhotonPersistentDisk.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n104 + i += n105 } return i, nil } @@ -5246,21 +5298,21 @@ func (m *PersistentVolumeSpec) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n105, err := (&v).MarshalTo(data[i:]) + n106, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n105 + i += n106 } } data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.PersistentVolumeSource.Size())) - n106, err := m.PersistentVolumeSource.MarshalTo(data[i:]) + n107, err := m.PersistentVolumeSource.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n106 + i += n107 if len(m.AccessModes) > 0 { for _, s := range m.AccessModes { data[i] = 0x1a @@ -5280,11 +5332,11 @@ func (m *PersistentVolumeSpec) MarshalTo(data []byte) (int, error) { data[i] = 0x22 i++ i = encodeVarintGenerated(data, i, uint64(m.ClaimRef.Size())) - n107, err := m.ClaimRef.MarshalTo(data[i:]) + n108, err := m.ClaimRef.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n107 + i += n108 } data[i] = 0x2a i++ @@ -5367,27 +5419,27 @@ func (m *Pod) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n108, err := m.ObjectMeta.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n108 - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) - n109, err := m.Spec.MarshalTo(data[i:]) + n109, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } i += n109 - data[i] = 0x1a + data[i] = 0x12 i++ - i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) - n110, err := m.Status.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) + n110, err := m.Spec.MarshalTo(data[i:]) if err != nil { return 0, err } i += n110 + data[i] = 0x1a + i++ + i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) + n111, err := m.Status.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n111 return i, nil } @@ -5452,11 +5504,11 @@ func (m *PodAffinityTerm) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.LabelSelector.Size())) - n111, err := m.LabelSelector.MarshalTo(data[i:]) + n112, err := m.LabelSelector.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n111 + i += n112 } if len(m.Namespaces) > 0 { for _, s := range m.Namespaces { @@ -5602,19 +5654,19 @@ func (m *PodCondition) MarshalTo(data []byte) (int, error) { data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.LastProbeTime.Size())) - n112, err := m.LastProbeTime.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n112 - data[i] = 0x22 - i++ - i = encodeVarintGenerated(data, i, uint64(m.LastTransitionTime.Size())) - n113, err := m.LastTransitionTime.MarshalTo(data[i:]) + n113, err := m.LastProbeTime.MarshalTo(data[i:]) if err != nil { return 0, err } i += n113 + data[i] = 0x22 + i++ + i = encodeVarintGenerated(data, i, uint64(m.LastTransitionTime.Size())) + n114, err := m.LastTransitionTime.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n114 data[i] = 0x2a i++ i = encodeVarintGenerated(data, i, uint64(len(m.Reason))) @@ -5713,11 +5765,11 @@ func (m *PodList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n114, err := m.ListMeta.MarshalTo(data[i:]) + n115, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n114 + i += n115 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -5777,11 +5829,11 @@ func (m *PodLogOptions) MarshalTo(data []byte) (int, error) { data[i] = 0x2a i++ i = encodeVarintGenerated(data, i, uint64(m.SinceTime.Size())) - n115, err := m.SinceTime.MarshalTo(data[i:]) + n116, err := m.SinceTime.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n115 + i += n116 } data[i] = 0x30 i++ @@ -5845,11 +5897,11 @@ func (m *PodSecurityContext) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.SELinuxOptions.Size())) - n116, err := m.SELinuxOptions.MarshalTo(data[i:]) + n117, err := m.SELinuxOptions.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n116 + i += n117 } if m.RunAsUser != nil { data[i] = 0x10 @@ -5900,11 +5952,11 @@ func (m *PodSignature) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.PodController.Size())) - n117, err := m.PodController.MarshalTo(data[i:]) + n118, err := m.PodController.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n117 + i += n118 } return i, nil } @@ -6023,11 +6075,11 @@ func (m *PodSpec) MarshalTo(data []byte) (int, error) { data[i] = 0x72 i++ i = encodeVarintGenerated(data, i, uint64(m.SecurityContext.Size())) - n118, err := m.SecurityContext.MarshalTo(data[i:]) + n119, err := m.SecurityContext.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n118 + i += n119 } if len(m.ImagePullSecrets) > 0 { for _, msg := range m.ImagePullSecrets { @@ -6107,11 +6159,11 @@ func (m *PodStatus) MarshalTo(data []byte) (int, error) { data[i] = 0x3a i++ i = encodeVarintGenerated(data, i, uint64(m.StartTime.Size())) - n119, err := m.StartTime.MarshalTo(data[i:]) + n120, err := m.StartTime.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n119 + i += n120 } if len(m.ContainerStatuses) > 0 { for _, msg := range m.ContainerStatuses { @@ -6146,19 +6198,19 @@ func (m *PodStatusResult) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n120, err := m.ObjectMeta.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n120 - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) - n121, err := m.Status.MarshalTo(data[i:]) + n121, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } i += n121 + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) + n122, err := m.Status.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n122 return i, nil } @@ -6180,19 +6232,19 @@ func (m *PodTemplate) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n122, err := m.ObjectMeta.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n122 - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.Template.Size())) - n123, err := m.Template.MarshalTo(data[i:]) + n123, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } i += n123 + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(m.Template.Size())) + n124, err := m.Template.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n124 return i, nil } @@ -6214,11 +6266,11 @@ func (m *PodTemplateList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n124, err := m.ListMeta.MarshalTo(data[i:]) + n125, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n124 + i += n125 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -6252,19 +6304,19 @@ func (m *PodTemplateSpec) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n125, err := m.ObjectMeta.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n125 - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) - n126, err := m.Spec.MarshalTo(data[i:]) + n126, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } i += n126 + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) + n127, err := m.Spec.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n127 return i, nil } @@ -6310,19 +6362,19 @@ func (m *PreferAvoidPodsEntry) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.PodSignature.Size())) - n127, err := m.PodSignature.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n127 - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.EvictionTime.Size())) - n128, err := m.EvictionTime.MarshalTo(data[i:]) + n128, err := m.PodSignature.MarshalTo(data[i:]) if err != nil { return 0, err } i += n128 + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(m.EvictionTime.Size())) + n129, err := m.EvictionTime.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n129 data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(len(m.Reason))) @@ -6355,11 +6407,11 @@ func (m *PreferredSchedulingTerm) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.Preference.Size())) - n129, err := m.Preference.MarshalTo(data[i:]) + n130, err := m.Preference.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n129 + i += n130 return i, nil } @@ -6381,11 +6433,11 @@ func (m *Probe) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.Handler.Size())) - n130, err := m.Handler.MarshalTo(data[i:]) + n131, err := m.Handler.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n130 + i += n131 data[i] = 0x10 i++ i = encodeVarintGenerated(data, i, uint64(m.InitialDelaySeconds)) @@ -6500,11 +6552,11 @@ func (m *RBDVolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x3a i++ i = encodeVarintGenerated(data, i, uint64(m.SecretRef.Size())) - n131, err := m.SecretRef.MarshalTo(data[i:]) + n132, err := m.SecretRef.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n131 + i += n132 } data[i] = 0x40 i++ @@ -6535,11 +6587,11 @@ func (m *RangeAllocation) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n132, err := m.ObjectMeta.MarshalTo(data[i:]) + n133, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n132 + i += n133 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(len(m.Range))) @@ -6571,27 +6623,27 @@ func (m *ReplicationController) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n133, err := m.ObjectMeta.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n133 - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) - n134, err := m.Spec.MarshalTo(data[i:]) + n134, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } i += n134 - data[i] = 0x1a + data[i] = 0x12 i++ - i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) - n135, err := m.Status.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) + n135, err := m.Spec.MarshalTo(data[i:]) if err != nil { return 0, err } i += n135 + data[i] = 0x1a + i++ + i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) + n136, err := m.Status.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n136 return i, nil } @@ -6621,11 +6673,11 @@ func (m *ReplicationControllerCondition) MarshalTo(data []byte) (int, error) { data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.LastTransitionTime.Size())) - n136, err := m.LastTransitionTime.MarshalTo(data[i:]) + n137, err := m.LastTransitionTime.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n136 + i += n137 data[i] = 0x22 i++ i = encodeVarintGenerated(data, i, uint64(len(m.Reason))) @@ -6655,11 +6707,11 @@ func (m *ReplicationControllerList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n137, err := m.ListMeta.MarshalTo(data[i:]) + n138, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n137 + i += n138 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -6716,11 +6768,11 @@ func (m *ReplicationControllerSpec) MarshalTo(data []byte) (int, error) { data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.Template.Size())) - n138, err := m.Template.MarshalTo(data[i:]) + n139, err := m.Template.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n138 + i += n139 } data[i] = 0x20 i++ @@ -6799,11 +6851,11 @@ func (m *ResourceFieldSelector) MarshalTo(data []byte) (int, error) { data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.Divisor.Size())) - n139, err := m.Divisor.MarshalTo(data[i:]) + n140, err := m.Divisor.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n139 + i += n140 return i, nil } @@ -6825,27 +6877,27 @@ func (m *ResourceQuota) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n140, err := m.ObjectMeta.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n140 - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) - n141, err := m.Spec.MarshalTo(data[i:]) + n141, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } i += n141 - data[i] = 0x1a + data[i] = 0x12 i++ - i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) - n142, err := m.Status.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) + n142, err := m.Spec.MarshalTo(data[i:]) if err != nil { return 0, err } i += n142 + data[i] = 0x1a + i++ + i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) + n143, err := m.Status.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n143 return i, nil } @@ -6867,11 +6919,11 @@ func (m *ResourceQuotaList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n143, err := m.ListMeta.MarshalTo(data[i:]) + n144, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n143 + i += n144 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -6917,11 +6969,11 @@ func (m *ResourceQuotaSpec) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n144, err := (&v).MarshalTo(data[i:]) + n145, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n144 + i += n145 } } if len(m.Scopes) > 0 { @@ -6972,11 +7024,11 @@ func (m *ResourceQuotaStatus) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n145, err := (&v).MarshalTo(data[i:]) + n146, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n145 + i += n146 } } if len(m.Used) > 0 { @@ -6994,11 +7046,11 @@ func (m *ResourceQuotaStatus) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n146, err := (&v).MarshalTo(data[i:]) + n147, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n146 + i += n147 } } return i, nil @@ -7034,11 +7086,11 @@ func (m *ResourceRequirements) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n147, err := (&v).MarshalTo(data[i:]) + n148, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n147 + i += n148 } } if len(m.Requests) > 0 { @@ -7056,11 +7108,11 @@ func (m *ResourceRequirements) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n148, err := (&v).MarshalTo(data[i:]) + n149, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n148 + i += n149 } } return i, nil @@ -7118,11 +7170,11 @@ func (m *Secret) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n149, err := m.ObjectMeta.MarshalTo(data[i:]) + n150, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n149 + i += n150 if len(m.Data) > 0 { for k := range m.Data { data[i] = 0x12 @@ -7182,11 +7234,11 @@ func (m *SecretKeySelector) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.LocalObjectReference.Size())) - n150, err := m.LocalObjectReference.MarshalTo(data[i:]) + n151, err := m.LocalObjectReference.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n150 + i += n151 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(len(m.Key))) @@ -7212,11 +7264,11 @@ func (m *SecretList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n151, err := m.ListMeta.MarshalTo(data[i:]) + n152, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n151 + i += n152 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -7290,11 +7342,11 @@ func (m *SecurityContext) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.Capabilities.Size())) - n152, err := m.Capabilities.MarshalTo(data[i:]) + n153, err := m.Capabilities.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n152 + i += n153 } if m.Privileged != nil { data[i] = 0x10 @@ -7310,11 +7362,11 @@ func (m *SecurityContext) MarshalTo(data []byte) (int, error) { data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.SELinuxOptions.Size())) - n153, err := m.SELinuxOptions.MarshalTo(data[i:]) + n154, err := m.SELinuxOptions.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n153 + i += n154 } if m.RunAsUser != nil { data[i] = 0x20 @@ -7362,11 +7414,11 @@ func (m *SerializedReference) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.Reference.Size())) - n154, err := m.Reference.MarshalTo(data[i:]) + n155, err := m.Reference.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n154 + i += n155 return i, nil } @@ -7388,27 +7440,27 @@ func (m *Service) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n155, err := m.ObjectMeta.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n155 - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) - n156, err := m.Spec.MarshalTo(data[i:]) + n156, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } i += n156 - data[i] = 0x1a + data[i] = 0x12 i++ - i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) - n157, err := m.Status.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) + n157, err := m.Spec.MarshalTo(data[i:]) if err != nil { return 0, err } i += n157 + data[i] = 0x1a + i++ + i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) + n158, err := m.Status.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n158 return i, nil } @@ -7430,11 +7482,11 @@ func (m *ServiceAccount) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n158, err := m.ObjectMeta.MarshalTo(data[i:]) + n159, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n158 + i += n159 if len(m.Secrets) > 0 { for _, msg := range m.Secrets { data[i] = 0x12 @@ -7480,11 +7532,11 @@ func (m *ServiceAccountList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n159, err := m.ListMeta.MarshalTo(data[i:]) + n160, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n159 + i += n160 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -7518,11 +7570,11 @@ func (m *ServiceList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n160, err := m.ListMeta.MarshalTo(data[i:]) + n161, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n160 + i += n161 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -7567,11 +7619,11 @@ func (m *ServicePort) MarshalTo(data []byte) (int, error) { data[i] = 0x22 i++ i = encodeVarintGenerated(data, i, uint64(m.TargetPort.Size())) - n161, err := m.TargetPort.MarshalTo(data[i:]) + n162, err := m.TargetPort.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n161 + i += n162 data[i] = 0x28 i++ i = encodeVarintGenerated(data, i, uint64(m.NodePort)) @@ -7730,11 +7782,37 @@ func (m *ServiceStatus) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.LoadBalancer.Size())) - n162, err := m.LoadBalancer.MarshalTo(data[i:]) + n163, err := m.LoadBalancer.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n162 + i += n163 + return i, nil +} + +func (m *Sysctl) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *Sysctl) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.Name))) + i += copy(data[i:], m.Name) + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.Value))) + i += copy(data[i:], m.Value) return i, nil } @@ -7756,11 +7834,11 @@ func (m *TCPSocketAction) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.Port.Size())) - n163, err := m.Port.MarshalTo(data[i:]) + n164, err := m.Port.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n163 + i += n164 return i, nil } @@ -7850,11 +7928,11 @@ func (m *Volume) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.VolumeSource.Size())) - n164, err := m.VolumeSource.MarshalTo(data[i:]) + n165, err := m.VolumeSource.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n164 + i += n165 return i, nil } @@ -7915,163 +7993,163 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.HostPath.Size())) - n165, err := m.HostPath.MarshalTo(data[i:]) - if err != nil { - return 0, err - } - i += n165 - } - if m.EmptyDir != nil { - data[i] = 0x12 - i++ - i = encodeVarintGenerated(data, i, uint64(m.EmptyDir.Size())) - n166, err := m.EmptyDir.MarshalTo(data[i:]) + n166, err := m.HostPath.MarshalTo(data[i:]) if err != nil { return 0, err } i += n166 } - if m.GCEPersistentDisk != nil { - data[i] = 0x1a + if m.EmptyDir != nil { + data[i] = 0x12 i++ - i = encodeVarintGenerated(data, i, uint64(m.GCEPersistentDisk.Size())) - n167, err := m.GCEPersistentDisk.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.EmptyDir.Size())) + n167, err := m.EmptyDir.MarshalTo(data[i:]) if err != nil { return 0, err } i += n167 } - if m.AWSElasticBlockStore != nil { - data[i] = 0x22 + if m.GCEPersistentDisk != nil { + data[i] = 0x1a i++ - i = encodeVarintGenerated(data, i, uint64(m.AWSElasticBlockStore.Size())) - n168, err := m.AWSElasticBlockStore.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.GCEPersistentDisk.Size())) + n168, err := m.GCEPersistentDisk.MarshalTo(data[i:]) if err != nil { return 0, err } i += n168 } - if m.GitRepo != nil { - data[i] = 0x2a + if m.AWSElasticBlockStore != nil { + data[i] = 0x22 i++ - i = encodeVarintGenerated(data, i, uint64(m.GitRepo.Size())) - n169, err := m.GitRepo.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.AWSElasticBlockStore.Size())) + n169, err := m.AWSElasticBlockStore.MarshalTo(data[i:]) if err != nil { return 0, err } i += n169 } - if m.Secret != nil { - data[i] = 0x32 + if m.GitRepo != nil { + data[i] = 0x2a i++ - i = encodeVarintGenerated(data, i, uint64(m.Secret.Size())) - n170, err := m.Secret.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.GitRepo.Size())) + n170, err := m.GitRepo.MarshalTo(data[i:]) if err != nil { return 0, err } i += n170 } - if m.NFS != nil { - data[i] = 0x3a + if m.Secret != nil { + data[i] = 0x32 i++ - i = encodeVarintGenerated(data, i, uint64(m.NFS.Size())) - n171, err := m.NFS.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Secret.Size())) + n171, err := m.Secret.MarshalTo(data[i:]) if err != nil { return 0, err } i += n171 } - if m.ISCSI != nil { - data[i] = 0x42 + if m.NFS != nil { + data[i] = 0x3a i++ - i = encodeVarintGenerated(data, i, uint64(m.ISCSI.Size())) - n172, err := m.ISCSI.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.NFS.Size())) + n172, err := m.NFS.MarshalTo(data[i:]) if err != nil { return 0, err } i += n172 } - if m.Glusterfs != nil { - data[i] = 0x4a + if m.ISCSI != nil { + data[i] = 0x42 i++ - i = encodeVarintGenerated(data, i, uint64(m.Glusterfs.Size())) - n173, err := m.Glusterfs.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.ISCSI.Size())) + n173, err := m.ISCSI.MarshalTo(data[i:]) if err != nil { return 0, err } i += n173 } - if m.PersistentVolumeClaim != nil { - data[i] = 0x52 + if m.Glusterfs != nil { + data[i] = 0x4a i++ - i = encodeVarintGenerated(data, i, uint64(m.PersistentVolumeClaim.Size())) - n174, err := m.PersistentVolumeClaim.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Glusterfs.Size())) + n174, err := m.Glusterfs.MarshalTo(data[i:]) if err != nil { return 0, err } i += n174 } - if m.RBD != nil { - data[i] = 0x5a + if m.PersistentVolumeClaim != nil { + data[i] = 0x52 i++ - i = encodeVarintGenerated(data, i, uint64(m.RBD.Size())) - n175, err := m.RBD.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.PersistentVolumeClaim.Size())) + n175, err := m.PersistentVolumeClaim.MarshalTo(data[i:]) if err != nil { return 0, err } i += n175 } - if m.FlexVolume != nil { - data[i] = 0x62 + if m.RBD != nil { + data[i] = 0x5a i++ - i = encodeVarintGenerated(data, i, uint64(m.FlexVolume.Size())) - n176, err := m.FlexVolume.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.RBD.Size())) + n176, err := m.RBD.MarshalTo(data[i:]) if err != nil { return 0, err } i += n176 } - if m.Cinder != nil { - data[i] = 0x6a + if m.FlexVolume != nil { + data[i] = 0x62 i++ - i = encodeVarintGenerated(data, i, uint64(m.Cinder.Size())) - n177, err := m.Cinder.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.FlexVolume.Size())) + n177, err := m.FlexVolume.MarshalTo(data[i:]) if err != nil { return 0, err } i += n177 } - if m.CephFS != nil { - data[i] = 0x72 + if m.Cinder != nil { + data[i] = 0x6a i++ - i = encodeVarintGenerated(data, i, uint64(m.CephFS.Size())) - n178, err := m.CephFS.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.Cinder.Size())) + n178, err := m.Cinder.MarshalTo(data[i:]) if err != nil { return 0, err } i += n178 } - if m.Flocker != nil { - data[i] = 0x7a + if m.CephFS != nil { + data[i] = 0x72 i++ - i = encodeVarintGenerated(data, i, uint64(m.Flocker.Size())) - n179, err := m.Flocker.MarshalTo(data[i:]) + i = encodeVarintGenerated(data, i, uint64(m.CephFS.Size())) + n179, err := m.CephFS.MarshalTo(data[i:]) if err != nil { return 0, err } i += n179 } + if m.Flocker != nil { + data[i] = 0x7a + i++ + i = encodeVarintGenerated(data, i, uint64(m.Flocker.Size())) + n180, err := m.Flocker.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n180 + } if m.DownwardAPI != nil { data[i] = 0x82 i++ data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.DownwardAPI.Size())) - n180, err := m.DownwardAPI.MarshalTo(data[i:]) + n181, err := m.DownwardAPI.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n180 + i += n181 } if m.FC != nil { data[i] = 0x8a @@ -8079,11 +8157,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.FC.Size())) - n181, err := m.FC.MarshalTo(data[i:]) + n182, err := m.FC.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n181 + i += n182 } if m.AzureFile != nil { data[i] = 0x92 @@ -8091,11 +8169,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.AzureFile.Size())) - n182, err := m.AzureFile.MarshalTo(data[i:]) + n183, err := m.AzureFile.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n182 + i += n183 } if m.ConfigMap != nil { data[i] = 0x9a @@ -8103,11 +8181,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.ConfigMap.Size())) - n183, err := m.ConfigMap.MarshalTo(data[i:]) + n184, err := m.ConfigMap.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n183 + i += n184 } if m.VsphereVolume != nil { data[i] = 0xa2 @@ -8115,11 +8193,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.VsphereVolume.Size())) - n184, err := m.VsphereVolume.MarshalTo(data[i:]) + n185, err := m.VsphereVolume.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n184 + i += n185 } if m.Quobyte != nil { data[i] = 0xaa @@ -8127,11 +8205,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.Quobyte.Size())) - n185, err := m.Quobyte.MarshalTo(data[i:]) + n186, err := m.Quobyte.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n185 + i += n186 } if m.AzureDisk != nil { data[i] = 0xb2 @@ -8139,11 +8217,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.AzureDisk.Size())) - n186, err := m.AzureDisk.MarshalTo(data[i:]) + n187, err := m.AzureDisk.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n186 + i += n187 } if m.PhotonPersistentDisk != nil { data[i] = 0xba @@ -8151,11 +8229,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.PhotonPersistentDisk.Size())) - n187, err := m.PhotonPersistentDisk.MarshalTo(data[i:]) + n188, err := m.PhotonPersistentDisk.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n187 + i += n188 } return i, nil } @@ -8207,11 +8285,11 @@ func (m *WeightedPodAffinityTerm) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.PodAffinityTerm.Size())) - n188, err := m.PodAffinityTerm.MarshalTo(data[i:]) + n189, err := m.PodAffinityTerm.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n188 + i += n189 return i, nil } @@ -9381,6 +9459,21 @@ func (m *NodeProxyOptions) Size() (n int) { return n } +func (m *NodeResources) Size() (n int) { + var l int + _ = l + if len(m.Capacity) > 0 { + for k, v := range m.Capacity { + _ = k + _ = v + l = v.Size() + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } + return n +} + func (m *NodeSelector) Size() (n int) { var l int _ = l @@ -10726,6 +10819,16 @@ func (m *ServiceStatus) Size() (n int) { return n } +func (m *Sysctl) Size() (n int) { + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Value) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + func (m *TCPSocketAction) Size() (n int) { var l int _ = l @@ -11901,6 +12004,26 @@ func (this *NodeProxyOptions) String() string { }, "") return s } +func (this *NodeResources) String() string { + if this == nil { + return "nil" + } + keysForCapacity := make([]string, 0, len(this.Capacity)) + for k := range this.Capacity { + keysForCapacity = append(keysForCapacity, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForCapacity) + mapStringForCapacity := "ResourceList{" + for _, k := range keysForCapacity { + mapStringForCapacity += fmt.Sprintf("%v: %v,", k, this.Capacity[ResourceName(k)]) + } + mapStringForCapacity += "}" + s := strings.Join([]string{`&NodeResources{`, + `Capacity:` + mapStringForCapacity + `,`, + `}`, + }, "") + return s +} func (this *NodeSelector) String() string { if this == nil { return "nil" @@ -13002,6 +13125,17 @@ func (this *ServiceStatus) String() string { }, "") return s } +func (this *Sysctl) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Sysctl{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `}`, + }, "") + return s +} func (this *TCPSocketAction) String() string { if this == nil { return "nil" @@ -24151,6 +24285,172 @@ func (m *NodeProxyOptions) Unmarshal(data []byte) error { } return nil } +func (m *NodeResources) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NodeResources: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NodeResources: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Capacity", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + var keykey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + keykey |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLenmapkey |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey := ResourceName(data[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + var valuekey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + valuekey |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + var mapmsglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + mapmsglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if mapmsglen < 0 { + return ErrInvalidLengthGenerated + } + postmsgIndex := iNdEx + mapmsglen + if mapmsglen < 0 { + return ErrInvalidLengthGenerated + } + if postmsgIndex > l { + return io.ErrUnexpectedEOF + } + mapvalue := &k8s_io_kubernetes_pkg_api_resource.Quantity{} + if err := mapvalue.Unmarshal(data[iNdEx:postmsgIndex]); err != nil { + return err + } + iNdEx = postmsgIndex + if m.Capacity == nil { + m.Capacity = make(ResourceList) + } + m.Capacity[ResourceName(mapkey)] = *mapvalue + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *NodeSelector) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 @@ -37382,6 +37682,114 @@ func (m *ServiceStatus) Unmarshal(data []byte) error { } return nil } +func (m *Sysctl) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Sysctl: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Sysctl: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(data[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Value = string(data[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *TCPSocketAction) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 @@ -39153,631 +39561,634 @@ var ( ) var fileDescriptorGenerated = []byte{ - // 10015 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xec, 0x7d, 0x6d, 0x6c, 0x25, 0xd7, - 0x75, 0x98, 0xe7, 0x3d, 0x7e, 0xbd, 0xc3, 0xcf, 0xbd, 0xfb, 0x21, 0x8a, 0x91, 0x96, 0xeb, 0x91, - 0xb5, 0x5e, 0x49, 0x2b, 0xae, 0x77, 0x25, 0x45, 0xb2, 0xa5, 0xca, 0x26, 0xf9, 0xc8, 0x5d, 0x7a, - 0x97, 0xbb, 0x4f, 0xf7, 0x71, 0xb5, 0xb2, 0xad, 0x4a, 0x1e, 0xbe, 0xb9, 0x24, 0xc7, 0x3b, 0x9c, - 0x79, 0x9a, 0x99, 0xc7, 0x5d, 0xda, 0x0d, 0x90, 0x3a, 0x6a, 0x8a, 0x22, 0x46, 0xea, 0xa2, 0x35, - 0x5a, 0xa0, 0x2d, 0xea, 0x16, 0x68, 0x91, 0x36, 0x68, 0x1a, 0xa7, 0x6e, 0x62, 0xb7, 0x86, 0x51, - 0xa0, 0xa9, 0xe1, 0x7e, 0xa4, 0x70, 0x80, 0xa0, 0x09, 0x12, 0x80, 0x8d, 0x18, 0x14, 0xfd, 0xd1, - 0x1f, 0x2d, 0xd0, 0x5f, 0x25, 0x82, 0xb6, 0xb8, 0x9f, 0x73, 0xef, 0xbc, 0x79, 0x9c, 0x79, 0xd4, - 0x92, 0x51, 0x82, 0xfe, 0x7b, 0xef, 0x9c, 0x73, 0xcf, 0xfd, 0x98, 0x73, 0xcf, 0x3d, 0xf7, 0xdc, - 0x73, 0xcf, 0x85, 0xcb, 0xf7, 0x5f, 0x89, 0xe7, 0xbc, 0xf0, 0xca, 0xfd, 0xce, 0x3a, 0x89, 0x02, - 0x92, 0x90, 0xf8, 0x4a, 0xfb, 0xfe, 0xe6, 0x15, 0xa7, 0xed, 0x5d, 0xd9, 0xb9, 0x7a, 0x65, 0x93, - 0x04, 0x24, 0x72, 0x12, 0xe2, 0xce, 0xb5, 0xa3, 0x30, 0x09, 0xd1, 0x13, 0x9c, 0x7a, 0x2e, 0xa5, - 0x9e, 0x6b, 0xdf, 0xdf, 0x9c, 0x73, 0xda, 0xde, 0xdc, 0xce, 0xd5, 0x99, 0xe7, 0x37, 0xbd, 0x64, - 0xab, 0xb3, 0x3e, 0xd7, 0x0a, 0xb7, 0xaf, 0x6c, 0x86, 0x9b, 0xe1, 0x15, 0x56, 0x68, 0xbd, 0xb3, - 0xc1, 0xfe, 0xb1, 0x3f, 0xec, 0x17, 0x67, 0x36, 0x73, 0xad, 0x77, 0xd5, 0x11, 0x89, 0xc3, 0x4e, - 0xd4, 0x22, 0xd9, 0x06, 0xcc, 0xbc, 0xd4, 0xbb, 0x4c, 0x27, 0xd8, 0x21, 0x51, 0xec, 0x85, 0x01, - 0x71, 0xbb, 0x8a, 0x3d, 0x9f, 0x5f, 0x2c, 0xea, 0x04, 0x89, 0xb7, 0xdd, 0x5d, 0xcb, 0xd5, 0x7c, - 0xf2, 0x4e, 0xe2, 0xf9, 0x57, 0xbc, 0x20, 0x89, 0x93, 0x28, 0x5b, 0xc4, 0xfe, 0x5d, 0x0b, 0x2e, - 0xcc, 0xdf, 0x6b, 0x2e, 0xf9, 0x4e, 0x9c, 0x78, 0xad, 0x05, 0x3f, 0x6c, 0xdd, 0x6f, 0x26, 0x61, - 0x44, 0xde, 0x0c, 0xfd, 0xce, 0x36, 0x69, 0xb2, 0xde, 0xa0, 0xcb, 0x30, 0xb2, 0xc3, 0xfe, 0xaf, - 0xd4, 0xa7, 0xad, 0x0b, 0xd6, 0xa5, 0xda, 0xc2, 0xd4, 0x8f, 0xf7, 0x66, 0x3f, 0xb6, 0xbf, 0x37, - 0x3b, 0xf2, 0xa6, 0x80, 0x63, 0x45, 0x81, 0x2e, 0xc2, 0xd0, 0x46, 0xbc, 0xb6, 0xdb, 0x26, 0xd3, - 0x15, 0x46, 0x3b, 0x21, 0x68, 0x87, 0x96, 0x9b, 0x14, 0x8a, 0x05, 0x16, 0x5d, 0x81, 0x5a, 0xdb, - 0x89, 0x12, 0x2f, 0xf1, 0xc2, 0x60, 0xba, 0x7a, 0xc1, 0xba, 0x34, 0xb8, 0x70, 0x4a, 0x90, 0xd6, - 0x1a, 0x12, 0x81, 0x53, 0x1a, 0xda, 0x8c, 0x88, 0x38, 0xee, 0x9d, 0xc0, 0xdf, 0x9d, 0x1e, 0xb8, - 0x60, 0x5d, 0x1a, 0x49, 0x9b, 0x81, 0x05, 0x1c, 0x2b, 0x0a, 0xfb, 0x7b, 0x15, 0x18, 0x99, 0xdf, - 0xd8, 0xf0, 0x02, 0x2f, 0xd9, 0x45, 0x5f, 0x86, 0xb1, 0x20, 0x74, 0x89, 0xfc, 0xcf, 0x7a, 0x31, - 0x7a, 0xed, 0xd9, 0xb9, 0xc3, 0xe4, 0x62, 0xee, 0xb6, 0x56, 0x62, 0x61, 0x6a, 0x7f, 0x6f, 0x76, - 0x4c, 0x87, 0x60, 0x83, 0x23, 0x7a, 0x1b, 0x46, 0xdb, 0xa1, 0xab, 0x2a, 0xa8, 0xb0, 0x0a, 0x9e, - 0x39, 0xbc, 0x82, 0x46, 0x5a, 0x60, 0x61, 0x72, 0x7f, 0x6f, 0x76, 0x54, 0x03, 0x60, 0x9d, 0x1d, - 0xf2, 0x61, 0x92, 0xfe, 0x0d, 0x12, 0x4f, 0xd5, 0x50, 0x65, 0x35, 0x3c, 0x5f, 0x5c, 0x83, 0x56, - 0x68, 0xe1, 0xf4, 0xfe, 0xde, 0xec, 0x64, 0x06, 0x88, 0xb3, 0xac, 0xed, 0xaf, 0xc2, 0xc4, 0x7c, - 0x92, 0x38, 0xad, 0x2d, 0xe2, 0xf2, 0xef, 0x8b, 0x5e, 0x84, 0x81, 0xc0, 0xd9, 0x26, 0xe2, 0xeb, - 0x5f, 0x10, 0xc3, 0x3e, 0x70, 0xdb, 0xd9, 0x26, 0x07, 0x7b, 0xb3, 0x53, 0x77, 0x03, 0xef, 0xbd, - 0x8e, 0x90, 0x19, 0x0a, 0xc3, 0x8c, 0x1a, 0x5d, 0x03, 0x70, 0xc9, 0x8e, 0xd7, 0x22, 0x0d, 0x27, - 0xd9, 0x12, 0xd2, 0x80, 0x44, 0x59, 0xa8, 0x2b, 0x0c, 0xd6, 0xa8, 0xec, 0xaf, 0x5b, 0x50, 0x9b, - 0xdf, 0x09, 0x3d, 0xb7, 0x11, 0xba, 0x31, 0xea, 0xc0, 0x64, 0x3b, 0x22, 0x1b, 0x24, 0x52, 0xa0, - 0x69, 0xeb, 0x42, 0xf5, 0xd2, 0xe8, 0xb5, 0x6b, 0x05, 0xfd, 0x36, 0x0b, 0x2d, 0x05, 0x49, 0xb4, - 0xbb, 0xf0, 0x98, 0xa8, 0x7a, 0x32, 0x83, 0xc5, 0xd9, 0x3a, 0xec, 0xbf, 0x56, 0x81, 0xb3, 0xf3, - 0x5f, 0xed, 0x44, 0xa4, 0xee, 0xc5, 0xf7, 0xb3, 0x53, 0xc1, 0xf5, 0xe2, 0xfb, 0xb7, 0xd3, 0xc1, - 0x50, 0x32, 0x58, 0x17, 0x70, 0xac, 0x28, 0xd0, 0xf3, 0x30, 0x4c, 0x7f, 0xdf, 0xc5, 0x2b, 0xa2, - 0xf7, 0xa7, 0x05, 0xf1, 0x68, 0xdd, 0x49, 0x9c, 0x3a, 0x47, 0x61, 0x49, 0x83, 0x56, 0x61, 0xb4, - 0xe5, 0xb4, 0xb6, 0xbc, 0x60, 0x73, 0x35, 0x74, 0x09, 0xfb, 0xc2, 0xb5, 0x85, 0xe7, 0x28, 0xf9, - 0x62, 0x0a, 0x3e, 0xd8, 0x9b, 0x9d, 0xe6, 0x6d, 0x13, 0x2c, 0x34, 0x1c, 0xd6, 0xcb, 0x23, 0x5b, - 0x4d, 0xc4, 0x01, 0xc6, 0x09, 0x72, 0x26, 0xe1, 0x25, 0x6d, 0x4e, 0x0d, 0xb2, 0x39, 0x35, 0xd6, - 0x63, 0x3e, 0xfd, 0x13, 0x4b, 0x8c, 0xc9, 0xb2, 0xe7, 0x9b, 0xea, 0xe1, 0x1a, 0x40, 0x4c, 0x5a, - 0x11, 0x49, 0xb4, 0x51, 0x51, 0x9f, 0xb9, 0xa9, 0x30, 0x58, 0xa3, 0xa2, 0x93, 0x3f, 0xde, 0x72, - 0x22, 0x26, 0x2d, 0x62, 0x6c, 0xd4, 0xe4, 0x6f, 0x4a, 0x04, 0x4e, 0x69, 0x8c, 0xc9, 0x5f, 0x2d, - 0x9c, 0xfc, 0xff, 0xd2, 0x82, 0xe1, 0x05, 0x2f, 0x70, 0xbd, 0x60, 0x13, 0xbd, 0x05, 0x23, 0xdb, - 0x24, 0x71, 0x5c, 0x27, 0x71, 0xc4, 0xbc, 0xbf, 0x74, 0xb8, 0xf0, 0xdc, 0x59, 0xff, 0x0a, 0x69, - 0x25, 0xab, 0x24, 0x71, 0xd2, 0x6e, 0xa4, 0x30, 0xac, 0xb8, 0xa1, 0xbb, 0x30, 0x94, 0x38, 0xd1, - 0x26, 0x49, 0xc4, 0x74, 0x7f, 0xbe, 0x0c, 0x5f, 0x4c, 0x45, 0x8d, 0x04, 0x2d, 0x92, 0x2a, 0xc6, - 0x35, 0xc6, 0x04, 0x0b, 0x66, 0x76, 0x0b, 0xc6, 0x16, 0x9d, 0xb6, 0xb3, 0xee, 0xf9, 0x5e, 0xe2, - 0x91, 0x18, 0x7d, 0x12, 0xaa, 0x8e, 0xeb, 0x32, 0xc1, 0xaf, 0x2d, 0x9c, 0xdd, 0xdf, 0x9b, 0xad, - 0xce, 0xbb, 0xee, 0xc1, 0xde, 0x2c, 0x28, 0xaa, 0x5d, 0x4c, 0x29, 0xd0, 0xb3, 0x30, 0xe0, 0x46, - 0x61, 0x7b, 0xba, 0xc2, 0x28, 0xcf, 0xd1, 0x19, 0x5a, 0x8f, 0xc2, 0x76, 0x86, 0x94, 0xd1, 0xd8, - 0xff, 0xb6, 0x02, 0x68, 0x91, 0xb4, 0xb7, 0x96, 0x9b, 0xc6, 0xb7, 0xbc, 0x04, 0x23, 0xdb, 0x61, - 0xe0, 0x25, 0x61, 0x14, 0x8b, 0x0a, 0x99, 0x3c, 0xac, 0x0a, 0x18, 0x56, 0x58, 0x74, 0x01, 0x06, - 0xda, 0xe9, 0xb4, 0x1e, 0x93, 0x2a, 0x81, 0x4d, 0x68, 0x86, 0xa1, 0x14, 0x9d, 0x98, 0x44, 0x42, - 0x8e, 0x15, 0xc5, 0xdd, 0x98, 0x44, 0x98, 0x61, 0x52, 0xc9, 0xa1, 0x32, 0x25, 0xa4, 0x34, 0x23, - 0x39, 0x14, 0x83, 0x35, 0x2a, 0xf4, 0x2e, 0xd4, 0xf8, 0x3f, 0x4c, 0x36, 0x98, 0xc8, 0x16, 0x2a, - 0x83, 0x5b, 0x61, 0xcb, 0xf1, 0xb3, 0x83, 0x3f, 0xce, 0x24, 0x4d, 0x32, 0xc2, 0x29, 0x4f, 0x43, - 0xd2, 0x86, 0x0a, 0x25, 0xed, 0x6f, 0x59, 0x80, 0x16, 0xbd, 0xc0, 0x25, 0xd1, 0x09, 0x2c, 0x99, - 0xfd, 0x4d, 0x82, 0x3f, 0xa0, 0x4d, 0x0b, 0xb7, 0xdb, 0x61, 0x40, 0x82, 0x64, 0x31, 0x0c, 0x5c, - 0xbe, 0x8c, 0x7e, 0x06, 0x06, 0x12, 0x5a, 0x15, 0x6f, 0xd6, 0x45, 0xf9, 0x59, 0x68, 0x05, 0x07, - 0x7b, 0xb3, 0xe7, 0xba, 0x4b, 0xb0, 0x26, 0xb0, 0x32, 0xe8, 0xd3, 0x30, 0x14, 0x27, 0x4e, 0xd2, - 0x89, 0x45, 0x43, 0x3f, 0x2e, 0x1b, 0xda, 0x64, 0xd0, 0x83, 0xbd, 0xd9, 0x49, 0x55, 0x8c, 0x83, - 0xb0, 0x28, 0x80, 0x9e, 0x81, 0xe1, 0x6d, 0x12, 0xc7, 0xce, 0xa6, 0x54, 0x6c, 0x93, 0xa2, 0xec, - 0xf0, 0x2a, 0x07, 0x63, 0x89, 0x47, 0x4f, 0xc1, 0x20, 0x89, 0xa2, 0x30, 0x12, 0x12, 0x31, 0x2e, - 0x08, 0x07, 0x97, 0x28, 0x10, 0x73, 0x9c, 0xfd, 0xdb, 0x16, 0x4c, 0xaa, 0xb6, 0xf2, 0xba, 0x8e, - 0x71, 0xaa, 0xbb, 0x00, 0x2d, 0xd9, 0xb1, 0x98, 0x4d, 0xb0, 0xd1, 0x6b, 0x9f, 0x3a, 0x9c, 0x77, - 0xf7, 0x40, 0xa6, 0x75, 0x28, 0x50, 0x8c, 0x35, 0xbe, 0xf6, 0x8f, 0x2d, 0x38, 0x9d, 0xe9, 0xd3, - 0x2d, 0x2f, 0x4e, 0xd0, 0x9f, 0xef, 0xea, 0xd7, 0x95, 0x43, 0xea, 0xd6, 0x2c, 0xca, 0x39, 0x5a, - 0x9c, 0x75, 0x4f, 0x09, 0x8a, 0x84, 0x68, 0x9d, 0xc3, 0x30, 0xe8, 0x25, 0x64, 0x5b, 0xf6, 0xeb, - 0xf9, 0x92, 0xfd, 0xe2, 0x0d, 0x4c, 0x3f, 0xcf, 0x0a, 0xe5, 0x81, 0x39, 0x2b, 0xfb, 0x7f, 0x59, - 0x50, 0x5b, 0x0c, 0x83, 0x0d, 0x6f, 0x73, 0xd5, 0x69, 0x1f, 0xe3, 0x87, 0x69, 0xc2, 0x00, 0xe3, - 0xca, 0x9b, 0x7e, 0xb5, 0xa8, 0xe9, 0xa2, 0x41, 0x73, 0x74, 0xf1, 0xe4, 0x56, 0x81, 0xd2, 0x4b, - 0x14, 0x84, 0x19, 0xb3, 0x99, 0x97, 0xa1, 0xa6, 0x08, 0xd0, 0x14, 0x54, 0xef, 0x13, 0x6e, 0x32, - 0xd6, 0x30, 0xfd, 0x89, 0xce, 0xc0, 0xe0, 0x8e, 0xe3, 0x77, 0xc4, 0x6c, 0xc5, 0xfc, 0xcf, 0x67, - 0x2a, 0xaf, 0x58, 0xf6, 0x0f, 0x2c, 0x38, 0xa3, 0x2a, 0xb9, 0x49, 0x76, 0x9b, 0xc4, 0x27, 0xad, - 0x24, 0x8c, 0xd0, 0xfb, 0x16, 0x9c, 0xf1, 0x73, 0xf4, 0x90, 0x18, 0x8d, 0xa3, 0x68, 0xb0, 0x27, - 0x44, 0xc3, 0xcf, 0xe4, 0x61, 0x71, 0x6e, 0x6d, 0xe8, 0x49, 0xde, 0x17, 0x3e, 0x79, 0x47, 0x05, - 0x83, 0xea, 0x4d, 0xb2, 0xcb, 0x3a, 0x46, 0x9b, 0x3f, 0xae, 0x9a, 0x7f, 0x12, 0x92, 0x77, 0xcb, - 0x94, 0xbc, 0x4f, 0x96, 0xfc, 0x7c, 0x3d, 0x64, 0xee, 0xef, 0x55, 0xe0, 0xac, 0xa2, 0x31, 0xd4, - 0xf1, 0x47, 0x64, 0xf8, 0xfb, 0xeb, 0xee, 0x4d, 0xb2, 0xbb, 0x16, 0xd2, 0xf5, 0x34, 0xbf, 0xbb, - 0xe8, 0x2a, 0x8c, 0xba, 0x64, 0xc3, 0xe9, 0xf8, 0x89, 0x32, 0x17, 0x07, 0xf9, 0x3e, 0xa2, 0x9e, - 0x82, 0xb1, 0x4e, 0x63, 0xff, 0x56, 0x8d, 0xcd, 0xca, 0xc4, 0xf1, 0x02, 0x12, 0xd1, 0x05, 0x5a, - 0xb3, 0xea, 0xc7, 0x74, 0xab, 0x5e, 0x58, 0xf0, 0x4f, 0xc1, 0xa0, 0xb7, 0x4d, 0x55, 0x76, 0xc5, - 0xd4, 0xc4, 0x2b, 0x14, 0x88, 0x39, 0x0e, 0x3d, 0x0d, 0xc3, 0xad, 0x70, 0x7b, 0xdb, 0x09, 0xdc, - 0xe9, 0x2a, 0x33, 0x19, 0x46, 0xa9, 0x56, 0x5f, 0xe4, 0x20, 0x2c, 0x71, 0xe8, 0x09, 0x18, 0x70, - 0xa2, 0xcd, 0x78, 0x7a, 0x80, 0xd1, 0x8c, 0xd0, 0x9a, 0xe6, 0xa3, 0xcd, 0x18, 0x33, 0x28, 0x35, - 0x05, 0x1e, 0x84, 0xd1, 0x7d, 0x2f, 0xd8, 0xac, 0x7b, 0x11, 0x5b, 0xd7, 0x35, 0x53, 0xe0, 0x9e, - 0xc2, 0x60, 0x8d, 0x0a, 0x35, 0x60, 0xb0, 0x1d, 0x46, 0x49, 0x3c, 0x3d, 0xc4, 0x86, 0xf3, 0xb9, - 0x42, 0xe9, 0xe1, 0xfd, 0x6e, 0x84, 0x51, 0x92, 0x76, 0x85, 0xfe, 0x8b, 0x31, 0x67, 0x84, 0x16, - 0xa1, 0x4a, 0x82, 0x9d, 0xe9, 0x61, 0xc6, 0xef, 0x13, 0x87, 0xf3, 0x5b, 0x0a, 0x76, 0xde, 0x74, - 0xa2, 0x74, 0x16, 0x2d, 0x05, 0x3b, 0x98, 0x96, 0x46, 0x2d, 0xa8, 0x49, 0x47, 0x40, 0x3c, 0x3d, - 0x52, 0x46, 0xc0, 0xb0, 0x20, 0xc7, 0xe4, 0xbd, 0x8e, 0x17, 0x91, 0x6d, 0x12, 0x24, 0x71, 0x6a, - 0x0f, 0x4b, 0x6c, 0x8c, 0x53, 0xbe, 0xa8, 0x05, 0x63, 0xdc, 0x7c, 0x58, 0x0d, 0x3b, 0x41, 0x12, - 0x4f, 0xd7, 0x58, 0x93, 0x0b, 0x36, 0x9c, 0x6f, 0xa6, 0x25, 0x16, 0xce, 0x08, 0xf6, 0x63, 0x1a, - 0x30, 0xc6, 0x06, 0x53, 0xf4, 0x36, 0x8c, 0xfb, 0xde, 0x0e, 0x09, 0x48, 0x1c, 0x37, 0xa2, 0x70, - 0x9d, 0x4c, 0x03, 0xeb, 0xcd, 0x53, 0x45, 0x9b, 0xaf, 0x70, 0x9d, 0x2c, 0x9c, 0xda, 0xdf, 0x9b, - 0x1d, 0xbf, 0xa5, 0x97, 0xc6, 0x26, 0x33, 0xf4, 0x2e, 0x4c, 0x50, 0x5b, 0xc5, 0x4b, 0xd9, 0x8f, - 0x96, 0x67, 0x8f, 0xf6, 0xf7, 0x66, 0x27, 0xb0, 0x51, 0x1c, 0x67, 0xd8, 0xa1, 0x35, 0xa8, 0xf9, - 0xde, 0x06, 0x69, 0xed, 0xb6, 0x7c, 0x32, 0x3d, 0xc6, 0x78, 0x17, 0x4c, 0xb9, 0x5b, 0x92, 0x9c, - 0xdb, 0x87, 0xea, 0x2f, 0x4e, 0x19, 0xa1, 0x37, 0xe1, 0x5c, 0x42, 0xa2, 0x6d, 0x2f, 0x70, 0xe8, - 0xa2, 0x2d, 0x8c, 0x17, 0xb6, 0xc3, 0x1d, 0x67, 0x52, 0x7b, 0x5e, 0x0c, 0xec, 0xb9, 0xb5, 0x5c, - 0x2a, 0xdc, 0xa3, 0x34, 0xba, 0x03, 0x93, 0x6c, 0x3e, 0x35, 0x3a, 0xbe, 0xdf, 0x08, 0x7d, 0xaf, - 0xb5, 0x3b, 0x3d, 0xc1, 0x18, 0x3e, 0x2d, 0xf7, 0xad, 0x2b, 0x26, 0x9a, 0xda, 0xf5, 0xe9, 0x3f, - 0x9c, 0x2d, 0x8d, 0x7c, 0x98, 0x8c, 0x49, 0xab, 0x13, 0x79, 0xc9, 0x2e, 0x95, 0x7d, 0xf2, 0x30, - 0x99, 0x9e, 0x2c, 0xb3, 0x4f, 0x69, 0x9a, 0x85, 0xb8, 0xd3, 0x20, 0x03, 0xc4, 0x59, 0xd6, 0x54, - 0x55, 0xc4, 0x89, 0xeb, 0x05, 0xd3, 0x53, 0xcc, 0x30, 0x55, 0xf3, 0xab, 0x49, 0x81, 0x98, 0xe3, - 0xd8, 0xb6, 0x8f, 0xfe, 0xb8, 0x43, 0x75, 0xef, 0x29, 0x46, 0x98, 0x6e, 0xfb, 0x24, 0x02, 0xa7, - 0x34, 0x74, 0xc1, 0x4a, 0x92, 0xdd, 0x69, 0xc4, 0x48, 0xd5, 0x54, 0x5b, 0x5b, 0xfb, 0x02, 0xa6, - 0x70, 0x7b, 0x1d, 0x26, 0xd4, 0xb4, 0x66, 0xa3, 0x83, 0x66, 0x61, 0x90, 0x6a, 0x2e, 0xb9, 0x7b, - 0xa9, 0xd1, 0x26, 0x50, 0x85, 0x16, 0x63, 0x0e, 0x67, 0x4d, 0xf0, 0xbe, 0x4a, 0x16, 0x76, 0x13, - 0xc2, 0xad, 0xd8, 0xaa, 0xd6, 0x04, 0x89, 0xc0, 0x29, 0x8d, 0xfd, 0x7f, 0xf8, 0xa2, 0x98, 0xea, - 0x8e, 0x12, 0x7a, 0xf3, 0x32, 0x8c, 0x6c, 0x85, 0x71, 0x42, 0xa9, 0x59, 0x1d, 0x83, 0xe9, 0x2a, - 0x78, 0x43, 0xc0, 0xb1, 0xa2, 0x40, 0xaf, 0xc2, 0x78, 0x4b, 0xaf, 0x40, 0xa8, 0xf2, 0xb3, 0xa2, - 0x88, 0x59, 0x3b, 0x36, 0x69, 0xd1, 0x2b, 0x30, 0xc2, 0x5c, 0x79, 0xad, 0xd0, 0x17, 0xf6, 0xb2, - 0x5c, 0x99, 0x46, 0x1a, 0x02, 0x7e, 0xa0, 0xfd, 0xc6, 0x8a, 0x9a, 0xee, 0x3a, 0x68, 0x13, 0x56, - 0x1a, 0x42, 0xdd, 0xaa, 0x5d, 0xc7, 0x0d, 0x06, 0xc5, 0x02, 0x6b, 0xff, 0x6a, 0x45, 0x1b, 0x65, - 0x6a, 0xf4, 0x11, 0xf4, 0x45, 0x18, 0x7e, 0xe0, 0x78, 0x89, 0x17, 0x6c, 0x8a, 0x15, 0xf4, 0x85, - 0x92, 0xba, 0x97, 0x15, 0xbf, 0xc7, 0x8b, 0xf2, 0x75, 0x42, 0xfc, 0xc1, 0x92, 0x21, 0xe5, 0x1d, - 0x75, 0x82, 0x80, 0xf2, 0xae, 0xf4, 0xcf, 0x1b, 0xf3, 0xa2, 0x9c, 0xb7, 0xf8, 0x83, 0x25, 0x43, - 0xb4, 0x01, 0x20, 0x67, 0x1f, 0x71, 0x85, 0x0b, 0xed, 0xa7, 0xfb, 0x61, 0xbf, 0xa6, 0x4a, 0x2f, - 0x4c, 0xd0, 0x95, 0x29, 0xfd, 0x8f, 0x35, 0xce, 0x76, 0x87, 0x19, 0x22, 0xdd, 0xcd, 0x42, 0x6f, - 0xd3, 0x09, 0xe0, 0x44, 0x09, 0x71, 0xe7, 0x13, 0x31, 0x74, 0xcf, 0x95, 0x34, 0xa8, 0xd6, 0xbc, - 0x6d, 0xa2, 0xcf, 0x16, 0xc1, 0x05, 0xa7, 0x0c, 0xed, 0xef, 0x57, 0x61, 0xba, 0x57, 0x7b, 0xa9, - 0x4c, 0x92, 0x87, 0x5e, 0xb2, 0x48, 0x6d, 0x05, 0xcb, 0x94, 0xc9, 0x25, 0x01, 0xc7, 0x8a, 0x82, - 0x0a, 0x47, 0xec, 0x6d, 0x06, 0x8e, 0x2f, 0xe4, 0x57, 0x09, 0x47, 0x93, 0x41, 0xb1, 0xc0, 0x52, - 0xba, 0x88, 0x38, 0xb1, 0x70, 0xe1, 0x6a, 0x42, 0x84, 0x19, 0x14, 0x0b, 0xac, 0xbe, 0xfd, 0x1b, - 0x28, 0xd8, 0xfe, 0x19, 0x63, 0x34, 0xf8, 0x88, 0xc7, 0x08, 0xbd, 0x0b, 0xb0, 0xe1, 0x05, 0x5e, - 0xbc, 0xc5, 0xd8, 0x0f, 0xf5, 0xcf, 0x5e, 0x59, 0x25, 0xcb, 0x8a, 0x0d, 0xd6, 0x58, 0xa2, 0x97, - 0x60, 0x54, 0xcd, 0xd0, 0x95, 0xfa, 0xf4, 0xb0, 0xe9, 0xf8, 0x4b, 0xd5, 0x55, 0x1d, 0xeb, 0x74, - 0xf6, 0x57, 0xb2, 0x22, 0x23, 0x26, 0x86, 0x36, 0xc2, 0x56, 0xd9, 0x11, 0xae, 0x1c, 0x3e, 0xc2, - 0xf6, 0x7f, 0xae, 0xd2, 0xbd, 0xb3, 0x56, 0x59, 0x27, 0x2e, 0xa1, 0xd4, 0xde, 0xa0, 0x1a, 0xde, - 0x49, 0x88, 0x98, 0x96, 0x97, 0xfb, 0x99, 0x37, 0xfa, 0x7a, 0x40, 0xa7, 0x03, 0xe7, 0x84, 0xb6, - 0xa0, 0xe6, 0x3b, 0x31, 0xdb, 0x49, 0x12, 0x31, 0x1d, 0xfb, 0x63, 0x9b, 0x5a, 0xe1, 0x4e, 0x9c, - 0x68, 0x0b, 0x2e, 0xaf, 0x25, 0x65, 0x4e, 0x97, 0x27, 0x6a, 0x1d, 0xc8, 0x93, 0x03, 0xd5, 0x1c, - 0x6a, 0x42, 0xec, 0x62, 0x8e, 0x43, 0xaf, 0xc0, 0x58, 0x44, 0x98, 0xa8, 0x2c, 0x52, 0x03, 0x88, - 0x09, 0xdf, 0x60, 0x6a, 0x29, 0x61, 0x0d, 0x87, 0x0d, 0xca, 0xd4, 0x50, 0x1e, 0x3a, 0xc4, 0x50, - 0x7e, 0x06, 0x86, 0xd9, 0x0f, 0x25, 0x15, 0xea, 0x0b, 0xad, 0x70, 0x30, 0x96, 0xf8, 0xac, 0x10, - 0x8d, 0x94, 0x14, 0xa2, 0x67, 0x61, 0xa2, 0xee, 0x90, 0xed, 0x30, 0x58, 0x0a, 0xdc, 0x76, 0xe8, - 0x05, 0x09, 0x9a, 0x86, 0x01, 0xb6, 0xa4, 0xf0, 0x19, 0x3f, 0x40, 0x39, 0xe0, 0x01, 0x6a, 0xec, - 0xda, 0xff, 0xd7, 0x82, 0xf1, 0x3a, 0xf1, 0x49, 0x42, 0xee, 0xb4, 0x99, 0xfb, 0x01, 0x2d, 0x03, - 0xda, 0x8c, 0x9c, 0x16, 0x69, 0x90, 0xc8, 0x0b, 0xdd, 0x26, 0x69, 0x85, 0x01, 0x73, 0xb8, 0xd3, - 0x35, 0xf2, 0xdc, 0xfe, 0xde, 0x2c, 0xba, 0xde, 0x85, 0xc5, 0x39, 0x25, 0x90, 0x0b, 0xe3, 0xed, - 0x88, 0x18, 0xfe, 0x12, 0xab, 0xd8, 0x3e, 0x6f, 0xe8, 0x45, 0xb8, 0xf9, 0x68, 0x80, 0xb0, 0xc9, - 0x14, 0x7d, 0x0e, 0xa6, 0xc2, 0xa8, 0xbd, 0xe5, 0x04, 0x75, 0xd2, 0x26, 0x81, 0x4b, 0x6d, 0x66, - 0xe1, 0x14, 0x3b, 0xb3, 0xbf, 0x37, 0x3b, 0x75, 0x27, 0x83, 0xc3, 0x5d, 0xd4, 0xf6, 0x2f, 0x57, - 0xe0, 0x6c, 0x3d, 0x7c, 0x10, 0x3c, 0x70, 0x22, 0x77, 0xbe, 0xb1, 0xc2, 0x0d, 0x61, 0xe6, 0x64, - 0x94, 0xce, 0x4d, 0xab, 0xa7, 0x73, 0xf3, 0x4b, 0x30, 0xb2, 0xe1, 0x11, 0xdf, 0xc5, 0x64, 0x43, - 0x74, 0xef, 0x6a, 0x19, 0x8f, 0xc6, 0x32, 0x2d, 0x23, 0xbd, 0x02, 0xdc, 0xb7, 0xba, 0x2c, 0xd8, - 0x60, 0xc5, 0x10, 0x75, 0x60, 0x4a, 0x5a, 0xfa, 0x12, 0x2b, 0x66, 0xc7, 0x0b, 0xe5, 0x36, 0x12, - 0x66, 0x35, 0x6c, 0x3c, 0x70, 0x86, 0x21, 0xee, 0xaa, 0x82, 0xee, 0xd0, 0xb6, 0xe9, 0xea, 0x30, - 0xc0, 0x64, 0x85, 0xed, 0xd0, 0xd8, 0x16, 0x92, 0x41, 0xed, 0x7f, 0x64, 0xc1, 0x63, 0x5d, 0xa3, - 0x25, 0xf6, 0xd7, 0x6f, 0xc9, 0x8d, 0x2d, 0x3f, 0x9d, 0x29, 0x68, 0x65, 0xee, 0x98, 0x97, 0xdb, - 0xe4, 0x56, 0x4a, 0x6c, 0x72, 0xef, 0xc0, 0x99, 0xa5, 0xed, 0x76, 0xb2, 0x5b, 0xf7, 0x4c, 0x9f, - 0xec, 0xcb, 0x30, 0xb4, 0x4d, 0x5c, 0xaf, 0xb3, 0x2d, 0x3e, 0xeb, 0xac, 0x54, 0xa4, 0xab, 0x0c, - 0x7a, 0xb0, 0x37, 0x3b, 0xde, 0x4c, 0xc2, 0xc8, 0xd9, 0x24, 0x1c, 0x80, 0x05, 0xb9, 0xfd, 0x81, - 0x05, 0x93, 0x72, 0x42, 0xcd, 0xbb, 0x6e, 0x44, 0xe2, 0x18, 0xcd, 0x40, 0xc5, 0x6b, 0x0b, 0x46, - 0x20, 0x18, 0x55, 0x56, 0x1a, 0xb8, 0xe2, 0xb5, 0xd1, 0x17, 0xa1, 0xc6, 0x5d, 0xf9, 0xa9, 0x70, - 0xf4, 0x79, 0x34, 0xc0, 0x76, 0x1f, 0x6b, 0x92, 0x07, 0x4e, 0xd9, 0x49, 0xcb, 0x92, 0xa9, 0xea, - 0xaa, 0xe9, 0x58, 0xbe, 0x21, 0xe0, 0x58, 0x51, 0xa0, 0x4b, 0x30, 0x12, 0x84, 0x2e, 0x3f, 0x65, - 0xe1, 0xcb, 0x2e, 0x13, 0xb9, 0xdb, 0x02, 0x86, 0x15, 0xd6, 0xfe, 0x86, 0x05, 0x63, 0xb2, 0x8f, - 0x25, 0x8d, 0x5c, 0x3a, 0x49, 0x52, 0x03, 0x37, 0x9d, 0x24, 0xd4, 0x48, 0x65, 0x18, 0xc3, 0x36, - 0xad, 0xf6, 0x63, 0x9b, 0xda, 0xdf, 0xaf, 0xc0, 0x84, 0x6c, 0x4e, 0xb3, 0xb3, 0x1e, 0x93, 0x04, - 0xbd, 0x03, 0x35, 0x87, 0x0f, 0x3e, 0x91, 0x72, 0xf6, 0x7c, 0xd1, 0x0e, 0xdd, 0xf8, 0x66, 0xa9, - 0x61, 0x30, 0x2f, 0xf9, 0xe0, 0x94, 0x25, 0xda, 0x81, 0x53, 0x41, 0x98, 0xb0, 0xf5, 0x40, 0xe1, - 0xcb, 0x79, 0x44, 0xb3, 0xf5, 0x3c, 0x2e, 0xea, 0x39, 0x75, 0x3b, 0xcb, 0x0f, 0x77, 0x57, 0x81, - 0xee, 0x48, 0x2f, 0x46, 0x95, 0xd5, 0xf5, 0x6c, 0xb9, 0xba, 0x7a, 0x3b, 0x31, 0xec, 0x1f, 0x5a, - 0x50, 0x93, 0x64, 0xc7, 0xe9, 0x13, 0xbf, 0x07, 0xc3, 0x31, 0xfb, 0x34, 0x72, 0x98, 0x2e, 0x97, - 0x6b, 0x3a, 0xff, 0x9e, 0xe9, 0xe2, 0xc7, 0xff, 0xc7, 0x58, 0x72, 0x63, 0x6e, 0x48, 0xd5, 0x81, - 0x8f, 0x9e, 0x1b, 0x52, 0x35, 0xad, 0x87, 0x1b, 0xf2, 0x97, 0x2c, 0x18, 0xe2, 0xce, 0xa1, 0x72, - 0x1e, 0x36, 0xcd, 0x97, 0x9c, 0x72, 0x7c, 0x93, 0x02, 0x85, 0x6b, 0x19, 0xdd, 0x83, 0x1a, 0xfb, - 0xb1, 0x1c, 0x85, 0xdb, 0x62, 0x21, 0x78, 0xb6, 0x8c, 0x73, 0x8a, 0x2b, 0x3e, 0xae, 0x4d, 0xde, - 0x94, 0x0c, 0x70, 0xca, 0xcb, 0xfe, 0x41, 0x95, 0xce, 0xfa, 0x94, 0xd4, 0x58, 0xd6, 0xac, 0x93, - 0x58, 0xd6, 0x2a, 0xc7, 0xbf, 0xac, 0xbd, 0x07, 0x93, 0x2d, 0xcd, 0x27, 0x9f, 0x2e, 0xa6, 0xd7, - 0x4a, 0xba, 0x9b, 0x35, 0x47, 0x3e, 0x77, 0x86, 0x2c, 0x9a, 0xec, 0x70, 0x96, 0x3f, 0x22, 0x30, - 0xc6, 0x0f, 0x14, 0x45, 0x7d, 0x03, 0x85, 0x32, 0xcb, 0xfd, 0x2e, 0xbc, 0x84, 0xaa, 0x8c, 0x05, - 0x9d, 0x34, 0x35, 0x46, 0xd8, 0x60, 0x6b, 0xff, 0x8d, 0x41, 0x18, 0x5c, 0xda, 0x21, 0x41, 0x72, - 0x8c, 0xb3, 0x7c, 0x1b, 0x26, 0xbc, 0x60, 0x27, 0xf4, 0x77, 0x88, 0xcb, 0xf1, 0x47, 0x5b, 0xd1, - 0xce, 0x89, 0x4a, 0x26, 0x56, 0x0c, 0x66, 0x38, 0xc3, 0xfc, 0x38, 0xf6, 0x93, 0x6f, 0xc0, 0x10, - 0x97, 0x08, 0xb1, 0x99, 0x2c, 0x70, 0x92, 0xb2, 0x01, 0x15, 0x33, 0x27, 0xdd, 0xf5, 0x72, 0xff, - 0xac, 0x60, 0x84, 0xee, 0xc3, 0xc4, 0x86, 0x17, 0xc5, 0x09, 0xdd, 0x10, 0xc6, 0x89, 0xb3, 0xdd, - 0x3e, 0xca, 0x46, 0x52, 0x0d, 0xc9, 0xb2, 0xc1, 0x0a, 0x67, 0x58, 0xa3, 0x2d, 0x18, 0xa7, 0xfb, - 0x98, 0xb4, 0xae, 0xe1, 0xfe, 0xeb, 0x52, 0xbe, 0xa4, 0x5b, 0x3a, 0x27, 0x6c, 0x32, 0xa6, 0xca, - 0xa8, 0xc5, 0x36, 0x3e, 0x23, 0x6c, 0x49, 0x57, 0xca, 0x88, 0xef, 0x78, 0x38, 0x8e, 0xea, 0x34, - 0x76, 0x7e, 0x5c, 0x33, 0x75, 0x5a, 0x7a, 0x4a, 0x6c, 0x7f, 0x97, 0x2e, 0x40, 0x74, 0x14, 0x4f, - 0x42, 0x77, 0xdf, 0x30, 0x75, 0xf7, 0x53, 0x25, 0x3e, 0x6e, 0x0f, 0xbd, 0xfd, 0x65, 0x18, 0xd5, - 0xbe, 0x3d, 0xba, 0x02, 0xb5, 0x96, 0x3c, 0xea, 0x14, 0x0a, 0x5c, 0x19, 0x10, 0xea, 0x0c, 0x14, - 0xa7, 0x34, 0x74, 0x60, 0xa8, 0xe1, 0x95, 0x8d, 0x88, 0xa0, 0x66, 0x19, 0x66, 0x18, 0xfb, 0x05, - 0x80, 0xa5, 0x87, 0xa4, 0x35, 0xdf, 0x62, 0x07, 0xf1, 0xda, 0xb9, 0x89, 0xd5, 0xfb, 0xdc, 0xc4, - 0x7e, 0x1b, 0xc6, 0x97, 0x1e, 0xd2, 0x95, 0x5d, 0x6e, 0xd3, 0x2e, 0xc2, 0x10, 0x61, 0x00, 0xd6, - 0xaa, 0x91, 0x54, 0x48, 0x39, 0x19, 0x16, 0x58, 0x76, 0x8c, 0xfe, 0xd0, 0x11, 0x13, 0x56, 0xdb, - 0xf2, 0x2e, 0x51, 0x20, 0xe6, 0x38, 0xfb, 0x3b, 0x16, 0x4c, 0x2c, 0x2f, 0x1a, 0x76, 0xf2, 0x1c, - 0x00, 0xb7, 0x37, 0xef, 0xdd, 0xbb, 0x2d, 0xfd, 0xa8, 0xdc, 0xd9, 0xa5, 0xa0, 0x58, 0xa3, 0x40, - 0x8f, 0x43, 0xd5, 0xef, 0x04, 0xc2, 0x0c, 0x1c, 0xde, 0xdf, 0x9b, 0xad, 0xde, 0xea, 0x04, 0x98, - 0xc2, 0xb4, 0xc0, 0x86, 0x6a, 0xe9, 0xc0, 0x86, 0xe2, 0xd0, 0xbe, 0x6f, 0x55, 0x61, 0x6a, 0xd9, - 0x27, 0x0f, 0x8d, 0x56, 0x5f, 0x84, 0x21, 0x37, 0xf2, 0x76, 0x48, 0x94, 0x75, 0x93, 0xd4, 0x19, - 0x14, 0x0b, 0x6c, 0xe9, 0x58, 0x0b, 0x23, 0xce, 0xa4, 0x7a, 0xcc, 0x71, 0x26, 0x85, 0x7d, 0x46, - 0x1b, 0x30, 0x1c, 0xf2, 0xef, 0x3f, 0x3d, 0xc8, 0x04, 0xfd, 0xd5, 0xc3, 0x1b, 0x93, 0x1d, 0x9f, - 0x39, 0x21, 0x3d, 0xfc, 0xd0, 0x5b, 0x29, 0x4b, 0x01, 0xc5, 0x92, 0xf9, 0xcc, 0x67, 0x60, 0x4c, - 0xa7, 0xec, 0xeb, 0xf4, 0xfb, 0xe7, 0x2c, 0x38, 0xbd, 0xec, 0x87, 0xad, 0xfb, 0x99, 0x60, 0x98, - 0x97, 0x60, 0x94, 0x4e, 0xd5, 0xd8, 0x88, 0x10, 0x33, 0x42, 0xe1, 0x04, 0x0a, 0xeb, 0x74, 0x5a, - 0xb1, 0xbb, 0x77, 0x57, 0xea, 0x79, 0x11, 0x74, 0x02, 0x85, 0x75, 0x3a, 0xfb, 0x3f, 0x59, 0xf0, - 0xe4, 0xf5, 0xc5, 0xa5, 0x06, 0x55, 0x23, 0x71, 0x42, 0x82, 0xa4, 0x2b, 0x88, 0xef, 0x22, 0x0c, - 0xb5, 0x5d, 0xad, 0x29, 0x4a, 0x04, 0x1a, 0x75, 0xd6, 0x0a, 0x81, 0xfd, 0xa8, 0x44, 0xb2, 0xfe, - 0x92, 0x05, 0xa7, 0xaf, 0x7b, 0x09, 0x26, 0xed, 0x30, 0x1b, 0x77, 0x17, 0x91, 0x76, 0x18, 0x7b, - 0x49, 0x18, 0xed, 0x66, 0xe3, 0xee, 0xb0, 0xc2, 0x60, 0x8d, 0x8a, 0xd7, 0xbc, 0xe3, 0x51, 0x05, - 0x2b, 0x3a, 0xa5, 0xd5, 0xcc, 0xe1, 0x58, 0x51, 0xd0, 0x8e, 0xb9, 0x5e, 0xc4, 0x6c, 0x91, 0x5d, - 0x31, 0x83, 0x55, 0xc7, 0xea, 0x12, 0x81, 0x53, 0x1a, 0xfb, 0xef, 0x58, 0x70, 0xf6, 0xba, 0xdf, - 0x89, 0x13, 0x12, 0x6d, 0xc4, 0x46, 0x63, 0x5f, 0x80, 0x1a, 0x91, 0x76, 0xb3, 0x68, 0xab, 0x5a, - 0x93, 0x94, 0x41, 0xcd, 0x83, 0xfe, 0x14, 0x5d, 0x89, 0x18, 0xb3, 0xfe, 0x22, 0xa2, 0xfe, 0x55, - 0x05, 0xc6, 0x6f, 0xac, 0xad, 0x35, 0xae, 0x93, 0x44, 0xe8, 0xe0, 0x62, 0x47, 0x4f, 0x43, 0xdb, - 0xe5, 0x8e, 0x5e, 0x9b, 0xeb, 0x31, 0xeb, 0x3a, 0x89, 0xe7, 0xcf, 0xf1, 0x18, 0xeb, 0xb9, 0x95, - 0x20, 0xb9, 0x13, 0x35, 0x93, 0xc8, 0x0b, 0x36, 0x73, 0x77, 0xc5, 0x72, 0x9d, 0xa8, 0xf6, 0x5a, - 0x27, 0xd0, 0x0b, 0x30, 0x14, 0xb7, 0xb6, 0x88, 0xda, 0xb4, 0xff, 0x94, 0x32, 0x43, 0x18, 0xf4, - 0x60, 0x6f, 0xb6, 0x76, 0x17, 0xaf, 0xf0, 0x3f, 0x58, 0x90, 0xa2, 0x77, 0x61, 0x74, 0x2b, 0x49, - 0xda, 0x37, 0x88, 0xe3, 0x92, 0x48, 0x6a, 0x89, 0x02, 0x2b, 0x90, 0x0e, 0x06, 0x2f, 0x90, 0x4e, - 0xac, 0x14, 0x16, 0x63, 0x9d, 0xa3, 0xdd, 0x04, 0x48, 0x71, 0x8f, 0x68, 0x6b, 0x63, 0xff, 0xc5, - 0x0a, 0x0c, 0xdf, 0x70, 0x02, 0xd7, 0x27, 0x11, 0x5a, 0x86, 0x01, 0xf2, 0x90, 0xb4, 0xca, 0x19, - 0xb0, 0xe9, 0x42, 0xca, 0x3d, 0x55, 0xf4, 0x3f, 0x66, 0xe5, 0x11, 0x86, 0x61, 0xda, 0xee, 0xeb, - 0x2a, 0x30, 0xf3, 0xb9, 0xe2, 0x51, 0x50, 0x22, 0xc1, 0x57, 0x61, 0x01, 0xc2, 0x92, 0x11, 0xf3, - 0xe9, 0xb4, 0xda, 0x4d, 0xaa, 0xdc, 0x92, 0x72, 0xb1, 0xd7, 0x6b, 0x8b, 0x0d, 0x4e, 0x2e, 0xf8, - 0x72, 0x9f, 0x8e, 0x04, 0xe2, 0x94, 0x9d, 0xfd, 0x0a, 0x9c, 0x61, 0xa7, 0x82, 0x4e, 0xb2, 0x65, - 0xcc, 0x99, 0x42, 0xe1, 0xb4, 0xff, 0x7e, 0x05, 0x4e, 0xad, 0x34, 0x17, 0x9b, 0xa6, 0x37, 0xee, - 0x15, 0x18, 0xe3, 0xcb, 0x33, 0x15, 0x3a, 0xc7, 0x17, 0xe5, 0x95, 0x1b, 0x7b, 0x4d, 0xc3, 0x61, - 0x83, 0x12, 0x3d, 0x09, 0x55, 0xef, 0xbd, 0x20, 0x1b, 0x1f, 0xb4, 0xf2, 0xc6, 0x6d, 0x4c, 0xe1, - 0x14, 0x4d, 0x57, 0x7a, 0xae, 0xe2, 0x14, 0x5a, 0xad, 0xf6, 0xaf, 0xc3, 0x84, 0x17, 0xb7, 0x62, - 0x6f, 0x25, 0xa0, 0xf3, 0xdf, 0x69, 0x49, 0xf1, 0x4d, 0x6d, 0x7f, 0xda, 0x54, 0x85, 0xc5, 0x19, - 0x6a, 0x4d, 0xdf, 0x0e, 0x96, 0xb6, 0x16, 0x8a, 0x23, 0x34, 0xbf, 0x02, 0x35, 0x15, 0x49, 0x23, - 0x03, 0xa0, 0xac, 0xfc, 0x00, 0xa8, 0x12, 0x0a, 0x47, 0xfa, 0x48, 0xab, 0xb9, 0x3e, 0xd2, 0x7f, - 0x6a, 0x41, 0x1a, 0x34, 0x80, 0x30, 0xd4, 0xda, 0x21, 0x3b, 0x80, 0x88, 0xe4, 0x61, 0xdf, 0xd3, - 0x05, 0x92, 0xc8, 0x67, 0x02, 0x97, 0x95, 0x86, 0x2c, 0x8b, 0x53, 0x36, 0xe8, 0x16, 0x0c, 0xb7, - 0x23, 0xd2, 0x4c, 0x58, 0x98, 0x6f, 0x1f, 0x1c, 0x99, 0x54, 0x37, 0x78, 0x49, 0x2c, 0x59, 0xd8, - 0xbf, 0x6e, 0x01, 0xdc, 0xf2, 0xb6, 0xbd, 0x04, 0x3b, 0xc1, 0x26, 0x39, 0xc6, 0x5d, 0xe4, 0x6d, - 0x18, 0x88, 0xdb, 0xa4, 0x55, 0xee, 0xe8, 0x28, 0x6d, 0x51, 0xb3, 0x4d, 0x5a, 0xe9, 0x67, 0xa0, - 0xff, 0x30, 0xe3, 0x63, 0xff, 0x0a, 0xc0, 0x44, 0x4a, 0x46, 0xcd, 0x78, 0xf4, 0xbc, 0x11, 0xd7, - 0xfa, 0x78, 0x26, 0xae, 0xb5, 0xc6, 0xa8, 0xb5, 0x50, 0xd6, 0x04, 0xaa, 0xdb, 0xce, 0x43, 0xb1, - 0x6b, 0x78, 0xa9, 0x6c, 0x83, 0x68, 0x4d, 0x73, 0xab, 0xce, 0x43, 0x6e, 0x46, 0x3d, 0x27, 0x05, - 0x68, 0xd5, 0x79, 0x78, 0xc0, 0x0f, 0x88, 0xd8, 0x0c, 0xa4, 0xdb, 0x94, 0xaf, 0xff, 0x97, 0xf4, - 0x3f, 0x53, 0x8a, 0xb4, 0x3a, 0x56, 0xab, 0x17, 0x08, 0x57, 0x5f, 0x9f, 0xb5, 0x7a, 0x41, 0xb6, - 0x56, 0x2f, 0x28, 0x51, 0xab, 0x17, 0xa0, 0xf7, 0x2d, 0x18, 0x16, 0x1e, 0x72, 0x16, 0x7e, 0x35, - 0x7a, 0xed, 0xd3, 0x7d, 0x55, 0x2d, 0x5c, 0xed, 0xbc, 0xfa, 0x2b, 0xd2, 0x76, 0x14, 0xd0, 0xc2, - 0x26, 0xc8, 0xaa, 0xd1, 0xb7, 0x2d, 0x98, 0x10, 0xbf, 0x31, 0x79, 0xaf, 0x43, 0xe2, 0x44, 0xac, - 0x52, 0x9f, 0x3b, 0x4a, 0x6b, 0x04, 0x0b, 0xde, 0xa8, 0x9f, 0x96, 0x2a, 0xc6, 0x44, 0x16, 0xb6, - 0x2d, 0xd3, 0x1e, 0xf4, 0x3d, 0x0b, 0xce, 0x6c, 0x3b, 0x0f, 0x79, 0x8d, 0x1c, 0x86, 0x9d, 0xc4, - 0x0b, 0x45, 0x88, 0xd9, 0x72, 0xbf, 0x72, 0xd2, 0xc5, 0x88, 0x37, 0xf7, 0x35, 0x79, 0x6c, 0x99, - 0x47, 0x52, 0xd8, 0xe8, 0xdc, 0x16, 0xce, 0xb8, 0x30, 0x22, 0x05, 0x33, 0xc7, 0x6a, 0x5f, 0xd0, - 0x17, 0xe3, 0xc3, 0x67, 0xa0, 0x74, 0xa0, 0xcd, 0xbd, 0xd1, 0x71, 0x82, 0xc4, 0x4b, 0x76, 0x35, - 0x1b, 0x9f, 0xd5, 0x22, 0x04, 0xf1, 0x18, 0x6b, 0xd9, 0x82, 0x31, 0x5d, 0xe6, 0x8e, 0xb1, 0xa6, - 0x10, 0x4e, 0xe7, 0xc8, 0xd3, 0x31, 0x56, 0xd8, 0x81, 0xc7, 0x7b, 0xca, 0xc5, 0xf1, 0x55, 0x6b, - 0xff, 0xd0, 0xd2, 0x15, 0xe6, 0x49, 0x38, 0x66, 0x56, 0x4d, 0xc7, 0xcc, 0xa5, 0xb2, 0x53, 0xa7, - 0x87, 0x77, 0x66, 0x43, 0x6f, 0x3f, 0x5d, 0x09, 0xd0, 0x1a, 0x0c, 0xf9, 0x14, 0x22, 0x4f, 0x83, - 0x2e, 0xf7, 0x33, 0x39, 0x53, 0xe3, 0x82, 0xc1, 0x63, 0x2c, 0x78, 0xd9, 0xbf, 0x61, 0xc1, 0xc0, - 0x49, 0x0c, 0x4f, 0xc3, 0x1c, 0x9e, 0x5e, 0x26, 0xaa, 0xb8, 0xeb, 0x39, 0x87, 0x9d, 0x07, 0x4b, - 0x0f, 0x13, 0x12, 0xc4, 0xcc, 0x94, 0xcc, 0x1d, 0xa1, 0x5f, 0xae, 0xc0, 0x28, 0xad, 0x48, 0xfa, - 0x89, 0x5e, 0x85, 0x71, 0xdf, 0x59, 0x27, 0xbe, 0x74, 0x27, 0x67, 0xb7, 0x5d, 0xb7, 0x74, 0x24, - 0x36, 0x69, 0x69, 0xe1, 0x0d, 0xdd, 0xdb, 0x2e, 0x4c, 0x22, 0x55, 0xd8, 0x70, 0xc5, 0x63, 0x93, - 0x96, 0x5a, 0xfe, 0x0f, 0x9c, 0xa4, 0xb5, 0x25, 0xb6, 0x64, 0xaa, 0xb9, 0xf7, 0x28, 0x10, 0x73, - 0x1c, 0x9a, 0x87, 0x49, 0x29, 0xb1, 0x6f, 0xf2, 0xa1, 0x13, 0xe6, 0xa2, 0xba, 0xa7, 0x87, 0x4d, - 0x34, 0xce, 0xd2, 0xa3, 0xcf, 0xc0, 0x04, 0x1d, 0x9c, 0xb0, 0x93, 0xc8, 0x60, 0x85, 0x41, 0x16, - 0xac, 0xc0, 0x82, 0x43, 0xd7, 0x0c, 0x0c, 0xce, 0x50, 0xda, 0xef, 0xc2, 0xe9, 0x5b, 0xa1, 0xe3, - 0x2e, 0x38, 0xbe, 0x13, 0xb4, 0x48, 0xb4, 0x12, 0x6c, 0x16, 0x9e, 0xeb, 0xea, 0x67, 0xaf, 0x95, - 0xa2, 0xb3, 0x57, 0x3b, 0x02, 0xa4, 0x57, 0x20, 0xc2, 0x6c, 0xde, 0x86, 0x61, 0x8f, 0x57, 0x25, - 0xa4, 0xf6, 0x6a, 0x91, 0x53, 0xa9, 0xab, 0x8d, 0x5a, 0xd8, 0x08, 0x07, 0x60, 0xc9, 0x92, 0xee, - 0x24, 0xf2, 0xbc, 0x50, 0xc5, 0x9b, 0x35, 0xfb, 0xaf, 0x58, 0x30, 0x79, 0x3b, 0x73, 0x19, 0xec, - 0x22, 0x0c, 0xc5, 0x24, 0xca, 0x71, 0xa9, 0x35, 0x19, 0x14, 0x0b, 0xec, 0x23, 0xdf, 0xa6, 0xff, - 0x42, 0x05, 0x6a, 0x2c, 0x66, 0xb3, 0xed, 0xb4, 0x8e, 0xd3, 0x28, 0x5d, 0x35, 0x8c, 0xd2, 0x82, - 0x4d, 0xa2, 0x6a, 0x50, 0x2f, 0x9b, 0x14, 0xdd, 0x55, 0x97, 0xa3, 0x4a, 0xed, 0x0f, 0x53, 0x86, - 0xfc, 0x1e, 0xcd, 0x84, 0x79, 0x97, 0x4a, 0x5e, 0x9c, 0x62, 0xa7, 0xa1, 0x8a, 0xf6, 0xa3, 0x77, - 0x1a, 0xaa, 0x9a, 0xd6, 0x43, 0x2b, 0x35, 0xb4, 0xd6, 0x33, 0xb5, 0xfd, 0x59, 0x16, 0x80, 0xe7, - 0xf8, 0xde, 0x57, 0x89, 0xba, 0x64, 0x38, 0x2b, 0xe2, 0xe9, 0x04, 0xf4, 0x80, 0x29, 0x18, 0xf1, - 0x8f, 0xdf, 0x1d, 0x4d, 0x8b, 0xd8, 0x37, 0x60, 0x32, 0x33, 0x76, 0xe8, 0x25, 0x18, 0x6c, 0x6f, - 0x39, 0x31, 0xc9, 0x44, 0x76, 0x0c, 0x36, 0x28, 0xf0, 0x60, 0x6f, 0x76, 0x42, 0x15, 0x60, 0x10, - 0xcc, 0xa9, 0xed, 0x3f, 0xb6, 0x60, 0xe0, 0x76, 0xe8, 0x1e, 0xa7, 0x8c, 0xdd, 0x30, 0x64, 0xec, - 0x62, 0xf1, 0x8d, 0xf3, 0x9e, 0xe2, 0xd5, 0xc8, 0x88, 0xd7, 0xa5, 0x12, 0xbc, 0x0e, 0x97, 0xac, - 0x6d, 0x18, 0x65, 0x37, 0xda, 0x45, 0x48, 0xcb, 0x0b, 0xc6, 0x06, 0x6a, 0x36, 0xb3, 0x81, 0x9a, - 0xd4, 0x48, 0xb5, 0x6d, 0xd4, 0x33, 0x30, 0x2c, 0x42, 0x28, 0xb2, 0x51, 0x87, 0x82, 0x16, 0x4b, - 0xbc, 0xfd, 0x6b, 0x55, 0x30, 0x6e, 0xd0, 0xa3, 0x1f, 0x59, 0x30, 0x17, 0xf1, 0x2b, 0x0f, 0x6e, - 0xbd, 0x13, 0x79, 0xc1, 0x66, 0xb3, 0xb5, 0x45, 0xdc, 0x8e, 0xef, 0x05, 0x9b, 0x2b, 0x9b, 0x41, - 0xa8, 0xc0, 0x4b, 0x0f, 0x49, 0xab, 0xc3, 0xbc, 0xab, 0xa5, 0x2f, 0xee, 0xab, 0x33, 0xd4, 0x6b, - 0xfb, 0x7b, 0xb3, 0x73, 0xb8, 0xaf, 0x5a, 0x70, 0x9f, 0xad, 0x42, 0xbf, 0x67, 0xc1, 0x15, 0x7e, - 0x87, 0xbc, 0x7c, 0x4f, 0x4a, 0x6d, 0x3c, 0x1b, 0x92, 0x69, 0xca, 0x6e, 0x8d, 0x44, 0xdb, 0x0b, - 0x2f, 0x8b, 0x41, 0xbe, 0xd2, 0xe8, 0xaf, 0x56, 0xdc, 0x6f, 0x33, 0xed, 0x7f, 0x53, 0x85, 0x71, - 0x3a, 0x9e, 0xe9, 0xfd, 0xd1, 0x97, 0x0c, 0x31, 0xf9, 0x78, 0x46, 0x4c, 0x4e, 0x19, 0xc4, 0x8f, - 0xe6, 0xea, 0x68, 0x02, 0xa7, 0x7c, 0x27, 0x4e, 0x6e, 0x10, 0x27, 0x4a, 0xd6, 0x89, 0xc3, 0x0e, - 0x2c, 0xc5, 0x24, 0xe8, 0xeb, 0x10, 0x54, 0xc5, 0xe5, 0xdc, 0xca, 0x72, 0xc3, 0xdd, 0x15, 0xa0, - 0x07, 0x80, 0xd8, 0xe9, 0x68, 0xe4, 0x04, 0x31, 0xef, 0x8c, 0x27, 0x1c, 0xb2, 0x7d, 0x56, 0x3b, - 0x23, 0xaa, 0x45, 0xb7, 0xba, 0xd8, 0xe1, 0x9c, 0x2a, 0xb4, 0x23, 0xf0, 0xc1, 0xb2, 0x47, 0xe0, - 0x43, 0x05, 0x01, 0xbf, 0x3f, 0x6f, 0xc1, 0x69, 0xfa, 0x61, 0xcc, 0xe0, 0xd0, 0x18, 0x85, 0x30, - 0x49, 0x7b, 0xe0, 0x93, 0x44, 0xc2, 0xc4, 0x0c, 0x2b, 0xb0, 0xa5, 0x4d, 0x3e, 0xa9, 0xc5, 0x76, - 0xd3, 0x64, 0x86, 0xb3, 0xdc, 0xed, 0x5f, 0xb3, 0x80, 0x45, 0x9f, 0x9d, 0xc4, 0x3a, 0x76, 0xdd, - 0x5c, 0xc7, 0xec, 0x62, 0xa5, 0xd1, 0x63, 0x09, 0x7b, 0x11, 0xa6, 0x28, 0xb6, 0x11, 0x85, 0x0f, - 0x77, 0xa5, 0x71, 0x5d, 0xec, 0x9b, 0xfd, 0xcb, 0x16, 0x57, 0x77, 0xca, 0x2a, 0x7e, 0x00, 0xa7, - 0x02, 0xed, 0x3f, 0x9d, 0xc8, 0xd2, 0x08, 0x9c, 0x2b, 0xaf, 0xd0, 0xd8, 0xfc, 0xd7, 0x22, 0xcc, - 0x32, 0x0c, 0x71, 0x77, 0x1d, 0xf6, 0x3f, 0xb0, 0xe0, 0x31, 0x9d, 0x50, 0xbb, 0x66, 0x56, 0xe4, - 0x10, 0xad, 0xc3, 0x48, 0xd8, 0x26, 0x91, 0x93, 0xee, 0x00, 0x2e, 0xc9, 0x11, 0xbf, 0x23, 0xe0, - 0x07, 0x7b, 0xb3, 0x67, 0x74, 0xee, 0x12, 0x8e, 0x55, 0x49, 0x64, 0xc3, 0x10, 0xdb, 0x89, 0xc6, - 0xe2, 0x82, 0x20, 0xcb, 0x44, 0xc1, 0x8e, 0x01, 0x62, 0x2c, 0x30, 0xf6, 0x5f, 0xb5, 0xf8, 0x28, - 0xeb, 0x4d, 0x47, 0x5f, 0x83, 0xa9, 0x6d, 0xba, 0x59, 0x58, 0x7a, 0xd8, 0xa6, 0x4b, 0x08, 0x3b, - 0xfe, 0xb4, 0xca, 0x28, 0xce, 0x1e, 0xdd, 0x5d, 0x98, 0x16, 0xad, 0x9f, 0x5a, 0xcd, 0xb0, 0xc5, - 0x5d, 0x15, 0xd9, 0xbf, 0x2f, 0x64, 0x95, 0x59, 0x2d, 0xcf, 0xc0, 0x70, 0x3b, 0x74, 0x17, 0x57, - 0xea, 0x58, 0x8c, 0x95, 0x9a, 0x6c, 0x0d, 0x0e, 0xc6, 0x12, 0x8f, 0xae, 0x01, 0x90, 0x87, 0x09, - 0x89, 0x02, 0xc7, 0x57, 0xc7, 0x96, 0xca, 0x48, 0x58, 0x52, 0x18, 0xac, 0x51, 0xd1, 0x32, 0xed, - 0x28, 0xdc, 0xf1, 0x5c, 0x16, 0xee, 0x5d, 0x35, 0xcb, 0x34, 0x14, 0x06, 0x6b, 0x54, 0x74, 0x8b, - 0xd6, 0x09, 0x62, 0xae, 0xc0, 0x9d, 0x75, 0x91, 0x40, 0x61, 0x24, 0xdd, 0xa2, 0xdd, 0xd5, 0x91, - 0xd8, 0xa4, 0xb5, 0x7f, 0xbb, 0x06, 0x90, 0x9a, 0x08, 0xe8, 0x7d, 0x0b, 0x46, 0x5a, 0x4e, 0xdb, - 0x69, 0xf1, 0xec, 0x38, 0xd5, 0xe2, 0x7b, 0x31, 0x69, 0xe1, 0xb9, 0x45, 0x51, 0x90, 0xfb, 0xb6, - 0x3e, 0x25, 0x05, 0x44, 0x82, 0x0b, 0xfd, 0x59, 0xaa, 0x66, 0xf4, 0x4d, 0x0b, 0x46, 0x1d, 0xdf, - 0x0f, 0x5b, 0x4e, 0xc2, 0x7a, 0x54, 0x29, 0xe3, 0xac, 0xd4, 0x5a, 0x32, 0x9f, 0x96, 0xe5, 0x8d, - 0x79, 0x41, 0x9e, 0x6a, 0x69, 0x98, 0xc2, 0xf6, 0xe8, 0x4d, 0x40, 0x9f, 0x92, 0xa6, 0x25, 0xff, - 0x28, 0x33, 0x59, 0xd3, 0xb2, 0xc6, 0x54, 0x83, 0x66, 0x55, 0xa2, 0x77, 0x8d, 0x5c, 0x01, 0x03, - 0x65, 0xee, 0xa6, 0x1a, 0x8b, 0x66, 0x51, 0x9a, 0x00, 0xf4, 0x45, 0x3d, 0x12, 0x76, 0xb0, 0xcc, - 0xc5, 0x4f, 0xcd, 0x76, 0x2b, 0x88, 0x82, 0x4d, 0x60, 0xd2, 0x35, 0x17, 0x09, 0x11, 0xda, 0x74, - 0xb5, 0xb8, 0x86, 0xcc, 0xea, 0x92, 0x2e, 0x0b, 0x19, 0x04, 0xce, 0x56, 0x81, 0xbe, 0xc8, 0xe3, - 0x94, 0x57, 0x82, 0x8d, 0x50, 0x44, 0x37, 0x5d, 0x2e, 0xf1, 0xcd, 0x77, 0xe3, 0x84, 0x6c, 0xd3, - 0x32, 0xe9, 0x32, 0x70, 0x5b, 0x70, 0xc1, 0x8a, 0x1f, 0x5a, 0x83, 0x21, 0x76, 0xab, 0x22, 0x9e, - 0x1e, 0x29, 0xe3, 0x26, 0x32, 0xef, 0x13, 0xa6, 0x8b, 0x2f, 0xfb, 0x1b, 0x63, 0xc1, 0x0b, 0xdd, - 0x90, 0xf7, 0x6f, 0xe3, 0x95, 0xe0, 0x6e, 0x4c, 0xd8, 0xfd, 0xdb, 0xda, 0xc2, 0x27, 0xd2, 0x0b, - 0xb5, 0x1c, 0x9e, 0x9b, 0x1d, 0xc9, 0x28, 0x49, 0xd7, 0x60, 0xf1, 0x5f, 0x26, 0x5d, 0x9a, 0x86, - 0x32, 0x0d, 0x35, 0x53, 0x34, 0xa5, 0x83, 0xfd, 0xa6, 0xc9, 0x0c, 0x67, 0xb9, 0xcf, 0x78, 0x30, - 0x6e, 0xcc, 0xd8, 0x63, 0x74, 0x76, 0xfa, 0x30, 0x95, 0x9d, 0x92, 0xc7, 0xe8, 0xe3, 0xfc, 0xa3, - 0x01, 0x98, 0x30, 0x05, 0x03, 0x5d, 0x81, 0xda, 0x36, 0x4b, 0x89, 0x94, 0x26, 0x62, 0x51, 0xf2, - 0xbf, 0x2a, 0x11, 0x38, 0xa5, 0x61, 0x29, 0x69, 0x58, 0x71, 0x2d, 0xe6, 0x24, 0x4d, 0x49, 0xa3, - 0x30, 0x58, 0xa3, 0xa2, 0x06, 0xdb, 0x7a, 0x18, 0x26, 0x4a, 0x71, 0x2b, 0x99, 0x59, 0x60, 0x50, - 0x2c, 0xb0, 0x54, 0x61, 0xdf, 0xa7, 0x1d, 0xf2, 0x4d, 0x7f, 0x97, 0x52, 0xd8, 0x37, 0x75, 0x24, - 0x36, 0x69, 0xe9, 0x02, 0x14, 0xc6, 0x4c, 0x08, 0x85, 0x59, 0x98, 0xc6, 0xf0, 0x34, 0xf9, 0x2d, - 0x23, 0x89, 0x47, 0x5f, 0x80, 0xc7, 0xd4, 0xa5, 0x20, 0xcc, 0xfd, 0x87, 0xb2, 0xc6, 0x21, 0x63, - 0x6f, 0xf7, 0xd8, 0x62, 0x3e, 0x19, 0xee, 0x55, 0x1e, 0xbd, 0x0e, 0x13, 0xc2, 0xa4, 0x93, 0x1c, - 0x87, 0xcd, 0x23, 0xde, 0x9b, 0x06, 0x16, 0x67, 0xa8, 0x51, 0x1d, 0xa6, 0x28, 0x84, 0x99, 0x52, - 0x92, 0x03, 0xbf, 0xdc, 0xa4, 0x56, 0xe6, 0x9b, 0x19, 0x3c, 0xee, 0x2a, 0x81, 0xe6, 0x61, 0x92, - 0xdb, 0x16, 0x74, 0x07, 0xc3, 0xbe, 0x83, 0x88, 0x46, 0x54, 0x93, 0xe0, 0x8e, 0x89, 0xc6, 0x59, - 0x7a, 0xf4, 0x0a, 0x8c, 0x39, 0x51, 0x6b, 0xcb, 0x4b, 0x48, 0x2b, 0xe9, 0x44, 0xfc, 0x66, 0xbb, - 0x76, 0x46, 0x3e, 0xaf, 0xe1, 0xb0, 0x41, 0x69, 0x7f, 0x15, 0x4e, 0xe7, 0x04, 0x3d, 0x53, 0xc1, - 0x71, 0xda, 0x9e, 0xec, 0x53, 0x26, 0x1a, 0x67, 0xbe, 0xb1, 0x22, 0x7b, 0xa3, 0x51, 0x51, 0xe9, - 0x64, 0x8e, 0x53, 0x2d, 0x3f, 0x9a, 0x92, 0xce, 0x65, 0x89, 0xc0, 0x29, 0x8d, 0xfd, 0xdf, 0x6b, - 0xa0, 0xb9, 0x19, 0x4a, 0xc4, 0x60, 0xbc, 0x02, 0x63, 0x32, 0xe5, 0x9f, 0x96, 0x6a, 0x4b, 0x75, - 0xf3, 0xba, 0x86, 0xc3, 0x06, 0x25, 0x6d, 0x5b, 0x20, 0x9d, 0x26, 0xd9, 0xd8, 0x1f, 0xe5, 0x4d, - 0xc1, 0x29, 0x0d, 0xba, 0x0c, 0x23, 0x31, 0xf1, 0x37, 0x6e, 0x79, 0xc1, 0x7d, 0x21, 0xd8, 0x4a, - 0x2b, 0x37, 0x05, 0x1c, 0x2b, 0x0a, 0xf4, 0x39, 0xa8, 0x76, 0x3c, 0x57, 0x88, 0xf2, 0x9c, 0xb4, - 0x3b, 0xef, 0xae, 0xd4, 0x0f, 0xf6, 0x66, 0x67, 0xf3, 0xf3, 0x18, 0xd2, 0x6d, 0x64, 0x3c, 0x47, - 0x27, 0x1f, 0x2d, 0x9a, 0xe7, 0x3f, 0x1e, 0xea, 0xd3, 0x7f, 0x7c, 0x0d, 0x40, 0xf4, 0x59, 0x4a, - 0x72, 0x35, 0xfd, 0x66, 0xd7, 0x15, 0x06, 0x6b, 0x54, 0x74, 0x33, 0xda, 0x8a, 0x88, 0x23, 0x77, - 0x6b, 0x3c, 0x22, 0x77, 0xe4, 0x43, 0x6c, 0x46, 0x17, 0xb3, 0xdc, 0x70, 0x77, 0x05, 0xa8, 0x0d, - 0xa7, 0x5c, 0x3a, 0x8f, 0x8c, 0x5a, 0x6b, 0x47, 0x88, 0x03, 0xa6, 0x35, 0xd6, 0xb3, 0x9c, 0x70, - 0x37, 0x73, 0xf4, 0x0e, 0xcc, 0x48, 0x60, 0xf7, 0xb5, 0x3f, 0x36, 0x5d, 0xaa, 0x0b, 0xe7, 0xf7, - 0xf7, 0x66, 0x67, 0xea, 0x3d, 0xa9, 0xf0, 0x21, 0x1c, 0xd0, 0xdb, 0x30, 0xc4, 0x4e, 0x1c, 0xe2, - 0xe9, 0x51, 0xb6, 0xda, 0xbd, 0x58, 0xd6, 0xe1, 0x36, 0xc7, 0xce, 0x2d, 0x44, 0x20, 0x63, 0x7a, - 0x8a, 0xc3, 0x80, 0x58, 0xf0, 0x44, 0x6d, 0x18, 0x75, 0x82, 0x20, 0x4c, 0x1c, 0x6e, 0x84, 0x8d, - 0x95, 0xb1, 0x23, 0xb5, 0x2a, 0xe6, 0xd3, 0xb2, 0xbc, 0x1e, 0x15, 0x1d, 0xa5, 0x61, 0xb0, 0x5e, - 0x05, 0x5d, 0xc6, 0xc3, 0x07, 0x54, 0x61, 0x4a, 0xa7, 0x7b, 0x3c, 0x3d, 0x5e, 0x66, 0x19, 0xbf, - 0x63, 0x14, 0xd2, 0x34, 0x98, 0xc9, 0x0c, 0x67, 0xb9, 0xa3, 0x39, 0xc3, 0x8f, 0x3a, 0x91, 0x86, - 0xe9, 0xa6, 0x7e, 0x54, 0xdd, 0x6d, 0xca, 0xae, 0x94, 0xf2, 0xd0, 0x3c, 0xa6, 0x09, 0x26, 0x33, - 0x57, 0x4a, 0x53, 0x14, 0xd6, 0xe9, 0x66, 0x3e, 0x0d, 0xa3, 0xda, 0x80, 0xf7, 0x13, 0x0f, 0x3a, - 0xf3, 0x3a, 0x4c, 0x65, 0x07, 0xb2, 0xaf, 0x78, 0xd2, 0xff, 0x59, 0x81, 0xc9, 0x9c, 0x93, 0x8c, - 0xfb, 0x1e, 0x8b, 0x98, 0x36, 0x54, 0xde, 0x4d, 0x2f, 0x70, 0x31, 0xc3, 0x98, 0x8a, 0xab, 0x52, - 0x42, 0x71, 0x49, 0x2d, 0x5a, 0xed, 0xa9, 0x45, 0x85, 0xb2, 0x1a, 0x38, 0xba, 0xb2, 0x32, 0x57, - 0x87, 0xc1, 0x52, 0xab, 0xc3, 0x23, 0x50, 0x70, 0xc6, 0x02, 0x33, 0x5c, 0x62, 0x81, 0x39, 0xb0, - 0x60, 0xc2, 0x94, 0xbc, 0x12, 0x23, 0xfe, 0x51, 0x1d, 0xc0, 0x39, 0xb6, 0x11, 0x4b, 0xa2, 0xd0, - 0xf7, 0x49, 0x24, 0x22, 0xc5, 0x26, 0xc4, 0xbe, 0x4a, 0x40, 0xb1, 0x46, 0x61, 0x7f, 0xbb, 0x02, - 0x53, 0x69, 0xd8, 0xb0, 0x48, 0x7d, 0x7a, 0x7c, 0x47, 0x03, 0x6b, 0xc6, 0xd1, 0x40, 0x51, 0x46, - 0xd3, 0x4c, 0xbb, 0x7a, 0x1e, 0x13, 0xbc, 0x9d, 0x39, 0x26, 0x78, 0xb1, 0x4f, 0xbe, 0x87, 0x1f, - 0x19, 0xfc, 0xb3, 0x0a, 0x9c, 0xcd, 0x16, 0x59, 0xf4, 0x1d, 0x6f, 0xfb, 0x18, 0xc7, 0xe9, 0x0b, - 0xc6, 0x38, 0xbd, 0xdc, 0x5f, 0x7f, 0x58, 0xe3, 0x7a, 0x0e, 0x96, 0x93, 0x19, 0xac, 0x4f, 0x1f, - 0x85, 0xf9, 0xe1, 0x23, 0xf6, 0x3b, 0x16, 0x3c, 0x9e, 0x5b, 0xee, 0x24, 0x5c, 0xa0, 0x6f, 0x99, - 0x2e, 0xd0, 0x17, 0x8e, 0xd0, 0xbd, 0x1e, 0x3e, 0xd1, 0xff, 0x5a, 0xe9, 0xd1, 0x2d, 0xe6, 0x2d, - 0xbb, 0x03, 0xa3, 0x4e, 0xab, 0x45, 0xe2, 0x78, 0x35, 0x74, 0x55, 0x2e, 0x9e, 0xe7, 0xd9, 0xfa, - 0x99, 0x82, 0x0f, 0xf6, 0x66, 0x67, 0xb2, 0x2c, 0x52, 0x34, 0xd6, 0x39, 0x98, 0x39, 0xb5, 0x2a, - 0xc7, 0x94, 0x53, 0xeb, 0x1a, 0xc0, 0x8e, 0xda, 0xa5, 0x67, 0x9d, 0x70, 0xda, 0xfe, 0x5d, 0xa3, - 0x42, 0xef, 0x30, 0xab, 0x97, 0x87, 0x48, 0x0c, 0x14, 0x4e, 0x38, 0xe3, 0x03, 0xea, 0xf1, 0x16, - 0xfc, 0xce, 0xa4, 0xf2, 0x58, 0x2a, 0x9e, 0xf6, 0x77, 0xab, 0xf0, 0x53, 0x87, 0x88, 0x1d, 0x9a, - 0x37, 0x4f, 0x3e, 0x9f, 0xcb, 0xba, 0xa7, 0x66, 0x72, 0x0b, 0x1b, 0xfe, 0xaa, 0xcc, 0xc7, 0xaa, - 0x7c, 0xe8, 0x8f, 0xf5, 0x2d, 0xdd, 0x99, 0xc8, 0x43, 0x1d, 0xaf, 0x1f, 0x79, 0x62, 0x3d, 0x3a, - 0xef, 0xe2, 0x09, 0x3a, 0x3e, 0xec, 0xaf, 0x5b, 0xf0, 0xf1, 0xdc, 0x4e, 0x19, 0x01, 0x16, 0x57, - 0xa0, 0xd6, 0xa2, 0x40, 0xed, 0x2e, 0x4a, 0x7a, 0xc5, 0x4c, 0x22, 0x70, 0x4a, 0x63, 0xc4, 0x51, - 0x54, 0x0a, 0xe3, 0x28, 0xfe, 0xbd, 0x05, 0x67, 0xb2, 0x8d, 0x38, 0x09, 0xad, 0xd3, 0x34, 0xb5, - 0xce, 0x5c, 0x7f, 0xdf, 0xbe, 0x87, 0xc2, 0xf9, 0xf6, 0x38, 0x9c, 0xeb, 0x5a, 0xac, 0xf8, 0x30, - 0xfe, 0xac, 0x05, 0xa7, 0x36, 0xd9, 0xfe, 0x42, 0xbb, 0xf1, 0x23, 0x3a, 0x56, 0x70, 0x4d, 0xea, - 0xd0, 0x8b, 0x42, 0x7c, 0xb7, 0xd4, 0x45, 0x82, 0xbb, 0x2b, 0x43, 0xdf, 0xb0, 0xe0, 0x8c, 0xf3, - 0x20, 0xee, 0xca, 0xa3, 0x2f, 0xe4, 0xe8, 0xf5, 0x02, 0x57, 0x5e, 0x41, 0x06, 0xfe, 0x85, 0xe9, - 0xfd, 0xbd, 0xd9, 0x33, 0x79, 0x54, 0x38, 0xb7, 0x56, 0xf4, 0xb6, 0xc8, 0x3f, 0x46, 0xcd, 0xbe, - 0x52, 0x77, 0xd7, 0xf2, 0xee, 0x1f, 0x70, 0x9d, 0x24, 0x31, 0x58, 0x71, 0x44, 0x5f, 0x86, 0xda, - 0xa6, 0xbc, 0xe4, 0x23, 0x94, 0x5e, 0xc1, 0xca, 0x92, 0x7b, 0x27, 0x88, 0x47, 0xb9, 0x2b, 0x14, - 0x4e, 0x99, 0xa2, 0x1b, 0x50, 0x0d, 0x36, 0x62, 0x71, 0x5f, 0xb7, 0x28, 0x8e, 0xc6, 0x8c, 0x5a, - 0xe2, 0x37, 0x10, 0x6f, 0x2f, 0x37, 0x31, 0x65, 0x41, 0x39, 0x45, 0xeb, 0xae, 0xf0, 0x61, 0x17, - 0x70, 0xc2, 0x0b, 0xf5, 0x6e, 0x4e, 0x78, 0xa1, 0x8e, 0x29, 0x0b, 0x16, 0xb0, 0x17, 0xb7, 0x62, - 0x4f, 0x38, 0xa8, 0x0b, 0x2e, 0x73, 0x77, 0xdd, 0xca, 0xe0, 0xa9, 0xe8, 0x18, 0x18, 0x73, 0x46, - 0x68, 0x0d, 0x86, 0x5a, 0x2c, 0x75, 0xb4, 0xf0, 0x1f, 0x14, 0x25, 0x14, 0xee, 0x4a, 0x33, 0xcd, - 0x0f, 0xd2, 0x38, 0x1c, 0x0b, 0x5e, 0x8c, 0x2b, 0x69, 0x6f, 0x6d, 0xc4, 0xc2, 0x3f, 0x50, 0xc4, - 0xb5, 0x2b, 0x09, 0xb8, 0xe0, 0xca, 0xe0, 0x58, 0xf0, 0x42, 0x75, 0xa8, 0x6c, 0xb4, 0x44, 0xfe, - 0xc7, 0x82, 0x1d, 0xad, 0x79, 0x9d, 0x74, 0x61, 0x68, 0x7f, 0x6f, 0xb6, 0xb2, 0xbc, 0x88, 0x2b, - 0x1b, 0x2d, 0xf4, 0x16, 0x0c, 0x6f, 0xf0, 0x0b, 0x82, 0x22, 0xd7, 0xe3, 0xd5, 0xa2, 0x5b, 0x8c, - 0x5d, 0xb7, 0x09, 0xf9, 0x4d, 0x06, 0x81, 0xc0, 0x92, 0x1d, 0x7a, 0x07, 0x60, 0x43, 0x5d, 0x79, - 0x14, 0xc9, 0x1e, 0xe7, 0xfa, 0xbb, 0x22, 0x29, 0x76, 0xcf, 0x0a, 0x8a, 0x35, 0x8e, 0x54, 0xe6, - 0x1d, 0x99, 0xfd, 0x9e, 0x25, 0x7a, 0x2c, 0x94, 0xf9, 0xdc, 0x64, 0xf9, 0x5c, 0xe6, 0x15, 0x0a, - 0xa7, 0x4c, 0x51, 0x07, 0xc6, 0x77, 0xe2, 0xf6, 0x16, 0x91, 0x53, 0x9f, 0x65, 0x7f, 0x1c, 0xbd, - 0xf6, 0x5a, 0x41, 0x4a, 0x4f, 0x51, 0xc4, 0x8b, 0x92, 0x8e, 0xe3, 0x77, 0x69, 0x30, 0x96, 0x46, - 0xe9, 0x4d, 0x9d, 0x2d, 0x36, 0x6b, 0xa1, 0x9f, 0xe4, 0xbd, 0x4e, 0xb8, 0xbe, 0x9b, 0x10, 0x91, - 0x1d, 0xb2, 0xe0, 0x93, 0xbc, 0xc1, 0x89, 0xbb, 0x3f, 0x89, 0x40, 0x60, 0xc9, 0x4e, 0x0d, 0x19, - 0xd3, 0xc6, 0x53, 0xa5, 0x87, 0xac, 0xab, 0x0f, 0xe9, 0x90, 0x31, 0xed, 0x9b, 0x32, 0x65, 0x5a, - 0xb7, 0xbd, 0x15, 0x26, 0x61, 0x90, 0xd1, 0xfd, 0xa7, 0xca, 0x68, 0xdd, 0x46, 0x4e, 0xc9, 0x6e, - 0xad, 0x9b, 0x47, 0x85, 0x73, 0x6b, 0xb5, 0x7f, 0x7f, 0xb0, 0x7b, 0xbd, 0x65, 0xe6, 0xf0, 0x2f, - 0x76, 0x9f, 0xae, 0x7e, 0xae, 0xff, 0xed, 0xde, 0x23, 0x3c, 0x67, 0xfd, 0x86, 0x05, 0xe7, 0xda, - 0xb9, 0x8b, 0xa9, 0x58, 0xb0, 0xfa, 0xdd, 0x35, 0xf2, 0x01, 0x53, 0xa9, 0x4f, 0xf3, 0xf1, 0xb8, - 0x47, 0x9d, 0x59, 0x0b, 0xb4, 0xfa, 0xa1, 0x2d, 0xd0, 0x7b, 0x30, 0xc2, 0x8c, 0xa6, 0x34, 0xf7, - 0x46, 0x9f, 0xe9, 0x2a, 0xd8, 0xd2, 0xb7, 0x28, 0x58, 0x60, 0xc5, 0x8c, 0x0e, 0xdc, 0x93, 0xd9, - 0x4e, 0x60, 0xc2, 0xd0, 0x22, 0x67, 0x2b, 0x77, 0x4d, 0x2c, 0x8b, 0x91, 0x78, 0xb2, 0x71, 0x18, - 0xf1, 0x41, 0x11, 0x01, 0x3e, 0xbc, 0xb2, 0x93, 0xb4, 0x68, 0xff, 0xb1, 0x95, 0x63, 0x7f, 0xf1, - 0x3d, 0xc8, 0x6b, 0xe6, 0x1e, 0xe4, 0x62, 0x76, 0x0f, 0xd2, 0xe5, 0x31, 0x30, 0xb6, 0x1f, 0xe5, - 0xf3, 0x16, 0x96, 0x4d, 0x0e, 0x62, 0xfb, 0x70, 0xa1, 0x68, 0x72, 0xb3, 0x00, 0x1e, 0x57, 0x1d, - 0x0a, 0xa6, 0x01, 0x3c, 0xee, 0x4a, 0x1d, 0x33, 0x4c, 0xd9, 0xeb, 0xdf, 0xf6, 0xff, 0xb6, 0xa0, - 0xda, 0x08, 0xdd, 0x63, 0xf4, 0x80, 0x5c, 0x37, 0x3c, 0x20, 0x4f, 0x17, 0xbe, 0xf9, 0xd3, 0xd3, - 0xdf, 0x71, 0x27, 0xe3, 0xef, 0xf8, 0x64, 0x31, 0xab, 0xc3, 0xbd, 0x1b, 0xdf, 0xab, 0x82, 0xfe, - 0x6a, 0x11, 0xfa, 0xad, 0xa3, 0x84, 0x74, 0x56, 0xcb, 0x3d, 0x64, 0x24, 0xea, 0x60, 0x01, 0x50, - 0xf2, 0xbe, 0xd7, 0x9f, 0xda, 0xc8, 0xce, 0x7b, 0xc4, 0xdb, 0xdc, 0x4a, 0x88, 0x9b, 0xed, 0xd8, - 0xc9, 0x45, 0x76, 0xfe, 0x37, 0x0b, 0x26, 0x33, 0xb5, 0xa3, 0xed, 0xbc, 0x2b, 0x23, 0x47, 0x75, - 0x69, 0x9c, 0x2a, 0xbc, 0x64, 0x32, 0x07, 0xa0, 0xdc, 0xf0, 0xd2, 0xf1, 0xc0, 0x8c, 0x30, 0xe5, - 0xa7, 0x8f, 0xb1, 0x46, 0x81, 0x5e, 0x82, 0xd1, 0x24, 0x6c, 0x87, 0x7e, 0xb8, 0xb9, 0x7b, 0x93, - 0xc8, 0x8c, 0x04, 0xea, 0x08, 0x63, 0x2d, 0x45, 0x61, 0x9d, 0xce, 0xfe, 0x41, 0x15, 0xb2, 0x8f, - 0x5e, 0xfd, 0x7f, 0x41, 0xfd, 0xd3, 0x23, 0xa8, 0xbf, 0x6b, 0xc1, 0x14, 0xad, 0x9d, 0xc5, 0xaf, - 0xc8, 0xf8, 0x4b, 0x95, 0x6e, 0xdc, 0x3a, 0x24, 0xdd, 0xf8, 0x45, 0xaa, 0xee, 0xdc, 0xb0, 0x23, - 0x53, 0xe0, 0x68, 0x5a, 0x8c, 0x42, 0xb1, 0xc0, 0x0a, 0x3a, 0x12, 0x45, 0xe2, 0x72, 0x8a, 0x4e, - 0x47, 0xa2, 0x08, 0x0b, 0xac, 0xcc, 0x46, 0x3e, 0x90, 0x9f, 0x8d, 0x9c, 0x67, 0x0c, 0x12, 0x71, - 0x13, 0xc2, 0x0e, 0xd0, 0x32, 0x06, 0xc9, 0x80, 0x8a, 0x94, 0xc6, 0xfe, 0x17, 0x55, 0x18, 0x6b, - 0x84, 0x6e, 0x1a, 0x5b, 0xfd, 0xa2, 0x11, 0x5b, 0x7d, 0x21, 0x13, 0x5b, 0x3d, 0xa5, 0xd3, 0x3e, - 0x9a, 0xd0, 0x6a, 0x91, 0x5b, 0x8a, 0xe5, 0xcb, 0x3f, 0x6a, 0x58, 0xb5, 0x91, 0x5b, 0x4a, 0x71, - 0xc2, 0x26, 0xe3, 0x3f, 0x53, 0xe1, 0xd4, 0x7f, 0x6c, 0xc1, 0x44, 0x23, 0x74, 0xa9, 0x88, 0xfe, - 0x59, 0x92, 0x47, 0x3d, 0x23, 0xd5, 0xd0, 0x21, 0x19, 0xa9, 0x7e, 0xd5, 0x82, 0xe1, 0x46, 0xe8, - 0x9e, 0x84, 0x2b, 0x71, 0xd9, 0x74, 0x25, 0x7e, 0xbc, 0x50, 0xf9, 0xf6, 0xf0, 0x1e, 0xfe, 0x46, - 0x15, 0xc6, 0x69, 0x93, 0xc3, 0x4d, 0xf9, 0xc1, 0x8c, 0xc1, 0xb1, 0x4a, 0x0c, 0x0e, 0x35, 0x07, - 0x43, 0xdf, 0x0f, 0x1f, 0x64, 0x3f, 0xde, 0x32, 0x83, 0x62, 0x81, 0x45, 0x97, 0x61, 0xa4, 0x1d, - 0x91, 0x1d, 0x2f, 0xec, 0xc4, 0xd9, 0xbb, 0x6e, 0x0d, 0x01, 0xc7, 0x8a, 0x02, 0xbd, 0x08, 0x63, - 0xb1, 0x17, 0xb4, 0x88, 0x0c, 0xac, 0x18, 0x60, 0x81, 0x15, 0x3c, 0xf1, 0x9f, 0x06, 0xc7, 0x06, - 0x15, 0x7a, 0x0b, 0x6a, 0xec, 0x3f, 0x9b, 0x43, 0x47, 0x48, 0x91, 0xce, 0xb3, 0x52, 0x49, 0x0e, - 0x38, 0x65, 0x86, 0xae, 0x01, 0x24, 0x32, 0x06, 0x24, 0x16, 0x67, 0xa6, 0xca, 0x38, 0x55, 0xd1, - 0x21, 0x31, 0xd6, 0xa8, 0xd0, 0x73, 0x50, 0x4b, 0x1c, 0xcf, 0xbf, 0xe5, 0x05, 0x24, 0x16, 0x51, - 0x34, 0x22, 0x81, 0xad, 0x00, 0xe2, 0x14, 0x4f, 0xd7, 0x7c, 0x76, 0xd3, 0x96, 0x3f, 0xc0, 0x30, - 0xc2, 0xa8, 0xd9, 0x9a, 0x7f, 0x4b, 0x41, 0xb1, 0x46, 0x61, 0xbf, 0xc0, 0xd6, 0xee, 0x3e, 0x63, - 0xef, 0x7f, 0x52, 0x01, 0xd4, 0x60, 0xb1, 0x26, 0xc6, 0x1b, 0x15, 0x5b, 0x30, 0x11, 0x93, 0x5b, - 0x5e, 0xd0, 0x79, 0x28, 0x58, 0x95, 0xbb, 0xed, 0xd0, 0x5c, 0xd2, 0xcb, 0xf0, 0xdb, 0xa5, 0x26, - 0x0c, 0x67, 0xf8, 0xd2, 0x21, 0x89, 0x3a, 0xc1, 0x7c, 0x7c, 0x37, 0x26, 0x91, 0x78, 0x65, 0x82, - 0x0d, 0x09, 0x96, 0x40, 0x9c, 0xe2, 0xa9, 0x0c, 0xb0, 0x3f, 0xb7, 0xc3, 0x00, 0x87, 0x61, 0x22, - 0xa5, 0x86, 0xa5, 0x1c, 0xd7, 0xe0, 0xd8, 0xa0, 0x42, 0xcb, 0x80, 0xe2, 0x4e, 0xbb, 0xed, 0xb3, - 0xa3, 0x2d, 0xc7, 0xbf, 0x1e, 0x85, 0x9d, 0x36, 0x0f, 0x37, 0x16, 0xd9, 0xba, 0x9b, 0x5d, 0x58, - 0x9c, 0x53, 0x82, 0x4e, 0xfa, 0x8d, 0x98, 0xfd, 0x16, 0xb7, 0x67, 0xb9, 0x83, 0xad, 0xc9, 0x40, - 0x58, 0xe2, 0xec, 0x0e, 0x5b, 0xaa, 0x58, 0xf6, 0xff, 0xa4, 0x13, 0x11, 0x44, 0x60, 0xbc, 0xcd, - 0x96, 0x23, 0x79, 0xbe, 0x5e, 0x6a, 0x28, 0x33, 0xd1, 0x2e, 0x3c, 0xcb, 0xb7, 0xce, 0x06, 0x9b, - 0x5c, 0xed, 0xff, 0x08, 0x4c, 0xd7, 0x88, 0x53, 0xc5, 0x61, 0x11, 0xcb, 0x2a, 0x6c, 0xb1, 0x4f, - 0x94, 0x79, 0xee, 0x26, 0xd5, 0xe3, 0x22, 0x32, 0x16, 0x4b, 0x2e, 0xe8, 0x4b, 0x3c, 0x40, 0x80, - 0xcd, 0xef, 0xf2, 0x6f, 0x50, 0x71, 0x7a, 0x23, 0x4a, 0x5b, 0xb0, 0xc0, 0x1a, 0x3b, 0x74, 0x0b, - 0xc6, 0x45, 0x8a, 0x78, 0xe1, 0x19, 0xa8, 0x1a, 0xbb, 0xe3, 0x71, 0xac, 0x23, 0x0f, 0xb2, 0x00, - 0x6c, 0x16, 0x46, 0x9b, 0xf0, 0xa4, 0xf6, 0x6e, 0x4c, 0x4e, 0x44, 0x16, 0x57, 0x1c, 0x1f, 0xdf, - 0xdf, 0x9b, 0x7d, 0x72, 0xed, 0x30, 0x42, 0x7c, 0x38, 0x1f, 0x74, 0x07, 0xce, 0x3a, 0xad, 0xc4, - 0xdb, 0x21, 0x75, 0xe2, 0xb8, 0xbe, 0x17, 0x10, 0xf3, 0x6a, 0xf5, 0xe3, 0xfb, 0x7b, 0xb3, 0x67, - 0xe7, 0xf3, 0x08, 0x70, 0x7e, 0x39, 0xf4, 0x1a, 0xd4, 0xdc, 0x20, 0x16, 0x63, 0x30, 0x64, 0x3c, - 0x91, 0x53, 0xab, 0xdf, 0x6e, 0xaa, 0xfe, 0xa7, 0x7f, 0x70, 0x5a, 0x00, 0xbd, 0xc7, 0x5f, 0xee, - 0x55, 0x1b, 0x12, 0xfe, 0x34, 0xd3, 0xcb, 0xa5, 0xb6, 0xc0, 0xc6, 0x2d, 0x10, 0xee, 0x34, 0x53, - 0x91, 0x8f, 0xc6, 0x05, 0x11, 0xa3, 0x0a, 0xf4, 0x79, 0x40, 0x31, 0x89, 0x76, 0xbc, 0x16, 0x99, - 0x6f, 0xb1, 0x94, 0x97, 0xec, 0x78, 0x6e, 0xc4, 0x08, 0xff, 0x47, 0xcd, 0x2e, 0x0a, 0x9c, 0x53, - 0x0a, 0xdd, 0xa0, 0x1a, 0x47, 0x87, 0x8a, 0x40, 0x55, 0x69, 0xda, 0x4d, 0xd7, 0x49, 0x3b, 0x22, - 0x2d, 0x27, 0x21, 0xae, 0xc9, 0x11, 0x67, 0xca, 0xd1, 0x65, 0x45, 0xa5, 0xf2, 0x06, 0x33, 0xbc, - 0xb2, 0x3b, 0x9d, 0x37, 0xdd, 0x29, 0x6d, 0x85, 0x71, 0x72, 0x9b, 0x24, 0x0f, 0xc2, 0xe8, 0x3e, - 0x73, 0xb6, 0x8f, 0x68, 0x29, 0xbe, 0x52, 0x14, 0xd6, 0xe9, 0xa8, 0x0d, 0xc4, 0x4e, 0x79, 0x56, - 0xea, 0xcc, 0x85, 0x3e, 0x92, 0xce, 0x9d, 0x1b, 0x1c, 0x8c, 0x25, 0x5e, 0x92, 0xae, 0x34, 0x16, - 0x99, 0x3b, 0x3c, 0x43, 0xba, 0xd2, 0x58, 0xc4, 0x12, 0x8f, 0xc2, 0xee, 0x87, 0x88, 0x26, 0xca, - 0x1c, 0x4d, 0x74, 0x6b, 0xf0, 0x92, 0x6f, 0x11, 0x3d, 0x84, 0x29, 0xf5, 0x18, 0x12, 0xcf, 0xbd, - 0x18, 0x4f, 0x4f, 0x96, 0x79, 0x37, 0x38, 0x37, 0x85, 0xa3, 0x8a, 0x4c, 0x5e, 0xc9, 0xf0, 0xc4, - 0x5d, 0xb5, 0x18, 0x29, 0x02, 0xa6, 0x0a, 0xd3, 0xb3, 0x5f, 0x81, 0x5a, 0xdc, 0x59, 0x77, 0xc3, - 0x6d, 0xc7, 0x0b, 0x98, 0xcf, 0x5a, 0x7f, 0x05, 0x57, 0x22, 0x70, 0x4a, 0x33, 0xf3, 0x59, 0x38, - 0xd5, 0x25, 0xd3, 0x7d, 0x85, 0xd4, 0xfd, 0xe2, 0x00, 0xd4, 0x94, 0x57, 0x07, 0x5d, 0x31, 0x1d, - 0x77, 0x8f, 0x67, 0x1d, 0x77, 0x23, 0x74, 0xe5, 0xd5, 0x7d, 0x75, 0xef, 0xe4, 0x3c, 0x83, 0xf9, - 0x6c, 0xe1, 0x47, 0x2c, 0x7f, 0xb3, 0xa5, 0x8f, 0x47, 0x42, 0x53, 0xb3, 0x7e, 0xe0, 0x50, 0xb3, - 0xbe, 0xe4, 0x2b, 0x47, 0xd4, 0x80, 0x6f, 0x87, 0xee, 0x4a, 0x23, 0xfb, 0x82, 0x47, 0x83, 0x02, - 0x31, 0xc7, 0x31, 0xbb, 0x8b, 0x2a, 0x65, 0x66, 0x77, 0x0d, 0x1f, 0xd5, 0xee, 0x92, 0x1c, 0x70, - 0xca, 0x0c, 0xed, 0xc0, 0xa9, 0x96, 0xf9, 0x22, 0x8b, 0xba, 0xb0, 0xf2, 0x7c, 0x1f, 0x2f, 0xa2, - 0x74, 0xb4, 0xec, 0xf3, 0x8b, 0x59, 0x7e, 0xb8, 0xbb, 0x0a, 0xfb, 0x07, 0xdc, 0x0b, 0x24, 0xb6, - 0x85, 0x24, 0xee, 0xf8, 0xc7, 0x99, 0x4c, 0xfa, 0x8e, 0xb1, 0x53, 0x7d, 0x04, 0xfe, 0xc7, 0xdf, - 0xb4, 0x98, 0xff, 0x71, 0x8d, 0x6c, 0xb7, 0x7d, 0x27, 0x39, 0xce, 0x68, 0xbd, 0x2f, 0xc1, 0x48, - 0x22, 0x6a, 0x29, 0x97, 0x01, 0x5b, 0x6b, 0x16, 0xf3, 0xc7, 0x2a, 0x45, 0x20, 0xa1, 0x58, 0x31, - 0xb4, 0xff, 0x35, 0xff, 0x0a, 0x12, 0x73, 0x12, 0x3b, 0xab, 0xdb, 0xe6, 0xce, 0xea, 0x99, 0xd2, - 0x9d, 0xe9, 0xb1, 0xc3, 0xfa, 0xae, 0xd9, 0x05, 0x66, 0xb0, 0x7d, 0xf4, 0x3d, 0xe2, 0xf6, 0x2a, - 0x98, 0xaf, 0xcc, 0xa0, 0xd7, 0x78, 0xa8, 0x2a, 0xd7, 0x88, 0xcf, 0xf6, 0x19, 0xa6, 0x6a, 0xff, - 0x7a, 0x05, 0xce, 0xe4, 0x3d, 0x3e, 0x8f, 0x5c, 0x18, 0x6b, 0x6b, 0xe6, 0x73, 0xb9, 0x44, 0x06, - 0xba, 0xc1, 0x9d, 0x9a, 0x2e, 0x3a, 0x14, 0x1b, 0x5c, 0x11, 0x81, 0x31, 0xb2, 0xe3, 0xb5, 0x94, - 0x7b, 0xa5, 0xd2, 0xbf, 0x8a, 0x52, 0xd5, 0x2c, 0x69, 0x8c, 0xb0, 0xc1, 0xf6, 0x18, 0x92, 0xb4, - 0xdb, 0xff, 0xd0, 0x82, 0xc7, 0x7a, 0x64, 0x3b, 0xa0, 0xd5, 0x3d, 0x60, 0x5e, 0x48, 0xf1, 0x8a, - 0x91, 0xaa, 0x8e, 0xfb, 0x26, 0xb1, 0xc0, 0xa2, 0x75, 0x00, 0xee, 0x5b, 0x64, 0x4f, 0xbb, 0x56, - 0xca, 0xc4, 0x00, 0x74, 0xdd, 0xac, 0xd6, 0x2e, 0xdd, 0xaa, 0xc7, 0x5c, 0x35, 0xae, 0xf6, 0x77, - 0xaa, 0x30, 0xc8, 0x5f, 0x97, 0x6c, 0xc0, 0xf0, 0x16, 0x4f, 0xae, 0xd8, 0x5f, 0x6e, 0xc7, 0xd4, - 0x4e, 0xe2, 0x00, 0x2c, 0xd9, 0xa0, 0x55, 0x38, 0xed, 0x05, 0x5e, 0xe2, 0x39, 0x7e, 0x9d, 0xf8, - 0xce, 0xae, 0x34, 0xbc, 0x79, 0x62, 0x6d, 0x99, 0x03, 0xf6, 0xf4, 0x4a, 0x37, 0x09, 0xce, 0x2b, - 0x87, 0x5e, 0xef, 0xca, 0x8e, 0xc4, 0x93, 0x56, 0xaa, 0xbb, 0x5a, 0x87, 0x67, 0x48, 0x42, 0xaf, - 0xc2, 0x78, 0xbb, 0x6b, 0x8b, 0xa1, 0x3d, 0x4b, 0x68, 0x6e, 0x2b, 0x4c, 0x5a, 0x54, 0x87, 0xa9, - 0xb8, 0xc3, 0x4e, 0x64, 0xd7, 0xb6, 0x22, 0x12, 0x6f, 0x85, 0xbe, 0x2b, 0x9e, 0xd3, 0x52, 0xe6, - 0x54, 0x33, 0x83, 0xc7, 0x5d, 0x25, 0x28, 0x97, 0x0d, 0xc7, 0xf3, 0x3b, 0x11, 0x49, 0xb9, 0x0c, - 0x99, 0x5c, 0x96, 0x33, 0x78, 0xdc, 0x55, 0xc2, 0xfe, 0x43, 0x0b, 0x4e, 0xe7, 0x84, 0x2d, 0xf0, - 0x68, 0xba, 0x4d, 0x2f, 0x4e, 0x54, 0xfa, 0x64, 0x2d, 0x9a, 0x8e, 0xc3, 0xb1, 0xa2, 0xa0, 0x52, - 0xc8, 0xf7, 0x8d, 0xd9, 0xe3, 0x40, 0x71, 0x30, 0x2b, 0xb0, 0xfd, 0xe5, 0x3a, 0x52, 0x8f, 0xe4, - 0x0f, 0xf4, 0x7c, 0x24, 0xff, 0x29, 0x18, 0xdc, 0x54, 0xbb, 0x73, 0xcd, 0x30, 0xe1, 0xfb, 0x73, - 0x8e, 0xb3, 0xbf, 0x55, 0x85, 0xc9, 0x4c, 0xf8, 0x12, 0x6d, 0x48, 0xe6, 0x2d, 0x7f, 0xe6, 0x52, - 0x58, 0x24, 0xed, 0xad, 0x9c, 0xf7, 0xfc, 0x2f, 0x9a, 0x4f, 0xfd, 0xa6, 0x6d, 0x5e, 0xa8, 0x1b, - 0x8f, 0x98, 0x95, 0x4d, 0xe9, 0xfe, 0x14, 0x0c, 0xb4, 0x43, 0xf5, 0x26, 0xa5, 0x12, 0x7a, 0xbc, - 0x50, 0x6f, 0x84, 0xa1, 0x8f, 0x19, 0x12, 0x3d, 0x2d, 0x7a, 0x9f, 0x71, 0x4e, 0x62, 0xc7, 0x0d, - 0x63, 0x6d, 0x08, 0x9e, 0x81, 0xe1, 0xfb, 0x64, 0x37, 0xf2, 0x82, 0xcd, 0xac, 0x6b, 0xf6, 0x26, - 0x07, 0x63, 0x89, 0x37, 0xd3, 0xb6, 0x0f, 0x1f, 0x73, 0xda, 0xf6, 0x91, 0xc2, 0x10, 0xcc, 0x5f, - 0xb1, 0x60, 0x92, 0xe5, 0x9c, 0x13, 0xd7, 0x60, 0xbd, 0x30, 0x38, 0xc6, 0x55, 0xf1, 0x29, 0x18, - 0x8c, 0x68, 0x65, 0xd9, 0x8c, 0xcb, 0xac, 0x05, 0x98, 0xe3, 0xd0, 0x13, 0xe2, 0xc5, 0x74, 0xfa, - 0xf9, 0xc6, 0x78, 0x06, 0xdb, 0xf4, 0xe9, 0x73, 0x16, 0xe0, 0x8f, 0x49, 0xdb, 0xf7, 0x78, 0x63, - 0x53, 0x4f, 0xcc, 0x47, 0x25, 0xc0, 0x3f, 0xb7, 0x71, 0x8f, 0x2a, 0xc0, 0x3f, 0x9f, 0xf9, 0xe1, - 0x26, 0xe8, 0xff, 0xa8, 0xc0, 0xf9, 0xdc, 0x72, 0xe9, 0xb1, 0xce, 0xb2, 0x71, 0xac, 0x73, 0x2d, - 0x73, 0xac, 0x63, 0x1f, 0x5e, 0xfa, 0xd1, 0x1c, 0xf4, 0xe4, 0x1f, 0xbf, 0x54, 0x4f, 0xf2, 0xf8, - 0x65, 0xa0, 0xac, 0xad, 0x30, 0x58, 0x60, 0x2b, 0xfc, 0x8e, 0x05, 0x8f, 0xe7, 0x8e, 0xd9, 0x47, - 0xef, 0x4a, 0x45, 0x6e, 0x33, 0x7b, 0x58, 0xd0, 0x7f, 0xbd, 0xda, 0xa3, 0x5b, 0xcc, 0x96, 0xbe, - 0x44, 0xf5, 0x0e, 0x43, 0xc6, 0xc2, 0x0c, 0x1a, 0xe3, 0x3a, 0x87, 0xc3, 0xb0, 0xc2, 0xa2, 0x58, - 0xbb, 0x92, 0xc0, 0x1b, 0xb9, 0x74, 0xc4, 0x29, 0x35, 0x67, 0x3a, 0xcf, 0xf4, 0xfb, 0xbc, 0x99, - 0x7b, 0x0a, 0xe8, 0x9e, 0xb6, 0x3d, 0xaa, 0x1e, 0x65, 0x7b, 0x34, 0x96, 0xbf, 0x35, 0x42, 0xf3, - 0x30, 0xb9, 0xed, 0x05, 0xec, 0xcd, 0x34, 0xd3, 0x0e, 0x51, 0xb7, 0xe0, 0x56, 0x4d, 0x34, 0xce, - 0xd2, 0xcf, 0xbc, 0x0a, 0xe3, 0x47, 0xf7, 0x98, 0x7c, 0x50, 0x85, 0x9f, 0x3a, 0x44, 0x2d, 0xf0, - 0xf5, 0xc0, 0xf8, 0x2e, 0xda, 0x7a, 0xd0, 0xf5, 0x6d, 0x1a, 0x70, 0x66, 0xa3, 0xe3, 0xfb, 0xbb, - 0x2c, 0x2c, 0x82, 0xb8, 0x92, 0x42, 0xd8, 0x78, 0xea, 0x35, 0xd3, 0xe5, 0x1c, 0x1a, 0x9c, 0x5b, - 0x12, 0x7d, 0x1e, 0x50, 0xb8, 0xce, 0x12, 0x31, 0xba, 0xe9, 0x8d, 0x65, 0xf6, 0x09, 0xaa, 0xe9, - 0x5c, 0xbd, 0xd3, 0x45, 0x81, 0x73, 0x4a, 0x51, 0x8b, 0x8f, 0x3d, 0x84, 0xaa, 0x9a, 0x95, 0xb1, - 0xf8, 0xb0, 0x8e, 0xc4, 0x26, 0x2d, 0xba, 0x0e, 0xa7, 0x9c, 0x1d, 0xc7, 0xe3, 0xd9, 0x66, 0x24, - 0x03, 0x6e, 0xf2, 0x29, 0x97, 0xc4, 0x7c, 0x96, 0x00, 0x77, 0x97, 0x41, 0x6d, 0xc3, 0xc9, 0xc4, - 0x13, 0x2f, 0xbf, 0x76, 0x04, 0x09, 0x2e, 0xed, 0x76, 0xb2, 0xff, 0xc0, 0xa2, 0x8b, 0x5e, 0xce, - 0x1b, 0x63, 0xc6, 0xd3, 0xdc, 0xda, 0x2d, 0x8d, 0xee, 0xa7, 0xb9, 0x99, 0xff, 0xd5, 0xa4, 0xe5, - 0xa2, 0x11, 0xa7, 0x61, 0x95, 0x86, 0x7d, 0x29, 0x6e, 0x27, 0x29, 0x0a, 0x74, 0x0f, 0x86, 0x5d, - 0x6f, 0xc7, 0x8b, 0xc3, 0xa8, 0xc4, 0x4b, 0xb8, 0x5d, 0xa1, 0x7a, 0xa9, 0xba, 0xac, 0x73, 0x26, - 0x58, 0x72, 0xb3, 0xff, 0x66, 0x05, 0xc6, 0x65, 0x7d, 0x6f, 0x74, 0x42, 0xa6, 0xc3, 0x8e, 0x6b, - 0x29, 0x7f, 0xc3, 0x58, 0xca, 0xaf, 0x94, 0xbb, 0xa2, 0xc5, 0x1a, 0xd5, 0x73, 0x09, 0xff, 0x42, - 0x66, 0x09, 0xbf, 0xda, 0x0f, 0xd3, 0x42, 0xef, 0xd1, 0x29, 0x83, 0xfe, 0x23, 0x94, 0xf8, 0x37, - 0xaf, 0x3b, 0x3d, 0x16, 0x8e, 0xef, 0x54, 0x32, 0xdd, 0x60, 0x0b, 0xc6, 0xd7, 0x60, 0x60, 0xcb, - 0x89, 0x5c, 0x71, 0x54, 0xf6, 0xe9, 0x3e, 0x3f, 0xc5, 0xdc, 0x0d, 0x27, 0x72, 0xb9, 0xda, 0xbf, - 0xac, 0x5e, 0x28, 0x71, 0x22, 0xb7, 0x30, 0xc8, 0x98, 0x55, 0x8a, 0x5e, 0x81, 0xa1, 0xb8, 0x15, - 0xb6, 0x55, 0x54, 0xd7, 0x05, 0xfe, 0x7a, 0x09, 0x85, 0x1c, 0xec, 0xcd, 0x22, 0xb3, 0x3a, 0x0a, - 0xc6, 0x82, 0x7e, 0x86, 0x40, 0x4d, 0x55, 0x7d, 0x8c, 0xe1, 0xac, 0x1f, 0x54, 0xe1, 0x74, 0x8e, - 0xa8, 0xa0, 0x9f, 0x31, 0x46, 0xed, 0xd5, 0xbe, 0x65, 0xed, 0x43, 0x8e, 0xdb, 0xcf, 0xb0, 0x0d, - 0x91, 0x2b, 0x64, 0xe3, 0x08, 0xd5, 0xdf, 0x8d, 0x49, 0xb6, 0x7a, 0x0a, 0x2a, 0xae, 0x9e, 0x56, - 0x7b, 0x42, 0x83, 0x4f, 0xab, 0x51, 0xed, 0x3c, 0xc6, 0x6f, 0xfc, 0xfe, 0x00, 0x9c, 0xc9, 0xbb, - 0x06, 0x8a, 0x7e, 0xde, 0xca, 0xa4, 0x0e, 0x7f, 0xbd, 0xff, 0xbb, 0xa4, 0x3c, 0x9f, 0xb8, 0x48, - 0x0f, 0x31, 0x67, 0x26, 0x13, 0x2f, 0x1c, 0x6d, 0x51, 0x3b, 0xbb, 0x18, 0x10, 0xf1, 0x2c, 0xf0, - 0x52, 0x1f, 0x7c, 0xee, 0x08, 0x4d, 0x11, 0x89, 0xe4, 0xe3, 0xcc, 0xc5, 0x00, 0x09, 0x2e, 0xbe, - 0x18, 0x20, 0xdb, 0x30, 0xb3, 0x09, 0xa3, 0x5a, 0xbf, 0x8e, 0x51, 0x04, 0x3c, 0xba, 0x26, 0x69, - 0xad, 0x3e, 0x46, 0x31, 0xf8, 0xdb, 0x16, 0x64, 0xc2, 0x35, 0x94, 0xd7, 0xc5, 0xea, 0xe9, 0x75, - 0xb9, 0x00, 0x03, 0x51, 0xe8, 0x93, 0x6c, 0x4e, 0x6b, 0x1c, 0xfa, 0x04, 0x33, 0x8c, 0x7a, 0x07, - 0xb1, 0xda, 0xeb, 0x1d, 0x44, 0xba, 0x1d, 0xf7, 0xc9, 0x0e, 0x91, 0x3e, 0x10, 0xa5, 0xbc, 0x6f, - 0x51, 0x20, 0xe6, 0x38, 0xfb, 0x47, 0x55, 0x18, 0xe2, 0x8e, 0x86, 0x63, 0x5c, 0x96, 0x1b, 0x62, - 0xcf, 0x5f, 0xea, 0x42, 0x26, 0x6f, 0xcd, 0x5c, 0xdd, 0x49, 0x1c, 0x2e, 0x50, 0xaa, 0x6f, 0xa9, - 0x9f, 0x00, 0xcd, 0x19, 0xbd, 0x9f, 0xc9, 0x6c, 0x69, 0x81, 0xf3, 0xd0, 0xc6, 0x62, 0x0b, 0x20, - 0x66, 0x4f, 0x62, 0x51, 0x1e, 0x22, 0x29, 0xde, 0x8b, 0xa5, 0xda, 0xd1, 0x54, 0xc5, 0x78, 0x6b, - 0xd2, 0x6c, 0x5c, 0x0a, 0x81, 0x35, 0xde, 0x33, 0x2f, 0x43, 0x4d, 0x11, 0x17, 0x59, 0xfa, 0x63, - 0xba, 0x48, 0xfe, 0x39, 0x98, 0xcc, 0xd4, 0xd5, 0xd7, 0x46, 0xe1, 0xfb, 0x16, 0x9c, 0xea, 0x7a, - 0xc2, 0x15, 0xbd, 0x6f, 0xc1, 0x19, 0x3f, 0xc7, 0xc3, 0x24, 0x3e, 0xf0, 0x51, 0x7c, 0x53, 0x6a, - 0x97, 0x90, 0x87, 0xc5, 0xb9, 0xb5, 0xc9, 0x34, 0x9f, 0x95, 0xfc, 0x34, 0x9f, 0xec, 0x1d, 0x20, - 0xde, 0xf6, 0x93, 0xb0, 0x80, 0x56, 0x4c, 0x0b, 0xe8, 0x13, 0x65, 0xc4, 0xa0, 0x87, 0xe9, 0xf3, - 0xef, 0x2c, 0x40, 0x9c, 0x20, 0xfb, 0x34, 0x1e, 0xf7, 0xd8, 0x69, 0x36, 0x7b, 0x2a, 0x37, 0x0a, - 0x83, 0x35, 0xaa, 0x3e, 0xd3, 0x9e, 0xab, 0x27, 0xa5, 0xca, 0xbd, 0x5b, 0x5f, 0x2d, 0xf1, 0x6e, - 0xfd, 0x6f, 0x56, 0x21, 0x1b, 0xda, 0x80, 0xbe, 0x0c, 0x63, 0x2d, 0xa7, 0xed, 0xac, 0x7b, 0xbe, - 0x97, 0x78, 0x24, 0x2e, 0x77, 0x6c, 0xb4, 0xa8, 0x95, 0x10, 0x3e, 0x5f, 0x0d, 0x82, 0x0d, 0x8e, - 0x68, 0x0e, 0xa0, 0x1d, 0x79, 0x3b, 0x9e, 0x4f, 0x36, 0x99, 0xdd, 0xa1, 0x92, 0xa4, 0x34, 0x14, - 0x14, 0x6b, 0x14, 0x39, 0x31, 0x74, 0xd5, 0x93, 0x88, 0xa1, 0x1b, 0xe8, 0x33, 0x86, 0x6e, 0xb0, - 0x54, 0x0c, 0x1d, 0x86, 0x73, 0xd2, 0x55, 0x4b, 0xff, 0x2f, 0x7b, 0x3e, 0xe1, 0x79, 0xfd, 0x44, - 0xe4, 0xe3, 0xcc, 0xfe, 0xde, 0xec, 0x39, 0x9c, 0x4b, 0x81, 0x7b, 0x94, 0xb4, 0x3b, 0x70, 0xba, - 0x49, 0x22, 0x8f, 0xa5, 0x5d, 0x72, 0xd3, 0x19, 0xf8, 0x0e, 0xd4, 0xa2, 0xcc, 0xe4, 0xef, 0xf3, - 0x4e, 0x9a, 0x96, 0xbc, 0x42, 0x4e, 0xf6, 0x94, 0xa5, 0xfd, 0x97, 0x2a, 0x30, 0x2c, 0x42, 0x88, - 0x8e, 0x71, 0x21, 0xb9, 0x69, 0xec, 0xef, 0x9e, 0x29, 0x9a, 0xb9, 0xac, 0x39, 0x3d, 0x77, 0x76, - 0xcd, 0xcc, 0xce, 0xee, 0xb9, 0x72, 0xec, 0x0e, 0xdf, 0xd3, 0xfd, 0xb0, 0x02, 0x13, 0x66, 0x28, - 0xd5, 0x31, 0x0e, 0xc7, 0x5b, 0x30, 0x1c, 0x8b, 0xf8, 0xa2, 0x4a, 0x99, 0x58, 0x8d, 0xec, 0x27, - 0x4d, 0xdf, 0xc0, 0x17, 0x11, 0x45, 0x92, 0x5d, 0x6e, 0x08, 0x53, 0xf5, 0x24, 0x42, 0x98, 0xec, - 0x1f, 0x31, 0x95, 0xaa, 0x0f, 0xe0, 0x49, 0xac, 0x09, 0x6f, 0x98, 0xda, 0xf7, 0x72, 0x29, 0x51, - 0x10, 0xed, 0xeb, 0xb1, 0x36, 0x7c, 0xcf, 0x82, 0x51, 0x41, 0x78, 0x12, 0x3d, 0xf8, 0xbc, 0xd9, - 0x83, 0xa7, 0x4b, 0xf5, 0xa0, 0x47, 0xd3, 0xff, 0x6e, 0x45, 0x35, 0xbd, 0x21, 0x9e, 0x0c, 0x2d, - 0x4c, 0xf4, 0x38, 0xd2, 0x8e, 0xc2, 0x24, 0x6c, 0x85, 0xbe, 0x58, 0xe5, 0x9f, 0x48, 0xa3, 0xce, - 0x39, 0xfc, 0x40, 0xfb, 0x8d, 0x15, 0x35, 0x8b, 0xa6, 0x0e, 0xa3, 0x44, 0x2c, 0x51, 0x79, 0x0f, - 0x96, 0xae, 0xcb, 0x07, 0xa1, 0x29, 0x4c, 0x5c, 0xd9, 0xe8, 0xf7, 0x21, 0xd4, 0x34, 0x86, 0x5c, - 0x71, 0xc2, 0x1a, 0x57, 0x19, 0xde, 0xc8, 0x6a, 0x18, 0x34, 0xdd, 0xa8, 0xb7, 0x05, 0x1c, 0x2b, - 0x0a, 0xfb, 0x65, 0xa6, 0x63, 0xd9, 0xf0, 0xf4, 0x17, 0x18, 0xfe, 0x0b, 0x43, 0x6a, 0x60, 0x99, - 0x93, 0xe4, 0x36, 0x0c, 0xd2, 0x2e, 0xca, 0x7d, 0x60, 0x39, 0x85, 0x46, 0x9b, 0xa0, 0x07, 0x88, - 0x45, 0x49, 0x8c, 0x39, 0x1b, 0x44, 0xba, 0x7c, 0xef, 0x2f, 0x97, 0xd6, 0x91, 0x7d, 0x78, 0xdb, - 0x59, 0xe2, 0x18, 0x96, 0x2c, 0x63, 0xa5, 0x91, 0x4d, 0xce, 0xb9, 0x28, 0x11, 0x38, 0xa5, 0x41, - 0x57, 0x84, 0xb9, 0x6e, 0xbe, 0x27, 0x2b, 0xcd, 0x75, 0x39, 0x24, 0x9a, 0xbd, 0x7e, 0x15, 0x46, - 0x55, 0x7a, 0xf2, 0x06, 0xcf, 0x32, 0x5d, 0xe3, 0xf6, 0xcb, 0x52, 0x0a, 0xc6, 0x3a, 0x0d, 0x5a, - 0x81, 0xd3, 0xae, 0x8a, 0x66, 0x6d, 0x74, 0xd6, 0x7d, 0xaf, 0x45, 0x8b, 0xf2, 0x9b, 0x24, 0x8f, - 0xed, 0xef, 0xcd, 0x9e, 0xae, 0x77, 0xa3, 0x71, 0x5e, 0x19, 0xb4, 0x06, 0x93, 0x31, 0x4f, 0xc3, - 0x2e, 0xef, 0x9c, 0x89, 0xec, 0x75, 0xcf, 0x4a, 0xa7, 0x7f, 0xd3, 0x44, 0x1f, 0x30, 0x10, 0x57, - 0x0a, 0x02, 0x84, 0xb3, 0x2c, 0xd0, 0xeb, 0x30, 0xe1, 0xeb, 0xcf, 0x29, 0x35, 0x44, 0x50, 0xaf, - 0x0a, 0x88, 0x30, 0x1e, 0x5b, 0x6a, 0xe0, 0x0c, 0x35, 0x7a, 0x0b, 0xa6, 0x75, 0x88, 0xb8, 0xd4, - 0xee, 0x04, 0x9b, 0x24, 0x16, 0xf9, 0x9f, 0x9f, 0xd8, 0xdf, 0x9b, 0x9d, 0xbe, 0xd5, 0x83, 0x06, - 0xf7, 0x2c, 0x8d, 0x5e, 0x81, 0x31, 0x39, 0x92, 0x5a, 0x80, 0x6f, 0x1a, 0x8a, 0xa3, 0xe1, 0xb0, - 0x41, 0xf9, 0xe1, 0xce, 0x36, 0xbe, 0x46, 0x0b, 0x6b, 0x8b, 0x2a, 0xfa, 0x0a, 0x8c, 0xe9, 0x6d, - 0x14, 0x6a, 0xf2, 0x53, 0xe5, 0x9f, 0xa8, 0x12, 0x8b, 0xb3, 0x6a, 0xb9, 0x8e, 0xc3, 0x06, 0x6f, - 0xbb, 0x05, 0x93, 0x99, 0x27, 0x72, 0xd5, 0x5b, 0xcb, 0xd6, 0xa3, 0x7a, 0x6b, 0xd9, 0xfe, 0xba, - 0x05, 0x83, 0x6b, 0x8e, 0x57, 0xfc, 0xd0, 0x41, 0x99, 0xc7, 0x8a, 0xd1, 0x4b, 0x30, 0x44, 0x36, - 0x36, 0x48, 0x4b, 0xbe, 0xdd, 0xfc, 0xa4, 0x7a, 0x79, 0x9f, 0x41, 0xe9, 0x4c, 0x62, 0x95, 0xf1, - 0xbf, 0x58, 0x10, 0xdb, 0xff, 0xc1, 0x02, 0x58, 0x0b, 0x7d, 0x79, 0xca, 0x52, 0xd0, 0x92, 0x85, - 0xae, 0x27, 0x17, 0x2e, 0xe6, 0x3c, 0xb9, 0x80, 0x52, 0x86, 0x39, 0x0f, 0x2e, 0xa8, 0xde, 0x54, - 0x4b, 0xf5, 0x66, 0xa0, 0x9f, 0xde, 0x7c, 0xd3, 0x02, 0x11, 0xf2, 0x52, 0x62, 0x59, 0x72, 0x65, - 0x9a, 0x74, 0x23, 0xbb, 0xc4, 0xb3, 0x65, 0xee, 0x6d, 0x88, 0x9c, 0x12, 0x4a, 0x94, 0x8c, 0x4c, - 0x12, 0x06, 0x57, 0xba, 0xf5, 0x1e, 0xe5, 0xe8, 0x55, 0x66, 0xf0, 0x15, 0xb7, 0xab, 0xaf, 0x44, - 0x5a, 0x2c, 0x8b, 0x38, 0x65, 0xac, 0xf2, 0x29, 0xe9, 0x59, 0xc4, 0x25, 0x02, 0xa7, 0x34, 0xe8, - 0x19, 0x18, 0x8e, 0x3b, 0xeb, 0x8c, 0x3c, 0x13, 0xff, 0xd2, 0xe4, 0x60, 0x2c, 0xf1, 0xf6, 0xcf, - 0x21, 0x30, 0xba, 0x66, 0xe4, 0x6e, 0xb2, 0x1e, 0x79, 0xee, 0xa6, 0xb7, 0x61, 0x84, 0x6c, 0xb7, - 0x93, 0xdd, 0xba, 0x17, 0x95, 0xcb, 0xa3, 0xb7, 0x24, 0xa8, 0xbb, 0xb9, 0x4b, 0x0c, 0x56, 0x1c, - 0x7b, 0x64, 0xe2, 0xaa, 0x7e, 0x24, 0x32, 0x71, 0x0d, 0xfc, 0x89, 0x64, 0xe2, 0x7a, 0x0b, 0x86, - 0x37, 0xf9, 0xdb, 0xfd, 0xe2, 0x9e, 0x5e, 0xc1, 0xf1, 0x55, 0xce, 0x43, 0xff, 0xfc, 0x42, 0x96, - 0x40, 0x60, 0xc9, 0x0e, 0xad, 0xc1, 0x10, 0xdf, 0x2c, 0x88, 0xe4, 0x56, 0x9f, 0x2a, 0xe3, 0x46, - 0xe9, 0xce, 0xf3, 0x24, 0x82, 0x9c, 0x04, 0x2f, 0x99, 0x79, 0x6b, 0xf8, 0xc3, 0x67, 0xde, 0x52, - 0xf9, 0xb2, 0x46, 0x1e, 0x55, 0xbe, 0x2c, 0x23, 0xef, 0x58, 0xed, 0x38, 0xf2, 0x8e, 0x7d, 0xd3, - 0x82, 0xb3, 0xed, 0xbc, 0xb4, 0x7d, 0x22, 0xf3, 0xd5, 0x67, 0x8f, 0x90, 0xc6, 0xd0, 0xa8, 0x9a, - 0x5d, 0x9f, 0xca, 0x25, 0xc3, 0xf9, 0x15, 0xcb, 0x04, 0x66, 0xa3, 0x1f, 0x3e, 0x81, 0xd9, 0x71, - 0xa7, 0xc8, 0x4a, 0xd3, 0x99, 0x8d, 0x1f, 0x4b, 0x3a, 0xb3, 0x89, 0x47, 0x98, 0xce, 0x4c, 0x4b, - 0x44, 0x36, 0xf9, 0x68, 0x13, 0x91, 0x6d, 0xc1, 0xa8, 0x1b, 0x3e, 0x08, 0x1e, 0x38, 0x91, 0x3b, - 0xdf, 0x58, 0x11, 0x79, 0xaf, 0x0a, 0x72, 0x2c, 0xd4, 0xd3, 0x02, 0x46, 0x0d, 0xdc, 0x5f, 0x98, - 0x22, 0xb1, 0xce, 0x5a, 0xa4, 0x64, 0x3b, 0xf5, 0x21, 0x53, 0xb2, 0x19, 0x89, 0xcd, 0xd0, 0x71, - 0x24, 0x36, 0xfb, 0x32, 0xbb, 0x69, 0xbd, 0xe1, 0x6d, 0xae, 0x3a, 0xed, 0xe9, 0xd3, 0x65, 0x6a, - 0x58, 0x94, 0xe4, 0xdd, 0x35, 0x28, 0x14, 0x4e, 0x99, 0x76, 0xa7, 0x4e, 0x3b, 0x73, 0xd2, 0xa9, - 0xd3, 0xce, 0x1e, 0x63, 0xea, 0xb4, 0x73, 0x27, 0x9a, 0x3a, 0xed, 0xb1, 0x3f, 0x91, 0xd4, 0x69, - 0x7f, 0x01, 0xce, 0x1f, 0xfe, 0x39, 0xd2, 0xe4, 0xbc, 0x8d, 0x74, 0x87, 0x9f, 0x49, 0xce, 0xcb, - 0x4c, 0x1d, 0x8d, 0xaa, 0x74, 0x06, 0xa7, 0x7f, 0x6e, 0xc1, 0x63, 0x3d, 0xf2, 0x9c, 0x94, 0xbe, - 0x7c, 0xd0, 0x86, 0xc9, 0xb6, 0x59, 0xb4, 0xf4, 0x35, 0x21, 0x23, 0xaf, 0x8a, 0x0a, 0x6b, 0xcb, - 0x20, 0x70, 0x96, 0xfd, 0xc2, 0x27, 0x7e, 0xfc, 0xc1, 0xf9, 0x8f, 0xfd, 0xe4, 0x83, 0xf3, 0x1f, - 0xfb, 0xbd, 0x0f, 0xce, 0x7f, 0xec, 0x67, 0xf7, 0xcf, 0x5b, 0x3f, 0xde, 0x3f, 0x6f, 0xfd, 0x64, - 0xff, 0xbc, 0xf5, 0x87, 0xfb, 0xe7, 0xad, 0x6f, 0xfe, 0xd1, 0xf9, 0x8f, 0x7d, 0xb1, 0xb2, 0x73, - 0xf5, 0xff, 0x05, 0x00, 0x00, 0xff, 0xff, 0x70, 0xfd, 0x33, 0x79, 0x2a, 0xb5, 0x00, 0x00, + // 10058 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xec, 0x7d, 0x6d, 0x8c, 0x24, 0xc7, + 0x75, 0x98, 0x7a, 0x66, 0xbf, 0xe6, 0xed, 0xe7, 0xd5, 0x7d, 0x70, 0xb9, 0x22, 0x6f, 0x4f, 0x4d, + 0xf1, 0x74, 0x24, 0x8f, 0x7b, 0xba, 0x23, 0x29, 0x52, 0x22, 0x43, 0x69, 0x77, 0x67, 0xf7, 0x6e, + 0x75, 0xb7, 0x77, 0xc3, 0x9a, 0x3d, 0x1e, 0x25, 0x31, 0xa4, 0x7a, 0xa7, 0x6b, 0x77, 0x5b, 0xd7, + 0xdb, 0x3d, 0xec, 0xee, 0xd9, 0xbb, 0x95, 0x62, 0xc0, 0x91, 0x19, 0x1b, 0x81, 0x05, 0x47, 0x41, + 0x22, 0x24, 0x40, 0x12, 0x44, 0x09, 0x90, 0xc0, 0x89, 0x11, 0xc7, 0x72, 0x14, 0x5b, 0x4a, 0x04, + 0x21, 0x40, 0x1c, 0x41, 0xf9, 0x70, 0x20, 0x03, 0x46, 0x6c, 0xd8, 0xc0, 0xc6, 0x5c, 0x23, 0xc8, + 0x8f, 0xfc, 0x48, 0x80, 0xfc, 0xca, 0xc1, 0x48, 0x82, 0xfa, 0xec, 0xaa, 0x9e, 0x9e, 0xed, 0x9e, + 0xe5, 0xed, 0xfa, 0x64, 0xf8, 0xdf, 0xcc, 0x7b, 0xaf, 0x5e, 0x7d, 0xf4, 0xab, 0x57, 0xaf, 0x5e, + 0xbd, 0x7a, 0x05, 0x17, 0xef, 0xbe, 0x12, 0xcf, 0x79, 0xe1, 0xa5, 0xbb, 0x9d, 0x75, 0x12, 0x05, + 0x24, 0x21, 0xf1, 0xa5, 0xf6, 0xdd, 0xcd, 0x4b, 0x4e, 0xdb, 0xbb, 0xb4, 0x73, 0xf9, 0xd2, 0x26, + 0x09, 0x48, 0xe4, 0x24, 0xc4, 0x9d, 0x6b, 0x47, 0x61, 0x12, 0xa2, 0x27, 0x38, 0xf5, 0x5c, 0x4a, + 0x3d, 0xd7, 0xbe, 0xbb, 0x39, 0xe7, 0xb4, 0xbd, 0xb9, 0x9d, 0xcb, 0x33, 0xcf, 0x6f, 0x7a, 0xc9, + 0x56, 0x67, 0x7d, 0xae, 0x15, 0x6e, 0x5f, 0xda, 0x0c, 0x37, 0xc3, 0x4b, 0xac, 0xd0, 0x7a, 0x67, + 0x83, 0xfd, 0x63, 0x7f, 0xd8, 0x2f, 0xce, 0x6c, 0xe6, 0x4a, 0xef, 0xaa, 0x23, 0x12, 0x87, 0x9d, + 0xa8, 0x45, 0xb2, 0x0d, 0x98, 0x79, 0xa9, 0x77, 0x99, 0x4e, 0xb0, 0x43, 0xa2, 0xd8, 0x0b, 0x03, + 0xe2, 0x76, 0x15, 0x7b, 0x3e, 0xbf, 0x58, 0xd4, 0x09, 0x12, 0x6f, 0xbb, 0xbb, 0x96, 0xcb, 0xf9, + 0xe4, 0x9d, 0xc4, 0xf3, 0x2f, 0x79, 0x41, 0x12, 0x27, 0x51, 0xb6, 0x88, 0xfd, 0x7b, 0x16, 0x9c, + 0x9b, 0xbf, 0xd3, 0x5c, 0xf2, 0x9d, 0x38, 0xf1, 0x5a, 0x0b, 0x7e, 0xd8, 0xba, 0xdb, 0x4c, 0xc2, + 0x88, 0xbc, 0x19, 0xfa, 0x9d, 0x6d, 0xd2, 0x64, 0xbd, 0x41, 0x17, 0x61, 0x64, 0x87, 0xfd, 0x5f, + 0xa9, 0x4f, 0x5b, 0xe7, 0xac, 0x0b, 0xb5, 0x85, 0xa9, 0x1f, 0xef, 0xcd, 0x7e, 0x64, 0x7f, 0x6f, + 0x76, 0xe4, 0x4d, 0x01, 0xc7, 0x8a, 0x02, 0x9d, 0x87, 0xa1, 0x8d, 0x78, 0x6d, 0xb7, 0x4d, 0xa6, + 0x2b, 0x8c, 0x76, 0x42, 0xd0, 0x0e, 0x2d, 0x37, 0x29, 0x14, 0x0b, 0x2c, 0xba, 0x04, 0xb5, 0xb6, + 0x13, 0x25, 0x5e, 0xe2, 0x85, 0xc1, 0x74, 0xf5, 0x9c, 0x75, 0x61, 0x70, 0xe1, 0x84, 0x20, 0xad, + 0x35, 0x24, 0x02, 0xa7, 0x34, 0xb4, 0x19, 0x11, 0x71, 0xdc, 0x5b, 0x81, 0xbf, 0x3b, 0x3d, 0x70, + 0xce, 0xba, 0x30, 0x92, 0x36, 0x03, 0x0b, 0x38, 0x56, 0x14, 0xf6, 0xf7, 0x2a, 0x30, 0x32, 0xbf, + 0xb1, 0xe1, 0x05, 0x5e, 0xb2, 0x8b, 0xbe, 0x0c, 0x63, 0x41, 0xe8, 0x12, 0xf9, 0x9f, 0xf5, 0x62, + 0xf4, 0xca, 0xb3, 0x73, 0x07, 0xc9, 0xc5, 0xdc, 0x4d, 0xad, 0xc4, 0xc2, 0xd4, 0xfe, 0xde, 0xec, + 0x98, 0x0e, 0xc1, 0x06, 0x47, 0xf4, 0x36, 0x8c, 0xb6, 0x43, 0x57, 0x55, 0x50, 0x61, 0x15, 0x3c, + 0x73, 0x70, 0x05, 0x8d, 0xb4, 0xc0, 0xc2, 0xe4, 0xfe, 0xde, 0xec, 0xa8, 0x06, 0xc0, 0x3a, 0x3b, + 0xe4, 0xc3, 0x24, 0xfd, 0x1b, 0x24, 0x9e, 0xaa, 0xa1, 0xca, 0x6a, 0x78, 0xbe, 0xb8, 0x06, 0xad, + 0xd0, 0xc2, 0xc9, 0xfd, 0xbd, 0xd9, 0xc9, 0x0c, 0x10, 0x67, 0x59, 0xdb, 0x5f, 0x85, 0x89, 0xf9, + 0x24, 0x71, 0x5a, 0x5b, 0xc4, 0xe5, 0xdf, 0x17, 0xbd, 0x08, 0x03, 0x81, 0xb3, 0x4d, 0xc4, 0xd7, + 0x3f, 0x27, 0x86, 0x7d, 0xe0, 0xa6, 0xb3, 0x4d, 0x1e, 0xec, 0xcd, 0x4e, 0xdd, 0x0e, 0xbc, 0xf7, + 0x3a, 0x42, 0x66, 0x28, 0x0c, 0x33, 0x6a, 0x74, 0x05, 0xc0, 0x25, 0x3b, 0x5e, 0x8b, 0x34, 0x9c, + 0x64, 0x4b, 0x48, 0x03, 0x12, 0x65, 0xa1, 0xae, 0x30, 0x58, 0xa3, 0xb2, 0xbf, 0x6e, 0x41, 0x6d, + 0x7e, 0x27, 0xf4, 0xdc, 0x46, 0xe8, 0xc6, 0xa8, 0x03, 0x93, 0xed, 0x88, 0x6c, 0x90, 0x48, 0x81, + 0xa6, 0xad, 0x73, 0xd5, 0x0b, 0xa3, 0x57, 0xae, 0x14, 0xf4, 0xdb, 0x2c, 0xb4, 0x14, 0x24, 0xd1, + 0xee, 0xc2, 0x63, 0xa2, 0xea, 0xc9, 0x0c, 0x16, 0x67, 0xeb, 0xb0, 0xff, 0x7a, 0x05, 0x4e, 0xcf, + 0x7f, 0xb5, 0x13, 0x91, 0xba, 0x17, 0xdf, 0xcd, 0x4e, 0x05, 0xd7, 0x8b, 0xef, 0xde, 0x4c, 0x07, + 0x43, 0xc9, 0x60, 0x5d, 0xc0, 0xb1, 0xa2, 0x40, 0xcf, 0xc3, 0x30, 0xfd, 0x7d, 0x1b, 0xaf, 0x88, + 0xde, 0x9f, 0x14, 0xc4, 0xa3, 0x75, 0x27, 0x71, 0xea, 0x1c, 0x85, 0x25, 0x0d, 0x5a, 0x85, 0xd1, + 0x96, 0xd3, 0xda, 0xf2, 0x82, 0xcd, 0xd5, 0xd0, 0x25, 0xec, 0x0b, 0xd7, 0x16, 0x9e, 0xa3, 0xe4, + 0x8b, 0x29, 0xf8, 0xc1, 0xde, 0xec, 0x34, 0x6f, 0x9b, 0x60, 0xa1, 0xe1, 0xb0, 0x5e, 0x1e, 0xd9, + 0x6a, 0x22, 0x0e, 0x30, 0x4e, 0x90, 0x33, 0x09, 0x2f, 0x68, 0x73, 0x6a, 0x90, 0xcd, 0xa9, 0xb1, + 0x1e, 0xf3, 0xe9, 0x9f, 0x5a, 0x62, 0x4c, 0x96, 0x3d, 0xdf, 0x54, 0x0f, 0x57, 0x00, 0x62, 0xd2, + 0x8a, 0x48, 0xa2, 0x8d, 0x8a, 0xfa, 0xcc, 0x4d, 0x85, 0xc1, 0x1a, 0x15, 0x9d, 0xfc, 0xf1, 0x96, + 0x13, 0x31, 0x69, 0x11, 0x63, 0xa3, 0x26, 0x7f, 0x53, 0x22, 0x70, 0x4a, 0x63, 0x4c, 0xfe, 0x6a, + 0xe1, 0xe4, 0xff, 0x57, 0x16, 0x0c, 0x2f, 0x78, 0x81, 0xeb, 0x05, 0x9b, 0xe8, 0x2d, 0x18, 0xd9, + 0x26, 0x89, 0xe3, 0x3a, 0x89, 0x23, 0xe6, 0xfd, 0x85, 0x83, 0x85, 0xe7, 0xd6, 0xfa, 0x57, 0x48, + 0x2b, 0x59, 0x25, 0x89, 0x93, 0x76, 0x23, 0x85, 0x61, 0xc5, 0x0d, 0xdd, 0x86, 0xa1, 0xc4, 0x89, + 0x36, 0x49, 0x22, 0xa6, 0xfb, 0xf3, 0x65, 0xf8, 0x62, 0x2a, 0x6a, 0x24, 0x68, 0x91, 0x54, 0x31, + 0xae, 0x31, 0x26, 0x58, 0x30, 0xb3, 0x5b, 0x30, 0xb6, 0xe8, 0xb4, 0x9d, 0x75, 0xcf, 0xf7, 0x12, + 0x8f, 0xc4, 0xe8, 0x13, 0x50, 0x75, 0x5c, 0x97, 0x09, 0x7e, 0x6d, 0xe1, 0xf4, 0xfe, 0xde, 0x6c, + 0x75, 0xde, 0x75, 0x1f, 0xec, 0xcd, 0x82, 0xa2, 0xda, 0xc5, 0x94, 0x02, 0x3d, 0x0b, 0x03, 0x6e, + 0x14, 0xb6, 0xa7, 0x2b, 0x8c, 0xf2, 0x0c, 0x9d, 0xa1, 0xf5, 0x28, 0x6c, 0x67, 0x48, 0x19, 0x8d, + 0xfd, 0xef, 0x2a, 0x80, 0x16, 0x49, 0x7b, 0x6b, 0xb9, 0x69, 0x7c, 0xcb, 0x0b, 0x30, 0xb2, 0x1d, + 0x06, 0x5e, 0x12, 0x46, 0xb1, 0xa8, 0x90, 0xc9, 0xc3, 0xaa, 0x80, 0x61, 0x85, 0x45, 0xe7, 0x60, + 0xa0, 0x9d, 0x4e, 0xeb, 0x31, 0xa9, 0x12, 0xd8, 0x84, 0x66, 0x18, 0x4a, 0xd1, 0x89, 0x49, 0x24, + 0xe4, 0x58, 0x51, 0xdc, 0x8e, 0x49, 0x84, 0x19, 0x26, 0x95, 0x1c, 0x2a, 0x53, 0x42, 0x4a, 0x33, + 0x92, 0x43, 0x31, 0x58, 0xa3, 0x42, 0xef, 0x42, 0x8d, 0xff, 0xc3, 0x64, 0x83, 0x89, 0x6c, 0xa1, + 0x32, 0xb8, 0x11, 0xb6, 0x1c, 0x3f, 0x3b, 0xf8, 0xe3, 0x4c, 0xd2, 0x24, 0x23, 0x9c, 0xf2, 0x34, + 0x24, 0x6d, 0xa8, 0x50, 0xd2, 0xfe, 0xb6, 0x05, 0x68, 0xd1, 0x0b, 0x5c, 0x12, 0x1d, 0xc3, 0x92, + 0xd9, 0xdf, 0x24, 0xf8, 0x43, 0xda, 0xb4, 0x70, 0xbb, 0x1d, 0x06, 0x24, 0x48, 0x16, 0xc3, 0xc0, + 0xe5, 0xcb, 0xe8, 0x67, 0x60, 0x20, 0xa1, 0x55, 0xf1, 0x66, 0x9d, 0x97, 0x9f, 0x85, 0x56, 0xf0, + 0x60, 0x6f, 0xf6, 0x4c, 0x77, 0x09, 0xd6, 0x04, 0x56, 0x06, 0x7d, 0x1a, 0x86, 0xe2, 0xc4, 0x49, + 0x3a, 0xb1, 0x68, 0xe8, 0xc7, 0x64, 0x43, 0x9b, 0x0c, 0xfa, 0x60, 0x6f, 0x76, 0x52, 0x15, 0xe3, + 0x20, 0x2c, 0x0a, 0xa0, 0x67, 0x60, 0x78, 0x9b, 0xc4, 0xb1, 0xb3, 0x29, 0x15, 0xdb, 0xa4, 0x28, + 0x3b, 0xbc, 0xca, 0xc1, 0x58, 0xe2, 0xd1, 0x53, 0x30, 0x48, 0xa2, 0x28, 0x8c, 0x84, 0x44, 0x8c, + 0x0b, 0xc2, 0xc1, 0x25, 0x0a, 0xc4, 0x1c, 0x67, 0xff, 0x8e, 0x05, 0x93, 0xaa, 0xad, 0xbc, 0xae, + 0x23, 0x9c, 0xea, 0x2e, 0x40, 0x4b, 0x76, 0x2c, 0x66, 0x13, 0x6c, 0xf4, 0xca, 0x27, 0x0f, 0xe6, + 0xdd, 0x3d, 0x90, 0x69, 0x1d, 0x0a, 0x14, 0x63, 0x8d, 0xaf, 0xfd, 0x63, 0x0b, 0x4e, 0x66, 0xfa, + 0x74, 0xc3, 0x8b, 0x13, 0xf4, 0x17, 0xbb, 0xfa, 0x75, 0xe9, 0x80, 0xba, 0x35, 0x8b, 0x72, 0x8e, + 0x16, 0x67, 0xdd, 0x53, 0x82, 0x22, 0x21, 0x5a, 0xe7, 0x30, 0x0c, 0x7a, 0x09, 0xd9, 0x96, 0xfd, + 0x7a, 0xbe, 0x64, 0xbf, 0x78, 0x03, 0xd3, 0xcf, 0xb3, 0x42, 0x79, 0x60, 0xce, 0xca, 0xfe, 0xdf, + 0x16, 0xd4, 0x16, 0xc3, 0x60, 0xc3, 0xdb, 0x5c, 0x75, 0xda, 0x47, 0xf8, 0x61, 0x9a, 0x30, 0xc0, + 0xb8, 0xf2, 0xa6, 0x5f, 0x2e, 0x6a, 0xba, 0x68, 0xd0, 0x1c, 0x5d, 0x3c, 0xb9, 0x55, 0xa0, 0xf4, + 0x12, 0x05, 0x61, 0xc6, 0x6c, 0xe6, 0x65, 0xa8, 0x29, 0x02, 0x34, 0x05, 0xd5, 0xbb, 0x84, 0x9b, + 0x8c, 0x35, 0x4c, 0x7f, 0xa2, 0x53, 0x30, 0xb8, 0xe3, 0xf8, 0x1d, 0x31, 0x5b, 0x31, 0xff, 0xf3, + 0x99, 0xca, 0x2b, 0x96, 0xfd, 0x03, 0x0b, 0x4e, 0xa9, 0x4a, 0xae, 0x93, 0xdd, 0x26, 0xf1, 0x49, + 0x2b, 0x09, 0x23, 0xf4, 0xbe, 0x05, 0xa7, 0xfc, 0x1c, 0x3d, 0x24, 0x46, 0xe3, 0x30, 0x1a, 0xec, + 0x09, 0xd1, 0xf0, 0x53, 0x79, 0x58, 0x9c, 0x5b, 0x1b, 0x7a, 0x92, 0xf7, 0x85, 0x4f, 0xde, 0x51, + 0xc1, 0xa0, 0x7a, 0x9d, 0xec, 0xb2, 0x8e, 0xd1, 0xe6, 0x8f, 0xab, 0xe6, 0x1f, 0x87, 0xe4, 0xdd, + 0x30, 0x25, 0xef, 0x13, 0x25, 0x3f, 0x5f, 0x0f, 0x99, 0xfb, 0xfb, 0x15, 0x38, 0xad, 0x68, 0x0c, + 0x75, 0xfc, 0x88, 0x0c, 0x7f, 0x7f, 0xdd, 0xbd, 0x4e, 0x76, 0xd7, 0x42, 0xba, 0x9e, 0xe6, 0x77, + 0x17, 0x5d, 0x86, 0x51, 0x97, 0x6c, 0x38, 0x1d, 0x3f, 0x51, 0xe6, 0xe2, 0x20, 0xdf, 0x47, 0xd4, + 0x53, 0x30, 0xd6, 0x69, 0xec, 0xdf, 0xae, 0xb1, 0x59, 0x99, 0x38, 0x5e, 0x40, 0x22, 0xba, 0x40, + 0x6b, 0x56, 0xfd, 0x98, 0x6e, 0xd5, 0x0b, 0x0b, 0xfe, 0x29, 0x18, 0xf4, 0xb6, 0xa9, 0xca, 0xae, + 0x98, 0x9a, 0x78, 0x85, 0x02, 0x31, 0xc7, 0xa1, 0xa7, 0x61, 0xb8, 0x15, 0x6e, 0x6f, 0x3b, 0x81, + 0x3b, 0x5d, 0x65, 0x26, 0xc3, 0x28, 0xd5, 0xea, 0x8b, 0x1c, 0x84, 0x25, 0x0e, 0x3d, 0x01, 0x03, + 0x4e, 0xb4, 0x19, 0x4f, 0x0f, 0x30, 0x9a, 0x11, 0x5a, 0xd3, 0x7c, 0xb4, 0x19, 0x63, 0x06, 0xa5, + 0xa6, 0xc0, 0xbd, 0x30, 0xba, 0xeb, 0x05, 0x9b, 0x75, 0x2f, 0x62, 0xeb, 0xba, 0x66, 0x0a, 0xdc, + 0x51, 0x18, 0xac, 0x51, 0xa1, 0x06, 0x0c, 0xb6, 0xc3, 0x28, 0x89, 0xa7, 0x87, 0xd8, 0x70, 0x3e, + 0x57, 0x28, 0x3d, 0xbc, 0xdf, 0x8d, 0x30, 0x4a, 0xd2, 0xae, 0xd0, 0x7f, 0x31, 0xe6, 0x8c, 0xd0, + 0x22, 0x54, 0x49, 0xb0, 0x33, 0x3d, 0xcc, 0xf8, 0x7d, 0xfc, 0x60, 0x7e, 0x4b, 0xc1, 0xce, 0x9b, + 0x4e, 0x94, 0xce, 0xa2, 0xa5, 0x60, 0x07, 0xd3, 0xd2, 0xa8, 0x05, 0x35, 0xe9, 0x08, 0x88, 0xa7, + 0x47, 0xca, 0x08, 0x18, 0x16, 0xe4, 0x98, 0xbc, 0xd7, 0xf1, 0x22, 0xb2, 0x4d, 0x82, 0x24, 0x4e, + 0xed, 0x61, 0x89, 0x8d, 0x71, 0xca, 0x17, 0xb5, 0x60, 0x8c, 0x9b, 0x0f, 0xab, 0x61, 0x27, 0x48, + 0xe2, 0xe9, 0x1a, 0x6b, 0x72, 0xc1, 0x86, 0xf3, 0xcd, 0xb4, 0xc4, 0xc2, 0x29, 0xc1, 0x7e, 0x4c, + 0x03, 0xc6, 0xd8, 0x60, 0x8a, 0xde, 0x86, 0x71, 0xdf, 0xdb, 0x21, 0x01, 0x89, 0xe3, 0x46, 0x14, + 0xae, 0x93, 0x69, 0x60, 0xbd, 0x79, 0xaa, 0x68, 0xf3, 0x15, 0xae, 0x93, 0x85, 0x13, 0xfb, 0x7b, + 0xb3, 0xe3, 0x37, 0xf4, 0xd2, 0xd8, 0x64, 0x86, 0xde, 0x85, 0x09, 0x6a, 0xab, 0x78, 0x29, 0xfb, + 0xd1, 0xf2, 0xec, 0xd1, 0xfe, 0xde, 0xec, 0x04, 0x36, 0x8a, 0xe3, 0x0c, 0x3b, 0xb4, 0x06, 0x35, + 0xdf, 0xdb, 0x20, 0xad, 0xdd, 0x96, 0x4f, 0xa6, 0xc7, 0x18, 0xef, 0x82, 0x29, 0x77, 0x43, 0x92, + 0x73, 0xfb, 0x50, 0xfd, 0xc5, 0x29, 0x23, 0xf4, 0x26, 0x9c, 0x49, 0x48, 0xb4, 0xed, 0x05, 0x0e, + 0x5d, 0xb4, 0x85, 0xf1, 0xc2, 0x76, 0xb8, 0xe3, 0x4c, 0x6a, 0xcf, 0x8a, 0x81, 0x3d, 0xb3, 0x96, + 0x4b, 0x85, 0x7b, 0x94, 0x46, 0xb7, 0x60, 0x92, 0xcd, 0xa7, 0x46, 0xc7, 0xf7, 0x1b, 0xa1, 0xef, + 0xb5, 0x76, 0xa7, 0x27, 0x18, 0xc3, 0xa7, 0xe5, 0xbe, 0x75, 0xc5, 0x44, 0x53, 0xbb, 0x3e, 0xfd, + 0x87, 0xb3, 0xa5, 0x91, 0x0f, 0x93, 0x31, 0x69, 0x75, 0x22, 0x2f, 0xd9, 0xa5, 0xb2, 0x4f, 0xee, + 0x27, 0xd3, 0x93, 0x65, 0xf6, 0x29, 0x4d, 0xb3, 0x10, 0x77, 0x1a, 0x64, 0x80, 0x38, 0xcb, 0x9a, + 0xaa, 0x8a, 0x38, 0x71, 0xbd, 0x60, 0x7a, 0x8a, 0x19, 0xa6, 0x6a, 0x7e, 0x35, 0x29, 0x10, 0x73, + 0x1c, 0xdb, 0xf6, 0xd1, 0x1f, 0xb7, 0xa8, 0xee, 0x3d, 0xc1, 0x08, 0xd3, 0x6d, 0x9f, 0x44, 0xe0, + 0x94, 0x86, 0x2e, 0x58, 0x49, 0xb2, 0x3b, 0x8d, 0x18, 0xa9, 0x9a, 0x6a, 0x6b, 0x6b, 0x5f, 0xc0, + 0x14, 0x6e, 0xaf, 0xc3, 0x84, 0x9a, 0xd6, 0x6c, 0x74, 0xd0, 0x2c, 0x0c, 0x52, 0xcd, 0x25, 0x77, + 0x2f, 0x35, 0xda, 0x04, 0xaa, 0xd0, 0x62, 0xcc, 0xe1, 0xac, 0x09, 0xde, 0x57, 0xc9, 0xc2, 0x6e, + 0x42, 0xb8, 0x15, 0x5b, 0xd5, 0x9a, 0x20, 0x11, 0x38, 0xa5, 0xb1, 0xff, 0x2f, 0x5f, 0x14, 0x53, + 0xdd, 0x51, 0x42, 0x6f, 0x5e, 0x84, 0x91, 0xad, 0x30, 0x4e, 0x28, 0x35, 0xab, 0x63, 0x30, 0x5d, + 0x05, 0xaf, 0x09, 0x38, 0x56, 0x14, 0xe8, 0x55, 0x18, 0x6f, 0xe9, 0x15, 0x08, 0x55, 0x7e, 0x5a, + 0x14, 0x31, 0x6b, 0xc7, 0x26, 0x2d, 0x7a, 0x05, 0x46, 0x98, 0x2b, 0xaf, 0x15, 0xfa, 0xc2, 0x5e, + 0x96, 0x2b, 0xd3, 0x48, 0x43, 0xc0, 0x1f, 0x68, 0xbf, 0xb1, 0xa2, 0xa6, 0xbb, 0x0e, 0xda, 0x84, + 0x95, 0x86, 0x50, 0xb7, 0x6a, 0xd7, 0x71, 0x8d, 0x41, 0xb1, 0xc0, 0xda, 0xbf, 0x56, 0xd1, 0x46, + 0x99, 0x1a, 0x7d, 0x04, 0x7d, 0x11, 0x86, 0xef, 0x39, 0x5e, 0xe2, 0x05, 0x9b, 0x62, 0x05, 0x7d, + 0xa1, 0xa4, 0xee, 0x65, 0xc5, 0xef, 0xf0, 0xa2, 0x7c, 0x9d, 0x10, 0x7f, 0xb0, 0x64, 0x48, 0x79, + 0x47, 0x9d, 0x20, 0xa0, 0xbc, 0x2b, 0xfd, 0xf3, 0xc6, 0xbc, 0x28, 0xe7, 0x2d, 0xfe, 0x60, 0xc9, + 0x10, 0x6d, 0x00, 0xc8, 0xd9, 0x47, 0x5c, 0xe1, 0x42, 0xfb, 0x54, 0x3f, 0xec, 0xd7, 0x54, 0xe9, + 0x85, 0x09, 0xba, 0x32, 0xa5, 0xff, 0xb1, 0xc6, 0xd9, 0xee, 0x30, 0x43, 0xa4, 0xbb, 0x59, 0xe8, + 0x6d, 0x3a, 0x01, 0x9c, 0x28, 0x21, 0xee, 0x7c, 0x22, 0x86, 0xee, 0xb9, 0x92, 0x06, 0xd5, 0x9a, + 0xb7, 0x4d, 0xf4, 0xd9, 0x22, 0xb8, 0xe0, 0x94, 0xa1, 0xfd, 0xfd, 0x2a, 0x4c, 0xf7, 0x6a, 0x2f, + 0x95, 0x49, 0x72, 0xdf, 0x4b, 0x16, 0xa9, 0xad, 0x60, 0x99, 0x32, 0xb9, 0x24, 0xe0, 0x58, 0x51, + 0x50, 0xe1, 0x88, 0xbd, 0xcd, 0xc0, 0xf1, 0x85, 0xfc, 0x2a, 0xe1, 0x68, 0x32, 0x28, 0x16, 0x58, + 0x4a, 0x17, 0x11, 0x27, 0x16, 0x2e, 0x5c, 0x4d, 0x88, 0x30, 0x83, 0x62, 0x81, 0xd5, 0xb7, 0x7f, + 0x03, 0x05, 0xdb, 0x3f, 0x63, 0x8c, 0x06, 0x1f, 0xf2, 0x18, 0xa1, 0x77, 0x01, 0x36, 0xbc, 0xc0, + 0x8b, 0xb7, 0x18, 0xfb, 0xa1, 0xfe, 0xd9, 0x2b, 0xab, 0x64, 0x59, 0xb1, 0xc1, 0x1a, 0x4b, 0xf4, + 0x12, 0x8c, 0xaa, 0x19, 0xba, 0x52, 0x9f, 0x1e, 0x36, 0x1d, 0x7f, 0xa9, 0xba, 0xaa, 0x63, 0x9d, + 0xce, 0xfe, 0x4a, 0x56, 0x64, 0xc4, 0xc4, 0xd0, 0x46, 0xd8, 0x2a, 0x3b, 0xc2, 0x95, 0x83, 0x47, + 0xd8, 0xfe, 0x2f, 0x55, 0xba, 0x77, 0xd6, 0x2a, 0xeb, 0xc4, 0x25, 0x94, 0xda, 0x1b, 0x54, 0xc3, + 0x3b, 0x09, 0x11, 0xd3, 0xf2, 0x62, 0x3f, 0xf3, 0x46, 0x5f, 0x0f, 0xe8, 0x74, 0xe0, 0x9c, 0xd0, + 0x16, 0xd4, 0x7c, 0x27, 0x66, 0x3b, 0x49, 0x22, 0xa6, 0x63, 0x7f, 0x6c, 0x53, 0x2b, 0xdc, 0x89, + 0x13, 0x6d, 0xc1, 0xe5, 0xb5, 0xa4, 0xcc, 0xe9, 0xf2, 0x44, 0xad, 0x03, 0x79, 0x72, 0xa0, 0x9a, + 0x43, 0x4d, 0x88, 0x5d, 0xcc, 0x71, 0xe8, 0x15, 0x18, 0x8b, 0x08, 0x13, 0x95, 0x45, 0x6a, 0x00, + 0x31, 0xe1, 0x1b, 0x4c, 0x2d, 0x25, 0xac, 0xe1, 0xb0, 0x41, 0x99, 0x1a, 0xca, 0x43, 0x07, 0x18, + 0xca, 0xcf, 0xc0, 0x30, 0xfb, 0xa1, 0xa4, 0x42, 0x7d, 0xa1, 0x15, 0x0e, 0xc6, 0x12, 0x9f, 0x15, + 0xa2, 0x91, 0x92, 0x42, 0xf4, 0x2c, 0x4c, 0xd4, 0x1d, 0xb2, 0x1d, 0x06, 0x4b, 0x81, 0xdb, 0x0e, + 0xbd, 0x20, 0x41, 0xd3, 0x30, 0xc0, 0x96, 0x14, 0x3e, 0xe3, 0x07, 0x28, 0x07, 0x3c, 0x40, 0x8d, + 0x5d, 0xfb, 0xff, 0x59, 0x30, 0x5e, 0x27, 0x3e, 0x49, 0xc8, 0xad, 0x36, 0x73, 0x3f, 0xa0, 0x65, + 0x40, 0x9b, 0x91, 0xd3, 0x22, 0x0d, 0x12, 0x79, 0xa1, 0xdb, 0x24, 0xad, 0x30, 0x60, 0x0e, 0x77, + 0xba, 0x46, 0x9e, 0xd9, 0xdf, 0x9b, 0x45, 0x57, 0xbb, 0xb0, 0x38, 0xa7, 0x04, 0x72, 0x61, 0xbc, + 0x1d, 0x11, 0xc3, 0x5f, 0x62, 0x15, 0xdb, 0xe7, 0x0d, 0xbd, 0x08, 0x37, 0x1f, 0x0d, 0x10, 0x36, + 0x99, 0xa2, 0xcf, 0xc1, 0x54, 0x18, 0xb5, 0xb7, 0x9c, 0xa0, 0x4e, 0xda, 0x24, 0x70, 0xa9, 0xcd, + 0x2c, 0x9c, 0x62, 0xa7, 0xf6, 0xf7, 0x66, 0xa7, 0x6e, 0x65, 0x70, 0xb8, 0x8b, 0xda, 0xfe, 0x95, + 0x0a, 0x9c, 0xae, 0x87, 0xf7, 0x82, 0x7b, 0x4e, 0xe4, 0xce, 0x37, 0x56, 0xb8, 0x21, 0xcc, 0x9c, + 0x8c, 0xd2, 0xb9, 0x69, 0xf5, 0x74, 0x6e, 0x7e, 0x09, 0x46, 0x36, 0x3c, 0xe2, 0xbb, 0x98, 0x6c, + 0x88, 0xee, 0x5d, 0x2e, 0xe3, 0xd1, 0x58, 0xa6, 0x65, 0xa4, 0x57, 0x80, 0xfb, 0x56, 0x97, 0x05, + 0x1b, 0xac, 0x18, 0xa2, 0x0e, 0x4c, 0x49, 0x4b, 0x5f, 0x62, 0xc5, 0xec, 0x78, 0xa1, 0xdc, 0x46, + 0xc2, 0xac, 0x86, 0x8d, 0x07, 0xce, 0x30, 0xc4, 0x5d, 0x55, 0xd0, 0x1d, 0xda, 0x36, 0x5d, 0x1d, + 0x06, 0x98, 0xac, 0xb0, 0x1d, 0x1a, 0xdb, 0x42, 0x32, 0xa8, 0xfd, 0x8f, 0x2d, 0x78, 0xac, 0x6b, + 0xb4, 0xc4, 0xfe, 0xfa, 0x2d, 0xb9, 0xb1, 0xe5, 0xa7, 0x33, 0x05, 0xad, 0xcc, 0x1d, 0xf3, 0x72, + 0x9b, 0xdc, 0x4a, 0x89, 0x4d, 0xee, 0x2d, 0x38, 0xb5, 0xb4, 0xdd, 0x4e, 0x76, 0xeb, 0x9e, 0xe9, + 0x93, 0x7d, 0x19, 0x86, 0xb6, 0x89, 0xeb, 0x75, 0xb6, 0xc5, 0x67, 0x9d, 0x95, 0x8a, 0x74, 0x95, + 0x41, 0x1f, 0xec, 0xcd, 0x8e, 0x37, 0x93, 0x30, 0x72, 0x36, 0x09, 0x07, 0x60, 0x41, 0x6e, 0x7f, + 0x60, 0xc1, 0xa4, 0x9c, 0x50, 0xf3, 0xae, 0x1b, 0x91, 0x38, 0x46, 0x33, 0x50, 0xf1, 0xda, 0x82, + 0x11, 0x08, 0x46, 0x95, 0x95, 0x06, 0xae, 0x78, 0x6d, 0xf4, 0x45, 0xa8, 0x71, 0x57, 0x7e, 0x2a, + 0x1c, 0x7d, 0x1e, 0x0d, 0xb0, 0xdd, 0xc7, 0x9a, 0xe4, 0x81, 0x53, 0x76, 0xd2, 0xb2, 0x64, 0xaa, + 0xba, 0x6a, 0x3a, 0x96, 0xaf, 0x09, 0x38, 0x56, 0x14, 0xe8, 0x02, 0x8c, 0x04, 0xa1, 0xcb, 0x4f, + 0x59, 0xf8, 0xb2, 0xcb, 0x44, 0xee, 0xa6, 0x80, 0x61, 0x85, 0xb5, 0xbf, 0x61, 0xc1, 0x98, 0xec, + 0x63, 0x49, 0x23, 0x97, 0x4e, 0x92, 0xd4, 0xc0, 0x4d, 0x27, 0x09, 0x35, 0x52, 0x19, 0xc6, 0xb0, + 0x4d, 0xab, 0xfd, 0xd8, 0xa6, 0xf6, 0xf7, 0x2b, 0x30, 0x21, 0x9b, 0xd3, 0xec, 0xac, 0xc7, 0x24, + 0x41, 0xef, 0x40, 0xcd, 0xe1, 0x83, 0x4f, 0xa4, 0x9c, 0x3d, 0x5f, 0xb4, 0x43, 0x37, 0xbe, 0x59, + 0x6a, 0x18, 0xcc, 0x4b, 0x3e, 0x38, 0x65, 0x89, 0x76, 0xe0, 0x44, 0x10, 0x26, 0x6c, 0x3d, 0x50, + 0xf8, 0x72, 0x1e, 0xd1, 0x6c, 0x3d, 0x8f, 0x8b, 0x7a, 0x4e, 0xdc, 0xcc, 0xf2, 0xc3, 0xdd, 0x55, + 0xa0, 0x5b, 0xd2, 0x8b, 0x51, 0x65, 0x75, 0x3d, 0x5b, 0xae, 0xae, 0xde, 0x4e, 0x0c, 0xfb, 0x87, + 0x16, 0xd4, 0x24, 0xd9, 0x51, 0xfa, 0xc4, 0xef, 0xc0, 0x70, 0xcc, 0x3e, 0x8d, 0x1c, 0xa6, 0x8b, + 0xe5, 0x9a, 0xce, 0xbf, 0x67, 0xba, 0xf8, 0xf1, 0xff, 0x31, 0x96, 0xdc, 0x98, 0x1b, 0x52, 0x75, + 0xe0, 0xd1, 0x73, 0x43, 0xaa, 0xa6, 0xf5, 0x70, 0x43, 0xfe, 0xb2, 0x05, 0x43, 0xdc, 0x39, 0x54, + 0xce, 0xc3, 0xa6, 0xf9, 0x92, 0x53, 0x8e, 0x6f, 0x52, 0xa0, 0x70, 0x2d, 0xa3, 0x3b, 0x50, 0x63, + 0x3f, 0x96, 0xa3, 0x70, 0x5b, 0x2c, 0x04, 0xcf, 0x96, 0x71, 0x4e, 0x71, 0xc5, 0xc7, 0xb5, 0xc9, + 0x9b, 0x92, 0x01, 0x4e, 0x79, 0xd9, 0x3f, 0xa8, 0xd2, 0x59, 0x9f, 0x92, 0x1a, 0xcb, 0x9a, 0x75, + 0x1c, 0xcb, 0x5a, 0xe5, 0xe8, 0x97, 0xb5, 0xf7, 0x60, 0xb2, 0xa5, 0xf9, 0xe4, 0xd3, 0xc5, 0xf4, + 0x4a, 0x49, 0x77, 0xb3, 0xe6, 0xc8, 0xe7, 0xce, 0x90, 0x45, 0x93, 0x1d, 0xce, 0xf2, 0x47, 0x04, + 0xc6, 0xf8, 0x81, 0xa2, 0xa8, 0x6f, 0xa0, 0x50, 0x66, 0xb9, 0xdf, 0x85, 0x97, 0x50, 0x95, 0xb1, + 0xa0, 0x93, 0xa6, 0xc6, 0x08, 0x1b, 0x6c, 0xed, 0xbf, 0x39, 0x08, 0x83, 0x4b, 0x3b, 0x24, 0x48, + 0x8e, 0x70, 0x96, 0x6f, 0xc3, 0x84, 0x17, 0xec, 0x84, 0xfe, 0x0e, 0x71, 0x39, 0xfe, 0x70, 0x2b, + 0xda, 0x19, 0x51, 0xc9, 0xc4, 0x8a, 0xc1, 0x0c, 0x67, 0x98, 0x1f, 0xc5, 0x7e, 0xf2, 0x0d, 0x18, + 0xe2, 0x12, 0x21, 0x36, 0x93, 0x05, 0x4e, 0x52, 0x36, 0xa0, 0x62, 0xe6, 0xa4, 0xbb, 0x5e, 0xee, + 0x9f, 0x15, 0x8c, 0xd0, 0x5d, 0x98, 0xd8, 0xf0, 0xa2, 0x38, 0xa1, 0x1b, 0xc2, 0x38, 0x71, 0xb6, + 0xdb, 0x87, 0xd9, 0x48, 0xaa, 0x21, 0x59, 0x36, 0x58, 0xe1, 0x0c, 0x6b, 0xb4, 0x05, 0xe3, 0x74, + 0x1f, 0x93, 0xd6, 0x35, 0xdc, 0x7f, 0x5d, 0xca, 0x97, 0x74, 0x43, 0xe7, 0x84, 0x4d, 0xc6, 0x54, + 0x19, 0xb5, 0xd8, 0xc6, 0x67, 0x84, 0x2d, 0xe9, 0x4a, 0x19, 0xf1, 0x1d, 0x0f, 0xc7, 0x51, 0x9d, + 0xc6, 0xce, 0x8f, 0x6b, 0xa6, 0x4e, 0x4b, 0x4f, 0x89, 0xed, 0xef, 0xd2, 0x05, 0x88, 0x8e, 0xe2, + 0x71, 0xe8, 0xee, 0x6b, 0xa6, 0xee, 0x7e, 0xaa, 0xc4, 0xc7, 0xed, 0xa1, 0xb7, 0xbf, 0x0c, 0xa3, + 0xda, 0xb7, 0x47, 0x97, 0xa0, 0xd6, 0x92, 0x47, 0x9d, 0x42, 0x81, 0x2b, 0x03, 0x42, 0x9d, 0x81, + 0xe2, 0x94, 0x86, 0x0e, 0x0c, 0x35, 0xbc, 0xb2, 0x11, 0x11, 0xd4, 0x2c, 0xc3, 0x0c, 0x63, 0xbf, + 0x00, 0xb0, 0x74, 0x9f, 0xb4, 0xe6, 0x5b, 0xec, 0x20, 0x5e, 0x3b, 0x37, 0xb1, 0x7a, 0x9f, 0x9b, + 0xd8, 0x6f, 0xc3, 0xf8, 0xd2, 0x7d, 0xba, 0xb2, 0xcb, 0x6d, 0xda, 0x79, 0x18, 0x22, 0x0c, 0xc0, + 0x5a, 0x35, 0x92, 0x0a, 0x29, 0x27, 0xc3, 0x02, 0xcb, 0x8e, 0xd1, 0xef, 0x3b, 0x62, 0xc2, 0x6a, + 0x5b, 0xde, 0x25, 0x0a, 0xc4, 0x1c, 0x67, 0x7f, 0xc7, 0x82, 0x89, 0xe5, 0x45, 0xc3, 0x4e, 0x9e, + 0x03, 0xe0, 0xf6, 0xe6, 0x9d, 0x3b, 0x37, 0xa5, 0x1f, 0x95, 0x3b, 0xbb, 0x14, 0x14, 0x6b, 0x14, + 0xe8, 0x71, 0xa8, 0xfa, 0x9d, 0x40, 0x98, 0x81, 0xc3, 0xfb, 0x7b, 0xb3, 0xd5, 0x1b, 0x9d, 0x00, + 0x53, 0x98, 0x16, 0xd8, 0x50, 0x2d, 0x1d, 0xd8, 0x50, 0x1c, 0xda, 0xf7, 0xad, 0x2a, 0x4c, 0x2d, + 0xfb, 0xe4, 0xbe, 0xd1, 0xea, 0xf3, 0x30, 0xe4, 0x46, 0xde, 0x0e, 0x89, 0xb2, 0x6e, 0x92, 0x3a, + 0x83, 0x62, 0x81, 0x2d, 0x1d, 0x6b, 0x61, 0xc4, 0x99, 0x54, 0x8f, 0x38, 0xce, 0xa4, 0xb0, 0xcf, + 0x68, 0x03, 0x86, 0x43, 0xfe, 0xfd, 0xa7, 0x07, 0x99, 0xa0, 0xbf, 0x7a, 0x70, 0x63, 0xb2, 0xe3, + 0x33, 0x27, 0xa4, 0x87, 0x1f, 0x7a, 0x2b, 0x65, 0x29, 0xa0, 0x58, 0x32, 0x9f, 0xf9, 0x0c, 0x8c, + 0xe9, 0x94, 0x7d, 0x9d, 0x7e, 0xff, 0x9c, 0x05, 0x27, 0x97, 0xfd, 0xb0, 0x75, 0x37, 0x13, 0x0c, + 0xf3, 0x12, 0x8c, 0xd2, 0xa9, 0x1a, 0x1b, 0x11, 0x62, 0x46, 0x28, 0x9c, 0x40, 0x61, 0x9d, 0x4e, + 0x2b, 0x76, 0xfb, 0xf6, 0x4a, 0x3d, 0x2f, 0x82, 0x4e, 0xa0, 0xb0, 0x4e, 0x67, 0xff, 0x67, 0x0b, + 0x9e, 0xbc, 0xba, 0xb8, 0xd4, 0xa0, 0x6a, 0x24, 0x4e, 0x48, 0x90, 0x74, 0x05, 0xf1, 0x9d, 0x87, + 0xa1, 0xb6, 0xab, 0x35, 0x45, 0x89, 0x40, 0xa3, 0xce, 0x5a, 0x21, 0xb0, 0x8f, 0x4a, 0x24, 0xeb, + 0x2f, 0x5b, 0x70, 0xf2, 0xaa, 0x97, 0x60, 0xd2, 0x0e, 0xb3, 0x71, 0x77, 0x11, 0x69, 0x87, 0xb1, + 0x97, 0x84, 0xd1, 0x6e, 0x36, 0xee, 0x0e, 0x2b, 0x0c, 0xd6, 0xa8, 0x78, 0xcd, 0x3b, 0x1e, 0x55, + 0xb0, 0xa2, 0x53, 0x5a, 0xcd, 0x1c, 0x8e, 0x15, 0x05, 0xed, 0x98, 0xeb, 0x45, 0xcc, 0x16, 0xd9, + 0x15, 0x33, 0x58, 0x75, 0xac, 0x2e, 0x11, 0x38, 0xa5, 0xb1, 0xff, 0xae, 0x05, 0xa7, 0xaf, 0xfa, + 0x9d, 0x38, 0x21, 0xd1, 0x46, 0x6c, 0x34, 0xf6, 0x05, 0xa8, 0x11, 0x69, 0x37, 0x8b, 0xb6, 0xaa, + 0x35, 0x49, 0x19, 0xd4, 0x3c, 0xe8, 0x4f, 0xd1, 0x95, 0x88, 0x31, 0xeb, 0x2f, 0x22, 0xea, 0x5f, + 0x57, 0x60, 0xfc, 0xda, 0xda, 0x5a, 0xe3, 0x2a, 0x49, 0x84, 0x0e, 0x2e, 0x76, 0xf4, 0x34, 0xb4, + 0x5d, 0xee, 0xe8, 0x95, 0xb9, 0x1e, 0xb3, 0xae, 0x93, 0x78, 0xfe, 0x1c, 0x8f, 0xb1, 0x9e, 0x5b, + 0x09, 0x92, 0x5b, 0x51, 0x33, 0x89, 0xbc, 0x60, 0x33, 0x77, 0x57, 0x2c, 0xd7, 0x89, 0x6a, 0xaf, + 0x75, 0x02, 0xbd, 0x00, 0x43, 0x71, 0x6b, 0x8b, 0xa8, 0x4d, 0xfb, 0x47, 0x95, 0x19, 0xc2, 0xa0, + 0x0f, 0xf6, 0x66, 0x6b, 0xb7, 0xf1, 0x0a, 0xff, 0x83, 0x05, 0x29, 0x7a, 0x17, 0x46, 0xb7, 0x92, + 0xa4, 0x7d, 0x8d, 0x38, 0x2e, 0x89, 0xa4, 0x96, 0x28, 0xb0, 0x02, 0xe9, 0x60, 0xf0, 0x02, 0xe9, + 0xc4, 0x4a, 0x61, 0x31, 0xd6, 0x39, 0xda, 0x4d, 0x80, 0x14, 0xf7, 0x90, 0xb6, 0x36, 0xf6, 0x5f, + 0xae, 0xc0, 0xf0, 0x35, 0x27, 0x70, 0x7d, 0x12, 0xa1, 0x65, 0x18, 0x20, 0xf7, 0x49, 0xab, 0x9c, + 0x01, 0x9b, 0x2e, 0xa4, 0xdc, 0x53, 0x45, 0xff, 0x63, 0x56, 0x1e, 0x61, 0x18, 0xa6, 0xed, 0xbe, + 0xaa, 0x02, 0x33, 0x9f, 0x2b, 0x1e, 0x05, 0x25, 0x12, 0x7c, 0x15, 0x16, 0x20, 0x2c, 0x19, 0x31, + 0x9f, 0x4e, 0xab, 0xdd, 0xa4, 0xca, 0x2d, 0x29, 0x17, 0x7b, 0xbd, 0xb6, 0xd8, 0xe0, 0xe4, 0x82, + 0x2f, 0xf7, 0xe9, 0x48, 0x20, 0x4e, 0xd9, 0xd9, 0xaf, 0xc0, 0x29, 0x76, 0x2a, 0xe8, 0x24, 0x5b, + 0xc6, 0x9c, 0x29, 0x14, 0x4e, 0xfb, 0x1f, 0x54, 0xe0, 0xc4, 0x4a, 0x73, 0xb1, 0x69, 0x7a, 0xe3, + 0x5e, 0x81, 0x31, 0xbe, 0x3c, 0x53, 0xa1, 0x73, 0x7c, 0x51, 0x5e, 0xb9, 0xb1, 0xd7, 0x34, 0x1c, + 0x36, 0x28, 0xd1, 0x93, 0x50, 0xf5, 0xde, 0x0b, 0xb2, 0xf1, 0x41, 0x2b, 0x6f, 0xdc, 0xc4, 0x14, + 0x4e, 0xd1, 0x74, 0xa5, 0xe7, 0x2a, 0x4e, 0xa1, 0xd5, 0x6a, 0xff, 0x3a, 0x4c, 0x78, 0x71, 0x2b, + 0xf6, 0x56, 0x02, 0x3a, 0xff, 0x9d, 0x96, 0x14, 0xdf, 0xd4, 0xf6, 0xa7, 0x4d, 0x55, 0x58, 0x9c, + 0xa1, 0xd6, 0xf4, 0xed, 0x60, 0x69, 0x6b, 0xa1, 0x38, 0x42, 0xf3, 0x2b, 0x50, 0x53, 0x91, 0x34, + 0x32, 0x00, 0xca, 0xca, 0x0f, 0x80, 0x2a, 0xa1, 0x70, 0xa4, 0x8f, 0xb4, 0x9a, 0xeb, 0x23, 0xfd, + 0x67, 0x16, 0xa4, 0x41, 0x03, 0x08, 0x43, 0xad, 0x1d, 0xb2, 0x03, 0x88, 0x48, 0x1e, 0xf6, 0x3d, + 0x5d, 0x20, 0x89, 0x7c, 0x26, 0x70, 0x59, 0x69, 0xc8, 0xb2, 0x38, 0x65, 0x83, 0x6e, 0xc0, 0x70, + 0x3b, 0x22, 0xcd, 0x84, 0x85, 0xf9, 0xf6, 0xc1, 0x91, 0x49, 0x75, 0x83, 0x97, 0xc4, 0x92, 0x85, + 0xfd, 0x1b, 0x16, 0xc0, 0x0d, 0x6f, 0xdb, 0x4b, 0xb0, 0x13, 0x6c, 0x92, 0x23, 0xdc, 0x45, 0xde, + 0x84, 0x81, 0xb8, 0x4d, 0x5a, 0xe5, 0x8e, 0x8e, 0xd2, 0x16, 0x35, 0xdb, 0xa4, 0x95, 0x7e, 0x06, + 0xfa, 0x0f, 0x33, 0x3e, 0xf6, 0xaf, 0x02, 0x4c, 0xa4, 0x64, 0xd4, 0x8c, 0x47, 0xcf, 0x1b, 0x71, + 0xad, 0x8f, 0x67, 0xe2, 0x5a, 0x6b, 0x8c, 0x5a, 0x0b, 0x65, 0x4d, 0xa0, 0xba, 0xed, 0xdc, 0x17, + 0xbb, 0x86, 0x97, 0xca, 0x36, 0x88, 0xd6, 0x34, 0xb7, 0xea, 0xdc, 0xe7, 0x66, 0xd4, 0x73, 0x52, + 0x80, 0x56, 0x9d, 0xfb, 0x0f, 0xf8, 0x01, 0x11, 0x9b, 0x81, 0x74, 0x9b, 0xf2, 0xf5, 0xff, 0x9a, + 0xfe, 0x67, 0x4a, 0x91, 0x56, 0xc7, 0x6a, 0xf5, 0x02, 0xe1, 0xea, 0xeb, 0xb3, 0x56, 0x2f, 0xc8, + 0xd6, 0xea, 0x05, 0x25, 0x6a, 0xf5, 0x02, 0xf4, 0xbe, 0x05, 0xc3, 0xc2, 0x43, 0xce, 0xc2, 0xaf, + 0x46, 0xaf, 0x7c, 0xba, 0xaf, 0xaa, 0x85, 0xab, 0x9d, 0x57, 0x7f, 0x49, 0xda, 0x8e, 0x02, 0x5a, + 0xd8, 0x04, 0x59, 0x35, 0xfa, 0xb6, 0x05, 0x13, 0xe2, 0x37, 0x26, 0xef, 0x75, 0x48, 0x9c, 0x88, + 0x55, 0xea, 0x73, 0x87, 0x69, 0x8d, 0x60, 0xc1, 0x1b, 0xf5, 0x29, 0xa9, 0x62, 0x4c, 0x64, 0x61, + 0xdb, 0x32, 0xed, 0x41, 0xdf, 0xb3, 0xe0, 0xd4, 0xb6, 0x73, 0x9f, 0xd7, 0xc8, 0x61, 0xd8, 0x49, + 0xbc, 0x50, 0x84, 0x98, 0x2d, 0xf7, 0x2b, 0x27, 0x5d, 0x8c, 0x78, 0x73, 0x5f, 0x93, 0xc7, 0x96, + 0x79, 0x24, 0x85, 0x8d, 0xce, 0x6d, 0xe1, 0x8c, 0x0b, 0x23, 0x52, 0x30, 0x73, 0xac, 0xf6, 0x05, + 0x7d, 0x31, 0x3e, 0x78, 0x06, 0x4a, 0x07, 0xda, 0xdc, 0x1b, 0x1d, 0x27, 0x48, 0xbc, 0x64, 0x57, + 0xb3, 0xf1, 0x59, 0x2d, 0x42, 0x10, 0x8f, 0xb0, 0x96, 0x2d, 0x18, 0xd3, 0x65, 0xee, 0x08, 0x6b, + 0x0a, 0xe1, 0x64, 0x8e, 0x3c, 0x1d, 0x61, 0x85, 0x1d, 0x78, 0xbc, 0xa7, 0x5c, 0x1c, 0x5d, 0xb5, + 0xf6, 0x0f, 0x2d, 0x5d, 0x61, 0x1e, 0x87, 0x63, 0x66, 0xd5, 0x74, 0xcc, 0x5c, 0x28, 0x3b, 0x75, + 0x7a, 0x78, 0x67, 0x36, 0xf4, 0xf6, 0xd3, 0x95, 0x00, 0xad, 0xc1, 0x90, 0x4f, 0x21, 0xf2, 0x34, + 0xe8, 0x62, 0x3f, 0x93, 0x33, 0x35, 0x2e, 0x18, 0x3c, 0xc6, 0x82, 0x97, 0xfd, 0x9b, 0x16, 0x0c, + 0x1c, 0xc7, 0xf0, 0x34, 0xcc, 0xe1, 0xe9, 0x65, 0xa2, 0x8a, 0xbb, 0x9e, 0x73, 0xd8, 0xb9, 0xb7, + 0x74, 0x3f, 0x21, 0x41, 0xcc, 0x4c, 0xc9, 0xdc, 0x11, 0xfa, 0x95, 0x0a, 0x8c, 0xd2, 0x8a, 0xa4, + 0x9f, 0xe8, 0x55, 0x18, 0xf7, 0x9d, 0x75, 0xe2, 0x4b, 0x77, 0x72, 0x76, 0xdb, 0x75, 0x43, 0x47, + 0x62, 0x93, 0x96, 0x16, 0xde, 0xd0, 0xbd, 0xed, 0xc2, 0x24, 0x52, 0x85, 0x0d, 0x57, 0x3c, 0x36, + 0x69, 0xa9, 0xe5, 0x7f, 0xcf, 0x49, 0x5a, 0x5b, 0x62, 0x4b, 0xa6, 0x9a, 0x7b, 0x87, 0x02, 0x31, + 0xc7, 0xa1, 0x79, 0x98, 0x94, 0x12, 0xfb, 0x26, 0x1f, 0x3a, 0x61, 0x2e, 0xaa, 0x7b, 0x7a, 0xd8, + 0x44, 0xe3, 0x2c, 0x3d, 0xfa, 0x0c, 0x4c, 0xd0, 0xc1, 0x09, 0x3b, 0x89, 0x0c, 0x56, 0x18, 0x64, + 0xc1, 0x0a, 0x2c, 0x38, 0x74, 0xcd, 0xc0, 0xe0, 0x0c, 0xa5, 0xfd, 0x2e, 0x9c, 0xbc, 0x11, 0x3a, + 0xee, 0x82, 0xe3, 0x3b, 0x41, 0x8b, 0x44, 0x2b, 0xc1, 0x66, 0xe1, 0xb9, 0xae, 0x7e, 0xf6, 0x5a, + 0x29, 0x3a, 0x7b, 0xb5, 0x23, 0x40, 0x7a, 0x05, 0x22, 0xcc, 0xe6, 0x6d, 0x18, 0xf6, 0x78, 0x55, + 0x42, 0x6a, 0x2f, 0x17, 0x39, 0x95, 0xba, 0xda, 0xa8, 0x85, 0x8d, 0x70, 0x00, 0x96, 0x2c, 0xe9, + 0x4e, 0x22, 0xcf, 0x0b, 0x55, 0xbc, 0x59, 0xb3, 0xff, 0xaa, 0x05, 0x93, 0x37, 0x33, 0x97, 0xc1, + 0xce, 0xc3, 0x50, 0x4c, 0xa2, 0x1c, 0x97, 0x5a, 0x93, 0x41, 0xb1, 0xc0, 0x3e, 0xf4, 0x6d, 0xfa, + 0x2f, 0x56, 0xa0, 0xc6, 0x62, 0x36, 0xdb, 0x4e, 0xeb, 0x28, 0x8d, 0xd2, 0x55, 0xc3, 0x28, 0x2d, + 0xd8, 0x24, 0xaa, 0x06, 0xf5, 0xb2, 0x49, 0xd1, 0x6d, 0x75, 0x39, 0xaa, 0xd4, 0xfe, 0x30, 0x65, + 0xc8, 0xef, 0xd1, 0x4c, 0x98, 0x77, 0xa9, 0xe4, 0xc5, 0x29, 0x76, 0x1a, 0xaa, 0x68, 0x1f, 0xbd, + 0xd3, 0x50, 0xd5, 0xb4, 0x1e, 0x5a, 0xa9, 0xa1, 0xb5, 0x9e, 0xa9, 0xed, 0xcf, 0xb2, 0x00, 0x3c, + 0xc7, 0xf7, 0xbe, 0x4a, 0xd4, 0x25, 0xc3, 0x59, 0x11, 0x4f, 0x27, 0xa0, 0x0f, 0x98, 0x82, 0x11, + 0xff, 0xf8, 0xdd, 0xd1, 0xb4, 0x88, 0x7d, 0x0d, 0x26, 0x33, 0x63, 0x87, 0x5e, 0x82, 0xc1, 0xf6, + 0x96, 0x13, 0x93, 0x4c, 0x64, 0xc7, 0x60, 0x83, 0x02, 0x1f, 0xec, 0xcd, 0x4e, 0xa8, 0x02, 0x0c, + 0x82, 0x39, 0xb5, 0xfd, 0x27, 0x16, 0x0c, 0xdc, 0x0c, 0xdd, 0xa3, 0x94, 0xb1, 0x6b, 0x86, 0x8c, + 0x9d, 0x2f, 0xbe, 0x71, 0xde, 0x53, 0xbc, 0x1a, 0x19, 0xf1, 0xba, 0x50, 0x82, 0xd7, 0xc1, 0x92, + 0xb5, 0x0d, 0xa3, 0xec, 0x46, 0xbb, 0x08, 0x69, 0x79, 0xc1, 0xd8, 0x40, 0xcd, 0x66, 0x36, 0x50, + 0x93, 0x1a, 0xa9, 0xb6, 0x8d, 0x7a, 0x06, 0x86, 0x45, 0x08, 0x45, 0x36, 0xea, 0x50, 0xd0, 0x62, + 0x89, 0xb7, 0x7f, 0xbd, 0x0a, 0xc6, 0x0d, 0x7a, 0xf4, 0x23, 0x0b, 0xe6, 0x22, 0x7e, 0xe5, 0xc1, + 0xad, 0x77, 0x22, 0x2f, 0xd8, 0x6c, 0xb6, 0xb6, 0x88, 0xdb, 0xf1, 0xbd, 0x60, 0x73, 0x65, 0x33, + 0x08, 0x15, 0x78, 0xe9, 0x3e, 0x69, 0x75, 0x98, 0x77, 0xb5, 0xf4, 0xc5, 0x7d, 0x75, 0x86, 0x7a, + 0x65, 0x7f, 0x6f, 0x76, 0x0e, 0xf7, 0x55, 0x0b, 0xee, 0xb3, 0x55, 0xe8, 0xf7, 0x2d, 0xb8, 0xc4, + 0xef, 0x90, 0x97, 0xef, 0x49, 0xa9, 0x8d, 0x67, 0x43, 0x32, 0x4d, 0xd9, 0xad, 0x91, 0x68, 0x7b, + 0xe1, 0x65, 0x31, 0xc8, 0x97, 0x1a, 0xfd, 0xd5, 0x8a, 0xfb, 0x6d, 0xa6, 0xfd, 0x6f, 0xab, 0x30, + 0x4e, 0xc7, 0x33, 0xbd, 0x3f, 0xfa, 0x92, 0x21, 0x26, 0x1f, 0xcb, 0x88, 0xc9, 0x09, 0x83, 0xf8, + 0xe1, 0x5c, 0x1d, 0x4d, 0xe0, 0x84, 0xef, 0xc4, 0xc9, 0x35, 0xe2, 0x44, 0xc9, 0x3a, 0x71, 0xd8, + 0x81, 0xa5, 0x98, 0x04, 0x7d, 0x1d, 0x82, 0xaa, 0xb8, 0x9c, 0x1b, 0x59, 0x6e, 0xb8, 0xbb, 0x02, + 0x74, 0x0f, 0x10, 0x3b, 0x1d, 0x8d, 0x9c, 0x20, 0xe6, 0x9d, 0xf1, 0x84, 0x43, 0xb6, 0xcf, 0x6a, + 0x67, 0x44, 0xb5, 0xe8, 0x46, 0x17, 0x3b, 0x9c, 0x53, 0x85, 0x76, 0x04, 0x3e, 0x58, 0xf6, 0x08, + 0x7c, 0xa8, 0x20, 0xe0, 0xf7, 0xe7, 0x2d, 0x38, 0x49, 0x3f, 0x8c, 0x19, 0x1c, 0x1a, 0xa3, 0x10, + 0x26, 0x69, 0x0f, 0x7c, 0x92, 0x48, 0x98, 0x98, 0x61, 0x05, 0xb6, 0xb4, 0xc9, 0x27, 0xb5, 0xd8, + 0xae, 0x9b, 0xcc, 0x70, 0x96, 0xbb, 0xfd, 0xeb, 0x16, 0xb0, 0xe8, 0xb3, 0xe3, 0x58, 0xc7, 0xae, + 0x9a, 0xeb, 0x98, 0x5d, 0xac, 0x34, 0x7a, 0x2c, 0x61, 0x2f, 0xc2, 0x14, 0xc5, 0x36, 0xa2, 0xf0, + 0xfe, 0xae, 0x34, 0xae, 0x8b, 0x7d, 0xb3, 0xef, 0x57, 0xf8, 0xcc, 0x51, 0xd7, 0xb7, 0xd0, 0x2f, + 0x58, 0x30, 0xd2, 0x72, 0xda, 0x4e, 0x8b, 0xa7, 0x20, 0x29, 0xe1, 0x87, 0x31, 0xca, 0xcf, 0x2d, + 0x8a, 0xb2, 0xdc, 0x87, 0xf0, 0x49, 0xd9, 0x75, 0x09, 0x2e, 0xf4, 0x1b, 0xa8, 0xca, 0x67, 0x3c, + 0x18, 0x37, 0x98, 0x1d, 0xe1, 0xc6, 0xf3, 0x17, 0x2c, 0xae, 0xf5, 0xd5, 0xe6, 0xe0, 0x1e, 0x9c, + 0x08, 0xb4, 0xff, 0x54, 0x9f, 0x49, 0x5b, 0x78, 0xae, 0xbc, 0x5e, 0x67, 0x6a, 0x50, 0x0b, 0xb4, + 0xcb, 0x30, 0xc4, 0xdd, 0x75, 0xd8, 0xff, 0xd0, 0x82, 0xc7, 0x74, 0x42, 0xed, 0xb6, 0x5d, 0x91, + 0x5f, 0xb8, 0x0e, 0x23, 0x61, 0x9b, 0x44, 0x4e, 0xba, 0x11, 0xba, 0x20, 0x47, 0xff, 0x96, 0x80, + 0x3f, 0xd8, 0x9b, 0x3d, 0xa5, 0x73, 0x97, 0x70, 0xac, 0x4a, 0x22, 0x1b, 0x86, 0xd8, 0xb8, 0xc4, + 0xe2, 0x9e, 0x24, 0x4b, 0xc8, 0xc1, 0x4e, 0x43, 0x62, 0x2c, 0x30, 0xf6, 0x5f, 0xb3, 0xb8, 0xb0, + 0xe9, 0x4d, 0x47, 0x5f, 0x83, 0xa9, 0x6d, 0xba, 0x67, 0x5a, 0xba, 0xdf, 0xa6, 0x2b, 0x29, 0x3b, + 0x05, 0xb6, 0xca, 0xac, 0x1f, 0x3d, 0xba, 0xbb, 0x30, 0x2d, 0x5a, 0x3f, 0xb5, 0x9a, 0x61, 0x8b, + 0xbb, 0x2a, 0xb2, 0xff, 0x40, 0x4c, 0x59, 0x66, 0xbc, 0x3d, 0x03, 0xc3, 0xed, 0xd0, 0x5d, 0x5c, + 0xa9, 0x63, 0x31, 0x56, 0x4a, 0xe7, 0x34, 0x38, 0x18, 0x4b, 0x3c, 0xba, 0x02, 0x40, 0xee, 0x27, + 0x24, 0x0a, 0x1c, 0x5f, 0x9d, 0xde, 0x2a, 0x5b, 0x69, 0x49, 0x61, 0xb0, 0x46, 0x45, 0xcb, 0xb4, + 0xa3, 0x70, 0xc7, 0x73, 0x59, 0xd4, 0x7b, 0xd5, 0x2c, 0xd3, 0x50, 0x18, 0xac, 0x51, 0xd1, 0x9d, + 0x6a, 0x27, 0x88, 0xf9, 0x3a, 0xe6, 0xac, 0x8b, 0x3c, 0x12, 0x23, 0xe9, 0x4e, 0xf5, 0xb6, 0x8e, + 0xc4, 0x26, 0xad, 0xfd, 0x3b, 0x35, 0x80, 0xd4, 0x52, 0x42, 0xef, 0x77, 0xcf, 0xd0, 0x4f, 0x95, + 0x35, 0xb3, 0x1e, 0xde, 0xf4, 0x44, 0xdf, 0xb4, 0x60, 0xd4, 0xf1, 0xfd, 0xb0, 0xe5, 0x24, 0xac, + 0x47, 0x95, 0xb2, 0xba, 0x42, 0xb4, 0x64, 0x3e, 0x2d, 0xcb, 0x1b, 0xf3, 0x82, 0x3c, 0xdc, 0xd3, + 0x30, 0x85, 0xed, 0xd1, 0x9b, 0x80, 0x3e, 0x29, 0x2d, 0x6c, 0xfe, 0x51, 0x66, 0xb2, 0x16, 0x76, + 0x8d, 0x69, 0x48, 0xcd, 0xb8, 0x46, 0xef, 0x1a, 0x29, 0x13, 0x06, 0xca, 0x5c, 0xd1, 0x35, 0x6c, + 0x87, 0xa2, 0x6c, 0x09, 0xe8, 0x8b, 0x7a, 0x40, 0xf0, 0x60, 0x99, 0xfb, 0xaf, 0x9a, 0x09, 0x5b, + 0x10, 0x0c, 0x9c, 0xc0, 0xa4, 0x6b, 0xae, 0x95, 0x22, 0xc2, 0xeb, 0x72, 0x71, 0x0d, 0x99, 0x45, + 0x36, 0x5d, 0x1d, 0x33, 0x08, 0x9c, 0xad, 0x02, 0x7d, 0x91, 0x87, 0x6b, 0xaf, 0x04, 0x1b, 0xa1, + 0x08, 0xf2, 0xba, 0x58, 0xe2, 0x9b, 0xef, 0xc6, 0x09, 0xd9, 0xa6, 0x65, 0xd2, 0xd5, 0xf0, 0xa6, + 0xe0, 0x82, 0x15, 0x3f, 0xb4, 0x06, 0x43, 0xec, 0x72, 0x49, 0x3c, 0x3d, 0x52, 0xc6, 0x5b, 0x66, + 0x5e, 0xab, 0x4c, 0x6d, 0x10, 0xf6, 0x37, 0xc6, 0x82, 0x17, 0xba, 0x26, 0xaf, 0x21, 0xc7, 0x2b, + 0xc1, 0xed, 0x98, 0xb0, 0x6b, 0xc8, 0xb5, 0x85, 0x8f, 0xa7, 0xf7, 0x8a, 0x39, 0x3c, 0x37, 0x49, + 0x94, 0x51, 0x92, 0x9a, 0x22, 0xe2, 0xbf, 0xcc, 0x3d, 0x35, 0x0d, 0x65, 0x1a, 0x6a, 0x66, 0xaa, + 0x4a, 0x07, 0xfb, 0x4d, 0x93, 0x19, 0xce, 0x72, 0x3f, 0xc6, 0x35, 0x70, 0xc6, 0x87, 0xa9, 0xec, + 0x94, 0x3c, 0xc2, 0x15, 0xf7, 0x8f, 0x07, 0x60, 0xc2, 0x14, 0x0c, 0x74, 0x09, 0x6a, 0xdb, 0x2c, + 0x33, 0x54, 0x9a, 0x8f, 0x46, 0xc9, 0xff, 0xaa, 0x44, 0xe0, 0x94, 0x86, 0x65, 0xe6, 0x61, 0xc5, + 0xb5, 0xd0, 0x9b, 0x34, 0x33, 0x8f, 0xc2, 0x60, 0x8d, 0x8a, 0xda, 0xad, 0xeb, 0x61, 0x98, 0x28, + 0xc5, 0xad, 0x64, 0x66, 0x81, 0x41, 0xb1, 0xc0, 0x52, 0x85, 0x7d, 0x97, 0x76, 0xc8, 0x37, 0xdd, + 0x7e, 0x4a, 0x61, 0x5f, 0xd7, 0x91, 0xd8, 0xa4, 0xa5, 0x0b, 0x50, 0x18, 0x33, 0x21, 0x14, 0xd6, + 0x71, 0x1a, 0xca, 0xd4, 0xe4, 0x97, 0xad, 0x24, 0x1e, 0x7d, 0x01, 0x1e, 0x53, 0x77, 0xa3, 0x30, + 0x77, 0xa3, 0xca, 0x1a, 0x87, 0x8c, 0x2d, 0xee, 0x63, 0x8b, 0xf9, 0x64, 0xb8, 0x57, 0x79, 0xf4, + 0x3a, 0x4c, 0x08, 0xcb, 0x56, 0x72, 0x1c, 0x36, 0x4f, 0xba, 0xaf, 0x1b, 0x58, 0x9c, 0xa1, 0x46, + 0x75, 0x98, 0xa2, 0x10, 0x66, 0x51, 0x4a, 0x0e, 0xfc, 0x8e, 0x97, 0x5a, 0x99, 0xaf, 0x67, 0xf0, + 0xb8, 0xab, 0x04, 0x9a, 0x87, 0x49, 0x6e, 0x5b, 0xd0, 0x8d, 0x1c, 0xfb, 0x0e, 0x22, 0x28, 0x53, + 0x4d, 0x82, 0x5b, 0x26, 0x1a, 0x67, 0xe9, 0xd1, 0x2b, 0x30, 0xe6, 0x44, 0xad, 0x2d, 0x2f, 0x21, + 0xad, 0xa4, 0x13, 0xf1, 0x0b, 0xfe, 0x5a, 0xa8, 0xc0, 0xbc, 0x86, 0xc3, 0x06, 0xa5, 0xfd, 0x55, + 0x38, 0x99, 0x13, 0xfb, 0x4d, 0x05, 0xc7, 0x69, 0x7b, 0xb2, 0x4f, 0x99, 0xa0, 0xa4, 0xf9, 0xc6, + 0x8a, 0xec, 0x8d, 0x46, 0x45, 0xa5, 0x93, 0xf9, 0x8f, 0xb5, 0x34, 0x71, 0x4a, 0x3a, 0x97, 0x25, + 0x02, 0xa7, 0x34, 0xf6, 0xff, 0xa8, 0x81, 0xe6, 0x6d, 0x29, 0x11, 0x8a, 0xf2, 0x0a, 0x8c, 0xc9, + 0xcc, 0x87, 0x5a, 0xc6, 0x31, 0xd5, 0xcd, 0xab, 0x1a, 0x0e, 0x1b, 0x94, 0xb4, 0x6d, 0x81, 0xf4, + 0x1d, 0x65, 0x43, 0xa0, 0x94, 0x53, 0x09, 0xa7, 0x34, 0xe8, 0x22, 0x8c, 0xc4, 0xc4, 0xdf, 0xb8, + 0xe1, 0x05, 0x77, 0x85, 0x60, 0x2b, 0xad, 0xdc, 0x14, 0x70, 0xac, 0x28, 0xd0, 0xe7, 0xa0, 0xda, + 0xf1, 0x5c, 0x21, 0xca, 0x73, 0xd2, 0xee, 0xbc, 0xbd, 0x52, 0x7f, 0xb0, 0x37, 0x3b, 0x9b, 0x9f, + 0xce, 0x91, 0xee, 0xa6, 0xe3, 0x39, 0x3a, 0xf9, 0x68, 0xd1, 0x3c, 0x37, 0xfa, 0x50, 0x9f, 0x6e, + 0xf4, 0x2b, 0x00, 0xa2, 0xcf, 0x52, 0x92, 0xab, 0xe9, 0x37, 0xbb, 0xaa, 0x30, 0x58, 0xa3, 0xa2, + 0x7b, 0xf2, 0x56, 0x44, 0x1c, 0xb9, 0x69, 0xe5, 0x81, 0xc9, 0x23, 0x1f, 0x62, 0x4f, 0xbe, 0x98, + 0xe5, 0x86, 0xbb, 0x2b, 0x40, 0x6d, 0x38, 0xe1, 0xd2, 0x79, 0x64, 0xd4, 0x5a, 0x3b, 0x44, 0x38, + 0x34, 0xad, 0xb1, 0x9e, 0xe5, 0x84, 0xbb, 0x99, 0xa3, 0x77, 0x60, 0x46, 0x02, 0xbb, 0x6f, 0x3f, + 0xb2, 0xe9, 0x52, 0x5d, 0x38, 0xbb, 0xbf, 0x37, 0x3b, 0x53, 0xef, 0x49, 0x85, 0x0f, 0xe0, 0x80, + 0xde, 0x86, 0x21, 0x76, 0xf0, 0x12, 0x4f, 0x8f, 0xb2, 0xd5, 0xee, 0xc5, 0xb2, 0x7e, 0xc7, 0x39, + 0x76, 0x7c, 0x23, 0xe2, 0x39, 0xd3, 0xc3, 0x2c, 0x06, 0xc4, 0x82, 0x27, 0x6a, 0xc3, 0xa8, 0x13, + 0x04, 0x61, 0xe2, 0x70, 0x23, 0x6c, 0xac, 0x8c, 0x1d, 0xa9, 0x55, 0x31, 0x9f, 0x96, 0xe5, 0xf5, + 0xa8, 0x20, 0x31, 0x0d, 0x83, 0xf5, 0x2a, 0xe8, 0x32, 0x1e, 0xde, 0xa3, 0x0a, 0x53, 0x9e, 0x3d, + 0xc4, 0xd3, 0xe3, 0x65, 0x96, 0xf1, 0x5b, 0x46, 0x21, 0x4d, 0x83, 0x99, 0xcc, 0x70, 0x96, 0x3b, + 0x9a, 0x33, 0xdc, 0xc9, 0x13, 0x69, 0xb4, 0x72, 0xea, 0x4e, 0xd6, 0xbd, 0xc7, 0xec, 0x66, 0x2d, + 0x8f, 0x50, 0x64, 0x9a, 0x60, 0x32, 0x73, 0xb3, 0x36, 0x45, 0x61, 0x9d, 0x6e, 0xe6, 0xd3, 0x30, + 0xaa, 0x0d, 0x78, 0x3f, 0x61, 0xb1, 0x33, 0xaf, 0xc3, 0x54, 0x76, 0x20, 0xfb, 0x0a, 0xab, 0xfd, + 0x5f, 0x15, 0x98, 0xcc, 0x39, 0xd0, 0xb9, 0xeb, 0xb1, 0xc0, 0x71, 0x43, 0xe5, 0x5d, 0xf7, 0x02, + 0x17, 0x33, 0x8c, 0xa9, 0xb8, 0x2a, 0x25, 0x14, 0x97, 0xd4, 0xa2, 0xd5, 0x9e, 0x5a, 0x54, 0x28, + 0xab, 0x81, 0xc3, 0x2b, 0x2b, 0x73, 0x75, 0x18, 0x2c, 0xb5, 0x3a, 0x3c, 0x04, 0x05, 0x67, 0x2c, + 0x30, 0xc3, 0x25, 0x16, 0x98, 0x07, 0x16, 0x4c, 0x98, 0x92, 0x57, 0x62, 0xc4, 0x1f, 0xd5, 0x01, + 0x9c, 0x63, 0x1b, 0xb1, 0x24, 0x0a, 0x7d, 0x9f, 0x44, 0x22, 0x60, 0x6e, 0x42, 0xec, 0xab, 0x04, + 0x14, 0x6b, 0x14, 0xf6, 0xb7, 0x2b, 0x30, 0x95, 0x46, 0x4f, 0x8b, 0x0c, 0xb0, 0x47, 0x77, 0x42, + 0xb2, 0x66, 0x9c, 0x90, 0x14, 0x25, 0x76, 0xcd, 0xb4, 0xab, 0xe7, 0x69, 0xc9, 0xdb, 0x99, 0xd3, + 0x92, 0x17, 0xfb, 0xe4, 0x7b, 0xf0, 0xc9, 0xc9, 0x3f, 0xaf, 0xc0, 0xe9, 0x6c, 0x91, 0x45, 0xdf, + 0xf1, 0xb6, 0x8f, 0x70, 0x9c, 0xbe, 0x60, 0x8c, 0xd3, 0xcb, 0xfd, 0xf5, 0x87, 0x35, 0xae, 0xe7, + 0x60, 0x39, 0x99, 0xc1, 0xfa, 0xf4, 0x61, 0x98, 0x1f, 0x3c, 0x62, 0xbf, 0x6b, 0xc1, 0xe3, 0xb9, + 0xe5, 0x8e, 0xc3, 0x13, 0xfc, 0x96, 0xe9, 0x09, 0x7e, 0xe1, 0x10, 0xdd, 0xeb, 0xe1, 0x1a, 0xfe, + 0x6f, 0x95, 0x1e, 0xdd, 0x62, 0xde, 0xb2, 0x5b, 0x30, 0xea, 0xb4, 0x5a, 0x24, 0x8e, 0x57, 0x43, + 0x57, 0xa5, 0x24, 0x7a, 0x9e, 0xad, 0x9f, 0x29, 0xf8, 0xc1, 0xde, 0xec, 0x4c, 0x96, 0x45, 0x8a, + 0xc6, 0x3a, 0x07, 0x33, 0xb5, 0x58, 0xe5, 0x88, 0x52, 0x8b, 0x5d, 0x01, 0xd8, 0x51, 0xbb, 0xf4, + 0xac, 0x13, 0x4e, 0xdb, 0xbf, 0x6b, 0x54, 0xe8, 0x1d, 0x66, 0xf5, 0xf2, 0x48, 0x91, 0x81, 0xc2, + 0x09, 0x67, 0x7c, 0x40, 0x3d, 0xec, 0x84, 0x5f, 0x1d, 0x55, 0x1e, 0x4b, 0xc5, 0xd3, 0xfe, 0x6e, + 0x15, 0x3e, 0x7a, 0x80, 0xd8, 0xa1, 0x79, 0xf3, 0x00, 0xf8, 0xb9, 0xac, 0x7b, 0x6a, 0x26, 0xb7, + 0xb0, 0xe1, 0xaf, 0xca, 0x7c, 0xac, 0xca, 0x87, 0xfe, 0x58, 0xdf, 0xd2, 0x9d, 0x89, 0x3c, 0xe2, + 0xf3, 0xea, 0xa1, 0x27, 0xd6, 0x4f, 0xa7, 0xf3, 0xff, 0xeb, 0x16, 0x7c, 0x2c, 0xb7, 0x53, 0x46, + 0x9c, 0xc9, 0x25, 0xa8, 0xb5, 0x28, 0x50, 0xbb, 0x92, 0x93, 0xde, 0xb4, 0x93, 0x08, 0x9c, 0xd2, + 0x18, 0xe1, 0x24, 0x95, 0xc2, 0x70, 0x92, 0xff, 0x60, 0xc1, 0xa9, 0x6c, 0x23, 0x8e, 0x43, 0xeb, + 0x34, 0x4d, 0xad, 0x33, 0xd7, 0xdf, 0xb7, 0xef, 0xa1, 0x70, 0xbe, 0x3d, 0x0e, 0x67, 0xba, 0x16, + 0x2b, 0x3e, 0x8c, 0x3f, 0x6b, 0xc1, 0x89, 0x4d, 0xb6, 0xbf, 0xd0, 0x2e, 0x3e, 0x89, 0x8e, 0x15, + 0xdc, 0x16, 0x3b, 0xf0, 0xbe, 0x14, 0xdf, 0x2d, 0x75, 0x91, 0xe0, 0xee, 0xca, 0xd0, 0x37, 0x2c, + 0x38, 0xe5, 0xdc, 0x8b, 0xbb, 0x9e, 0x13, 0x10, 0x72, 0xf4, 0x7a, 0x81, 0x2b, 0xaf, 0xe0, 0x21, + 0x82, 0x85, 0xe9, 0xfd, 0xbd, 0xd9, 0x53, 0x79, 0x54, 0x38, 0xb7, 0x56, 0xf4, 0xb6, 0x48, 0xc3, + 0x46, 0xcd, 0xbe, 0x52, 0x57, 0xf8, 0xf2, 0xae, 0x61, 0x70, 0x9d, 0x24, 0x31, 0x58, 0x71, 0x44, + 0x5f, 0x86, 0xda, 0xa6, 0xbc, 0xeb, 0x24, 0x94, 0x5e, 0xc1, 0xca, 0x92, 0x7b, 0x35, 0x8a, 0x07, + 0xfb, 0x2b, 0x14, 0x4e, 0x99, 0xa2, 0x6b, 0x50, 0x0d, 0x36, 0x62, 0x71, 0x6d, 0xb9, 0x28, 0x9c, + 0xc8, 0x0c, 0xde, 0xe2, 0x17, 0x31, 0x6f, 0x2e, 0x37, 0x31, 0x65, 0x41, 0x39, 0x45, 0xeb, 0xae, + 0xf0, 0x61, 0x17, 0x70, 0xc2, 0x0b, 0xf5, 0x6e, 0x4e, 0x78, 0xa1, 0x8e, 0x29, 0x0b, 0x16, 0xb7, + 0x18, 0xb7, 0x62, 0x4f, 0x38, 0xa8, 0x0b, 0xee, 0xb4, 0x77, 0x5d, 0x4e, 0xe1, 0x19, 0xf9, 0x18, + 0x18, 0x73, 0x46, 0x68, 0x0d, 0x86, 0x5a, 0x2c, 0x83, 0xb6, 0xf0, 0x1f, 0x14, 0xe5, 0x55, 0xee, + 0xca, 0xb6, 0xcd, 0x0f, 0xd2, 0x38, 0x1c, 0x0b, 0x5e, 0x8c, 0x2b, 0x69, 0x6f, 0x6d, 0xc4, 0xc2, + 0x3f, 0x50, 0xc4, 0xb5, 0x2b, 0x17, 0xba, 0xe0, 0xca, 0xe0, 0x58, 0xf0, 0x42, 0x75, 0xa8, 0x6c, + 0xb4, 0x44, 0x1a, 0xcc, 0x82, 0x1d, 0xad, 0x79, 0xab, 0x76, 0x61, 0x68, 0x7f, 0x6f, 0xb6, 0xb2, + 0xbc, 0x88, 0x2b, 0x1b, 0x2d, 0xf4, 0x16, 0x0c, 0x6f, 0xf0, 0x7b, 0x92, 0x22, 0xe5, 0xe5, 0xe5, + 0xa2, 0xcb, 0x9c, 0x5d, 0x97, 0x2a, 0xf9, 0x85, 0x0e, 0x81, 0xc0, 0x92, 0x1d, 0x7a, 0x07, 0x60, + 0x43, 0xdd, 0xfc, 0x14, 0x39, 0x2f, 0xe7, 0xfa, 0xbb, 0x29, 0x2a, 0x76, 0xcf, 0x0a, 0x8a, 0x35, + 0x8e, 0x54, 0xe6, 0x1d, 0xf9, 0x08, 0x00, 0xcb, 0x77, 0x59, 0x28, 0xf3, 0xb9, 0x6f, 0x06, 0x70, + 0x99, 0x57, 0x28, 0x9c, 0x32, 0x45, 0x1d, 0x18, 0xdf, 0x89, 0xdb, 0x5b, 0x44, 0x4e, 0x7d, 0x96, + 0x04, 0x73, 0xf4, 0xca, 0x6b, 0x05, 0x99, 0x4d, 0x45, 0x11, 0x2f, 0x4a, 0x3a, 0x8e, 0xdf, 0xa5, + 0xc1, 0x58, 0x36, 0xa9, 0x37, 0x75, 0xb6, 0xd8, 0xac, 0x85, 0x7e, 0x92, 0xf7, 0x3a, 0xe1, 0xfa, + 0x6e, 0x42, 0x44, 0x92, 0xcc, 0x82, 0x4f, 0xf2, 0x06, 0x27, 0xee, 0xfe, 0x24, 0x02, 0x81, 0x25, + 0x3b, 0x35, 0x64, 0x4c, 0x1b, 0x4f, 0x95, 0x1e, 0xb2, 0xae, 0x3e, 0xa4, 0x43, 0xc6, 0xb4, 0x6f, + 0xca, 0x94, 0x69, 0xdd, 0xf6, 0x56, 0x98, 0x84, 0x41, 0x46, 0xf7, 0x9f, 0x28, 0xa3, 0x75, 0x1b, + 0x39, 0x25, 0xbb, 0xb5, 0x6e, 0x1e, 0x15, 0xce, 0xad, 0xd5, 0xfe, 0x83, 0xc1, 0xee, 0xf5, 0x96, + 0x99, 0xc3, 0xbf, 0xd4, 0x7d, 0xba, 0xfa, 0xb9, 0xfe, 0xb7, 0x7b, 0x0f, 0xf1, 0x9c, 0xf5, 0x1b, + 0x16, 0x9c, 0x69, 0xe7, 0x2e, 0xa6, 0x62, 0xc1, 0xea, 0x77, 0xd7, 0xc8, 0x07, 0x4c, 0x65, 0x80, + 0xcd, 0xc7, 0xe3, 0x1e, 0x75, 0x66, 0x2d, 0xd0, 0xea, 0x87, 0xb6, 0x40, 0xef, 0xc0, 0x08, 0x33, + 0x9a, 0xd2, 0x14, 0x24, 0x7d, 0x66, 0xed, 0x60, 0x4b, 0xdf, 0xa2, 0x60, 0x81, 0x15, 0x33, 0x3a, + 0x70, 0x4f, 0x66, 0x3b, 0x81, 0x09, 0x43, 0x8b, 0xd4, 0xb5, 0xdc, 0x35, 0xb1, 0x2c, 0x46, 0xe2, + 0xc9, 0xc6, 0x41, 0xc4, 0x0f, 0x8a, 0x08, 0xf0, 0xc1, 0x95, 0x1d, 0xa7, 0x45, 0xfb, 0x4f, 0xac, + 0x1c, 0xfb, 0x8b, 0xef, 0x41, 0x5e, 0x33, 0xf7, 0x20, 0xe7, 0xb3, 0x7b, 0x90, 0x2e, 0x8f, 0x81, + 0xb1, 0xfd, 0x28, 0x9f, 0xbe, 0xb1, 0x6c, 0x8e, 0x14, 0xdb, 0x87, 0x73, 0x45, 0x93, 0x9b, 0xc5, + 0x31, 0xb9, 0xea, 0x50, 0x30, 0x8d, 0x63, 0x72, 0x57, 0xea, 0x98, 0x61, 0xca, 0xde, 0x82, 0xb7, + 0xff, 0x8f, 0x05, 0xd5, 0x46, 0xe8, 0x1e, 0xa1, 0x07, 0xe4, 0xaa, 0xe1, 0x01, 0x79, 0xba, 0xf0, + 0xe9, 0xa3, 0x9e, 0xfe, 0x8e, 0x5b, 0x19, 0x7f, 0xc7, 0x27, 0x8a, 0x59, 0x1d, 0xec, 0xdd, 0xf8, + 0x5e, 0x15, 0xf4, 0xc7, 0x9b, 0xd0, 0x6f, 0x1f, 0x26, 0xb2, 0xb5, 0x5a, 0xee, 0x3d, 0x27, 0x51, + 0x07, 0x0b, 0x80, 0x92, 0xd7, 0xde, 0x7e, 0x6a, 0x03, 0x5c, 0xef, 0x10, 0x6f, 0x73, 0x2b, 0x21, + 0x6e, 0xb6, 0x63, 0xc7, 0x17, 0xe0, 0xfa, 0xdf, 0x2d, 0x98, 0xcc, 0xd4, 0x8e, 0xb6, 0xf3, 0x6e, + 0xce, 0x1c, 0xd6, 0xa5, 0x71, 0xa2, 0xf0, 0xae, 0xcd, 0x1c, 0x80, 0x72, 0xc3, 0x4b, 0xc7, 0x03, + 0x33, 0xc2, 0x94, 0x9f, 0x3e, 0xc6, 0x1a, 0x05, 0x7a, 0x09, 0x46, 0x93, 0xb0, 0x1d, 0xfa, 0xe1, + 0xe6, 0xee, 0x75, 0x22, 0x13, 0x33, 0xa8, 0x23, 0x8c, 0xb5, 0x14, 0x85, 0x75, 0x3a, 0xfb, 0x07, + 0x55, 0xc8, 0xbe, 0xfd, 0xf5, 0xe7, 0x82, 0xfa, 0xd3, 0x23, 0xa8, 0xbf, 0x67, 0xc1, 0x14, 0xad, + 0x9d, 0xc5, 0xaf, 0xc8, 0x30, 0x54, 0x95, 0x75, 0xdd, 0x3a, 0x20, 0xeb, 0xfa, 0x79, 0xaa, 0xee, + 0xdc, 0xb0, 0x23, 0x33, 0x01, 0x69, 0x5a, 0x8c, 0x42, 0xb1, 0xc0, 0x0a, 0x3a, 0x12, 0x45, 0xe2, + 0x8e, 0x8e, 0x4e, 0x47, 0xa2, 0x08, 0x0b, 0xac, 0x4c, 0xca, 0x3e, 0x90, 0x9f, 0x94, 0x9d, 0x27, + 0x4e, 0x12, 0x71, 0x13, 0xc2, 0x0e, 0xd0, 0x12, 0x27, 0xc9, 0x80, 0x8a, 0x94, 0xc6, 0xfe, 0x97, + 0x55, 0x18, 0x6b, 0x84, 0x6e, 0x1a, 0x62, 0xfe, 0xa2, 0x11, 0x62, 0x7e, 0x2e, 0x13, 0x62, 0x3e, + 0xa5, 0xd3, 0x3e, 0x9c, 0x08, 0x73, 0x91, 0x62, 0x8b, 0x3d, 0x1b, 0x70, 0xd8, 0xe8, 0x72, 0x23, + 0xc5, 0x96, 0xe2, 0x84, 0x4d, 0xc6, 0x7f, 0xa6, 0xa2, 0xca, 0xff, 0xc4, 0x82, 0x89, 0x46, 0xe8, + 0x52, 0x11, 0xfd, 0xb3, 0x24, 0x8f, 0x7a, 0x62, 0xae, 0xa1, 0x03, 0x12, 0x73, 0xfd, 0x9a, 0x05, + 0xc3, 0x8d, 0xd0, 0x3d, 0x0e, 0x57, 0xe2, 0xb2, 0xe9, 0x4a, 0xfc, 0x58, 0xa1, 0xf2, 0xed, 0xe1, + 0x3d, 0xfc, 0xcd, 0x2a, 0x8c, 0xd3, 0x26, 0x87, 0x9b, 0xf2, 0x83, 0x19, 0x83, 0x63, 0x95, 0x18, + 0x1c, 0x6a, 0x0e, 0x86, 0xbe, 0x1f, 0xde, 0xcb, 0x7e, 0xbc, 0x65, 0x06, 0xc5, 0x02, 0x8b, 0x2e, + 0xc2, 0x48, 0x3b, 0x22, 0x3b, 0x5e, 0xd8, 0x89, 0xb3, 0x57, 0xfe, 0x1a, 0x02, 0x8e, 0x15, 0x05, + 0x7a, 0x11, 0xc6, 0x62, 0x2f, 0x68, 0x11, 0x19, 0x58, 0x31, 0xc0, 0x02, 0x2b, 0x78, 0xfe, 0x43, + 0x0d, 0x8e, 0x0d, 0x2a, 0xf4, 0x16, 0xd4, 0xd8, 0x7f, 0x36, 0x87, 0x0e, 0x91, 0x29, 0x9e, 0x27, + 0xe7, 0x92, 0x1c, 0x70, 0xca, 0x0c, 0x5d, 0x01, 0x48, 0x64, 0x0c, 0x48, 0x2c, 0xce, 0x4c, 0x95, + 0x71, 0xaa, 0xa2, 0x43, 0x62, 0xac, 0x51, 0xa1, 0xe7, 0xa0, 0x96, 0x38, 0x9e, 0x7f, 0xc3, 0x0b, + 0x48, 0x2c, 0xa2, 0x68, 0x44, 0x1e, 0x5f, 0x01, 0xc4, 0x29, 0x9e, 0xae, 0xf9, 0xec, 0xc2, 0x31, + 0x7f, 0x87, 0x62, 0x84, 0x51, 0xb3, 0x35, 0xff, 0x86, 0x82, 0x62, 0x8d, 0xc2, 0x7e, 0x81, 0xad, + 0xdd, 0x7d, 0x5e, 0x41, 0xf8, 0x49, 0x05, 0x50, 0x83, 0xc5, 0x9a, 0x18, 0x4f, 0x75, 0x6c, 0xc1, + 0x44, 0x4c, 0x6e, 0x78, 0x41, 0xe7, 0xbe, 0x60, 0x55, 0xee, 0xd2, 0x47, 0x73, 0x49, 0x2f, 0xc3, + 0x2f, 0xd9, 0x9a, 0x30, 0x9c, 0xe1, 0x4b, 0x87, 0x24, 0xea, 0x04, 0xf3, 0xf1, 0xed, 0x98, 0x44, + 0xe2, 0xb1, 0x0d, 0x36, 0x24, 0x58, 0x02, 0x71, 0x8a, 0xa7, 0x32, 0xc0, 0xfe, 0xdc, 0x0c, 0x03, + 0x1c, 0x86, 0x89, 0x94, 0x1a, 0x96, 0x79, 0x5d, 0x83, 0x63, 0x83, 0x0a, 0x2d, 0x03, 0x8a, 0x3b, + 0xed, 0xb6, 0xcf, 0x8e, 0xb6, 0x1c, 0xff, 0x6a, 0x14, 0x76, 0xda, 0x3c, 0xdc, 0x58, 0x24, 0x2d, + 0x6f, 0x76, 0x61, 0x71, 0x4e, 0x09, 0x3a, 0xe9, 0x37, 0x62, 0xf6, 0x5b, 0x5c, 0x22, 0xe6, 0x0e, + 0xb6, 0x26, 0x03, 0x61, 0x89, 0xb3, 0x3b, 0x6c, 0xa9, 0x62, 0x8f, 0x20, 0x24, 0x9d, 0x88, 0x20, + 0x02, 0xe3, 0x6d, 0xb6, 0x1c, 0xc9, 0xf3, 0xf5, 0x52, 0x43, 0x99, 0x89, 0x76, 0xe1, 0xc9, 0xce, + 0x75, 0x36, 0xd8, 0xe4, 0x6a, 0xff, 0x27, 0x60, 0xba, 0x46, 0x9c, 0x2a, 0x0e, 0x8b, 0x58, 0x56, + 0x61, 0x8b, 0x7d, 0xbc, 0xcc, 0xab, 0x3f, 0xa9, 0x1e, 0x17, 0x91, 0xb1, 0x58, 0x72, 0x41, 0x5f, + 0xe2, 0x01, 0x02, 0x6c, 0x7e, 0x97, 0x7f, 0x8a, 0x8b, 0xd3, 0x1b, 0x51, 0xda, 0x82, 0x05, 0xd6, + 0xd8, 0xa1, 0x1b, 0x30, 0x2e, 0x32, 0xe5, 0x0b, 0xcf, 0x40, 0xd5, 0xd8, 0x1d, 0x8f, 0x63, 0x1d, + 0xf9, 0x20, 0x0b, 0xc0, 0x66, 0x61, 0xb4, 0x09, 0x4f, 0x6a, 0xcf, 0xe7, 0xe4, 0x44, 0x64, 0x71, + 0xc5, 0xf1, 0xb1, 0xfd, 0xbd, 0xd9, 0x27, 0xd7, 0x0e, 0x22, 0xc4, 0x07, 0xf3, 0x41, 0xb7, 0xe0, + 0xb4, 0xd3, 0x4a, 0xbc, 0x1d, 0x52, 0x27, 0x8e, 0xeb, 0x7b, 0x01, 0x31, 0x6f, 0x98, 0x3f, 0xbe, + 0xbf, 0x37, 0x7b, 0x7a, 0x3e, 0x8f, 0x00, 0xe7, 0x97, 0x43, 0xaf, 0x41, 0xcd, 0x0d, 0x62, 0x31, + 0x06, 0x43, 0xc6, 0x4b, 0x41, 0xb5, 0xfa, 0xcd, 0xa6, 0xea, 0x7f, 0xfa, 0x07, 0xa7, 0x05, 0xd0, + 0x7b, 0xfc, 0x01, 0x63, 0xb5, 0x21, 0xe1, 0x2f, 0x54, 0xbd, 0x5c, 0x6a, 0x0b, 0x6c, 0xdc, 0x02, + 0xe1, 0x4e, 0x33, 0x15, 0xf9, 0x68, 0x5c, 0x10, 0x31, 0xaa, 0x40, 0x9f, 0x07, 0x14, 0x93, 0x68, + 0xc7, 0x6b, 0x91, 0xf9, 0x16, 0xcb, 0xfc, 0xc9, 0x8e, 0xe7, 0x46, 0x8c, 0xf0, 0x7f, 0xd4, 0xec, + 0xa2, 0xc0, 0x39, 0xa5, 0xd0, 0x35, 0xaa, 0x71, 0x74, 0xa8, 0x08, 0x54, 0x95, 0xa6, 0xdd, 0x74, + 0x9d, 0xb4, 0x23, 0xd2, 0x72, 0x12, 0xe2, 0x9a, 0x1c, 0x71, 0xa6, 0x1c, 0x5d, 0x56, 0x54, 0x46, + 0x73, 0x30, 0xc3, 0x2b, 0xbb, 0xb3, 0x9a, 0xd3, 0x9d, 0xd2, 0x56, 0x18, 0x27, 0x37, 0x49, 0x72, + 0x2f, 0x8c, 0xee, 0x32, 0x67, 0xfb, 0x88, 0x96, 0xe9, 0x2c, 0x45, 0x61, 0x9d, 0x8e, 0xda, 0x40, + 0xec, 0x94, 0x67, 0xa5, 0xce, 0x5c, 0xe8, 0x23, 0xe9, 0xdc, 0xb9, 0xc6, 0xc1, 0x58, 0xe2, 0x25, + 0xe9, 0x4a, 0x63, 0x91, 0xb9, 0xc3, 0x33, 0xa4, 0x2b, 0x8d, 0x45, 0x2c, 0xf1, 0x28, 0xec, 0x7e, + 0x8f, 0x69, 0xa2, 0xcc, 0xd1, 0x44, 0xb7, 0x06, 0x2f, 0xf9, 0x24, 0xd3, 0x7d, 0x98, 0x52, 0x6f, + 0x42, 0xf1, 0x14, 0x94, 0xf1, 0xf4, 0x64, 0x99, 0xe7, 0x93, 0x73, 0x33, 0x59, 0xaa, 0xc8, 0xe4, + 0x95, 0x0c, 0x4f, 0xdc, 0x55, 0x8b, 0x91, 0x29, 0x61, 0xaa, 0x30, 0x4b, 0xfd, 0x25, 0xa8, 0xc5, + 0x9d, 0x75, 0x37, 0xdc, 0x76, 0xbc, 0x80, 0xf9, 0xac, 0xf5, 0xc7, 0x80, 0x25, 0x02, 0xa7, 0x34, + 0x33, 0x9f, 0x85, 0x13, 0x5d, 0x32, 0xdd, 0x57, 0x48, 0xdd, 0x2f, 0x0d, 0x40, 0x4d, 0x79, 0x75, + 0xd0, 0x25, 0xd3, 0x71, 0xf7, 0x78, 0xd6, 0x71, 0x37, 0x42, 0x57, 0x5e, 0xdd, 0x57, 0xf7, 0x4e, + 0xce, 0x6b, 0xa0, 0xcf, 0x16, 0x7e, 0xc4, 0xf2, 0x37, 0x5b, 0xfa, 0x78, 0x2b, 0x35, 0x35, 0xeb, + 0x07, 0x0e, 0x34, 0xeb, 0x4b, 0x3e, 0xf6, 0x44, 0x0d, 0xf8, 0x76, 0xe8, 0xae, 0x34, 0xb2, 0x0f, + 0x99, 0x34, 0x28, 0x10, 0x73, 0x1c, 0xb3, 0xbb, 0xa8, 0x52, 0x66, 0x76, 0xd7, 0xf0, 0x61, 0xed, + 0x2e, 0xc9, 0x01, 0xa7, 0xcc, 0xd0, 0x0e, 0x9c, 0x68, 0x99, 0x0f, 0xd3, 0xa8, 0x0b, 0x2b, 0xcf, + 0xf7, 0xf1, 0x30, 0x4c, 0x47, 0x4b, 0xc2, 0xbf, 0x98, 0xe5, 0x87, 0xbb, 0xab, 0xb0, 0x7f, 0xc0, + 0xbd, 0x40, 0x62, 0x5b, 0x48, 0xe2, 0x8e, 0x7f, 0x94, 0x39, 0xb5, 0x6f, 0x19, 0x3b, 0xd5, 0x87, + 0xe0, 0x7f, 0xfc, 0x2d, 0x8b, 0xf9, 0x1f, 0xd7, 0xc8, 0x76, 0xdb, 0x77, 0x92, 0xa3, 0x8c, 0xd6, + 0xfb, 0x12, 0x8c, 0x24, 0xa2, 0x96, 0x72, 0x89, 0xc0, 0xb5, 0x66, 0x31, 0x7f, 0xac, 0x52, 0x04, + 0x12, 0x8a, 0x15, 0x43, 0xfb, 0xdf, 0xf0, 0xaf, 0x20, 0x31, 0xc7, 0xb1, 0xb3, 0xba, 0x69, 0xee, + 0xac, 0x9e, 0x29, 0xdd, 0x99, 0x1e, 0x3b, 0xac, 0xef, 0x9a, 0x5d, 0x60, 0x06, 0xdb, 0xa3, 0xef, + 0x11, 0xb7, 0x57, 0xc1, 0x7c, 0x6c, 0x07, 0xbd, 0xc6, 0x43, 0x55, 0xb9, 0x46, 0x7c, 0xb6, 0xcf, + 0x30, 0x55, 0xfb, 0x37, 0x2a, 0x70, 0x2a, 0xef, 0x0d, 0x7e, 0xe4, 0xc2, 0x58, 0x5b, 0x33, 0x9f, + 0xcb, 0xe5, 0x73, 0xd0, 0x0d, 0xee, 0xd4, 0x74, 0xd1, 0xa1, 0xd8, 0xe0, 0x8a, 0x08, 0x8c, 0x91, + 0x1d, 0xaf, 0xa5, 0xdc, 0x2b, 0x95, 0xfe, 0x55, 0x94, 0xaa, 0x66, 0x49, 0x63, 0x84, 0x0d, 0xb6, + 0x47, 0x90, 0xab, 0xde, 0xfe, 0x47, 0x16, 0x3c, 0xd6, 0x23, 0xe9, 0x03, 0xad, 0xee, 0x1e, 0xf3, + 0x42, 0x8a, 0xc7, 0x9c, 0x54, 0x75, 0xdc, 0x37, 0x89, 0x05, 0x16, 0xad, 0x03, 0x70, 0xdf, 0x22, + 0x7b, 0xe1, 0xb6, 0x52, 0x26, 0x06, 0xa0, 0xeb, 0x66, 0xb5, 0x76, 0xe9, 0x56, 0xbd, 0x69, 0xab, + 0x71, 0xb5, 0xbf, 0x53, 0x85, 0x41, 0xfe, 0xc8, 0x66, 0x03, 0x86, 0xb7, 0x78, 0x8e, 0xc9, 0xfe, + 0x52, 0x5c, 0xa6, 0x76, 0x12, 0x07, 0x60, 0xc9, 0x06, 0xad, 0xc2, 0x49, 0x2f, 0xf0, 0x12, 0xcf, + 0xf1, 0xeb, 0xc4, 0x77, 0x76, 0xa5, 0xe1, 0xcd, 0xf3, 0x8b, 0xcb, 0x54, 0xb8, 0x27, 0x57, 0xba, + 0x49, 0x70, 0x5e, 0x39, 0xf4, 0x7a, 0x57, 0x92, 0x28, 0x9e, 0xbb, 0x53, 0xdd, 0xd5, 0x3a, 0x38, + 0x51, 0x14, 0x7a, 0x15, 0xc6, 0xdb, 0x5d, 0x5b, 0x0c, 0xed, 0x75, 0x46, 0x73, 0x5b, 0x61, 0xd2, + 0xa2, 0x3a, 0x4c, 0xc5, 0x1d, 0x76, 0x22, 0xbb, 0xb6, 0x15, 0x91, 0x78, 0x2b, 0xf4, 0x5d, 0xf1, + 0xaa, 0x98, 0x32, 0xa7, 0x9a, 0x19, 0x3c, 0xee, 0x2a, 0x41, 0xb9, 0x6c, 0x38, 0x9e, 0xdf, 0x89, + 0x48, 0xca, 0x65, 0xc8, 0xe4, 0xb2, 0x9c, 0xc1, 0xe3, 0xae, 0x12, 0xf6, 0x1f, 0x59, 0x70, 0x32, + 0x27, 0x6c, 0x81, 0x47, 0xd3, 0x6d, 0x7a, 0x71, 0xa2, 0xb2, 0x48, 0x6b, 0xd1, 0x74, 0x1c, 0x8e, + 0x15, 0x05, 0x95, 0x42, 0xbe, 0x6f, 0xcc, 0x1e, 0x07, 0x8a, 0x83, 0x59, 0x81, 0xed, 0x2f, 0xe5, + 0x13, 0x3a, 0x07, 0x03, 0x9d, 0x98, 0xc8, 0x17, 0xdf, 0x95, 0x86, 0x62, 0x2e, 0x02, 0x86, 0xa1, + 0x86, 0xc9, 0xa6, 0xda, 0x9d, 0x6b, 0x86, 0x09, 0xdf, 0x9f, 0x73, 0x9c, 0xfd, 0xad, 0x2a, 0x4c, + 0x66, 0xc2, 0x97, 0x68, 0x43, 0xb6, 0xc3, 0xc0, 0x4b, 0x42, 0x95, 0x6d, 0x88, 0xb9, 0x14, 0x16, + 0x49, 0x7b, 0x6b, 0x55, 0xc0, 0xb1, 0xa2, 0x40, 0xe7, 0xcd, 0x17, 0x8f, 0xd3, 0x36, 0x2f, 0xd4, + 0x8d, 0xb7, 0xdc, 0xca, 0x66, 0xb6, 0x7f, 0x0a, 0x06, 0xda, 0xa1, 0x7a, 0x9a, 0x53, 0x09, 0x3d, + 0x5e, 0xa8, 0x37, 0xc2, 0xd0, 0xc7, 0x0c, 0x89, 0x9e, 0x16, 0xbd, 0xcf, 0x38, 0x27, 0xb1, 0xe3, + 0x86, 0xb1, 0x36, 0x04, 0xcf, 0xc0, 0xf0, 0x5d, 0xb2, 0x1b, 0x79, 0xc1, 0x66, 0xd6, 0x35, 0x7b, + 0x9d, 0x83, 0xb1, 0xc4, 0x9b, 0xd9, 0xeb, 0x87, 0x8f, 0x38, 0x7b, 0xfd, 0x48, 0x61, 0x08, 0xe6, + 0xaf, 0x5a, 0x30, 0xc9, 0x52, 0xef, 0x89, 0x6b, 0xb0, 0x5e, 0x18, 0x1c, 0xe1, 0xaa, 0xf8, 0x14, + 0x0c, 0x46, 0xb4, 0xb2, 0x6c, 0xe2, 0x69, 0xd6, 0x02, 0xcc, 0x71, 0xe8, 0x09, 0xf1, 0x70, 0x3c, + 0xfd, 0x7c, 0x63, 0x3c, 0x91, 0x6f, 0xfa, 0x02, 0x3c, 0x0b, 0xf0, 0xc7, 0xa4, 0xed, 0x7b, 0xbc, + 0xb1, 0xa9, 0x27, 0xe6, 0x51, 0x09, 0xf0, 0xcf, 0x6d, 0xdc, 0xc3, 0x0a, 0xf0, 0xcf, 0x67, 0x7e, + 0xb0, 0x09, 0xfa, 0x3f, 0x2b, 0x70, 0x36, 0xb7, 0x5c, 0x7a, 0xac, 0xb3, 0x6c, 0x1c, 0xeb, 0x5c, + 0xc9, 0x1c, 0xeb, 0xd8, 0x07, 0x97, 0x7e, 0x38, 0x07, 0x3d, 0xf9, 0xc7, 0x2f, 0xd5, 0xe3, 0x3c, + 0x7e, 0x19, 0x28, 0x6b, 0x2b, 0x0c, 0x16, 0xd8, 0x0a, 0xbf, 0x6b, 0xc1, 0xe3, 0xb9, 0x63, 0xf6, + 0xe8, 0x5d, 0xa9, 0xc8, 0x6d, 0x66, 0x0f, 0x0b, 0xfa, 0x6f, 0x54, 0x7b, 0x74, 0x8b, 0xd9, 0xd2, + 0x17, 0xa8, 0xde, 0x61, 0xc8, 0x58, 0x98, 0x41, 0x63, 0x5c, 0xe7, 0x70, 0x18, 0x56, 0x58, 0x14, + 0x6b, 0x57, 0x12, 0x78, 0x23, 0x97, 0x0e, 0x39, 0xa5, 0xe6, 0x4c, 0xe7, 0x99, 0x7e, 0x9f, 0x37, + 0x73, 0x4f, 0x01, 0xdd, 0xd1, 0xb6, 0x47, 0xd5, 0xc3, 0x6c, 0x8f, 0xc6, 0xf2, 0xb7, 0x46, 0x68, + 0x1e, 0x26, 0xb7, 0xbd, 0x80, 0x3d, 0x1d, 0x67, 0xda, 0x21, 0xea, 0x16, 0xdc, 0xaa, 0x89, 0xc6, + 0x59, 0xfa, 0x99, 0x57, 0x61, 0xfc, 0xf0, 0x1e, 0x93, 0x0f, 0xaa, 0xf0, 0xd1, 0x03, 0xd4, 0x02, + 0x5f, 0x0f, 0x8c, 0xef, 0xa2, 0xad, 0x07, 0x5d, 0xdf, 0xa6, 0x01, 0xa7, 0x36, 0x3a, 0xbe, 0xbf, + 0xcb, 0xc2, 0x22, 0x88, 0x2b, 0x29, 0x84, 0x8d, 0xa7, 0x1e, 0x75, 0x5d, 0xce, 0xa1, 0xc1, 0xb9, + 0x25, 0xd1, 0xe7, 0x01, 0x85, 0xeb, 0x2c, 0x1f, 0xa5, 0x9b, 0xde, 0x58, 0x66, 0x9f, 0xa0, 0x9a, + 0xce, 0xd5, 0x5b, 0x5d, 0x14, 0x38, 0xa7, 0x14, 0xb5, 0xf8, 0xd8, 0x7b, 0xb0, 0xaa, 0x59, 0x19, + 0x8b, 0x0f, 0xeb, 0x48, 0x6c, 0xd2, 0xa2, 0xab, 0x70, 0xc2, 0xd9, 0x71, 0x3c, 0x9e, 0x6d, 0x46, + 0x32, 0xe0, 0x26, 0x9f, 0x72, 0x49, 0xcc, 0x67, 0x09, 0x70, 0x77, 0x19, 0xd4, 0x36, 0x9c, 0x4c, + 0x3c, 0xff, 0xf4, 0x6b, 0x87, 0x90, 0xe0, 0xd2, 0x6e, 0x27, 0xfb, 0x0f, 0x2d, 0xba, 0xe8, 0xe5, + 0x3c, 0xb5, 0x66, 0xbc, 0x50, 0xae, 0xdd, 0xd2, 0xe8, 0x7e, 0xa1, 0x9c, 0xf9, 0x5f, 0x4d, 0x5a, + 0x2e, 0x1a, 0x71, 0x1a, 0x56, 0x69, 0xd8, 0x97, 0xe2, 0x76, 0x92, 0xa2, 0x40, 0x77, 0x60, 0xd8, + 0xf5, 0x76, 0xbc, 0x38, 0x8c, 0x4a, 0x3c, 0x08, 0xdc, 0x15, 0xaa, 0x97, 0xaa, 0xcb, 0x3a, 0x67, + 0x82, 0x25, 0x37, 0xfb, 0x6f, 0x55, 0x60, 0x5c, 0xd6, 0xf7, 0x46, 0x27, 0x64, 0x3a, 0xec, 0xa8, + 0x96, 0xf2, 0x37, 0x8c, 0xa5, 0xfc, 0x52, 0xb9, 0x2b, 0x5a, 0xac, 0x51, 0x3d, 0x97, 0xf0, 0x2f, + 0x64, 0x96, 0xf0, 0xcb, 0xfd, 0x30, 0x2d, 0xf4, 0x1e, 0x9d, 0x30, 0xe8, 0x1f, 0xa1, 0xfc, 0xc7, + 0x79, 0xdd, 0xe9, 0xb1, 0x70, 0x7c, 0xa7, 0x92, 0xe9, 0x06, 0x5b, 0x30, 0xbe, 0x06, 0x03, 0x5b, + 0x4e, 0xe4, 0x96, 0xcb, 0xb7, 0xd6, 0x55, 0x7c, 0xee, 0x9a, 0x13, 0xb9, 0x5c, 0xed, 0x5f, 0x54, + 0x0f, 0xb5, 0x38, 0x91, 0x5b, 0x18, 0x64, 0xcc, 0x2a, 0x45, 0xaf, 0xc0, 0x50, 0xdc, 0x0a, 0xdb, + 0x2a, 0xaa, 0xeb, 0x1c, 0x7f, 0xc4, 0x85, 0x42, 0x1e, 0xec, 0xcd, 0x22, 0xb3, 0x3a, 0x0a, 0xc6, + 0x82, 0x7e, 0x86, 0x40, 0x4d, 0x55, 0x7d, 0x84, 0xe1, 0xac, 0x1f, 0x54, 0xe1, 0x64, 0x8e, 0xa8, + 0xa0, 0x9f, 0x31, 0x46, 0xed, 0xd5, 0xbe, 0x65, 0xed, 0x43, 0x8e, 0xdb, 0xcf, 0xb0, 0x0d, 0x91, + 0x2b, 0x64, 0xe3, 0x10, 0xd5, 0xdf, 0x8e, 0x49, 0xb6, 0x7a, 0x0a, 0x2a, 0xae, 0x9e, 0x56, 0x7b, + 0x4c, 0x83, 0x4f, 0xab, 0x51, 0xed, 0x3c, 0xc2, 0x6f, 0xfc, 0xfe, 0x00, 0x9c, 0xca, 0xbb, 0x06, + 0x8a, 0x7e, 0xde, 0xca, 0x64, 0x50, 0x7f, 0xbd, 0xff, 0xbb, 0xa4, 0x3c, 0xad, 0xba, 0x48, 0x0f, + 0x31, 0x67, 0xe6, 0x54, 0x2f, 0x1c, 0x6d, 0x51, 0x3b, 0xbb, 0x18, 0x10, 0xf1, 0x64, 0xf8, 0x52, + 0x1f, 0x7c, 0xee, 0x10, 0x4d, 0x11, 0xf9, 0xf4, 0xe3, 0xcc, 0xc5, 0x00, 0x09, 0x2e, 0xbe, 0x18, + 0x20, 0xdb, 0x30, 0xb3, 0x09, 0xa3, 0x5a, 0xbf, 0x8e, 0x50, 0x04, 0x3c, 0xba, 0x26, 0x69, 0xad, + 0x3e, 0x42, 0x31, 0xf8, 0x3b, 0x16, 0x64, 0xc2, 0x35, 0x94, 0xd7, 0xc5, 0xea, 0xe9, 0x75, 0x39, + 0x07, 0x03, 0x51, 0xe8, 0x93, 0x6c, 0x6a, 0x6f, 0x1c, 0xfa, 0x04, 0x33, 0x8c, 0x7a, 0x0e, 0xb2, + 0xda, 0xeb, 0x39, 0x48, 0xba, 0x1d, 0xf7, 0xc9, 0x0e, 0x91, 0x3e, 0x10, 0xa5, 0xbc, 0x6f, 0x50, + 0x20, 0xe6, 0x38, 0xfb, 0x47, 0x55, 0x18, 0xe2, 0x8e, 0x86, 0x23, 0x5c, 0x96, 0x1b, 0x62, 0xcf, + 0x5f, 0xea, 0x42, 0x26, 0x6f, 0xcd, 0x5c, 0xdd, 0x49, 0x1c, 0x2e, 0x50, 0xaa, 0x6f, 0xa9, 0x9f, + 0x00, 0xcd, 0x19, 0xbd, 0x9f, 0xc9, 0x6c, 0x69, 0x81, 0xf3, 0xd0, 0xc6, 0x62, 0x0b, 0x20, 0x66, + 0x2f, 0x83, 0x51, 0x1e, 0x22, 0x29, 0xde, 0x8b, 0xa5, 0xda, 0xd1, 0x54, 0xc5, 0x78, 0x6b, 0xd2, + 0x6c, 0x5c, 0x0a, 0x81, 0x35, 0xde, 0x33, 0x2f, 0x43, 0x4d, 0x11, 0x17, 0x59, 0xfa, 0x63, 0xba, + 0x48, 0xfe, 0x05, 0x98, 0xcc, 0xd4, 0xd5, 0xd7, 0x46, 0xe1, 0xfb, 0x16, 0x9c, 0xe8, 0x7a, 0xc9, + 0x16, 0xbd, 0x6f, 0xc1, 0x29, 0x3f, 0xc7, 0xc3, 0x24, 0x3e, 0xf0, 0x61, 0x7c, 0x53, 0x6a, 0x97, + 0x90, 0x87, 0xc5, 0xb9, 0xb5, 0xc9, 0x34, 0x9f, 0x95, 0xfc, 0x34, 0x9f, 0xec, 0x39, 0x24, 0xde, + 0xf6, 0xe3, 0xb0, 0x80, 0x56, 0x4c, 0x0b, 0xe8, 0xe3, 0x65, 0xc4, 0xa0, 0x87, 0xe9, 0xf3, 0xef, + 0x2d, 0x40, 0x9c, 0x20, 0xfb, 0x42, 0x20, 0xf7, 0xd8, 0x69, 0x36, 0x7b, 0x2a, 0x37, 0x0a, 0x83, + 0x35, 0xaa, 0x3e, 0xb3, 0xbf, 0xab, 0x97, 0xb5, 0xca, 0x3d, 0xdf, 0x5f, 0x2d, 0xf1, 0x7c, 0xff, + 0x6f, 0x55, 0x21, 0x1b, 0xda, 0x80, 0xbe, 0x0c, 0x63, 0x2d, 0xa7, 0xed, 0xac, 0x7b, 0xbe, 0x97, + 0x78, 0x24, 0x2e, 0x77, 0x6c, 0xb4, 0xa8, 0x95, 0x10, 0x3e, 0x5f, 0x0d, 0x82, 0x0d, 0x8e, 0x68, + 0x0e, 0xa0, 0x1d, 0x79, 0x3b, 0x9e, 0x4f, 0x36, 0x99, 0xdd, 0xa1, 0x92, 0xa4, 0x34, 0x14, 0x14, + 0x6b, 0x14, 0x39, 0x31, 0x74, 0xd5, 0xe3, 0x88, 0xa1, 0x1b, 0xe8, 0x33, 0x86, 0x6e, 0xb0, 0x54, + 0x0c, 0x1d, 0x86, 0x33, 0xd2, 0x55, 0x4b, 0xff, 0x2f, 0x7b, 0x3e, 0xe1, 0x79, 0xfd, 0x44, 0xe4, + 0xe3, 0xcc, 0xfe, 0xde, 0xec, 0x19, 0x9c, 0x4b, 0x81, 0x7b, 0x94, 0xb4, 0x3b, 0x70, 0xb2, 0x49, + 0x22, 0x8f, 0xa5, 0x5d, 0x72, 0xd3, 0x19, 0xf8, 0x0e, 0xd4, 0xa2, 0xcc, 0xe4, 0xef, 0xf3, 0x4e, + 0x9a, 0x96, 0xbc, 0x42, 0x4e, 0xf6, 0x94, 0xa5, 0xfd, 0x57, 0x2a, 0x30, 0x2c, 0x42, 0x88, 0x8e, + 0x70, 0x21, 0xb9, 0x6e, 0xec, 0xef, 0x9e, 0x29, 0x9a, 0xb9, 0xac, 0x39, 0x3d, 0x77, 0x76, 0xcd, + 0xcc, 0xce, 0xee, 0xb9, 0x72, 0xec, 0x0e, 0xde, 0xd3, 0xfd, 0xb0, 0x02, 0x13, 0x66, 0x28, 0xd5, + 0x11, 0x0e, 0xc7, 0x5b, 0x30, 0x1c, 0x8b, 0xf8, 0xa2, 0x4a, 0x99, 0x58, 0x8d, 0xec, 0x27, 0x55, + 0x9b, 0x76, 0x19, 0x51, 0x24, 0xd9, 0xe5, 0x86, 0x30, 0x55, 0x8f, 0x23, 0x84, 0xc9, 0xfe, 0x11, + 0x53, 0xa9, 0xfa, 0x00, 0x1e, 0xc7, 0x9a, 0xf0, 0x86, 0xa9, 0x7d, 0x2f, 0x96, 0x12, 0x05, 0xd1, + 0xbe, 0x1e, 0x6b, 0xc3, 0xf7, 0x2c, 0x18, 0x15, 0x84, 0xc7, 0xd1, 0x83, 0xcf, 0x9b, 0x3d, 0x78, + 0xba, 0x54, 0x0f, 0x7a, 0x34, 0xfd, 0xef, 0x55, 0x54, 0xd3, 0x1b, 0xe2, 0xe5, 0xd4, 0xc2, 0x44, + 0x8f, 0x23, 0xed, 0x28, 0x4c, 0xc2, 0x56, 0xe8, 0x8b, 0x55, 0xfe, 0x89, 0x34, 0xea, 0x9c, 0xc3, + 0x1f, 0x68, 0xbf, 0xb1, 0xa2, 0x66, 0xd1, 0xd4, 0x61, 0x94, 0x88, 0x25, 0x2a, 0xef, 0xdd, 0xd6, + 0x75, 0xf9, 0x2e, 0x36, 0x85, 0x89, 0x2b, 0x1b, 0xfd, 0xbe, 0x07, 0x9b, 0xc6, 0x90, 0x2b, 0x4e, + 0x58, 0xe3, 0x2a, 0xc3, 0x1b, 0x59, 0x0d, 0x83, 0xa6, 0x1b, 0xf5, 0xa6, 0x80, 0x63, 0x45, 0x61, + 0xbf, 0xcc, 0x74, 0x2c, 0x1b, 0x9e, 0xfe, 0x02, 0xc3, 0x7f, 0x71, 0x48, 0x0d, 0x2c, 0x73, 0x92, + 0xdc, 0x84, 0x41, 0xda, 0x45, 0xb9, 0x0f, 0x2c, 0xa7, 0xd0, 0x68, 0x13, 0xf4, 0x00, 0xb1, 0x28, + 0x89, 0x31, 0x67, 0x83, 0x48, 0x97, 0xef, 0xfd, 0xe5, 0xd2, 0x3a, 0xb2, 0x0f, 0x6f, 0x3b, 0x4b, + 0x1c, 0xc3, 0x92, 0x65, 0xac, 0x34, 0xb2, 0xc9, 0x39, 0x17, 0x25, 0x02, 0xa7, 0x34, 0xe8, 0x92, + 0x30, 0xd7, 0xcd, 0x67, 0x75, 0xa5, 0xb9, 0x2e, 0x87, 0x44, 0xb3, 0xd7, 0x2f, 0xc3, 0xa8, 0x4a, + 0x4f, 0xde, 0xe0, 0x59, 0xa6, 0x6b, 0xdc, 0x7e, 0x59, 0x4a, 0xc1, 0x58, 0xa7, 0x41, 0x2b, 0x70, + 0xd2, 0x55, 0xd1, 0xac, 0x8d, 0xce, 0xba, 0xef, 0xb5, 0x68, 0x51, 0x7e, 0x93, 0xe4, 0xb1, 0xfd, + 0xbd, 0xd9, 0x93, 0xf5, 0x6e, 0x34, 0xce, 0x2b, 0x83, 0xd6, 0x60, 0x32, 0xe6, 0x69, 0xd8, 0xe5, + 0x9d, 0x33, 0x91, 0xbd, 0xee, 0x59, 0xe9, 0xf4, 0x6f, 0x9a, 0xe8, 0x07, 0x0c, 0xc4, 0x95, 0x82, + 0x00, 0xe1, 0x2c, 0x0b, 0xf4, 0x3a, 0x4c, 0xf8, 0xfa, 0xab, 0x52, 0x0d, 0x11, 0xd4, 0xab, 0x02, + 0x22, 0x8c, 0x37, 0xa7, 0x1a, 0x38, 0x43, 0x8d, 0xde, 0x82, 0x69, 0x1d, 0x22, 0x2e, 0xb5, 0x3b, + 0xc1, 0x26, 0x89, 0x45, 0xfe, 0xe7, 0x27, 0xf6, 0xf7, 0x66, 0xa7, 0x6f, 0xf4, 0xa0, 0xc1, 0x3d, + 0x4b, 0xa3, 0x57, 0x60, 0x4c, 0x8e, 0xa4, 0x16, 0xe0, 0x9b, 0x86, 0xe2, 0x68, 0x38, 0x6c, 0x50, + 0x7e, 0xb8, 0xb3, 0x8d, 0xaf, 0xd1, 0xc2, 0xda, 0xa2, 0x8a, 0xbe, 0x02, 0x63, 0x7a, 0x1b, 0x85, + 0x9a, 0xfc, 0x64, 0xf9, 0x97, 0xba, 0xc4, 0xe2, 0xac, 0x5a, 0xae, 0xe3, 0xb0, 0xc1, 0xdb, 0xbe, + 0x05, 0x43, 0xcd, 0xdd, 0xb8, 0x95, 0xf8, 0x0f, 0xeb, 0x45, 0xe5, 0x16, 0x4c, 0x66, 0x9e, 0x1e, + 0x56, 0x6f, 0x58, 0x5b, 0x0f, 0xeb, 0x0d, 0x6b, 0xfb, 0xeb, 0x16, 0x0c, 0xae, 0x39, 0x5e, 0xf1, + 0xcb, 0x09, 0x65, 0x9a, 0x8c, 0x5e, 0x82, 0x21, 0xb2, 0xb1, 0x41, 0x5a, 0xf2, 0x4d, 0xec, 0x27, + 0xa5, 0x51, 0xb3, 0xc4, 0xa0, 0x74, 0x6a, 0xb2, 0xca, 0xf8, 0x5f, 0x2c, 0x88, 0xed, 0xff, 0x68, + 0x01, 0xac, 0x85, 0xbe, 0x3c, 0xb6, 0x29, 0x68, 0xc9, 0x42, 0xd7, 0x1b, 0x0e, 0xe7, 0x73, 0xde, + 0x70, 0x40, 0x29, 0xc3, 0x9c, 0x17, 0x1c, 0x54, 0x6f, 0xaa, 0xa5, 0x7a, 0x33, 0xd0, 0x4f, 0x6f, + 0xbe, 0x69, 0x81, 0x88, 0xa1, 0x29, 0x21, 0x09, 0xae, 0xcc, 0xbb, 0x6e, 0xa4, 0xab, 0x78, 0xb6, + 0xcc, 0x45, 0x10, 0x91, 0xa4, 0x42, 0xc9, 0xa6, 0x91, 0x9a, 0xc2, 0xe0, 0x4a, 0xf7, 0xf2, 0xa3, + 0x1c, 0xbd, 0xca, 0x2c, 0xc8, 0xe2, 0x76, 0xf5, 0x95, 0x99, 0x8b, 0xa5, 0x25, 0xa7, 0x8c, 0x55, + 0x82, 0x26, 0x3d, 0x2d, 0xb9, 0x44, 0xe0, 0x94, 0x06, 0x3d, 0x03, 0xc3, 0x71, 0x67, 0x9d, 0x91, + 0x67, 0x02, 0x6a, 0x9a, 0x1c, 0x8c, 0x25, 0xde, 0xfe, 0x39, 0x04, 0x46, 0xd7, 0x8c, 0x64, 0x50, + 0xd6, 0x43, 0x4f, 0x06, 0xf5, 0x36, 0x8c, 0x90, 0xed, 0x76, 0xb2, 0x5b, 0xf7, 0xa2, 0x72, 0x89, + 0xf9, 0x96, 0x04, 0x75, 0x37, 0x77, 0x89, 0xc1, 0x8a, 0x63, 0x8f, 0xd4, 0x5e, 0xd5, 0x47, 0x22, + 0xb5, 0xd7, 0xc0, 0x9f, 0x4a, 0x6a, 0xaf, 0xb7, 0x60, 0x78, 0xd3, 0x4b, 0x30, 0x69, 0x87, 0xe2, + 0xe2, 0x5f, 0xc1, 0x79, 0xd8, 0x55, 0x4e, 0xdc, 0x9d, 0xaf, 0x47, 0x20, 0xb0, 0x64, 0x87, 0xd6, + 0x60, 0x88, 0xef, 0x3e, 0x44, 0xb6, 0xac, 0x4f, 0x96, 0xf1, 0xcb, 0x74, 0x27, 0x8e, 0x12, 0x51, + 0x53, 0x82, 0x97, 0x4c, 0xe5, 0x35, 0xfc, 0xe1, 0x53, 0x79, 0xa9, 0x04, 0x5c, 0x23, 0x0f, 0x2b, + 0x01, 0x97, 0x91, 0xc8, 0xac, 0x76, 0x14, 0x89, 0xcc, 0xbe, 0x69, 0xc1, 0xe9, 0x76, 0x5e, 0x1e, + 0x40, 0x91, 0x4a, 0xeb, 0xb3, 0x87, 0xc8, 0x8b, 0x68, 0x54, 0xcd, 0xee, 0x63, 0xe5, 0x92, 0xe1, + 0xfc, 0x8a, 0x65, 0x46, 0xb4, 0xd1, 0x0f, 0x9f, 0x11, 0xed, 0xa8, 0x73, 0x6e, 0xa5, 0xf9, 0xd1, + 0xc6, 0x8f, 0x24, 0x3f, 0xda, 0xc4, 0x43, 0xcc, 0x8f, 0xa6, 0x65, 0x36, 0x9b, 0x7c, 0xb8, 0x99, + 0xcd, 0xb6, 0x60, 0xd4, 0x0d, 0xef, 0x05, 0xf7, 0x9c, 0xc8, 0x9d, 0x6f, 0xac, 0x88, 0x44, 0x5a, + 0x05, 0x49, 0x1b, 0xea, 0x69, 0x01, 0xa3, 0x06, 0xee, 0x80, 0x4c, 0x91, 0x58, 0x67, 0x2d, 0x72, + 0xbc, 0x9d, 0xf8, 0x90, 0x39, 0xde, 0x8c, 0x4c, 0x69, 0xe8, 0x28, 0x32, 0xa5, 0x7d, 0x99, 0x5d, + 0xdd, 0xde, 0xf0, 0x36, 0x57, 0x9d, 0xf6, 0xf4, 0xc9, 0x32, 0x35, 0x2c, 0x4a, 0xf2, 0xee, 0x1a, + 0x14, 0x0a, 0xa7, 0x4c, 0xbb, 0x73, 0xb1, 0x9d, 0x3a, 0xee, 0x5c, 0x6c, 0xa7, 0x8f, 0x30, 0x17, + 0xdb, 0x99, 0x63, 0xcd, 0xc5, 0xf6, 0xd8, 0x9f, 0x4a, 0x2e, 0xb6, 0xbf, 0x04, 0x67, 0x0f, 0xfe, + 0x1c, 0x69, 0xb6, 0xdf, 0x46, 0xea, 0x32, 0xc8, 0x64, 0xfb, 0x65, 0xa6, 0x8e, 0x46, 0x55, 0x3a, + 0x25, 0xd4, 0xbf, 0xb0, 0xe0, 0xb1, 0x1e, 0x89, 0x53, 0x4a, 0xdf, 0x66, 0x68, 0xc3, 0x64, 0xdb, + 0x2c, 0x5a, 0xfa, 0xde, 0x91, 0x91, 0xa8, 0x45, 0xc5, 0xc9, 0x65, 0x10, 0x38, 0xcb, 0x7e, 0xe1, + 0xe3, 0x3f, 0xfe, 0xe0, 0xec, 0x47, 0x7e, 0xf2, 0xc1, 0xd9, 0x8f, 0xfc, 0xfe, 0x07, 0x67, 0x3f, + 0xf2, 0xb3, 0xfb, 0x67, 0xad, 0x1f, 0xef, 0x9f, 0xb5, 0x7e, 0xb2, 0x7f, 0xd6, 0xfa, 0xa3, 0xfd, + 0xb3, 0xd6, 0x37, 0xff, 0xf8, 0xec, 0x47, 0xbe, 0x58, 0xd9, 0xb9, 0xfc, 0xff, 0x03, 0x00, 0x00, + 0xff, 0xff, 0xda, 0x1e, 0x86, 0x19, 0x82, 0xb6, 0x00, 0x00, } diff --git a/pkg/api/v1/generated.proto b/pkg/api/v1/generated.proto index f6fa8a4a125..1b37c24cf70 100644 --- a/pkg/api/v1/generated.proto +++ b/pkg/api/v1/generated.proto @@ -1465,6 +1465,13 @@ message NodeProxyOptions { optional string path = 1; } +// NodeResources is an object for conveying resource information about a node. +// see http://releases.k8s.io/HEAD/docs/design/resources.md for more details. +message NodeResources { + // Capacity represents the available resources of a node + map capacity = 1; +} + // A node selector represents the union of the results of one or more label queries // over a set of nodes; that is, it represents the OR of the selectors represented // by the node selector terms. @@ -3360,6 +3367,12 @@ message ServiceStatus { optional LoadBalancerStatus loadBalancer = 1; } +message Sysctl { + optional string name = 1; + + optional string value = 2; +} + // TCPSocketAction describes an action based on opening a socket message TCPSocketAction { // Number or name of the port to access on the container. diff --git a/pkg/api/v1/helpers.go b/pkg/api/v1/helpers.go index 5ea0d329ff6..dec2b30c2af 100644 --- a/pkg/api/v1/helpers.go +++ b/pkg/api/v1/helpers.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,18 +16,441 @@ limitations under the License. package v1 -import "k8s.io/kubernetes/pkg/types" +import ( + "encoding/json" + "fmt" + "strings" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/fields" + "k8s.io/kubernetes/pkg/labels" + "k8s.io/kubernetes/pkg/selection" + "k8s.io/kubernetes/pkg/types" + "k8s.io/kubernetes/pkg/util/sets" +) + +// IsOpaqueIntResourceName returns true if the resource name has the opaque +// integer resource prefix. +func IsOpaqueIntResourceName(name ResourceName) bool { + return strings.HasPrefix(string(name), ResourceOpaqueIntPrefix) +} + +// OpaqueIntResourceName returns a ResourceName with the canonical opaque +// integer prefix prepended. If the argument already has the prefix, it is +// returned unmodified. +func OpaqueIntResourceName(name string) ResourceName { + if IsOpaqueIntResourceName(ResourceName(name)) { + return ResourceName(name) + } + return ResourceName(fmt.Sprintf("%s%s", api.ResourceOpaqueIntPrefix, name)) +} // NewDeleteOptions returns a DeleteOptions indicating the resource should // be deleted within the specified grace period. Use zero to indicate // immediate deletion. If you would prefer to use the default grace period, -// use &v1.DeleteOptions{} directly. +// use &api.DeleteOptions{} directly. func NewDeleteOptions(grace int64) *DeleteOptions { return &DeleteOptions{GracePeriodSeconds: &grace} } +// NewPreconditionDeleteOptions returns a DeleteOptions with a UID precondition set. +func NewPreconditionDeleteOptions(uid string) *DeleteOptions { + u := types.UID(uid) + p := Preconditions{UID: &u} + return &DeleteOptions{Preconditions: &p} +} + // NewUIDPreconditions returns a Preconditions with UID set. func NewUIDPreconditions(uid string) *Preconditions { u := types.UID(uid) return &Preconditions{UID: &u} } + +// this function aims to check if the service's ClusterIP is set or not +// the objective is not to perform validation here +func IsServiceIPSet(service *Service) bool { + return service.Spec.ClusterIP != ClusterIPNone && service.Spec.ClusterIP != "" +} + +// this function aims to check if the service's cluster IP is requested or not +func IsServiceIPRequested(service *Service) bool { + // ExternalName services are CNAME aliases to external ones. Ignore the IP. + if service.Spec.Type == ServiceTypeExternalName { + return false + } + return service.Spec.ClusterIP == "" +} + +var standardFinalizers = sets.NewString( + string(FinalizerKubernetes), + FinalizerOrphan, +) + +// HasAnnotation returns a bool if passed in annotation exists +func HasAnnotation(obj ObjectMeta, ann string) bool { + _, found := obj.Annotations[ann] + return found +} + +// SetMetaDataAnnotation sets the annotation and value +func SetMetaDataAnnotation(obj *ObjectMeta, ann string, value string) { + if obj.Annotations == nil { + obj.Annotations = make(map[string]string) + } + obj.Annotations[ann] = value +} + +func IsStandardFinalizerName(str string) bool { + return standardFinalizers.Has(str) +} + +// SingleObject returns a ListOptions for watching a single object. +func SingleObject(meta ObjectMeta) ListOptions { + return ListOptions{ + FieldSelector: fields.OneTermEqualSelector("metadata.name", meta.Name).String(), + ResourceVersion: meta.ResourceVersion, + } +} + +// AddToNodeAddresses appends the NodeAddresses to the passed-by-pointer slice, +// only if they do not already exist +func AddToNodeAddresses(addresses *[]NodeAddress, addAddresses ...NodeAddress) { + for _, add := range addAddresses { + exists := false + for _, existing := range *addresses { + if existing.Address == add.Address && existing.Type == add.Type { + exists = true + break + } + } + if !exists { + *addresses = append(*addresses, add) + } + } +} + +// TODO: make method on LoadBalancerStatus? +func LoadBalancerStatusEqual(l, r *LoadBalancerStatus) bool { + return ingressSliceEqual(l.Ingress, r.Ingress) +} + +func ingressSliceEqual(lhs, rhs []LoadBalancerIngress) bool { + if len(lhs) != len(rhs) { + return false + } + for i := range lhs { + if !ingressEqual(&lhs[i], &rhs[i]) { + return false + } + } + return true +} + +func ingressEqual(lhs, rhs *LoadBalancerIngress) bool { + if lhs.IP != rhs.IP { + return false + } + if lhs.Hostname != rhs.Hostname { + return false + } + return true +} + +// TODO: make method on LoadBalancerStatus? +func LoadBalancerStatusDeepCopy(lb *LoadBalancerStatus) *LoadBalancerStatus { + c := &LoadBalancerStatus{} + c.Ingress = make([]LoadBalancerIngress, len(lb.Ingress)) + for i := range lb.Ingress { + c.Ingress[i] = lb.Ingress[i] + } + return c +} + +// GetAccessModesAsString returns a string representation of an array of access modes. +// modes, when present, are always in the same order: RWO,ROX,RWX. +func GetAccessModesAsString(modes []PersistentVolumeAccessMode) string { + modes = removeDuplicateAccessModes(modes) + modesStr := []string{} + if containsAccessMode(modes, ReadWriteOnce) { + modesStr = append(modesStr, "RWO") + } + if containsAccessMode(modes, ReadOnlyMany) { + modesStr = append(modesStr, "ROX") + } + if containsAccessMode(modes, ReadWriteMany) { + modesStr = append(modesStr, "RWX") + } + return strings.Join(modesStr, ",") +} + +// GetAccessModesAsString returns an array of AccessModes from a string created by GetAccessModesAsString +func GetAccessModesFromString(modes string) []PersistentVolumeAccessMode { + strmodes := strings.Split(modes, ",") + accessModes := []PersistentVolumeAccessMode{} + for _, s := range strmodes { + s = strings.Trim(s, " ") + switch { + case s == "RWO": + accessModes = append(accessModes, ReadWriteOnce) + case s == "ROX": + accessModes = append(accessModes, ReadOnlyMany) + case s == "RWX": + accessModes = append(accessModes, ReadWriteMany) + } + } + return accessModes +} + +// removeDuplicateAccessModes returns an array of access modes without any duplicates +func removeDuplicateAccessModes(modes []PersistentVolumeAccessMode) []PersistentVolumeAccessMode { + accessModes := []PersistentVolumeAccessMode{} + for _, m := range modes { + if !containsAccessMode(accessModes, m) { + accessModes = append(accessModes, m) + } + } + return accessModes +} + +func containsAccessMode(modes []PersistentVolumeAccessMode, mode PersistentVolumeAccessMode) bool { + for _, m := range modes { + if m == mode { + return true + } + } + return false +} + +// NodeSelectorRequirementsAsSelector converts the []NodeSelectorRequirement api type into a struct that implements +// labels.Selector. +func NodeSelectorRequirementsAsSelector(nsm []NodeSelectorRequirement) (labels.Selector, error) { + if len(nsm) == 0 { + return labels.Nothing(), nil + } + selector := labels.NewSelector() + for _, expr := range nsm { + var op selection.Operator + switch expr.Operator { + case NodeSelectorOpIn: + op = selection.In + case NodeSelectorOpNotIn: + op = selection.NotIn + case NodeSelectorOpExists: + op = selection.Exists + case NodeSelectorOpDoesNotExist: + op = selection.DoesNotExist + case NodeSelectorOpGt: + op = selection.GreaterThan + case NodeSelectorOpLt: + op = selection.LessThan + default: + return nil, fmt.Errorf("%q is not a valid node selector operator", expr.Operator) + } + r, err := labels.NewRequirement(expr.Key, op, expr.Values) + if err != nil { + return nil, err + } + selector = selector.Add(*r) + } + return selector, nil +} + +const ( + // AffinityAnnotationKey represents the key of affinity data (json serialized) + // in the Annotations of a Pod. + AffinityAnnotationKey string = "scheduler.alpha.kubernetes.io/affinity" + + // TolerationsAnnotationKey represents the key of tolerations data (json serialized) + // in the Annotations of a Pod. + TolerationsAnnotationKey string = "scheduler.alpha.kubernetes.io/tolerations" + + // TaintsAnnotationKey represents the key of taints data (json serialized) + // in the Annotations of a Node. + TaintsAnnotationKey string = "scheduler.alpha.kubernetes.io/taints" + + // SeccompPodAnnotationKey represents the key of a seccomp profile applied + // to all containers of a pod. + SeccompPodAnnotationKey string = "seccomp.security.alpha.kubernetes.io/pod" + + // SeccompContainerAnnotationKeyPrefix represents the key of a seccomp profile applied + // to one container of a pod. + SeccompContainerAnnotationKeyPrefix string = "container.seccomp.security.alpha.kubernetes.io/" + + // CreatedByAnnotation represents the key used to store the spec(json) + // used to create the resource. + CreatedByAnnotation = "kubernetes.io/created-by" + + // PreferAvoidPodsAnnotationKey represents the key of preferAvoidPods data (json serialized) + // in the Annotations of a Node. + PreferAvoidPodsAnnotationKey string = "scheduler.alpha.kubernetes.io/preferAvoidPods" + + // SysctlsPodAnnotationKey represents the key of sysctls which are set for the infrastructure + // container of a pod. The annotation value is a comma separated list of sysctl_name=value + // key-value pairs. Only a limited set of whitelisted and isolated sysctls is supported by + // the kubelet. Pods with other sysctls will fail to launch. + SysctlsPodAnnotationKey string = "security.alpha.kubernetes.io/sysctls" + + // UnsafeSysctlsPodAnnotationKey represents the key of sysctls which are set for the infrastructure + // container of a pod. The annotation value is a comma separated list of sysctl_name=value + // key-value pairs. Unsafe sysctls must be explicitly enabled for a kubelet. They are properly + // namespaced to a pod or a container, but their isolation is usually unclear or weak. Their use + // is at-your-own-risk. Pods that attempt to set an unsafe sysctl that is not enabled for a kubelet + // will fail to launch. + UnsafeSysctlsPodAnnotationKey string = "security.alpha.kubernetes.io/unsafe-sysctls" +) + +// GetAffinityFromPod gets the json serialized affinity data from Pod.Annotations +// and converts it to the Affinity type in api. +func GetAffinityFromPodAnnotations(annotations map[string]string) (*Affinity, error) { + if len(annotations) > 0 && annotations[AffinityAnnotationKey] != "" { + var affinity Affinity + err := json.Unmarshal([]byte(annotations[AffinityAnnotationKey]), &affinity) + if err != nil { + return nil, err + } + return &affinity, nil + } + return nil, nil +} + +// GetTolerationsFromPodAnnotations gets the json serialized tolerations data from Pod.Annotations +// and converts it to the []Toleration type in api. +func GetTolerationsFromPodAnnotations(annotations map[string]string) ([]Toleration, error) { + var tolerations []Toleration + if len(annotations) > 0 && annotations[TolerationsAnnotationKey] != "" { + err := json.Unmarshal([]byte(annotations[TolerationsAnnotationKey]), &tolerations) + if err != nil { + return tolerations, err + } + } + return tolerations, nil +} + +// GetTaintsFromNodeAnnotations gets the json serialized taints data from Pod.Annotations +// and converts it to the []Taint type in api. +func GetTaintsFromNodeAnnotations(annotations map[string]string) ([]Taint, error) { + var taints []Taint + if len(annotations) > 0 && annotations[TaintsAnnotationKey] != "" { + err := json.Unmarshal([]byte(annotations[TaintsAnnotationKey]), &taints) + if err != nil { + return []Taint{}, err + } + } + return taints, nil +} + +// TolerationToleratesTaint checks if the toleration tolerates the taint. +func TolerationToleratesTaint(toleration *Toleration, taint *Taint) bool { + if len(toleration.Effect) != 0 && toleration.Effect != taint.Effect { + return false + } + + if toleration.Key != taint.Key { + return false + } + // TODO: Use proper defaulting when Toleration becomes a field of PodSpec + if (len(toleration.Operator) == 0 || toleration.Operator == TolerationOpEqual) && toleration.Value == taint.Value { + return true + } + if toleration.Operator == TolerationOpExists { + return true + } + return false +} + +// TaintToleratedByTolerations checks if taint is tolerated by any of the tolerations. +func TaintToleratedByTolerations(taint *Taint, tolerations []Toleration) bool { + tolerated := false + for i := range tolerations { + if TolerationToleratesTaint(&tolerations[i], taint) { + tolerated = true + break + } + } + return tolerated +} + +// MatchTaint checks if the taint matches taintToMatch. Taints are unique by key:effect, +// if the two taints have same key:effect, regard as they match. +func (t *Taint) MatchTaint(taintToMatch Taint) bool { + return t.Key == taintToMatch.Key && t.Effect == taintToMatch.Effect +} + +// taint.ToString() converts taint struct to string in format key=value:effect or key:effect. +func (t *Taint) ToString() string { + if len(t.Value) == 0 { + return fmt.Sprintf("%v:%v", t.Key, t.Effect) + } + return fmt.Sprintf("%v=%v:%v", t.Key, t.Value, t.Effect) +} + +func GetAvoidPodsFromNodeAnnotations(annotations map[string]string) (AvoidPods, error) { + var avoidPods AvoidPods + if len(annotations) > 0 && annotations[PreferAvoidPodsAnnotationKey] != "" { + err := json.Unmarshal([]byte(annotations[PreferAvoidPodsAnnotationKey]), &avoidPods) + if err != nil { + return avoidPods, err + } + } + return avoidPods, nil +} + +// SysctlsFromPodAnnotations parses the sysctl annotations into a slice of safe Sysctls +// and a slice of unsafe Sysctls. This is only a convenience wrapper around +// SysctlsFromPodAnnotation. +func SysctlsFromPodAnnotations(a map[string]string) ([]Sysctl, []Sysctl, error) { + safe, err := SysctlsFromPodAnnotation(a[SysctlsPodAnnotationKey]) + if err != nil { + return nil, nil, err + } + unsafe, err := SysctlsFromPodAnnotation(a[UnsafeSysctlsPodAnnotationKey]) + if err != nil { + return nil, nil, err + } + + return safe, unsafe, nil +} + +// SysctlsFromPodAnnotation parses an annotation value into a slice of Sysctls. +func SysctlsFromPodAnnotation(annotation string) ([]Sysctl, error) { + if len(annotation) == 0 { + return nil, nil + } + + kvs := strings.Split(annotation, ",") + sysctls := make([]Sysctl, len(kvs)) + for i, kv := range kvs { + cs := strings.Split(kv, "=") + if len(cs) != 2 || len(cs[0]) == 0 { + return nil, fmt.Errorf("sysctl %q not of the format sysctl_name=value", kv) + } + sysctls[i].Name = cs[0] + sysctls[i].Value = cs[1] + } + return sysctls, nil +} + +// PodAnnotationsFromSysctls creates an annotation value for a slice of Sysctls. +func PodAnnotationsFromSysctls(sysctls []Sysctl) string { + if len(sysctls) == 0 { + return "" + } + + kvs := make([]string, len(sysctls)) + for i := range sysctls { + kvs[i] = fmt.Sprintf("%s=%s", sysctls[i].Name, sysctls[i].Value) + } + return strings.Join(kvs, ",") +} + +type Sysctl struct { + Name string + Value string +} + +// NodeResources is an object for conveying resource information about a node. +// see http://releases.k8s.io/HEAD/docs/design/resources.md for more details. +type NodeResources struct { + // Capacity represents the available resources of a node + Capacity ResourceList +} diff --git a/pkg/api/v1/helpers_test.go b/pkg/api/v1/helpers_test.go new file mode 100644 index 00000000000..b6a60e19f07 --- /dev/null +++ b/pkg/api/v1/helpers_test.go @@ -0,0 +1,479 @@ +/* +Copyright 2015 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "reflect" + "testing" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/labels" +) + +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 !api.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"}, + }}, + out: mustParse("foo>1"), + }, + { + in: []NodeSelectorRequirement{{ + Key: "bar", + Operator: NodeSelectorOpLt, + Values: []string{"7"}, + }}, + out: mustParse("bar<7"), + }, + } + + 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) + } + } +} + +func TestTaintToString(t *testing.T) { + testCases := []struct { + taint *Taint + expectedString string + }{ + { + taint: &Taint{ + Key: "foo", + Value: "bar", + Effect: TaintEffectNoSchedule, + }, + expectedString: "foo=bar:NoSchedule", + }, + { + taint: &Taint{ + Key: "foo", + Effect: TaintEffectNoSchedule, + }, + expectedString: "foo:NoSchedule", + }, + } + + for i, tc := range testCases { + if tc.expectedString != tc.taint.ToString() { + t.Errorf("[%v] expected taint %v converted to %s, got %s", i, tc.taint, tc.expectedString, tc.taint.ToString()) + } + } +} + +func TestMatchTaint(t *testing.T) { + testCases := []struct { + description string + taint *Taint + taintToMatch Taint + expectMatch bool + }{ + { + description: "two taints with the same key,value,effect should match", + taint: &Taint{ + Key: "foo", + Value: "bar", + Effect: TaintEffectNoSchedule, + }, + taintToMatch: Taint{ + Key: "foo", + Value: "bar", + Effect: TaintEffectNoSchedule, + }, + expectMatch: true, + }, + { + description: "two taints with the same key,effect but different value should match", + taint: &Taint{ + Key: "foo", + Value: "bar", + Effect: TaintEffectNoSchedule, + }, + taintToMatch: Taint{ + Key: "foo", + Value: "different-value", + Effect: TaintEffectNoSchedule, + }, + expectMatch: true, + }, + { + description: "two taints with the different key cannot match", + taint: &Taint{ + Key: "foo", + Value: "bar", + Effect: TaintEffectNoSchedule, + }, + taintToMatch: Taint{ + Key: "different-key", + Value: "bar", + Effect: TaintEffectNoSchedule, + }, + expectMatch: false, + }, + { + description: "two taints with the different effect cannot match", + taint: &Taint{ + Key: "foo", + Value: "bar", + Effect: TaintEffectNoSchedule, + }, + taintToMatch: Taint{ + Key: "foo", + Value: "bar", + Effect: TaintEffectPreferNoSchedule, + }, + expectMatch: false, + }, + } + + for _, tc := range testCases { + if tc.expectMatch != tc.taint.MatchTaint(tc.taintToMatch) { + t.Errorf("[%s] expect taint %s match taint %s", tc.description, tc.taint.ToString(), tc.taintToMatch.ToString()) + } + } +} + +func TestGetAvoidPodsFromNode(t *testing.T) { + controllerFlag := true + testCases := []struct { + node *Node + expectValue AvoidPods + expectErr bool + }{ + { + node: &Node{}, + expectValue: AvoidPods{}, + expectErr: false, + }, + { + node: &Node{ + ObjectMeta: ObjectMeta{ + Annotations: map[string]string{ + PreferAvoidPodsAnnotationKey: ` + { + "preferAvoidPods": [ + { + "podSignature": { + "podController": { + "apiVersion": "v1", + "kind": "ReplicationController", + "name": "foo", + "uid": "abcdef123456", + "controller": true + } + }, + "reason": "some reason", + "message": "some message" + } + ] + }`, + }, + }, + }, + expectValue: AvoidPods{ + PreferAvoidPods: []PreferAvoidPodsEntry{ + { + PodSignature: PodSignature{ + PodController: &OwnerReference{ + APIVersion: "v1", + Kind: "ReplicationController", + Name: "foo", + UID: "abcdef123456", + Controller: &controllerFlag, + }, + }, + Reason: "some reason", + Message: "some message", + }, + }, + }, + expectErr: false, + }, + { + node: &Node{ + // Missing end symbol of "podController" and "podSignature" + ObjectMeta: ObjectMeta{ + Annotations: map[string]string{ + PreferAvoidPodsAnnotationKey: ` + { + "preferAvoidPods": [ + { + "podSignature": { + "podController": { + "kind": "ReplicationController", + "apiVersion": "v1" + "reason": "some reason", + "message": "some message" + } + ] + }`, + }, + }, + }, + expectValue: AvoidPods{}, + expectErr: true, + }, + } + + for i, tc := range testCases { + v, err := GetAvoidPodsFromNodeAnnotations(tc.node.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) + } + if !reflect.DeepEqual(tc.expectValue, v) { + t.Errorf("[%v]expect value %v but got %v with %v", i, tc.expectValue, v, v.PreferAvoidPods[0].PodSignature.PodController.Controller) + } + } +} + +func TestSysctlsFromPodAnnotation(t *testing.T) { + type Test struct { + annotation string + expectValue []Sysctl + expectErr bool + } + for i, test := range []Test{ + { + annotation: "", + expectValue: nil, + }, + { + annotation: "foo.bar", + expectErr: true, + }, + { + annotation: "=123", + expectErr: true, + }, + { + annotation: "foo.bar=", + expectValue: []Sysctl{{Name: "foo.bar", Value: ""}}, + }, + { + annotation: "foo.bar=42", + expectValue: []Sysctl{{Name: "foo.bar", Value: "42"}}, + }, + { + annotation: "foo.bar=42,", + expectErr: true, + }, + { + annotation: "foo.bar=42,abc.def=1", + expectValue: []Sysctl{{Name: "foo.bar", Value: "42"}, {Name: "abc.def", Value: "1"}}, + }, + } { + sysctls, err := SysctlsFromPodAnnotation(test.annotation) + if test.expectErr && err == nil { + t.Errorf("[%v]expected error but got none", i) + } else if !test.expectErr && err != nil { + t.Errorf("[%v]did not expect error but got: %v", i, err) + } else if !reflect.DeepEqual(sysctls, test.expectValue) { + t.Errorf("[%v]expect value %v but got %v", i, test.expectValue, sysctls) + } + } +} diff --git a/pkg/api/v1/pod/BUILD b/pkg/api/v1/pod/BUILD new file mode 100644 index 00000000000..a55580ac5e8 --- /dev/null +++ b/pkg/api/v1/pod/BUILD @@ -0,0 +1,32 @@ +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +load( + "@io_bazel_rules_go//go:def.bzl", + "go_binary", + "go_library", + "go_test", + "cgo_library", +) + +go_library( + name = "go_default_library", + srcs = ["util.go"], + tags = ["automanaged"], + deps = [ + "//pkg/api/v1:go_default_library", + "//pkg/util/intstr:go_default_library", + ], +) + +go_test( + name = "go_default_test", + srcs = ["util_test.go"], + library = "go_default_library", + tags = ["automanaged"], + deps = [ + "//pkg/api/v1:go_default_library", + "//pkg/util/intstr:go_default_library", + ], +) diff --git a/pkg/api/v1/pod/util.go b/pkg/api/v1/pod/util.go new file mode 100644 index 00000000000..1b2d7edb9a3 --- /dev/null +++ b/pkg/api/v1/pod/util.go @@ -0,0 +1,120 @@ +/* +Copyright 2015 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package pod + +import ( + "encoding/json" + "fmt" + + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/util/intstr" +) + +const ( + // TODO: to be de!eted after v1.3 is released. PodSpec has a dedicated Hostname field. + // 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" + + // TODO: to be de!eted after v1.3 is released. PodSpec has a dedicated Subdomain field. + // The annotation value is a string specifying the subdomain e.g. "my-web-service" + // If specified, on 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 +// match is found, fail. +func FindPort(pod *v1.Pod, svcPort *v1.ServicePort) (int, error) { + portName := svcPort.TargetPort + switch portName.Type { + case intstr.String: + name := portName.StrVal + for _, container := range pod.Spec.Containers { + for _, port := range container.Ports { + if port.Name == name && port.Protocol == svcPort.Protocol { + return int(port.ContainerPort), nil + } + } + } + case intstr.Int: + return portName.IntValue(), nil + } + + return 0, fmt.Errorf("no suitable port for manifest: %s", pod.UID) +} + +// TODO: remove this function when init containers becomes a stable feature +func SetInitContainersAndStatuses(pod *v1.Pod) error { + var initContainersAnnotation string + initContainersAnnotation = pod.Annotations[v1.PodInitContainersAnnotationKey] + initContainersAnnotation = pod.Annotations[v1.PodInitContainersBetaAnnotationKey] + if len(initContainersAnnotation) > 0 { + var values []v1.Container + if err := json.Unmarshal([]byte(initContainersAnnotation), &values); err != nil { + return err + } + pod.Spec.InitContainers = values + } + + var initContainerStatusesAnnotation string + initContainerStatusesAnnotation = pod.Annotations[v1.PodInitContainerStatusesAnnotationKey] + initContainerStatusesAnnotation = pod.Annotations[v1.PodInitContainerStatusesBetaAnnotationKey] + if len(initContainerStatusesAnnotation) > 0 { + var values []v1.ContainerStatus + if err := json.Unmarshal([]byte(initContainerStatusesAnnotation), &values); err != nil { + return err + } + pod.Status.InitContainerStatuses = values + } + return nil +} + +// TODO: remove this function when init containers becomes a stable feature +func SetInitContainersAnnotations(pod *v1.Pod) error { + if len(pod.Spec.InitContainers) > 0 { + value, err := json.Marshal(pod.Spec.InitContainers) + if err != nil { + return err + } + if pod.Annotations == nil { + pod.Annotations = make(map[string]string) + } + pod.Annotations[v1.PodInitContainersAnnotationKey] = string(value) + pod.Annotations[v1.PodInitContainersBetaAnnotationKey] = string(value) + } + return nil +} + +// TODO: remove this function when init containers becomes a stable feature +func SetInitContainersStatusesAnnotations(pod *v1.Pod) error { + if len(pod.Status.InitContainerStatuses) > 0 { + value, err := json.Marshal(pod.Status.InitContainerStatuses) + if err != nil { + return err + } + if pod.Annotations == nil { + pod.Annotations = make(map[string]string) + } + pod.Annotations[v1.PodInitContainerStatusesAnnotationKey] = string(value) + pod.Annotations[v1.PodInitContainerStatusesBetaAnnotationKey] = string(value) + } + return nil +} diff --git a/pkg/api/pod/util_test.go b/pkg/api/v1/pod/util_test.go similarity index 81% rename from pkg/api/pod/util_test.go rename to pkg/api/v1/pod/util_test.go index 5dd8ff88098..842398d6fa1 100644 --- a/pkg/api/pod/util_test.go +++ b/pkg/api/v1/pod/util_test.go @@ -19,26 +19,26 @@ package pod import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/intstr" ) func TestFindPort(t *testing.T) { testCases := []struct { name string - containers []api.Container + containers []v1.Container port intstr.IntOrString expected int pass bool }{{ name: "valid int, no ports", - containers: []api.Container{{}}, + containers: []v1.Container{{}}, port: intstr.FromInt(93), expected: 93, pass: true, }, { name: "valid int, with ports", - containers: []api.Container{{Ports: []api.ContainerPort{{ + containers: []v1.Container{{Ports: []v1.ContainerPort{{ Name: "", ContainerPort: 11, Protocol: "TCP", @@ -52,13 +52,13 @@ func TestFindPort(t *testing.T) { pass: true, }, { name: "valid str, no ports", - containers: []api.Container{{}}, + containers: []v1.Container{{}}, port: intstr.FromString("p"), expected: 0, pass: false, }, { name: "valid str, one ctr with ports", - containers: []api.Container{{Ports: []api.ContainerPort{{ + containers: []v1.Container{{Ports: []v1.ContainerPort{{ Name: "", ContainerPort: 11, Protocol: "UDP", @@ -76,7 +76,7 @@ func TestFindPort(t *testing.T) { pass: true, }, { name: "valid str, two ctr with ports", - containers: []api.Container{{}, {Ports: []api.ContainerPort{{ + containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ Name: "", ContainerPort: 11, Protocol: "UDP", @@ -94,7 +94,7 @@ func TestFindPort(t *testing.T) { pass: true, }, { name: "valid str, two ctr with same port", - containers: []api.Container{{}, {Ports: []api.ContainerPort{{ + containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ Name: "", ContainerPort: 11, Protocol: "UDP", @@ -112,7 +112,7 @@ func TestFindPort(t *testing.T) { pass: true, }, { name: "valid str, invalid protocol", - containers: []api.Container{{}, {Ports: []api.ContainerPort{{ + containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ Name: "a", ContainerPort: 11, Protocol: "snmp", @@ -123,7 +123,7 @@ func TestFindPort(t *testing.T) { pass: false, }, { name: "valid hostPort", - containers: []api.Container{{}, {Ports: []api.ContainerPort{{ + containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ Name: "a", ContainerPort: 11, HostPort: 81, @@ -136,7 +136,7 @@ func TestFindPort(t *testing.T) { }, { name: "invalid hostPort", - containers: []api.Container{{}, {Ports: []api.ContainerPort{{ + containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ Name: "a", ContainerPort: 11, HostPort: -1, @@ -150,7 +150,7 @@ func TestFindPort(t *testing.T) { }, { name: "invalid ContainerPort", - containers: []api.Container{{}, {Ports: []api.ContainerPort{{ + containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ Name: "a", ContainerPort: -1, Protocol: "TCP", @@ -163,7 +163,7 @@ func TestFindPort(t *testing.T) { }, { name: "HostIP Address", - containers: []api.Container{{}, {Ports: []api.ContainerPort{{ + containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ Name: "a", ContainerPort: 11, HostIP: "192.168.1.1", @@ -177,8 +177,8 @@ func TestFindPort(t *testing.T) { } for _, tc := range testCases { - port, err := FindPort(&api.Pod{Spec: api.PodSpec{Containers: tc.containers}}, - &api.ServicePort{Protocol: "TCP", TargetPort: tc.port}) + port, err := FindPort(&v1.Pod{Spec: v1.PodSpec{Containers: tc.containers}}, + &v1.ServicePort{Protocol: "TCP", TargetPort: tc.port}) if err != nil && tc.pass { t.Errorf("unexpected error for %s: %v", tc.name, err) } diff --git a/pkg/api/v1/ref.go b/pkg/api/v1/ref.go new file mode 100644 index 00000000000..f9427350a77 --- /dev/null +++ b/pkg/api/v1/ref.go @@ -0,0 +1,133 @@ +/* +Copyright 2014 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "errors" + "fmt" + "k8s.io/kubernetes/pkg/api" + "net/url" + "strings" + + "k8s.io/kubernetes/pkg/api/meta" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/runtime" +) + +var ( + // Errors that could be returned by GetReference. + ErrNilObject = errors.New("can't reference a nil object") + ErrNoSelfLink = errors.New("selfLink was empty, can't make reference") +) + +// GetReference returns an ObjectReference which refers to the given +// object, or an error if the object doesn't follow the conventions +// that would allow this. +// TODO: should take a meta.Interface see http://issue.k8s.io/7127 +func GetReference(obj runtime.Object) (*ObjectReference, error) { + if obj == nil { + return nil, ErrNilObject + } + if ref, ok := obj.(*ObjectReference); ok { + // Don't make a reference to a reference. + return ref, nil + } + + gvk := obj.GetObjectKind().GroupVersionKind() + + // if the object referenced is actually persisted, we can just get kind from meta + // if we are building an object reference to something not yet persisted, we should fallback to scheme + kind := gvk.Kind + if len(kind) == 0 { + // TODO: this is wrong + gvks, _, err := api.Scheme.ObjectKinds(obj) + if err != nil { + return nil, err + } + kind = gvks[0].Kind + } + + // An object that implements only List has enough metadata to build a reference + var listMeta meta.List + objectMeta, err := meta.Accessor(obj) + if err != nil { + listMeta, err = meta.ListAccessor(obj) + if err != nil { + return nil, err + } + } else { + listMeta = objectMeta + } + + // if the object referenced is actually persisted, we can also get version from meta + version := gvk.GroupVersion().String() + if len(version) == 0 { + selfLink := listMeta.GetSelfLink() + if len(selfLink) == 0 { + return nil, ErrNoSelfLink + } + selfLinkUrl, err := url.Parse(selfLink) + if err != nil { + return nil, err + } + // example paths: ///* + parts := strings.Split(selfLinkUrl.Path, "/") + if len(parts) < 3 { + return nil, fmt.Errorf("unexpected self link format: '%v'; got version '%v'", selfLink, version) + } + version = parts[2] + } + + // only has list metadata + if objectMeta == nil { + return &ObjectReference{ + Kind: kind, + APIVersion: version, + ResourceVersion: listMeta.GetResourceVersion(), + }, nil + } + + return &ObjectReference{ + Kind: kind, + APIVersion: version, + Name: objectMeta.GetName(), + Namespace: objectMeta.GetNamespace(), + UID: objectMeta.GetUID(), + ResourceVersion: objectMeta.GetResourceVersion(), + }, nil +} + +// GetPartialReference is exactly like GetReference, but allows you to set the FieldPath. +func GetPartialReference(obj runtime.Object, fieldPath string) (*ObjectReference, error) { + ref, err := GetReference(obj) + if err != nil { + return nil, err + } + ref.FieldPath = fieldPath + return ref, nil +} + +// IsAnAPIObject allows clients to preemptively get a reference to an API object and pass it to places that +// intend only to get a reference to that object. This simplifies the event recording interface. +func (obj *ObjectReference) SetGroupVersionKind(gvk unversioned.GroupVersionKind) { + obj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind() +} +func (obj *ObjectReference) GroupVersionKind() unversioned.GroupVersionKind { + return unversioned.FromAPIVersionAndKind(obj.APIVersion, obj.Kind) +} + +func (obj *ObjectReference) GetObjectKind() unversioned.ObjectKind { return obj } diff --git a/pkg/api/v1/resource_helpers.go b/pkg/api/v1/resource_helpers.go new file mode 100644 index 00000000000..9b7b9d16498 --- /dev/null +++ b/pkg/api/v1/resource_helpers.go @@ -0,0 +1,229 @@ +/* +Copyright 2014 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "time" + + "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/unversioned" +) + +// Returns string version of ResourceName. +func (self ResourceName) String() string { + return string(self) +} + +// Returns the CPU limit if specified. +func (self *ResourceList) Cpu() *resource.Quantity { + if val, ok := (*self)[ResourceCPU]; ok { + return &val + } + return &resource.Quantity{Format: resource.DecimalSI} +} + +// Returns the Memory limit if specified. +func (self *ResourceList) Memory() *resource.Quantity { + if val, ok := (*self)[ResourceMemory]; ok { + return &val + } + return &resource.Quantity{Format: resource.BinarySI} +} + +func (self *ResourceList) Pods() *resource.Quantity { + if val, ok := (*self)[ResourcePods]; ok { + return &val + } + return &resource.Quantity{} +} + +func (self *ResourceList) NvidiaGPU() *resource.Quantity { + if val, ok := (*self)[ResourceNvidiaGPU]; ok { + return &val + } + return &resource.Quantity{} +} + +func GetContainerStatus(statuses []ContainerStatus, name string) (ContainerStatus, bool) { + for i := range statuses { + if statuses[i].Name == name { + return statuses[i], true + } + } + return ContainerStatus{}, false +} + +func GetExistingContainerStatus(statuses []ContainerStatus, name string) ContainerStatus { + for i := range statuses { + if statuses[i].Name == name { + return statuses[i] + } + } + return ContainerStatus{} +} + +// IsPodAvailable returns true if a pod is available; false otherwise. +// Precondition for an available pod is that it must be ready. On top +// of that, there are two cases when a pod can be considered available: +// 1. minReadySeconds == 0, or +// 2. LastTransitionTime (is set) + minReadySeconds < current time +func IsPodAvailable(pod *Pod, minReadySeconds int32, now unversioned.Time) bool { + if !IsPodReady(pod) { + return false + } + + c := GetPodReadyCondition(pod.Status) + minReadySecondsDuration := time.Duration(minReadySeconds) * time.Second + if minReadySeconds == 0 || !c.LastTransitionTime.IsZero() && c.LastTransitionTime.Add(minReadySecondsDuration).Before(now.Time) { + return true + } + return false +} + +// IsPodReady returns true if a pod is ready; false otherwise. +func IsPodReady(pod *Pod) bool { + return IsPodReadyConditionTrue(pod.Status) +} + +// IsPodReady retruns true if a pod is ready; false otherwise. +func IsPodReadyConditionTrue(status PodStatus) bool { + condition := GetPodReadyCondition(status) + return condition != nil && condition.Status == ConditionTrue +} + +// Extracts the pod ready condition from the given status and returns that. +// Returns nil if the condition is not present. +func GetPodReadyCondition(status PodStatus) *PodCondition { + _, condition := GetPodCondition(&status, PodReady) + return condition +} + +// GetPodCondition extracts the provided condition from the given status and returns that. +// Returns nil and -1 if the condition is not present, and the index of the located condition. +func GetPodCondition(status *PodStatus, conditionType PodConditionType) (int, *PodCondition) { + if status == nil { + return -1, nil + } + for i := range status.Conditions { + if status.Conditions[i].Type == conditionType { + return i, &status.Conditions[i] + } + } + return -1, nil +} + +// GetNodeCondition extracts the provided condition from the given status and returns that. +// Returns nil and -1 if the condition is not present, and the index of the located condition. +func GetNodeCondition(status *NodeStatus, conditionType NodeConditionType) (int, *NodeCondition) { + if status == nil { + return -1, nil + } + for i := range status.Conditions { + if status.Conditions[i].Type == conditionType { + return i, &status.Conditions[i] + } + } + return -1, nil +} + +// Updates existing pod condition or creates a new one. Sets LastTransitionTime to now if the +// status has changed. +// Returns true if pod condition has changed or has been added. +func UpdatePodCondition(status *PodStatus, condition *PodCondition) bool { + condition.LastTransitionTime = unversioned.Now() + // Try to find this pod condition. + conditionIndex, oldCondition := GetPodCondition(status, condition.Type) + + if oldCondition == nil { + // We are adding new pod condition. + status.Conditions = append(status.Conditions, *condition) + return true + } else { + // We are updating an existing condition, so we need to check if it has changed. + if condition.Status == oldCondition.Status { + condition.LastTransitionTime = oldCondition.LastTransitionTime + } + + isEqual := condition.Status == oldCondition.Status && + condition.Reason == oldCondition.Reason && + condition.Message == oldCondition.Message && + condition.LastProbeTime.Equal(oldCondition.LastProbeTime) && + condition.LastTransitionTime.Equal(oldCondition.LastTransitionTime) + + status.Conditions[conditionIndex] = *condition + // Return true if one of the fields have changed. + return !isEqual + } +} + +// IsNodeReady returns true if a node is ready; false otherwise. +func IsNodeReady(node *Node) bool { + for _, c := range node.Status.Conditions { + if c.Type == NodeReady { + return c.Status == ConditionTrue + } + } + return false +} + +// PodRequestsAndLimits returns a dictionary of all defined resources summed up for all +// containers of the pod. +func PodRequestsAndLimits(pod *Pod) (reqs map[ResourceName]resource.Quantity, limits map[ResourceName]resource.Quantity, err error) { + reqs, limits = map[ResourceName]resource.Quantity{}, map[ResourceName]resource.Quantity{} + for _, container := range pod.Spec.Containers { + for name, quantity := range container.Resources.Requests { + if value, ok := reqs[name]; !ok { + reqs[name] = *quantity.Copy() + } else { + value.Add(quantity) + reqs[name] = value + } + } + for name, quantity := range container.Resources.Limits { + if value, ok := limits[name]; !ok { + limits[name] = *quantity.Copy() + } else { + value.Add(quantity) + limits[name] = value + } + } + } + // init containers define the minimum of any resource + for _, container := range pod.Spec.InitContainers { + for name, quantity := range container.Resources.Requests { + value, ok := reqs[name] + if !ok { + reqs[name] = *quantity.Copy() + continue + } + if quantity.Cmp(value) > 0 { + reqs[name] = *quantity.Copy() + } + } + for name, quantity := range container.Resources.Limits { + value, ok := limits[name] + if !ok { + limits[name] = *quantity.Copy() + continue + } + if quantity.Cmp(value) > 0 { + limits[name] = *quantity.Copy() + } + } + } + return +} diff --git a/pkg/api/v1/resource_helpers_test.go b/pkg/api/v1/resource_helpers_test.go new file mode 100644 index 00000000000..e6d7fe3552b --- /dev/null +++ b/pkg/api/v1/resource_helpers_test.go @@ -0,0 +1,120 @@ +/* +Copyright 2015 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "testing" + "time" + + "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/unversioned" +) + +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.Cmp(cpuLimit) != 0 { + t.Errorf("expected cpulimit %v, got %v", cpuLimit, res) + } + if res := resourceSpec.Limits.Memory(); res.Cmp(memoryLimit) != 0 { + 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.Cmp(memoryLimit) != 0 { + 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) + } +} + +func newPod(now unversioned.Time, ready bool, beforeSec int) *Pod { + conditionStatus := ConditionFalse + if ready { + conditionStatus = ConditionTrue + } + return &Pod{ + Status: PodStatus{ + Conditions: []PodCondition{ + { + Type: PodReady, + LastTransitionTime: unversioned.NewTime(now.Time.Add(-1 * time.Duration(beforeSec) * time.Second)), + Status: conditionStatus, + }, + }, + }, + } +} + +func TestIsPodAvailable(t *testing.T) { + now := unversioned.Now() + tests := []struct { + pod *Pod + minReadySeconds int32 + expected bool + }{ + { + pod: newPod(now, false, 0), + minReadySeconds: 0, + expected: false, + }, + { + pod: newPod(now, true, 0), + minReadySeconds: 1, + expected: false, + }, + { + pod: newPod(now, true, 0), + minReadySeconds: 0, + expected: true, + }, + { + pod: newPod(now, true, 51), + minReadySeconds: 50, + expected: true, + }, + } + + for i, test := range tests { + isAvailable := IsPodAvailable(test.pod, test.minReadySeconds, now) + if isAvailable != test.expected { + t.Errorf("[tc #%d] expected available pod: %t, got: %t", i, test.expected, isAvailable) + } + } +} diff --git a/pkg/api/v1/service/BUILD b/pkg/api/v1/service/BUILD new file mode 100644 index 00000000000..843a8c644b5 --- /dev/null +++ b/pkg/api/v1/service/BUILD @@ -0,0 +1,36 @@ +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +load( + "@io_bazel_rules_go//go:def.bzl", + "go_binary", + "go_library", + "go_test", + "cgo_library", +) + +go_library( + name = "go_default_library", + srcs = [ + "annotations.go", + "util.go", + ], + tags = ["automanaged"], + deps = [ + "//pkg/api/v1:go_default_library", + "//pkg/util/net/sets:go_default_library", + "//vendor:github.com/golang/glog", + ], +) + +go_test( + name = "go_default_test", + srcs = ["util_test.go"], + library = "go_default_library", + tags = ["automanaged"], + deps = [ + "//pkg/api/v1:go_default_library", + "//pkg/util/net/sets:go_default_library", + ], +) diff --git a/pkg/api/v1/service/annotations.go b/pkg/api/v1/service/annotations.go new file mode 100644 index 00000000000..141e572124a --- /dev/null +++ b/pkg/api/v1/service/annotations.go @@ -0,0 +1,111 @@ +/* +Copyright 2016 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package service + +import ( + "strconv" + + "github.com/golang/glog" + "k8s.io/kubernetes/pkg/api/v1" +) + +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" + + // AnnotationValueExternalTrafficLocal Value of annotation to specify local endpoints behaviour + AnnotationValueExternalTrafficLocal = "OnlyLocal" + // AnnotationValueExternalTrafficGlobal Value of annotation to specify global (legacy) behaviour + AnnotationValueExternalTrafficGlobal = "Global" + + // TODO: The alpha annotations have been deprecated, remove them when we move this feature to GA. + + // AlphaAnnotationHealthCheckNodePort Annotation specifying the healthcheck nodePort for the service + // If not specified, annotation is created by the service api backend with the allocated nodePort + // Will use user-specified nodePort value if specified by the client + AlphaAnnotationHealthCheckNodePort = "service.alpha.kubernetes.io/healthcheck-nodeport" + + // AlphaAnnotationExternalTraffic An annotation that denotes if this Service desires to route external traffic to local + // endpoints only. This preserves Source IP and avoids a second hop. + AlphaAnnotationExternalTraffic = "service.alpha.kubernetes.io/external-traffic" + + // BetaAnnotationHealthCheckNodePort is the beta version of AlphaAnnotationHealthCheckNodePort. + BetaAnnotationHealthCheckNodePort = "service.beta.kubernetes.io/healthcheck-nodeport" + + // BetaAnnotationExternalTraffic is the beta version of AlphaAnnotationExternalTraffic. + BetaAnnotationExternalTraffic = "service.beta.kubernetes.io/external-traffic" +) + +// NeedsHealthCheck Check service for health check annotations +func NeedsHealthCheck(service *v1.Service) bool { + // First check the alpha annotation and then the beta. This is so existing + // Services continue to work till the user decides to transition to beta. + // If they transition to beta, there's no way to go back to alpha without + // rolling back the cluster. + for _, annotation := range []string{AlphaAnnotationExternalTraffic, BetaAnnotationExternalTraffic} { + if l, ok := service.Annotations[annotation]; ok { + if l == AnnotationValueExternalTrafficLocal { + return true + } else if l == AnnotationValueExternalTrafficGlobal { + return false + } else { + glog.Errorf("Invalid value for annotation %v: %v", annotation, l) + } + } + } + return false +} + +// GetServiceHealthCheckNodePort Return health check node port annotation for service, if one exists +func GetServiceHealthCheckNodePort(service *v1.Service) int32 { + if !NeedsHealthCheck(service) { + return 0 + } + // First check the alpha annotation and then the beta. This is so existing + // Services continue to work till the user decides to transition to beta. + // If they transition to beta, there's no way to go back to alpha without + // rolling back the cluster. + for _, annotation := range []string{AlphaAnnotationHealthCheckNodePort, BetaAnnotationHealthCheckNodePort} { + if l, ok := service.Annotations[annotation]; ok { + p, err := strconv.Atoi(l) + if err != nil { + glog.Errorf("Failed to parse annotation %v: %v", annotation, err) + continue + } + return int32(p) + } + } + return 0 +} + +// GetServiceHealthCheckPathPort Return the path and nodePort programmed into the Cloud LB Health Check +func GetServiceHealthCheckPathPort(service *v1.Service) (string, int32) { + if !NeedsHealthCheck(service) { + return "", 0 + } + port := GetServiceHealthCheckNodePort(service) + if port == 0 { + return "", 0 + } + return "/healthz", port +} diff --git a/pkg/api/v1/service/util.go b/pkg/api/v1/service/util.go new file mode 100644 index 00000000000..3c00a495245 --- /dev/null +++ b/pkg/api/v1/service/util.go @@ -0,0 +1,68 @@ +/* +Copyright 2016 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package service + +import ( + "fmt" + "strings" + + "k8s.io/kubernetes/pkg/api/v1" + 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 first try to parse and verify LoadBalancerSourceRanges field from a service. +// If the field is not specified, turn to parse and verify the AnnotationLoadBalancerSourceRangesKey annotation from a service, +// extracting the source ranges to allow, and if not present returns a default (allow-all) value. +func GetLoadBalancerSourceRanges(service *v1.Service) (netsets.IPNet, error) { + var ipnets netsets.IPNet + var err error + // if SourceRange field is specified, ignore sourceRange annotation + if len(service.Spec.LoadBalancerSourceRanges) > 0 { + specs := service.Spec.LoadBalancerSourceRanges + ipnets, err = netsets.ParseIPNets(specs...) + + if err != nil { + return nil, fmt.Errorf("service.Spec.LoadBalancerSourceRanges: %v is not valid. Expecting a list of IP ranges. For example, 10.0.0.0/24. Error msg: %v", specs, err) + } + } else { + val := service.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("%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/pkg/api/v1/service/util_test.go b/pkg/api/v1/service/util_test.go new file mode 100644 index 00000000000..28572f3c829 --- /dev/null +++ b/pkg/api/v1/service/util_test.go @@ -0,0 +1,131 @@ +/* +Copyright 2016 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package service + +import ( + "testing" + + "strings" + + "k8s.io/kubernetes/pkg/api/v1" + netsets "k8s.io/kubernetes/pkg/util/net/sets" +) + +func TestGetLoadBalancerSourceRanges(t *testing.T) { + checkError := func(v string) { + annotations := make(map[string]string) + annotations[AnnotationLoadBalancerSourceRangesKey] = v + svc := v1.Service{} + svc.Annotations = annotations + _, err := GetLoadBalancerSourceRanges(&svc) + if err == nil { + t.Errorf("Expected error parsing: %q", v) + } + svc = v1.Service{} + svc.Spec.LoadBalancerSourceRanges = strings.Split(v, ",") + _, err = GetLoadBalancerSourceRanges(&svc) + if err == nil { + t.Errorf("Expected error parsing: %q", v) + } + } + checkError("10.0.0.1/33") + checkError("foo.bar") + checkError("10.0.0.1/32,*") + checkError("10.0.0.1/32,") + checkError("10.0.0.1/32, ") + checkError("10.0.0.1") + + checkOK := func(v string) netsets.IPNet { + annotations := make(map[string]string) + annotations[AnnotationLoadBalancerSourceRangesKey] = v + svc := v1.Service{} + svc.Annotations = annotations + cidrs, err := GetLoadBalancerSourceRanges(&svc) + if err != nil { + t.Errorf("Unexpected error parsing: %q", v) + } + svc = v1.Service{} + svc.Spec.LoadBalancerSourceRanges = strings.Split(v, ",") + cidrs, err = GetLoadBalancerSourceRanges(&svc) + if err != nil { + t.Errorf("Unexpected error parsing: %q", v) + } + return cidrs + } + cidrs := checkOK("192.168.0.1/32") + if len(cidrs) != 1 { + t.Errorf("Expected exactly one CIDR: %v", cidrs.StringSlice()) + } + cidrs = checkOK("192.168.0.1/32,192.168.0.1/32") + if len(cidrs) != 1 { + t.Errorf("Expected exactly one CIDR (after de-dup): %v", cidrs.StringSlice()) + } + cidrs = checkOK("192.168.0.1/32,192.168.0.2/32") + if len(cidrs) != 2 { + t.Errorf("Expected two CIDRs: %v", cidrs.StringSlice()) + } + cidrs = checkOK(" 192.168.0.1/32 , 192.168.0.2/32 ") + if len(cidrs) != 2 { + t.Errorf("Expected two CIDRs: %v", cidrs.StringSlice()) + } + // check LoadBalancerSourceRanges not specified + svc := v1.Service{} + cidrs, err := GetLoadBalancerSourceRanges(&svc) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + if len(cidrs) != 1 { + t.Errorf("Expected exactly one CIDR: %v", cidrs.StringSlice()) + } + if !IsAllowAll(cidrs) { + t.Errorf("Expected default to be allow-all: %v", cidrs.StringSlice()) + } + // check SourceRanges annotation is empty + annotations := make(map[string]string) + annotations[AnnotationLoadBalancerSourceRangesKey] = "" + svc = v1.Service{} + svc.Annotations = annotations + cidrs, err = GetLoadBalancerSourceRanges(&svc) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + if len(cidrs) != 1 { + t.Errorf("Expected exactly one CIDR: %v", cidrs.StringSlice()) + } + if !IsAllowAll(cidrs) { + t.Errorf("Expected default to be allow-all: %v", cidrs.StringSlice()) + } +} + +func TestAllowAll(t *testing.T) { + checkAllowAll := func(allowAll bool, cidrs ...string) { + ipnets, err := netsets.ParseIPNets(cidrs...) + if err != nil { + t.Errorf("Unexpected error parsing cidrs: %v", cidrs) + } + if allowAll != IsAllowAll(ipnets) { + t.Errorf("IsAllowAll did not return expected value for %v", cidrs) + } + } + checkAllowAll(false, "10.0.0.1/32") + checkAllowAll(false, "10.0.0.1/32", "10.0.0.2/32") + checkAllowAll(false, "10.0.0.1/32", "10.0.0.1/32") + + checkAllowAll(true, "0.0.0.0/0") + checkAllowAll(true, "192.168.0.0/0") + checkAllowAll(true, "192.168.0.1/32", "0.0.0.0/0") +} diff --git a/pkg/api/v1/types.go b/pkg/api/v1/types.go index cc8abfa958c..ba06fd4489f 100644 --- a/pkg/api/v1/types.go +++ b/pkg/api/v1/types.go @@ -2995,6 +2995,8 @@ const ( NodeDiskPressure NodeConditionType = "DiskPressure" // NodeNetworkUnavailable means that network for the node is not correctly configured. NodeNetworkUnavailable NodeConditionType = "NetworkUnavailable" + // NodeInodePressure means the kublet is under pressure due to insufficient available inodes. + NodeInodePressure NodeConditionType = "InodePressure" ) // NodeCondition contains condition information for a node. @@ -3056,6 +3058,11 @@ const ( // Number of Pods that may be running on this Node: see ResourcePods ) +const ( + // Namespace prefix for opaque counted resources (alpha). + ResourceOpaqueIntPrefix = "pod.alpha.kubernetes.io/opaque-int-resource-" +) + // ResourceList is a set of (resource name, quantity) pairs. type ResourceList map[ResourceName]resource.Quantity @@ -3790,6 +3797,35 @@ const ( // DockerConfigKey is the key of the required data for SecretTypeDockercfg secrets DockerConfigKey = ".dockercfg" + // SecretTypeDockerConfigJson contains a dockercfg file that follows the same format rules as ~/.docker/config.json + // + // Required fields: + // - Secret.Data[".dockerconfigjson"] - a serialized ~/.docker/config.json file + SecretTypeDockerConfigJson SecretType = "kubernetes.io/dockerconfigjson" + + // DockerConfigJsonKey is the key of the required data for SecretTypeDockerConfigJson secrets + DockerConfigJsonKey = ".dockerconfigjson" + + // SecretTypeBasicAuth contains data needed for basic authentication. + // + // Required at least one of fields: + // - Secret.Data["username"] - username used for authentication + // - Secret.Data["password"] - password or token needed for authentication + SecretTypeBasicAuth SecretType = "kubernetes.io/basic-auth" + + // BasicAuthUsernameKey is the key of the username for SecretTypeBasicAuth secrets + BasicAuthUsernameKey = "username" + // BasicAuthPasswordKey is the key of the password or token for SecretTypeBasicAuth secrets + BasicAuthPasswordKey = "password" + + // SecretTypeSSHAuth contains data needed for SSH authetication. + // + // Required field: + // - Secret.Data["ssh-privatekey"] - private SSH key needed for authentication + SecretTypeSSHAuth SecretType = "kubernetes.io/ssh-auth" + + // SSHAuthPrivateKey is the key of the required SSH private key for SecretTypeSSHAuth secrets + SSHAuthPrivateKey = "ssh-privatekey" // SecretTypeTLS contains information about a TLS client or server secret. It // is primarily used with TLS termination of the Ingress resource, but may be // used in other types. @@ -4011,4 +4047,14 @@ type RangeAllocation struct { const ( // "default-scheduler" is the name of default scheduler. DefaultSchedulerName = "default-scheduler" + + // RequiredDuringScheduling affinity is not symmetric, but there is an implicit PreferredDuringScheduling affinity rule + // corresponding to every RequiredDuringScheduling affinity rule. + // When the --hard-pod-affinity-weight scheduler flag is not specified, + // DefaultHardPodAffinityWeight defines the weight of the implicit PreferredDuringScheduling affinity rule. + DefaultHardPodAffinitySymmetricWeight int = 1 + + // When the --failure-domains scheduler flag is not specified, + // DefaultFailureDomains defines the set of label keys used when TopologyKey is empty in PreferredDuringScheduling anti-affinity. + DefaultFailureDomains string = unversioned.LabelHostname + "," + unversioned.LabelZoneFailureDomain + "," + unversioned.LabelZoneRegion ) diff --git a/pkg/api/v1/validation/BUILD b/pkg/api/v1/validation/BUILD new file mode 100644 index 00000000000..d99e0190862 --- /dev/null +++ b/pkg/api/v1/validation/BUILD @@ -0,0 +1,25 @@ +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +load( + "@io_bazel_rules_go//go:def.bzl", + "go_binary", + "go_library", + "go_test", + "cgo_library", +) + +go_library( + name = "go_default_library", + srcs = ["validation.go"], + tags = ["automanaged"], + deps = [ + "//pkg/api:go_default_library", + "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/util/sets:go_default_library", + "//pkg/util/validation:go_default_library", + "//pkg/util/validation/field:go_default_library", + ], +) diff --git a/pkg/api/v1/validation/validation.go b/pkg/api/v1/validation/validation.go new file mode 100644 index 00000000000..f6138a49fdf --- /dev/null +++ b/pkg/api/v1/validation/validation.go @@ -0,0 +1,159 @@ +/* +Copyright 2014 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package validation + +import ( + "fmt" + "strings" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/util/sets" + "k8s.io/kubernetes/pkg/util/validation" + "k8s.io/kubernetes/pkg/util/validation/field" +) + +const isNegativeErrorMsg string = `must be greater than or equal to 0` +const isNotIntegerErrorMsg string = `must be an integer` + +func ValidateResourceRequirements(requirements *v1.ResourceRequirements, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + limPath := fldPath.Child("limits") + reqPath := fldPath.Child("requests") + for resourceName, quantity := range requirements.Limits { + fldPath := limPath.Key(string(resourceName)) + // Validate resource name. + allErrs = append(allErrs, validateContainerResourceName(string(resourceName), fldPath)...) + + // Validate resource quantity. + allErrs = append(allErrs, ValidateResourceQuantityValue(string(resourceName), quantity, fldPath)...) + + // Check that request <= limit. + requestQuantity, exists := requirements.Requests[resourceName] + if exists { + // For GPUs, not only requests can't exceed limits, they also can't be lower, i.e. must be equal. + if resourceName == v1.ResourceNvidiaGPU && quantity.Cmp(requestQuantity) != 0 { + allErrs = append(allErrs, field.Invalid(reqPath, requestQuantity.String(), fmt.Sprintf("must be equal to %s limit", v1.ResourceNvidiaGPU))) + } else if quantity.Cmp(requestQuantity) < 0 { + allErrs = append(allErrs, field.Invalid(limPath, quantity.String(), fmt.Sprintf("must be greater than or equal to %s request", resourceName))) + } + } + } + for resourceName, quantity := range requirements.Requests { + fldPath := reqPath.Key(string(resourceName)) + // Validate resource name. + allErrs = append(allErrs, validateContainerResourceName(string(resourceName), fldPath)...) + // Validate resource quantity. + allErrs = append(allErrs, ValidateResourceQuantityValue(string(resourceName), quantity, fldPath)...) + } + + return allErrs +} + +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{} +} + +// ValidateResourceQuantityValue enforces that specified quantity is valid for specified resource +func ValidateResourceQuantityValue(resource string, value resource.Quantity, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + allErrs = append(allErrs, ValidateNonnegativeQuantity(value, fldPath)...) + if api.IsIntegerResourceName(resource) { + if value.MilliValue()%int64(1000) != int64(0) { + allErrs = append(allErrs, field.Invalid(fldPath, value, isNotIntegerErrorMsg)) + } + } + return allErrs +} + +// Validates that a Quantity is not negative +func ValidateNonnegativeQuantity(value resource.Quantity, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + if value.Cmp(resource.Quantity{}) < 0 { + allErrs = append(allErrs, field.Invalid(fldPath, value.String(), isNegativeErrorMsg)) + } + return allErrs +} + +// Validate compute resource typename. +// Refer to docs/design/resources.md for more details. +func validateResourceName(value string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + for _, msg := range validation.IsQualifiedName(value) { + allErrs = append(allErrs, field.Invalid(fldPath, value, msg)) + } + if len(allErrs) != 0 { + return allErrs + } + + if len(strings.Split(value, "/")) == 1 { + if !api.IsStandardResourceName(value) { + return append(allErrs, field.Invalid(fldPath, value, "must be a standard resource type or fully qualified")) + } + } + + return field.ErrorList{} +} + +func ValidatePodLogOptions(opts *v1.PodLogOptions) field.ErrorList { + allErrs := field.ErrorList{} + if opts.TailLines != nil && *opts.TailLines < 0 { + allErrs = append(allErrs, field.Invalid(field.NewPath("tailLines"), *opts.TailLines, isNegativeErrorMsg)) + } + if opts.LimitBytes != nil && *opts.LimitBytes < 1 { + allErrs = append(allErrs, field.Invalid(field.NewPath("limitBytes"), *opts.LimitBytes, "must be greater than 0")) + } + switch { + case opts.SinceSeconds != nil && opts.SinceTime != nil: + allErrs = append(allErrs, field.Forbidden(field.NewPath(""), "at most one of `sinceTime` or `sinceSeconds` may be specified")) + case opts.SinceSeconds != nil: + if *opts.SinceSeconds < 1 { + allErrs = append(allErrs, field.Invalid(field.NewPath("sinceSeconds"), *opts.SinceSeconds, "must be greater than 0")) + } + } + return allErrs +} + +func AccumulateUniqueHostPorts(containers []v1.Container, accumulator *sets.String, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + + for ci, ctr := range containers { + idxPath := fldPath.Index(ci) + portsPath := idxPath.Child("ports") + for pi := range ctr.Ports { + idxPath := portsPath.Index(pi) + port := ctr.Ports[pi].HostPort + if port == 0 { + continue + } + str := fmt.Sprintf("%d/%s", port, ctr.Ports[pi].Protocol) + if accumulator.Has(str) { + allErrs = append(allErrs, field.Duplicate(idxPath.Child("hostPort"), str)) + } else { + accumulator.Insert(str) + } + } + } + return allErrs +} diff --git a/pkg/api/v1/zz_generated.conversion.go b/pkg/api/v1/zz_generated.conversion.go index 8dd547c58d8..85b0615e970 100644 --- a/pkg/api/v1/zz_generated.conversion.go +++ b/pkg/api/v1/zz_generated.conversion.go @@ -189,6 +189,8 @@ func RegisterConversions(scheme *runtime.Scheme) error { Convert_api_NodeList_To_v1_NodeList, Convert_v1_NodeProxyOptions_To_api_NodeProxyOptions, Convert_api_NodeProxyOptions_To_v1_NodeProxyOptions, + Convert_v1_NodeResources_To_api_NodeResources, + Convert_api_NodeResources_To_v1_NodeResources, Convert_v1_NodeSelector_To_api_NodeSelector, Convert_api_NodeSelector_To_v1_NodeSelector, Convert_v1_NodeSelectorRequirement_To_api_NodeSelectorRequirement, @@ -333,6 +335,8 @@ func RegisterConversions(scheme *runtime.Scheme) error { Convert_api_ServiceSpec_To_v1_ServiceSpec, Convert_v1_ServiceStatus_To_api_ServiceStatus, Convert_api_ServiceStatus_To_v1_ServiceStatus, + Convert_v1_Sysctl_To_api_Sysctl, + Convert_api_Sysctl_To_v1_Sysctl, Convert_v1_TCPSocketAction_To_api_TCPSocketAction, Convert_api_TCPSocketAction_To_v1_TCPSocketAction, Convert_v1_Taint_To_api_Taint, @@ -2152,6 +2156,24 @@ func Convert_api_NodeProxyOptions_To_v1_NodeProxyOptions(in *api.NodeProxyOption return autoConvert_api_NodeProxyOptions_To_v1_NodeProxyOptions(in, out, s) } +func autoConvert_v1_NodeResources_To_api_NodeResources(in *NodeResources, out *api.NodeResources, s conversion.Scope) error { + out.Capacity = *(*api.ResourceList)(unsafe.Pointer(&in.Capacity)) + return nil +} + +func Convert_v1_NodeResources_To_api_NodeResources(in *NodeResources, out *api.NodeResources, s conversion.Scope) error { + return autoConvert_v1_NodeResources_To_api_NodeResources(in, out, s) +} + +func autoConvert_api_NodeResources_To_v1_NodeResources(in *api.NodeResources, out *NodeResources, s conversion.Scope) error { + out.Capacity = *(*ResourceList)(unsafe.Pointer(&in.Capacity)) + return nil +} + +func Convert_api_NodeResources_To_v1_NodeResources(in *api.NodeResources, out *NodeResources, s conversion.Scope) error { + return autoConvert_api_NodeResources_To_v1_NodeResources(in, out, s) +} + func autoConvert_v1_NodeSelector_To_api_NodeSelector(in *NodeSelector, out *api.NodeSelector, s conversion.Scope) error { out.NodeSelectorTerms = *(*[]api.NodeSelectorTerm)(unsafe.Pointer(&in.NodeSelectorTerms)) return nil @@ -4155,6 +4177,26 @@ func Convert_api_ServiceStatus_To_v1_ServiceStatus(in *api.ServiceStatus, out *S return autoConvert_api_ServiceStatus_To_v1_ServiceStatus(in, out, s) } +func autoConvert_v1_Sysctl_To_api_Sysctl(in *Sysctl, out *api.Sysctl, s conversion.Scope) error { + out.Name = in.Name + out.Value = in.Value + return nil +} + +func Convert_v1_Sysctl_To_api_Sysctl(in *Sysctl, out *api.Sysctl, s conversion.Scope) error { + return autoConvert_v1_Sysctl_To_api_Sysctl(in, out, s) +} + +func autoConvert_api_Sysctl_To_v1_Sysctl(in *api.Sysctl, out *Sysctl, s conversion.Scope) error { + out.Name = in.Name + out.Value = in.Value + return nil +} + +func Convert_api_Sysctl_To_v1_Sysctl(in *api.Sysctl, out *Sysctl, s conversion.Scope) error { + return autoConvert_api_Sysctl_To_v1_Sysctl(in, out, s) +} + func autoConvert_v1_TCPSocketAction_To_api_TCPSocketAction(in *TCPSocketAction, out *api.TCPSocketAction, s conversion.Scope) error { out.Port = in.Port return nil diff --git a/pkg/api/v1/zz_generated.deepcopy.go b/pkg/api/v1/zz_generated.deepcopy.go index 29db7732606..e72949bc304 100644 --- a/pkg/api/v1/zz_generated.deepcopy.go +++ b/pkg/api/v1/zz_generated.deepcopy.go @@ -112,6 +112,7 @@ func RegisterDeepCopies(scheme *runtime.Scheme) error { conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeDaemonEndpoints, InType: reflect.TypeOf(&NodeDaemonEndpoints{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeList, InType: reflect.TypeOf(&NodeList{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeProxyOptions, InType: reflect.TypeOf(&NodeProxyOptions{})}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeResources, InType: reflect.TypeOf(&NodeResources{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeSelector, InType: reflect.TypeOf(&NodeSelector{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeSelectorRequirement, InType: reflect.TypeOf(&NodeSelectorRequirement{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeSelectorTerm, InType: reflect.TypeOf(&NodeSelectorTerm{})}, @@ -184,6 +185,7 @@ func RegisterDeepCopies(scheme *runtime.Scheme) error { conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ServiceProxyOptions, InType: reflect.TypeOf(&ServiceProxyOptions{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ServiceSpec, InType: reflect.TypeOf(&ServiceSpec{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ServiceStatus, InType: reflect.TypeOf(&ServiceStatus{})}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Sysctl, InType: reflect.TypeOf(&Sysctl{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_TCPSocketAction, InType: reflect.TypeOf(&TCPSocketAction{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Taint, InType: reflect.TypeOf(&Taint{})}, conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Toleration, InType: reflect.TypeOf(&Toleration{})}, @@ -1689,6 +1691,23 @@ func DeepCopy_v1_NodeProxyOptions(in interface{}, out interface{}, c *conversion } } +func DeepCopy_v1_NodeResources(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeResources) + out := out.(*NodeResources) + if in.Capacity != nil { + in, out := &in.Capacity, &out.Capacity + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Capacity = nil + } + return nil + } +} + func DeepCopy_v1_NodeSelector(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*NodeSelector) @@ -3494,6 +3513,16 @@ func DeepCopy_v1_ServiceStatus(in interface{}, out interface{}, c *conversion.Cl } } +func DeepCopy_v1_Sysctl(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Sysctl) + out := out.(*Sysctl) + out.Name = in.Name + out.Value = in.Value + return nil + } +} + func DeepCopy_v1_TCPSocketAction(in interface{}, out interface{}, c *conversion.Cloner) error { { in := in.(*TCPSocketAction) diff --git a/pkg/apis/rbac/v1alpha1/BUILD b/pkg/apis/rbac/v1alpha1/BUILD index b13e99eb379..a6001d43e4a 100644 --- a/pkg/apis/rbac/v1alpha1/BUILD +++ b/pkg/apis/rbac/v1alpha1/BUILD @@ -16,6 +16,7 @@ go_library( "defaults.go", "doc.go", "generated.pb.go", + "helpers.go", "register.go", "types.generated.go", "types.go", diff --git a/pkg/apis/rbac/v1alpha1/generated.pb.go b/pkg/apis/rbac/v1alpha1/generated.pb.go index 8c2ab6c6f8b..e8138819fb8 100644 --- a/pkg/apis/rbac/v1alpha1/generated.pb.go +++ b/pkg/apis/rbac/v1alpha1/generated.pb.go @@ -27,9 +27,11 @@ limitations under the License. It has these top-level messages: ClusterRole ClusterRoleBinding + ClusterRoleBindingBuilder ClusterRoleBindingList ClusterRoleList PolicyRule + PolicyRuleBuilder Role RoleBinding RoleBindingList @@ -65,48 +67,60 @@ func (m *ClusterRoleBinding) Reset() { *m = ClusterRoleBindin func (*ClusterRoleBinding) ProtoMessage() {} func (*ClusterRoleBinding) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{1} } +func (m *ClusterRoleBindingBuilder) Reset() { *m = ClusterRoleBindingBuilder{} } +func (*ClusterRoleBindingBuilder) ProtoMessage() {} +func (*ClusterRoleBindingBuilder) Descriptor() ([]byte, []int) { + return fileDescriptorGenerated, []int{2} +} + func (m *ClusterRoleBindingList) Reset() { *m = ClusterRoleBindingList{} } func (*ClusterRoleBindingList) ProtoMessage() {} -func (*ClusterRoleBindingList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{2} } +func (*ClusterRoleBindingList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{3} } func (m *ClusterRoleList) Reset() { *m = ClusterRoleList{} } func (*ClusterRoleList) ProtoMessage() {} -func (*ClusterRoleList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{3} } +func (*ClusterRoleList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{4} } func (m *PolicyRule) Reset() { *m = PolicyRule{} } func (*PolicyRule) ProtoMessage() {} -func (*PolicyRule) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{4} } +func (*PolicyRule) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{5} } + +func (m *PolicyRuleBuilder) Reset() { *m = PolicyRuleBuilder{} } +func (*PolicyRuleBuilder) ProtoMessage() {} +func (*PolicyRuleBuilder) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{6} } func (m *Role) Reset() { *m = Role{} } func (*Role) ProtoMessage() {} -func (*Role) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{5} } +func (*Role) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{7} } func (m *RoleBinding) Reset() { *m = RoleBinding{} } func (*RoleBinding) ProtoMessage() {} -func (*RoleBinding) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{6} } +func (*RoleBinding) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{8} } func (m *RoleBindingList) Reset() { *m = RoleBindingList{} } func (*RoleBindingList) ProtoMessage() {} -func (*RoleBindingList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{7} } +func (*RoleBindingList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{9} } func (m *RoleList) Reset() { *m = RoleList{} } func (*RoleList) ProtoMessage() {} -func (*RoleList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{8} } +func (*RoleList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{10} } func (m *RoleRef) Reset() { *m = RoleRef{} } func (*RoleRef) ProtoMessage() {} -func (*RoleRef) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{9} } +func (*RoleRef) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{11} } func (m *Subject) Reset() { *m = Subject{} } func (*Subject) ProtoMessage() {} -func (*Subject) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{10} } +func (*Subject) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{12} } func init() { proto.RegisterType((*ClusterRole)(nil), "k8s.io.kubernetes.pkg.apis.rbac.v1alpha1.ClusterRole") proto.RegisterType((*ClusterRoleBinding)(nil), "k8s.io.kubernetes.pkg.apis.rbac.v1alpha1.ClusterRoleBinding") + proto.RegisterType((*ClusterRoleBindingBuilder)(nil), "k8s.io.kubernetes.pkg.apis.rbac.v1alpha1.ClusterRoleBindingBuilder") proto.RegisterType((*ClusterRoleBindingList)(nil), "k8s.io.kubernetes.pkg.apis.rbac.v1alpha1.ClusterRoleBindingList") proto.RegisterType((*ClusterRoleList)(nil), "k8s.io.kubernetes.pkg.apis.rbac.v1alpha1.ClusterRoleList") proto.RegisterType((*PolicyRule)(nil), "k8s.io.kubernetes.pkg.apis.rbac.v1alpha1.PolicyRule") + proto.RegisterType((*PolicyRuleBuilder)(nil), "k8s.io.kubernetes.pkg.apis.rbac.v1alpha1.PolicyRuleBuilder") proto.RegisterType((*Role)(nil), "k8s.io.kubernetes.pkg.apis.rbac.v1alpha1.Role") proto.RegisterType((*RoleBinding)(nil), "k8s.io.kubernetes.pkg.apis.rbac.v1alpha1.RoleBinding") proto.RegisterType((*RoleBindingList)(nil), "k8s.io.kubernetes.pkg.apis.rbac.v1alpha1.RoleBindingList") @@ -198,6 +212,32 @@ func (m *ClusterRoleBinding) MarshalTo(data []byte) (int, error) { return i, nil } +func (m *ClusterRoleBindingBuilder) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *ClusterRoleBindingBuilder) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(m.ClusterRoleBinding.Size())) + n4, err := m.ClusterRoleBinding.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n4 + return i, nil +} + func (m *ClusterRoleBindingList) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) @@ -216,11 +256,11 @@ func (m *ClusterRoleBindingList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n4, err := m.ListMeta.MarshalTo(data[i:]) + n5, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n4 + i += n5 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -254,11 +294,11 @@ func (m *ClusterRoleList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n5, err := m.ListMeta.MarshalTo(data[i:]) + n6, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n5 + i += n6 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -307,11 +347,11 @@ func (m *PolicyRule) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.AttributeRestrictions.Size())) - n6, err := m.AttributeRestrictions.MarshalTo(data[i:]) + n7, err := m.AttributeRestrictions.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n6 + i += n7 if len(m.APIGroups) > 0 { for _, s := range m.APIGroups { data[i] = 0x1a @@ -375,6 +415,32 @@ func (m *PolicyRule) MarshalTo(data []byte) (int, error) { return i, nil } +func (m *PolicyRuleBuilder) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *PolicyRuleBuilder) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(m.PolicyRule.Size())) + n8, err := m.PolicyRule.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n8 + return i, nil +} + func (m *Role) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) @@ -393,11 +459,11 @@ func (m *Role) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n7, err := m.ObjectMeta.MarshalTo(data[i:]) + n9, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n7 + i += n9 if len(m.Rules) > 0 { for _, msg := range m.Rules { data[i] = 0x12 @@ -431,11 +497,11 @@ func (m *RoleBinding) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n8, err := m.ObjectMeta.MarshalTo(data[i:]) + n10, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n8 + i += n10 if len(m.Subjects) > 0 { for _, msg := range m.Subjects { data[i] = 0x12 @@ -451,11 +517,11 @@ func (m *RoleBinding) MarshalTo(data []byte) (int, error) { data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.RoleRef.Size())) - n9, err := m.RoleRef.MarshalTo(data[i:]) + n11, err := m.RoleRef.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n9 + i += n11 return i, nil } @@ -477,11 +543,11 @@ func (m *RoleBindingList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n10, err := m.ListMeta.MarshalTo(data[i:]) + n12, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n10 + i += n12 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -515,11 +581,11 @@ func (m *RoleList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n11, err := m.ListMeta.MarshalTo(data[i:]) + n13, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n11 + i += n13 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -656,6 +722,14 @@ func (m *ClusterRoleBinding) Size() (n int) { return n } +func (m *ClusterRoleBindingBuilder) Size() (n int) { + var l int + _ = l + l = m.ClusterRoleBinding.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + func (m *ClusterRoleBindingList) Size() (n int) { var l int _ = l @@ -722,6 +796,14 @@ func (m *PolicyRule) Size() (n int) { return n } +func (m *PolicyRuleBuilder) Size() (n int) { + var l int + _ = l + l = m.PolicyRule.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + func (m *Role) Size() (n int) { var l int _ = l @@ -842,6 +924,16 @@ func (this *ClusterRoleBinding) String() string { }, "") return s } +func (this *ClusterRoleBindingBuilder) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ClusterRoleBindingBuilder{`, + `ClusterRoleBinding:` + strings.Replace(strings.Replace(this.ClusterRoleBinding.String(), "ClusterRoleBinding", "ClusterRoleBinding", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} func (this *ClusterRoleBindingList) String() string { if this == nil { return "nil" @@ -879,6 +971,16 @@ func (this *PolicyRule) String() string { }, "") return s } +func (this *PolicyRuleBuilder) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PolicyRuleBuilder{`, + `PolicyRule:` + strings.Replace(strings.Replace(this.PolicyRule.String(), "PolicyRule", "PolicyRule", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} func (this *Role) String() string { if this == nil { return "nil" @@ -1209,6 +1311,86 @@ func (m *ClusterRoleBinding) Unmarshal(data []byte) error { } return nil } +func (m *ClusterRoleBindingBuilder) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ClusterRoleBindingBuilder: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ClusterRoleBindingBuilder: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ClusterRoleBinding", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ClusterRoleBinding.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *ClusterRoleBindingList) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 @@ -1656,6 +1838,86 @@ func (m *PolicyRule) Unmarshal(data []byte) error { } return nil } +func (m *PolicyRuleBuilder) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PolicyRuleBuilder: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PolicyRuleBuilder: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PolicyRule", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PolicyRule.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *Role) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 @@ -2539,56 +2801,60 @@ var ( ) var fileDescriptorGenerated = []byte{ - // 815 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xec, 0x54, 0x41, 0x6b, 0xe3, 0x46, - 0x18, 0xb5, 0x62, 0xbb, 0xb1, 0xc6, 0x35, 0x6e, 0x54, 0x52, 0x84, 0xa1, 0xb2, 0xf1, 0xc9, 0x34, - 0xc9, 0x08, 0x9b, 0x86, 0xe6, 0xd0, 0x1e, 0xa2, 0x52, 0x4a, 0x68, 0x9a, 0x86, 0x09, 0x0d, 0x6d, - 0x68, 0x29, 0x63, 0x7b, 0xe2, 0x4c, 0x2d, 0x4b, 0x62, 0x66, 0xe4, 0xb6, 0xf4, 0x12, 0xf6, 0x17, - 0xec, 0xaf, 0xd8, 0xdb, 0x5e, 0xf6, 0xba, 0xb0, 0x87, 0x3d, 0xe5, 0xb0, 0x87, 0x1c, 0x97, 0x3d, - 0x98, 0x8d, 0xf6, 0x8f, 0x2c, 0x1a, 0x49, 0x96, 0x1d, 0xdb, 0x1b, 0x27, 0xb0, 0x81, 0x85, 0x3d, - 0x25, 0xf3, 0x7d, 0xef, 0xbd, 0xf9, 0xde, 0xe7, 0xd1, 0x03, 0x3b, 0xfd, 0x1d, 0x0e, 0xa9, 0x6b, - 0xf6, 0xfd, 0x36, 0x61, 0x0e, 0x11, 0x84, 0x9b, 0x5e, 0xbf, 0x67, 0x62, 0x8f, 0x72, 0x93, 0xb5, - 0x71, 0xc7, 0x1c, 0x36, 0xb1, 0xed, 0x9d, 0xe1, 0xa6, 0xd9, 0x23, 0x0e, 0x61, 0x58, 0x90, 0x2e, - 0xf4, 0x98, 0x2b, 0x5c, 0xad, 0x11, 0x31, 0x61, 0xca, 0x84, 0x5e, 0xbf, 0x07, 0x43, 0x26, 0x0c, - 0x99, 0x30, 0x61, 0x56, 0xb6, 0x7a, 0x54, 0x9c, 0xf9, 0x6d, 0xd8, 0x71, 0x07, 0x66, 0xcf, 0xed, - 0xb9, 0xa6, 0x14, 0x68, 0xfb, 0xa7, 0xf2, 0x24, 0x0f, 0xf2, 0xbf, 0x48, 0xb8, 0xd2, 0x5a, 0x38, - 0x92, 0xc9, 0x08, 0x77, 0x7d, 0xd6, 0x21, 0xd7, 0x87, 0xa9, 0x6c, 0x2f, 0xe6, 0xf8, 0xce, 0x90, - 0x30, 0x4e, 0x5d, 0x87, 0x74, 0x67, 0x68, 0x9b, 0x8b, 0x69, 0xc3, 0x19, 0xc7, 0x95, 0xad, 0xf9, - 0x68, 0xe6, 0x3b, 0x82, 0x0e, 0x66, 0x67, 0x6a, 0xce, 0x87, 0xfb, 0x82, 0xda, 0x26, 0x75, 0x04, - 0x17, 0xec, 0x3a, 0xa5, 0xfe, 0x5c, 0x01, 0xc5, 0xef, 0x6d, 0x9f, 0x0b, 0xc2, 0x90, 0x6b, 0x13, - 0xed, 0x37, 0x50, 0x18, 0x10, 0x81, 0xbb, 0x58, 0x60, 0x5d, 0xa9, 0x29, 0x8d, 0x62, 0xab, 0x01, - 0x17, 0xae, 0x1d, 0x0e, 0x9b, 0xf0, 0x97, 0xf6, 0xdf, 0xa4, 0x23, 0x7e, 0x26, 0x02, 0x5b, 0xda, - 0xc5, 0xa8, 0x9a, 0x09, 0x46, 0x55, 0x90, 0xd6, 0xd0, 0x58, 0x4d, 0xfb, 0x1d, 0xe4, 0x99, 0x6f, - 0x13, 0xae, 0xaf, 0xd4, 0xb2, 0x8d, 0x62, 0xeb, 0x6b, 0xb8, 0xec, 0xaf, 0x09, 0x0f, 0x5d, 0x9b, - 0x76, 0xfe, 0x43, 0xbe, 0x4d, 0xac, 0x52, 0x7c, 0x45, 0x3e, 0x3c, 0x71, 0x14, 0x29, 0xd6, 0x1f, - 0xaf, 0x00, 0x6d, 0xc2, 0x84, 0x45, 0x9d, 0x2e, 0x75, 0x7a, 0xef, 0xd1, 0xcb, 0x5f, 0xa0, 0xc0, - 0x7d, 0xd9, 0x48, 0xec, 0x34, 0x97, 0xb7, 0x73, 0x14, 0x31, 0xad, 0xcf, 0xe2, 0x2b, 0x0a, 0x71, - 0x81, 0xa3, 0xb1, 0xa8, 0xf6, 0x07, 0x58, 0x65, 0xae, 0x4d, 0x10, 0x39, 0xd5, 0xb3, 0x72, 0xf2, - 0x5b, 0xe8, 0xa3, 0x88, 0x68, 0x95, 0x63, 0xfd, 0xd5, 0xb8, 0x80, 0x12, 0xc9, 0xfa, 0x2b, 0x05, - 0x7c, 0x31, 0xbb, 0xaf, 0x7d, 0xca, 0x85, 0xf6, 0xe7, 0xcc, 0xce, 0xcc, 0x77, 0xec, 0x6c, 0xe2, - 0xa5, 0xc3, 0x90, 0x2e, 0x57, 0x37, 0xf6, 0x95, 0x54, 0x26, 0x16, 0x87, 0x41, 0x9e, 0x0a, 0x32, - 0x48, 0xb6, 0xf6, 0xed, 0xf2, 0xae, 0x66, 0xe7, 0x4d, 0x1f, 0xc3, 0x5e, 0x28, 0x89, 0x22, 0xe5, - 0xfa, 0x0b, 0x05, 0x94, 0x27, 0xc0, 0xf7, 0xe1, 0xea, 0x64, 0xda, 0xd5, 0xf6, 0xdd, 0x5c, 0xcd, - 0xb7, 0xf3, 0x20, 0x0b, 0x40, 0xfa, 0x01, 0x68, 0x55, 0x90, 0x1f, 0x12, 0xd6, 0xe6, 0xba, 0x52, - 0xcb, 0x36, 0x54, 0x4b, 0x0d, 0xf1, 0xc7, 0x61, 0x01, 0x45, 0x75, 0xed, 0x5c, 0x01, 0xeb, 0x58, - 0x08, 0x46, 0xdb, 0xbe, 0x20, 0x88, 0x70, 0xc1, 0x68, 0x47, 0x50, 0xd7, 0x09, 0x87, 0x0b, 0x8d, - 0x6f, 0x2c, 0x18, 0x2e, 0xce, 0x14, 0x88, 0xf0, 0x3f, 0x3f, 0xfc, 0x2b, 0x88, 0x13, 0xfa, 0xb7, - 0xbe, 0x8c, 0x47, 0x5a, 0xdf, 0x9d, 0xa7, 0x88, 0xe6, 0x5f, 0xa4, 0x6d, 0x00, 0x15, 0x7b, 0xf4, - 0x47, 0xe6, 0xfa, 0x1e, 0xd7, 0xb3, 0x72, 0xce, 0x52, 0x30, 0xaa, 0xaa, 0xbb, 0x87, 0x7b, 0x51, - 0x11, 0xa5, 0xfd, 0x10, 0x9c, 0x64, 0x2c, 0xd7, 0x73, 0x29, 0x18, 0x25, 0x45, 0x94, 0xf6, 0xb5, - 0x6f, 0x40, 0x29, 0x39, 0x1c, 0xe0, 0x01, 0xe1, 0x7a, 0x5e, 0x12, 0xd6, 0x82, 0x51, 0xb5, 0x84, - 0x26, 0x1b, 0x68, 0x1a, 0xa7, 0x7d, 0x07, 0xca, 0x8e, 0xeb, 0x24, 0x90, 0x5f, 0xd1, 0x3e, 0xd7, - 0x3f, 0x91, 0xd4, 0xcf, 0x83, 0x51, 0xb5, 0x7c, 0x30, 0xdd, 0x42, 0xd7, 0xb1, 0xf5, 0xa7, 0x0a, - 0xc8, 0x7d, 0xb8, 0xf1, 0xf8, 0x68, 0x05, 0x14, 0x3f, 0xe6, 0xe2, 0x12, 0xb9, 0x18, 0x46, 0xc7, - 0x3d, 0x07, 0xe2, 0xdd, 0xa3, 0xe3, 0xe6, 0x24, 0x7c, 0xa6, 0x80, 0xc2, 0x7d, 0x45, 0xe0, 0xd1, - 0xb4, 0x0f, 0x78, 0x4b, 0x1f, 0xf3, 0x0d, 0xfc, 0x0f, 0x92, 0xdf, 0x48, 0xdb, 0x04, 0x85, 0x24, - 0x33, 0xe4, 0xf8, 0x6a, 0x3a, 0x4d, 0x12, 0x2b, 0x68, 0x8c, 0xd0, 0x6a, 0x20, 0xd7, 0xa7, 0x4e, - 0x57, 0x46, 0x9e, 0x6a, 0x7d, 0x1a, 0x23, 0x73, 0x3f, 0x51, 0xa7, 0x8b, 0x64, 0x27, 0x44, 0x38, - 0x78, 0x40, 0xe4, 0x2b, 0x9a, 0x40, 0x84, 0x69, 0x81, 0x64, 0xa7, 0xfe, 0x44, 0x01, 0xab, 0xf1, - 0x0b, 0x1c, 0xeb, 0x29, 0x0b, 0xf5, 0x5a, 0x00, 0x60, 0x8f, 0x1e, 0x47, 0x4b, 0x8b, 0xef, 0x1d, - 0x7f, 0x2b, 0xbb, 0x87, 0x7b, 0x71, 0x07, 0x4d, 0xa0, 0x6e, 0x9e, 0x41, 0x33, 0x81, 0x1a, 0xfe, - 0xe5, 0x1e, 0xee, 0x10, 0x3d, 0x27, 0x61, 0x6b, 0x31, 0x4c, 0x3d, 0x48, 0x1a, 0x28, 0xc5, 0x58, - 0x5f, 0x5d, 0x5c, 0x19, 0x99, 0xcb, 0x2b, 0x23, 0xf3, 0xf2, 0xca, 0xc8, 0x9c, 0x07, 0x86, 0x72, - 0x11, 0x18, 0xca, 0x65, 0x60, 0x28, 0xaf, 0x03, 0x43, 0x79, 0xf8, 0xc6, 0xc8, 0x9c, 0x14, 0x92, - 0xc5, 0xbf, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x62, 0x32, 0x8a, 0x1f, 0x89, 0x0b, 0x00, 0x00, + // 875 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xec, 0x55, 0xcf, 0x8b, 0x23, 0x45, + 0x14, 0x4e, 0x4d, 0x12, 0x27, 0x79, 0xe3, 0x30, 0x4e, 0xc9, 0x4a, 0x1b, 0x30, 0x19, 0x72, 0x0a, + 0xee, 0x6e, 0x37, 0x19, 0x5c, 0xdc, 0x83, 0x1e, 0xa6, 0x45, 0x64, 0x70, 0x1d, 0x87, 0x5a, 0x5c, + 0x74, 0x51, 0xa4, 0x92, 0xd4, 0x66, 0xca, 0x74, 0xba, 0x9b, 0xaa, 0xea, 0xa8, 0x88, 0xb0, 0x78, + 0xf2, 0xe8, 0x5f, 0xb1, 0x37, 0x2f, 0x5e, 0x05, 0x0f, 0x9e, 0xe6, 0xe0, 0x61, 0x8f, 0xe2, 0x21, + 0x38, 0xf1, 0x1f, 0x91, 0xae, 0xae, 0xfe, 0x31, 0x93, 0x8e, 0x9b, 0x19, 0x71, 0x40, 0xd8, 0x53, + 0xd2, 0xef, 0x7d, 0xdf, 0x57, 0xef, 0xab, 0x57, 0xf5, 0x0a, 0xee, 0x4e, 0xee, 0x4a, 0x9b, 0x07, + 0xce, 0x24, 0x1a, 0x30, 0xe1, 0x33, 0xc5, 0xa4, 0x13, 0x4e, 0xc6, 0x0e, 0x0d, 0xb9, 0x74, 0xc4, + 0x80, 0x0e, 0x9d, 0x59, 0x9f, 0x7a, 0xe1, 0x09, 0xed, 0x3b, 0x63, 0xe6, 0x33, 0x41, 0x15, 0x1b, + 0xd9, 0xa1, 0x08, 0x54, 0x80, 0x7b, 0x09, 0xd3, 0xce, 0x99, 0x76, 0x38, 0x19, 0xdb, 0x31, 0xd3, + 0x8e, 0x99, 0x76, 0xca, 0x6c, 0xdd, 0x1e, 0x73, 0x75, 0x12, 0x0d, 0xec, 0x61, 0x30, 0x75, 0xc6, + 0xc1, 0x38, 0x70, 0xb4, 0xc0, 0x20, 0x7a, 0xa4, 0xbf, 0xf4, 0x87, 0xfe, 0x97, 0x08, 0xb7, 0xf6, + 0x57, 0x96, 0xe4, 0x08, 0x26, 0x83, 0x48, 0x0c, 0xd9, 0xc5, 0x62, 0x5a, 0x77, 0x56, 0x73, 0x22, + 0x7f, 0xc6, 0x84, 0xe4, 0x81, 0xcf, 0x46, 0x4b, 0xb4, 0x5b, 0xab, 0x69, 0xb3, 0x25, 0xc7, 0xad, + 0xdb, 0xe5, 0x68, 0x11, 0xf9, 0x8a, 0x4f, 0x97, 0x6b, 0xea, 0x97, 0xc3, 0x23, 0xc5, 0x3d, 0x87, + 0xfb, 0x4a, 0x2a, 0x71, 0x91, 0xd2, 0xfd, 0x15, 0xc1, 0xd6, 0x3b, 0x5e, 0x24, 0x15, 0x13, 0x24, + 0xf0, 0x18, 0xfe, 0x18, 0x1a, 0x53, 0xa6, 0xe8, 0x88, 0x2a, 0x6a, 0xa1, 0x3d, 0xd4, 0xdb, 0xda, + 0xef, 0xd9, 0x2b, 0xb7, 0xdd, 0x9e, 0xf5, 0xed, 0x0f, 0x07, 0x5f, 0xb0, 0xa1, 0xfa, 0x80, 0x29, + 0xea, 0xe2, 0xd3, 0x79, 0xa7, 0xb2, 0x98, 0x77, 0x20, 0x8f, 0x91, 0x4c, 0x0d, 0x7f, 0x02, 0x75, + 0x11, 0x79, 0x4c, 0x5a, 0x1b, 0x7b, 0xd5, 0xde, 0xd6, 0xfe, 0x1b, 0xf6, 0xba, 0xdd, 0xb4, 0x8f, + 0x03, 0x8f, 0x0f, 0xbf, 0x26, 0x91, 0xc7, 0xdc, 0x6d, 0xb3, 0x44, 0x3d, 0xfe, 0x92, 0x24, 0x51, + 0xec, 0xfe, 0xb8, 0x01, 0xb8, 0x60, 0xc2, 0xe5, 0xfe, 0x88, 0xfb, 0xe3, 0xff, 0xd0, 0xcb, 0xe7, + 0xd0, 0x90, 0x91, 0x4e, 0xa4, 0x76, 0xfa, 0xeb, 0xdb, 0xb9, 0x9f, 0x30, 0xdd, 0x97, 0xcc, 0x12, + 0x0d, 0x13, 0x90, 0x24, 0x13, 0xc5, 0x9f, 0xc2, 0xa6, 0x08, 0x3c, 0x46, 0xd8, 0x23, 0xab, 0xaa, + 0x2b, 0xbf, 0x84, 0x3e, 0x49, 0x88, 0xee, 0x8e, 0xd1, 0xdf, 0x34, 0x01, 0x92, 0x4a, 0x76, 0x9f, + 0x20, 0x78, 0x75, 0x79, 0xbf, 0xdc, 0x88, 0x7b, 0x23, 0x26, 0xf0, 0xf7, 0x08, 0xf0, 0x70, 0x29, + 0x6b, 0x76, 0xf0, 0xad, 0xf5, 0xeb, 0x28, 0x59, 0xa1, 0x65, 0x4a, 0x2a, 0xe9, 0x16, 0x29, 0x59, + 0xb3, 0xfb, 0x07, 0x82, 0x57, 0x96, 0xa1, 0xf7, 0xb8, 0x54, 0xf8, 0xb3, 0xa5, 0xe6, 0x3a, 0xff, + 0xd0, 0xdc, 0xc2, 0x95, 0xb4, 0x63, 0xba, 0xee, 0x71, 0xd6, 0x80, 0x34, 0x52, 0xe8, 0x30, 0x85, + 0x3a, 0x57, 0x6c, 0x9a, 0xb6, 0xf7, 0xdf, 0xd9, 0xce, 0x4e, 0xed, 0x61, 0x2c, 0x49, 0x12, 0xe5, + 0xee, 0x6f, 0x08, 0x76, 0x0a, 0xe0, 0xeb, 0x70, 0xf5, 0xf0, 0xbc, 0xab, 0x3b, 0x57, 0x73, 0x55, + 0x6e, 0xe7, 0xbb, 0x2a, 0x40, 0x7e, 0x53, 0x71, 0x07, 0xea, 0x33, 0x26, 0x06, 0xd2, 0x42, 0x7b, + 0xd5, 0x5e, 0xd3, 0x6d, 0xc6, 0xf8, 0x07, 0x71, 0x80, 0x24, 0x71, 0xfc, 0x18, 0xc1, 0x0d, 0xaa, + 0x94, 0xe0, 0x83, 0x48, 0x31, 0xc2, 0xa4, 0x12, 0x7c, 0xa8, 0x78, 0xe0, 0xc7, 0xc5, 0xc5, 0xc6, + 0x6f, 0xae, 0x28, 0xce, 0x0c, 0x3f, 0x9b, 0xd0, 0x2f, 0xdf, 0xfd, 0x4a, 0x31, 0x3f, 0xf6, 0xef, + 0xbe, 0x66, 0x4a, 0xba, 0x71, 0x50, 0xa6, 0x48, 0xca, 0x17, 0xc2, 0x37, 0xa1, 0x49, 0x43, 0xfe, + 0x9e, 0x08, 0xa2, 0x50, 0x5a, 0x55, 0x5d, 0xe7, 0xf6, 0x62, 0xde, 0x69, 0x1e, 0x1c, 0x1f, 0x26, + 0x41, 0x92, 0xe7, 0x63, 0x70, 0xfa, 0x18, 0x48, 0xab, 0x96, 0x83, 0x49, 0x1a, 0x24, 0x79, 0x1e, + 0xbf, 0x09, 0xdb, 0xe9, 0xc7, 0x11, 0x9d, 0x32, 0x69, 0xd5, 0x35, 0x61, 0x77, 0x31, 0xef, 0x6c, + 0x93, 0x62, 0x82, 0x9c, 0xc7, 0xe1, 0xb7, 0x61, 0xc7, 0x0f, 0xfc, 0x14, 0xf2, 0x11, 0xb9, 0x27, + 0xad, 0x17, 0x34, 0xf5, 0xe5, 0xc5, 0xbc, 0xb3, 0x73, 0x74, 0x3e, 0x45, 0x2e, 0x62, 0xbb, 0xdf, + 0xc2, 0x6e, 0x61, 0x5a, 0x9a, 0x0b, 0x7d, 0x02, 0x10, 0x66, 0x41, 0x73, 0xac, 0xae, 0x36, 0x7e, + 0xb3, 0xa9, 0x98, 0xc7, 0x48, 0x41, 0xbb, 0xfb, 0x33, 0x82, 0xda, 0xff, 0xf7, 0x19, 0x79, 0xb2, + 0x01, 0x5b, 0xcf, 0xdf, 0x8f, 0x35, 0xde, 0x8f, 0x78, 0x72, 0x5d, 0xf3, 0x3c, 0xbe, 0xfa, 0xe4, + 0x7a, 0xf6, 0x20, 0xfe, 0x05, 0x41, 0xe3, 0xba, 0x26, 0xf0, 0xfd, 0xf3, 0x3e, 0xec, 0x4b, 0xfa, + 0x28, 0x37, 0xf0, 0x0d, 0xa4, 0x3d, 0xc2, 0xb7, 0xa0, 0x91, 0x8e, 0x2c, 0x5d, 0x7e, 0x33, 0xaf, + 0x26, 0x9d, 0x6a, 0x24, 0x43, 0xe0, 0x3d, 0xa8, 0x4d, 0xb8, 0x3f, 0xd2, 0x13, 0xb7, 0xe9, 0xbe, + 0x68, 0x90, 0xb5, 0xf7, 0xb9, 0x3f, 0x22, 0x3a, 0x13, 0x23, 0x7c, 0x3a, 0x65, 0xfa, 0x14, 0x15, + 0x10, 0xf1, 0xb0, 0x22, 0x3a, 0xd3, 0xfd, 0x09, 0xc1, 0xa6, 0x39, 0x81, 0x99, 0x1e, 0x5a, 0xa9, + 0xb7, 0x0f, 0x40, 0x43, 0xfe, 0x20, 0xd9, 0x34, 0xb3, 0x6e, 0x76, 0x57, 0x0e, 0x8e, 0x0f, 0x4d, + 0x86, 0x14, 0x50, 0xcf, 0xae, 0x01, 0x3b, 0xd0, 0x8c, 0x7f, 0x65, 0x48, 0x87, 0xcc, 0xaa, 0x69, + 0xd8, 0xae, 0x81, 0x35, 0x8f, 0xd2, 0x04, 0xc9, 0x31, 0xee, 0xeb, 0xa7, 0x67, 0xed, 0xca, 0xd3, + 0xb3, 0x76, 0xe5, 0xf7, 0xb3, 0x76, 0xe5, 0xf1, 0xa2, 0x8d, 0x4e, 0x17, 0x6d, 0xf4, 0x74, 0xd1, + 0x46, 0x7f, 0x2e, 0xda, 0xe8, 0x87, 0xbf, 0xda, 0x95, 0x87, 0x8d, 0x74, 0xe3, 0xff, 0x0e, 0x00, + 0x00, 0xff, 0xff, 0x90, 0x88, 0x4e, 0x35, 0xb1, 0x0c, 0x00, 0x00, } diff --git a/pkg/apis/rbac/v1alpha1/generated.proto b/pkg/apis/rbac/v1alpha1/generated.proto index 09f11e33b06..7ff93edcfa9 100644 --- a/pkg/apis/rbac/v1alpha1/generated.proto +++ b/pkg/apis/rbac/v1alpha1/generated.proto @@ -55,6 +55,14 @@ message ClusterRoleBinding { optional RoleRef roleRef = 3; } +// +k8s:deepcopy-gen=false +// ClusterRoleBindingBuilder let's us attach methods. A no-no for API types. +// We use it to construct bindings in code. It's more compact than trying to write them +// out in a literal. +message ClusterRoleBindingBuilder { + optional ClusterRoleBinding clusterRoleBinding = 1; +} + // ClusterRoleBindingList is a collection of ClusterRoleBindings message ClusterRoleBindingList { // Standard object's metadata. @@ -107,6 +115,14 @@ message PolicyRule { repeated string nonResourceURLs = 6; } +// +k8s:deepcopy-gen=false +// PolicyRuleBuilder let's us attach methods. A no-no for API types. +// We use it to construct rules in code. It's more compact than trying to write them +// out in a literal and allows us to perform some basic checking during construction +message PolicyRuleBuilder { + optional PolicyRule policyRule = 1; +} + // Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. message Role { // Standard object's metadata. diff --git a/pkg/apis/rbac/v1alpha1/helpers.go b/pkg/apis/rbac/v1alpha1/helpers.go new file mode 100644 index 00000000000..f424e57b040 --- /dev/null +++ b/pkg/apis/rbac/v1alpha1/helpers.go @@ -0,0 +1,148 @@ +/* +Copyright 2016 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "fmt" + + "k8s.io/kubernetes/pkg/api/v1" +) + +// +k8s:deepcopy-gen=false +// PolicyRuleBuilder let's us attach methods. A no-no for API types. +// We use it to construct rules in code. It's more compact than trying to write them +// out in a literal and allows us to perform some basic checking during construction +type PolicyRuleBuilder struct { + PolicyRule PolicyRule +} + +func NewRule(verbs ...string) *PolicyRuleBuilder { + return &PolicyRuleBuilder{ + PolicyRule: PolicyRule{Verbs: verbs}, + } +} + +func (r *PolicyRuleBuilder) Groups(groups ...string) *PolicyRuleBuilder { + r.PolicyRule.APIGroups = append(r.PolicyRule.APIGroups, groups...) + return r +} + +func (r *PolicyRuleBuilder) Resources(resources ...string) *PolicyRuleBuilder { + r.PolicyRule.Resources = append(r.PolicyRule.Resources, resources...) + return r +} + +func (r *PolicyRuleBuilder) Names(names ...string) *PolicyRuleBuilder { + r.PolicyRule.ResourceNames = append(r.PolicyRule.ResourceNames, names...) + return r +} + +func (r *PolicyRuleBuilder) URLs(urls ...string) *PolicyRuleBuilder { + r.PolicyRule.NonResourceURLs = append(r.PolicyRule.NonResourceURLs, urls...) + return r +} + +func (r *PolicyRuleBuilder) RuleOrDie() PolicyRule { + ret, err := r.Rule() + if err != nil { + panic(err) + } + return ret +} + +func (r *PolicyRuleBuilder) Rule() (PolicyRule, error) { + if len(r.PolicyRule.Verbs) == 0 { + return PolicyRule{}, fmt.Errorf("verbs are required: %#v", r.PolicyRule) + } + + switch { + case len(r.PolicyRule.NonResourceURLs) > 0: + if len(r.PolicyRule.APIGroups) != 0 || len(r.PolicyRule.Resources) != 0 || len(r.PolicyRule.ResourceNames) != 0 { + return PolicyRule{}, fmt.Errorf("non-resource rule may not have apiGroups, resources, or resourceNames: %#v", r.PolicyRule) + } + case len(r.PolicyRule.Resources) > 0: + if len(r.PolicyRule.NonResourceURLs) != 0 { + return PolicyRule{}, fmt.Errorf("resource rule may not have nonResourceURLs: %#v", r.PolicyRule) + } + if len(r.PolicyRule.APIGroups) == 0 { + // this a common bug + return PolicyRule{}, fmt.Errorf("resource rule must have apiGroups: %#v", r.PolicyRule) + } + default: + return PolicyRule{}, fmt.Errorf("a rule must have either nonResourceURLs or resources: %#v", r.PolicyRule) + } + + return r.PolicyRule, nil +} + +// +k8s:deepcopy-gen=false +// ClusterRoleBindingBuilder let's us attach methods. A no-no for API types. +// We use it to construct bindings in code. It's more compact than trying to write them +// out in a literal. +type ClusterRoleBindingBuilder struct { + ClusterRoleBinding ClusterRoleBinding +} + +func NewClusterBinding(clusterRoleName string) *ClusterRoleBindingBuilder { + return &ClusterRoleBindingBuilder{ + ClusterRoleBinding: ClusterRoleBinding{ + ObjectMeta: v1.ObjectMeta{Name: clusterRoleName}, + RoleRef: RoleRef{ + APIGroup: GroupName, + Kind: "ClusterRole", + Name: clusterRoleName, + }, + }, + } +} + +func (r *ClusterRoleBindingBuilder) Groups(groups ...string) *ClusterRoleBindingBuilder { + for _, group := range groups { + r.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, Subject{Kind: GroupKind, Name: group}) + } + return r +} + +func (r *ClusterRoleBindingBuilder) Users(users ...string) *ClusterRoleBindingBuilder { + for _, user := range users { + r.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, Subject{Kind: UserKind, Name: user}) + } + return r +} + +func (r *ClusterRoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *ClusterRoleBindingBuilder { + for _, saName := range serviceAccountNames { + r.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, Subject{Kind: ServiceAccountKind, Namespace: namespace, Name: saName}) + } + return r +} + +func (r *ClusterRoleBindingBuilder) BindingOrDie() ClusterRoleBinding { + ret, err := r.Binding() + if err != nil { + panic(err) + } + return ret +} + +func (r *ClusterRoleBindingBuilder) Binding() (ClusterRoleBinding, error) { + if len(r.ClusterRoleBinding.Subjects) == 0 { + return ClusterRoleBinding{}, fmt.Errorf("subjects are required: %#v", r.ClusterRoleBinding) + } + + return r.ClusterRoleBinding, nil +} diff --git a/pkg/apis/rbac/v1alpha1/types.go b/pkg/apis/rbac/v1alpha1/types.go index 42617aca61f..9b336bb533d 100644 --- a/pkg/apis/rbac/v1alpha1/types.go +++ b/pkg/apis/rbac/v1alpha1/types.go @@ -27,6 +27,24 @@ import ( // 2. evaluation of RoleBindings in the namespace requested - short circuit on match // 3. deny by default +const ( + APIGroupAll = "*" + ResourceAll = "*" + VerbAll = "*" + NonResourceAll = "*" + + GroupKind = "Group" + ServiceAccountKind = "ServiceAccount" + UserKind = "User" + + UserAll = "*" +) + +// Authorization is calculated against +// 1. evaluation of ClusterRoleBindings - short circuit on match +// 2. evaluation of RoleBindings in the namespace requested - short circuit on match +// 3. deny by default + // PolicyRule holds information that describes a policy rule, but does not contain information // about who the rule applies to or which namespace the rule applies to. type PolicyRule struct { diff --git a/pkg/apis/rbac/v1alpha1/zz_generated.conversion.go b/pkg/apis/rbac/v1alpha1/zz_generated.conversion.go index 21c79541f40..a6397b29b75 100644 --- a/pkg/apis/rbac/v1alpha1/zz_generated.conversion.go +++ b/pkg/apis/rbac/v1alpha1/zz_generated.conversion.go @@ -39,12 +39,16 @@ func RegisterConversions(scheme *runtime.Scheme) error { Convert_rbac_ClusterRole_To_v1alpha1_ClusterRole, Convert_v1alpha1_ClusterRoleBinding_To_rbac_ClusterRoleBinding, Convert_rbac_ClusterRoleBinding_To_v1alpha1_ClusterRoleBinding, + Convert_v1alpha1_ClusterRoleBindingBuilder_To_rbac_ClusterRoleBindingBuilder, + Convert_rbac_ClusterRoleBindingBuilder_To_v1alpha1_ClusterRoleBindingBuilder, Convert_v1alpha1_ClusterRoleBindingList_To_rbac_ClusterRoleBindingList, Convert_rbac_ClusterRoleBindingList_To_v1alpha1_ClusterRoleBindingList, Convert_v1alpha1_ClusterRoleList_To_rbac_ClusterRoleList, Convert_rbac_ClusterRoleList_To_v1alpha1_ClusterRoleList, Convert_v1alpha1_PolicyRule_To_rbac_PolicyRule, Convert_rbac_PolicyRule_To_v1alpha1_PolicyRule, + Convert_v1alpha1_PolicyRuleBuilder_To_rbac_PolicyRuleBuilder, + Convert_rbac_PolicyRuleBuilder_To_v1alpha1_PolicyRuleBuilder, Convert_v1alpha1_Role_To_rbac_Role, Convert_rbac_Role_To_v1alpha1_Role, Convert_v1alpha1_RoleBinding_To_rbac_RoleBinding, @@ -138,6 +142,28 @@ func Convert_rbac_ClusterRoleBinding_To_v1alpha1_ClusterRoleBinding(in *rbac.Clu return autoConvert_rbac_ClusterRoleBinding_To_v1alpha1_ClusterRoleBinding(in, out, s) } +func autoConvert_v1alpha1_ClusterRoleBindingBuilder_To_rbac_ClusterRoleBindingBuilder(in *ClusterRoleBindingBuilder, out *rbac.ClusterRoleBindingBuilder, s conversion.Scope) error { + if err := Convert_v1alpha1_ClusterRoleBinding_To_rbac_ClusterRoleBinding(&in.ClusterRoleBinding, &out.ClusterRoleBinding, s); err != nil { + return err + } + return nil +} + +func Convert_v1alpha1_ClusterRoleBindingBuilder_To_rbac_ClusterRoleBindingBuilder(in *ClusterRoleBindingBuilder, out *rbac.ClusterRoleBindingBuilder, s conversion.Scope) error { + return autoConvert_v1alpha1_ClusterRoleBindingBuilder_To_rbac_ClusterRoleBindingBuilder(in, out, s) +} + +func autoConvert_rbac_ClusterRoleBindingBuilder_To_v1alpha1_ClusterRoleBindingBuilder(in *rbac.ClusterRoleBindingBuilder, out *ClusterRoleBindingBuilder, s conversion.Scope) error { + if err := Convert_rbac_ClusterRoleBinding_To_v1alpha1_ClusterRoleBinding(&in.ClusterRoleBinding, &out.ClusterRoleBinding, s); err != nil { + return err + } + return nil +} + +func Convert_rbac_ClusterRoleBindingBuilder_To_v1alpha1_ClusterRoleBindingBuilder(in *rbac.ClusterRoleBindingBuilder, out *ClusterRoleBindingBuilder, s conversion.Scope) error { + return autoConvert_rbac_ClusterRoleBindingBuilder_To_v1alpha1_ClusterRoleBindingBuilder(in, out, s) +} + func autoConvert_v1alpha1_ClusterRoleBindingList_To_rbac_ClusterRoleBindingList(in *ClusterRoleBindingList, out *rbac.ClusterRoleBindingList, s conversion.Scope) error { out.ListMeta = in.ListMeta out.Items = *(*[]rbac.ClusterRoleBinding)(unsafe.Pointer(&in.Items)) @@ -230,6 +256,28 @@ func Convert_rbac_PolicyRule_To_v1alpha1_PolicyRule(in *rbac.PolicyRule, out *Po return autoConvert_rbac_PolicyRule_To_v1alpha1_PolicyRule(in, out, s) } +func autoConvert_v1alpha1_PolicyRuleBuilder_To_rbac_PolicyRuleBuilder(in *PolicyRuleBuilder, out *rbac.PolicyRuleBuilder, s conversion.Scope) error { + if err := Convert_v1alpha1_PolicyRule_To_rbac_PolicyRule(&in.PolicyRule, &out.PolicyRule, s); err != nil { + return err + } + return nil +} + +func Convert_v1alpha1_PolicyRuleBuilder_To_rbac_PolicyRuleBuilder(in *PolicyRuleBuilder, out *rbac.PolicyRuleBuilder, s conversion.Scope) error { + return autoConvert_v1alpha1_PolicyRuleBuilder_To_rbac_PolicyRuleBuilder(in, out, s) +} + +func autoConvert_rbac_PolicyRuleBuilder_To_v1alpha1_PolicyRuleBuilder(in *rbac.PolicyRuleBuilder, out *PolicyRuleBuilder, s conversion.Scope) error { + if err := Convert_rbac_PolicyRule_To_v1alpha1_PolicyRule(&in.PolicyRule, &out.PolicyRule, s); err != nil { + return err + } + return nil +} + +func Convert_rbac_PolicyRuleBuilder_To_v1alpha1_PolicyRuleBuilder(in *rbac.PolicyRuleBuilder, out *PolicyRuleBuilder, s conversion.Scope) error { + return autoConvert_rbac_PolicyRuleBuilder_To_v1alpha1_PolicyRuleBuilder(in, out, s) +} + func autoConvert_v1alpha1_Role_To_rbac_Role(in *Role, out *rbac.Role, s conversion.Scope) error { // TODO: Inefficient conversion - can we improve it? if err := s.Convert(&in.ObjectMeta, &out.ObjectMeta, 0); err != nil { diff --git a/pkg/apis/storage/v1beta1/util/BUILD b/pkg/apis/storage/v1beta1/util/BUILD new file mode 100644 index 00000000000..3d13988c2f9 --- /dev/null +++ b/pkg/apis/storage/v1beta1/util/BUILD @@ -0,0 +1,18 @@ +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +load( + "@io_bazel_rules_go//go:def.bzl", + "go_binary", + "go_library", + "go_test", + "cgo_library", +) + +go_library( + name = "go_default_library", + srcs = ["helpers.go"], + tags = ["automanaged"], + deps = ["//pkg/api/v1:go_default_library"], +) diff --git a/pkg/apis/storage/v1beta1/util/helpers.go b/pkg/apis/storage/v1beta1/util/helpers.go new file mode 100644 index 00000000000..3aa0aafc678 --- /dev/null +++ b/pkg/apis/storage/v1beta1/util/helpers.go @@ -0,0 +1,134 @@ +/* +Copyright 2016 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package util + +import "k8s.io/kubernetes/pkg/api/v1" + +// IsDefaultStorageClassAnnotation represents a StorageClass annotation that +// marks a class as the default StorageClass +//TODO: Update IsDefaultStorageClassannotation and remove Beta when no longer used +const IsDefaultStorageClassAnnotation = "storageclass.beta.kubernetes.io/is-default-class" +const BetaIsDefaultStorageClassAnnotation = "storageclass.beta.kubernetes.io/is-default-class" + +// AlphaStorageClassAnnotation represents the previous alpha storage class +// annotation. it's no longer used and held here for posterity. +const AlphaStorageClassAnnotation = "volume.alpha.kubernetes.io/storage-class" + +// BetaStorageClassAnnotation represents the beta/previous StorageClass annotation. +// It's currently still used and will be held for backwards compatibility +const BetaStorageClassAnnotation = "volume.beta.kubernetes.io/storage-class" + +// StorageClassAnnotation represents the storage class associated with a resource. +// It currently matches the Beta value and can change when official is set. +// - in PersistentVolumeClaim it represents required class to match. +// Only PersistentVolumes with the same class (i.e. annotation with the same +// value) can be bound to the claim. In case no such volume exists, the +// controller will provision a new one using StorageClass instance with +// the same name as the annotation value. +// - in PersistentVolume it represents storage class to which the persistent +// volume belongs. +//TODO: Update this to final annotation value as it matches BetaStorageClassAnnotation for now +const StorageClassAnnotation = "volume.beta.kubernetes.io/storage-class" + +// GetVolumeStorageClass returns value of StorageClassAnnotation or empty string in case +// the annotation does not exist. +// TODO: change to PersistentVolume.Spec.Class value when this attribute is +// introduced. +func GetVolumeStorageClass(volume *v1.PersistentVolume) string { + if class, found := volume.Annotations[StorageClassAnnotation]; found { + return class + } + + // 'nil' is interpreted as "", i.e. the volume does not belong to any class. + return "" +} + +// GetClaimStorageClass returns name of class that is requested by given claim. +// Request for `nil` class is interpreted as request for class "", +// i.e. for a classless PV. +// TODO: change to PersistentVolumeClaim.Spec.Class value when this +// attribute is introduced. +func GetClaimStorageClass(claim *v1.PersistentVolumeClaim) string { + if class, found := claim.Annotations[StorageClassAnnotation]; found { + return class + } + + return "" +} + +// GetStorageClassAnnotation returns the StorageClass value +// if the annotation is set, empty string if not +// TODO: remove Alpha and Beta when no longer used or needed +func GetStorageClassAnnotation(obj v1.ObjectMeta) string { + if class, ok := obj.Annotations[StorageClassAnnotation]; ok { + return class + } + if class, ok := obj.Annotations[BetaStorageClassAnnotation]; ok { + return class + } + if class, ok := obj.Annotations[AlphaStorageClassAnnotation]; ok { + return class + } + + return "" +} + +// HasStorageClassAnnotation returns a boolean +// if the annotation is set +// TODO: remove Alpha and Beta when no longer used or needed +func HasStorageClassAnnotation(obj v1.ObjectMeta) bool { + if _, found := obj.Annotations[StorageClassAnnotation]; found { + return found + } + if _, found := obj.Annotations[BetaStorageClassAnnotation]; found { + return found + } + if _, found := obj.Annotations[AlphaStorageClassAnnotation]; found { + return found + } + + return false + +} + +// IsDefaultAnnotationText returns a pretty Yes/No String if +// the annotation is set +// TODO: remove Beta when no longer needed +func IsDefaultAnnotationText(obj v1.ObjectMeta) string { + if obj.Annotations[IsDefaultStorageClassAnnotation] == "true" { + return "Yes" + } + if obj.Annotations[BetaIsDefaultStorageClassAnnotation] == "true" { + return "Yes" + } + + return "No" +} + +// IsDefaultAnnotation returns a boolean if +// the annotation is set +// TODO: remove Beta when no longer needed +func IsDefaultAnnotation(obj v1.ObjectMeta) bool { + if obj.Annotations[IsDefaultStorageClassAnnotation] == "true" { + return true + } + if obj.Annotations[BetaIsDefaultStorageClassAnnotation] == "true" { + return true + } + + return false +} diff --git a/pkg/client/cache/BUILD b/pkg/client/cache/BUILD index eba219a415d..11d43efc6ea 100644 --- a/pkg/client/cache/BUILD +++ b/pkg/client/cache/BUILD @@ -39,12 +39,15 @@ go_library( "//pkg/api/errors:go_default_library", "//pkg/api/meta:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/apps:go_default_library", - "//pkg/apis/certificates:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/apps/v1beta1:go_default_library", + "//pkg/apis/certificates/v1alpha1:go_default_library", "//pkg/apis/extensions:go_default_library", - "//pkg/apis/policy:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", + "//pkg/apis/policy/v1beta1:go_default_library", "//pkg/apis/rbac:go_default_library", "//pkg/apis/storage:go_default_library", + "//pkg/apis/storage/v1beta1:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/fields:go_default_library", "//pkg/labels:go_default_library", @@ -82,8 +85,9 @@ go_test( "//pkg/api/errors:go_default_library", "//pkg/api/testapi:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/testing/cache:go_default_library", diff --git a/pkg/client/cache/controller_test.go b/pkg/client/cache/controller_test.go index f26c839b808..053775dad72 100644 --- a/pkg/client/cache/controller_test.go +++ b/pkg/client/cache/controller_test.go @@ -23,7 +23,7 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" fcache "k8s.io/kubernetes/pkg/client/testing/cache" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/sets" @@ -51,7 +51,7 @@ func Example() { cfg := &Config{ Queue: fifo, ListerWatcher: source, - ObjectType: &api.Pod{}, + ObjectType: &v1.Pod{}, FullResyncPeriod: time.Millisecond * 100, RetryOnError: false, @@ -101,7 +101,7 @@ func Example() { 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}}) + source.Add(&v1.Pod{ObjectMeta: v1.ObjectMeta{Name: name}}) } // Let's wait for the controller to process the things we just added. @@ -130,7 +130,7 @@ func ExampleNewInformer() { // logs anything deleted. _, controller := NewInformer( source, - &api.Pod{}, + &v1.Pod{}, time.Millisecond*100, ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { @@ -158,7 +158,7 @@ func ExampleNewInformer() { 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}}) + source.Add(&v1.Pod{ObjectMeta: v1.ObjectMeta{Name: name}}) } // Let's wait for the controller to process the things we just added. @@ -206,7 +206,7 @@ func TestHammerController(t *testing.T) { // Make a controller which just logs all the changes it gets. _, controller := NewInformer( source, - &api.Pod{}, + &v1.Pod{}, time.Millisecond*100, ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { recordFunc("add", obj) }, @@ -253,7 +253,7 @@ func TestHammerController(t *testing.T) { name = l[r.Intn(len(l))] } - pod := &api.Pod{} + pod := &v1.Pod{} f.Fuzz(pod) pod.ObjectMeta.Name = name pod.ObjectMeta.Namespace = "default" @@ -315,9 +315,9 @@ func TestUpdate(t *testing.T) { pair{FROM, FROM}: true, } - pod := func(name, check string, final bool) *api.Pod { - p := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := func(name, check string, final bool) *v1.Pod { + p := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: map[string]string{"check": check}, }, @@ -327,7 +327,7 @@ func TestUpdate(t *testing.T) { } return p } - deletePod := func(p *api.Pod) bool { + deletePod := func(p *v1.Pod) bool { return p.Labels["final"] == "true" } @@ -350,20 +350,20 @@ func TestUpdate(t *testing.T) { watchCh := make(chan struct{}) _, controller := NewInformer( &testLW{ - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { watch, err := source.Watch(options) close(watchCh) return watch, err }, - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return source.List(options) }, }, - &api.Pod{}, + &v1.Pod{}, 0, ResourceEventHandlerFuncs{ UpdateFunc: func(oldObj, newObj interface{}) { - o, n := oldObj.(*api.Pod), newObj.(*api.Pod) + o, n := oldObj.(*v1.Pod), newObj.(*v1.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) diff --git a/pkg/client/cache/index_test.go b/pkg/client/cache/index_test.go index f36df387fd1..debb7babf60 100644 --- a/pkg/client/cache/index_test.go +++ b/pkg/client/cache/index_test.go @@ -21,19 +21,20 @@ import ( "testing" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) func testIndexFunc(obj interface{}) ([]string, error) { - pod := obj.(*api.Pod) + pod := obj.(*v1.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"}}} + pod1 := &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "one", Labels: map[string]string{"foo": "bar"}}} + pod2 := &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "two", Labels: map[string]string{"foo": "bar"}}} + pod3 := &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "tre", Labels: map[string]string{"foo": "biz"}}} index.Add(pod1) index.Add(pod2) @@ -52,7 +53,7 @@ func TestGetIndexFuncValues(t *testing.T) { } func testUsersIndexFunc(obj interface{}) ([]string, error) { - pod := obj.(*api.Pod) + pod := obj.(*v1.Pod) usersString := pod.Annotations["users"] return strings.Split(usersString, ","), nil @@ -61,9 +62,9 @@ func testUsersIndexFunc(obj interface{}) ([]string, error) { 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"}}} + pod1 := &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "one", Annotations: map[string]string{"users": "ernie,bert"}}} + pod2 := &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "two", Annotations: map[string]string{"users": "bert,oscar"}}} + pod3 := &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "tre", Annotations: map[string]string{"users": "ernie,elmo"}}} index.Add(pod1) index.Add(pod2) @@ -121,7 +122,7 @@ func TestMultiIndexKeys(t *testing.T) { if err != nil { t.Errorf("unexpected error: %v", err) } - copyOfPod2 := obj.(*api.Pod) + copyOfPod2 := obj.(*v1.Pod) copyOfPod2.Annotations["users"] = "oscar" index.Update(copyOfPod2) bertPods, err = index.ByIndex("byUser", "bert") diff --git a/pkg/client/cache/listers.go b/pkg/client/cache/listers.go index bc65876e036..e6cd930c725 100644 --- a/pkg/client/cache/listers.go +++ b/pkg/client/cache/listers.go @@ -20,15 +20,16 @@ import ( "fmt" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/apps" - "k8s.io/kubernetes/pkg/apis/certificates" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/apis/policy" - "k8s.io/kubernetes/pkg/apis/storage" + "k8s.io/kubernetes/pkg/api/v1" + apps "k8s.io/kubernetes/pkg/apis/apps/v1beta1" + certificates "k8s.io/kubernetes/pkg/apis/certificates/v1alpha1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + policy "k8s.io/kubernetes/pkg/apis/policy/v1beta1" + storageinternal "k8s.io/kubernetes/pkg/apis/storage" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" ) @@ -50,7 +51,7 @@ func ListAll(store Store, selector labels.Selector, appendFn AppendFunc) error { } func ListAllByNamespace(indexer Indexer, namespace string, selector labels.Selector, appendFn AppendFunc) error { - if namespace == api.NamespaceAll { + if namespace == v1.NamespaceAll { for _, m := range indexer.List() { metadata, err := meta.Accessor(m) if err != nil { @@ -63,7 +64,7 @@ func ListAllByNamespace(indexer Indexer, namespace string, selector labels.Selec return nil } - items, err := indexer.Index(NamespaceIndex, &api.ObjectMeta{Namespace: namespace}) + items, err := indexer.Index(NamespaceIndex, &v1.ObjectMeta{Namespace: namespace}) if err != nil { // Ignore error; do slow search without index. glog.Warningf("can not retrieve list of objects using index : %v", err) @@ -170,7 +171,7 @@ func (s *genericNamespaceLister) Get(name string) (runtime.Object, error) { // NodeConditionPredicate is a function that indicates whether the given node's conditions meet // some set of criteria defined by the function. -type NodeConditionPredicate func(node *api.Node) bool +type NodeConditionPredicate func(node *v1.Node) bool // StoreToNodeLister makes a Store have the List method of the client.NodeInterface // The Store must contain (only) Nodes. @@ -178,9 +179,9 @@ type StoreToNodeLister struct { Store } -func (s *StoreToNodeLister) List() (machines api.NodeList, err error) { +func (s *StoreToNodeLister) List() (machines v1.NodeList, err error) { for _, m := range s.Store.List() { - machines.Items = append(machines.Items, *(m.(*api.Node))) + machines.Items = append(machines.Items, *(m.(*v1.Node))) } return machines, nil } @@ -199,9 +200,9 @@ type storeToNodeConditionLister struct { } // List returns a list of nodes that match the conditions defined by the predicate functions in the storeToNodeConditionLister. -func (s storeToNodeConditionLister) List() (nodes []*api.Node, err error) { +func (s storeToNodeConditionLister) List() (nodes []*v1.Node, err error) { for _, m := range s.store.List() { - node := m.(*api.Node) + node := m.(*v1.Node) if s.predicate(node) { nodes = append(nodes, node) } else { @@ -236,7 +237,7 @@ func (s *StoreToDaemonSetLister) List() (dss extensions.DaemonSetList, err error // GetPodDaemonSets returns a list of daemon sets managing a pod. // Returns an error if and only if no matching daemon sets are found. -func (s *StoreToDaemonSetLister) GetPodDaemonSets(pod *api.Pod) (daemonSets []extensions.DaemonSet, err error) { +func (s *StoreToDaemonSetLister) GetPodDaemonSets(pod *v1.Pod) (daemonSets []extensions.DaemonSet, err error) { var selector labels.Selector var daemonSet extensions.DaemonSet @@ -274,17 +275,17 @@ type StoreToEndpointsLister struct { } // List lists all endpoints in the store. -func (s *StoreToEndpointsLister) List() (services api.EndpointsList, err error) { +func (s *StoreToEndpointsLister) List() (services v1.EndpointsList, err error) { for _, m := range s.Store.List() { - services.Items = append(services.Items, *(m.(*api.Endpoints))) + services.Items = append(services.Items, *(m.(*v1.Endpoints))) } return services, nil } // GetServiceEndpoints returns the endpoints of a service, matched on service name. -func (s *StoreToEndpointsLister) GetServiceEndpoints(svc *api.Service) (ep api.Endpoints, err error) { +func (s *StoreToEndpointsLister) GetServiceEndpoints(svc *v1.Service) (ep v1.Endpoints, err error) { for _, m := range s.Store.List() { - ep = *m.(*api.Endpoints) + ep = *m.(*v1.Endpoints) if svc.Name == ep.Name && svc.Namespace == ep.Namespace { return ep, nil } @@ -299,8 +300,8 @@ type StoreToPVFetcher struct { } // GetPersistentVolumeInfo returns cached data for the PersistentVolume 'id'. -func (s *StoreToPVFetcher) GetPersistentVolumeInfo(id string) (*api.PersistentVolume, error) { - o, exists, err := s.Get(&api.PersistentVolume{ObjectMeta: api.ObjectMeta{Name: id}}) +func (s *StoreToPVFetcher) GetPersistentVolumeInfo(id string) (*v1.PersistentVolume, error) { + o, exists, err := s.Get(&v1.PersistentVolume{ObjectMeta: v1.ObjectMeta{Name: id}}) if err != nil { return nil, fmt.Errorf("error retrieving PersistentVolume '%v' from cache: %v", id, err) @@ -310,7 +311,7 @@ func (s *StoreToPVFetcher) GetPersistentVolumeInfo(id string) (*api.PersistentVo return nil, fmt.Errorf("PersistentVolume '%v' not found", id) } - return o.(*api.PersistentVolume), nil + return o.(*v1.PersistentVolume), nil } // StoreToStatefulSetLister gives a store List and Exists methods. The store must contain only StatefulSets. @@ -345,7 +346,7 @@ func (s *StoreToStatefulSetLister) StatefulSets(namespace string) storeStatefulS } // GetPodStatefulSets returns a list of StatefulSets managing a pod. Returns an error only if no matching StatefulSets are found. -func (s *StoreToStatefulSetLister) GetPodStatefulSets(pod *api.Pod) (psList []apps.StatefulSet, err error) { +func (s *StoreToStatefulSetLister) GetPodStatefulSets(pod *v1.Pod) (psList []apps.StatefulSet, err error) { var selector labels.Selector var ps apps.StatefulSet @@ -404,7 +405,7 @@ type StoreToPodDisruptionBudgetLister struct { } // GetPodPodDisruptionBudgets returns a list of PodDisruptionBudgets matching a pod. Returns an error only if no matching PodDisruptionBudgets are found. -func (s *StoreToPodDisruptionBudgetLister) GetPodPodDisruptionBudgets(pod *api.Pod) (pdbList []policy.PodDisruptionBudget, err error) { +func (s *StoreToPodDisruptionBudgetLister) GetPodPodDisruptionBudgets(pod *v1.Pod) (pdbList []policy.PodDisruptionBudget, err error) { var selector labels.Selector if len(pod.Labels) == 0 { @@ -466,13 +467,13 @@ func (s *storageClassLister) List(selector labels.Selector) (ret []*storage.Stor // List returns a list of storage classes func (s *storageClassLister) Get(name string) (*storage.StorageClass, error) { - key := &storage.StorageClass{ObjectMeta: api.ObjectMeta{Name: name}} + key := &storage.StorageClass{ObjectMeta: v1.ObjectMeta{Name: name}} obj, exists, err := s.indexer.Get(key) if err != nil { return nil, err } if !exists { - return nil, errors.NewNotFound(storage.Resource("storageclass"), name) + return nil, errors.NewNotFound(storageinternal.Resource("storageclass"), name) } return obj.(*storage.StorageClass), nil } diff --git a/pkg/client/cache/listers_core.go b/pkg/client/cache/listers_core.go index 1e8eb6055e8..65e64ae3dbc 100644 --- a/pkg/client/cache/listers_core.go +++ b/pkg/client/cache/listers_core.go @@ -21,6 +21,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" ) @@ -40,9 +41,9 @@ type StoreToPodLister struct { Indexer Indexer } -func (s *StoreToPodLister) List(selector labels.Selector) (ret []*api.Pod, err error) { +func (s *StoreToPodLister) List(selector labels.Selector) (ret []*v1.Pod, err error) { err = ListAll(s.Indexer, selector, func(m interface{}) { - ret = append(ret, m.(*api.Pod)) + ret = append(ret, m.(*v1.Pod)) }) return ret, err } @@ -56,14 +57,14 @@ type storePodsNamespacer struct { namespace string } -func (s storePodsNamespacer) List(selector labels.Selector) (ret []*api.Pod, err error) { +func (s storePodsNamespacer) List(selector labels.Selector) (ret []*v1.Pod, err error) { err = ListAllByNamespace(s.Indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*api.Pod)) + ret = append(ret, m.(*v1.Pod)) }) return ret, err } -func (s storePodsNamespacer) Get(name string) (*api.Pod, error) { +func (s storePodsNamespacer) Get(name string) (*v1.Pod, error) { obj, exists, err := s.Indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err @@ -71,7 +72,7 @@ func (s storePodsNamespacer) Get(name string) (*api.Pod, error) { if !exists { return nil, errors.NewNotFound(api.Resource("pod"), name) } - return obj.(*api.Pod), nil + return obj.(*v1.Pod), nil } // StoreToServiceLister helps list services @@ -79,9 +80,9 @@ type StoreToServiceLister struct { Indexer Indexer } -func (s *StoreToServiceLister) List(selector labels.Selector) (ret []*api.Service, err error) { +func (s *StoreToServiceLister) List(selector labels.Selector) (ret []*v1.Service, err error) { err = ListAll(s.Indexer, selector, func(m interface{}) { - ret = append(ret, m.(*api.Service)) + ret = append(ret, m.(*v1.Service)) }) return ret, err } @@ -95,14 +96,14 @@ type storeServicesNamespacer struct { namespace string } -func (s storeServicesNamespacer) List(selector labels.Selector) (ret []*api.Service, err error) { +func (s storeServicesNamespacer) List(selector labels.Selector) (ret []*v1.Service, err error) { err = ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*api.Service)) + ret = append(ret, m.(*v1.Service)) }) return ret, err } -func (s storeServicesNamespacer) Get(name string) (*api.Service, error) { +func (s storeServicesNamespacer) Get(name string) (*v1.Service, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err @@ -110,12 +111,12 @@ func (s storeServicesNamespacer) Get(name string) (*api.Service, error) { if !exists { return nil, errors.NewNotFound(api.Resource("service"), name) } - return obj.(*api.Service), nil + return obj.(*v1.Service), nil } // TODO: Move this back to scheduler as a helper function that takes a Store, // rather than a method of StoreToServiceLister. -func (s *StoreToServiceLister) GetPodServices(pod *api.Pod) (services []*api.Service, err error) { +func (s *StoreToServiceLister) GetPodServices(pod *v1.Pod) (services []*v1.Service, err error) { allServices, err := s.Services(pod.Namespace).List(labels.Everything()) if err != nil { return nil, err @@ -141,9 +142,9 @@ type StoreToReplicationControllerLister struct { Indexer Indexer } -func (s *StoreToReplicationControllerLister) List(selector labels.Selector) (ret []*api.ReplicationController, err error) { +func (s *StoreToReplicationControllerLister) List(selector labels.Selector) (ret []*v1.ReplicationController, err error) { err = ListAll(s.Indexer, selector, func(m interface{}) { - ret = append(ret, m.(*api.ReplicationController)) + ret = append(ret, m.(*v1.ReplicationController)) }) return ret, err } @@ -157,14 +158,14 @@ type storeReplicationControllersNamespacer struct { namespace string } -func (s storeReplicationControllersNamespacer) List(selector labels.Selector) (ret []*api.ReplicationController, err error) { +func (s storeReplicationControllersNamespacer) List(selector labels.Selector) (ret []*v1.ReplicationController, err error) { err = ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*api.ReplicationController)) + ret = append(ret, m.(*v1.ReplicationController)) }) return ret, err } -func (s storeReplicationControllersNamespacer) Get(name string) (*api.ReplicationController, error) { +func (s storeReplicationControllersNamespacer) Get(name string) (*v1.ReplicationController, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err @@ -172,24 +173,24 @@ func (s storeReplicationControllersNamespacer) Get(name string) (*api.Replicatio if !exists { return nil, errors.NewNotFound(api.Resource("replicationcontroller"), name) } - return obj.(*api.ReplicationController), nil + return obj.(*v1.ReplicationController), nil } // GetPodControllers returns a list of replication controllers managing a pod. Returns an error only if no matching controllers are found. -func (s *StoreToReplicationControllerLister) GetPodControllers(pod *api.Pod) (controllers []*api.ReplicationController, err error) { +func (s *StoreToReplicationControllerLister) GetPodControllers(pod *v1.Pod) (controllers []*v1.ReplicationController, err error) { if len(pod.Labels) == 0 { err = fmt.Errorf("no controllers found for pod %v because it has no labels", pod.Name) return } - key := &api.ReplicationController{ObjectMeta: api.ObjectMeta{Namespace: pod.Namespace}} + key := &v1.ReplicationController{ObjectMeta: v1.ObjectMeta{Namespace: pod.Namespace}} items, err := s.Indexer.Index(NamespaceIndex, key) if err != nil { return } for _, m := range items { - rc := m.(*api.ReplicationController) + rc := m.(*v1.ReplicationController) selector := labels.Set(rc.Spec.Selector).AsSelectorPreValidated() // If an rc with a nil or empty selector creeps in, it should match nothing, not everything. @@ -209,9 +210,9 @@ type StoreToServiceAccountLister struct { Indexer Indexer } -func (s *StoreToServiceAccountLister) List(selector labels.Selector) (ret []*api.ServiceAccount, err error) { +func (s *StoreToServiceAccountLister) List(selector labels.Selector) (ret []*v1.ServiceAccount, err error) { err = ListAll(s.Indexer, selector, func(m interface{}) { - ret = append(ret, m.(*api.ServiceAccount)) + ret = append(ret, m.(*v1.ServiceAccount)) }) return ret, err } @@ -225,14 +226,14 @@ type storeServiceAccountsNamespacer struct { namespace string } -func (s storeServiceAccountsNamespacer) List(selector labels.Selector) (ret []*api.ServiceAccount, err error) { +func (s storeServiceAccountsNamespacer) List(selector labels.Selector) (ret []*v1.ServiceAccount, err error) { err = ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*api.ServiceAccount)) + ret = append(ret, m.(*v1.ServiceAccount)) }) return ret, err } -func (s storeServiceAccountsNamespacer) Get(name string) (*api.ServiceAccount, error) { +func (s storeServiceAccountsNamespacer) Get(name string) (*v1.ServiceAccount, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err @@ -240,7 +241,7 @@ func (s storeServiceAccountsNamespacer) Get(name string) (*api.ServiceAccount, e if !exists { return nil, errors.NewNotFound(api.Resource("serviceaccount"), name) } - return obj.(*api.ServiceAccount), nil + return obj.(*v1.ServiceAccount), nil } // StoreToLimitRangeLister helps list limit ranges @@ -248,9 +249,9 @@ type StoreToLimitRangeLister struct { Indexer Indexer } -func (s *StoreToLimitRangeLister) List(selector labels.Selector) (ret []*api.LimitRange, err error) { +func (s *StoreToLimitRangeLister) List(selector labels.Selector) (ret []*v1.LimitRange, err error) { err = ListAll(s.Indexer, selector, func(m interface{}) { - ret = append(ret, m.(*api.LimitRange)) + ret = append(ret, m.(*v1.LimitRange)) }) return ret, err } @@ -261,9 +262,9 @@ type StoreToPersistentVolumeClaimLister struct { } // List returns all persistentvolumeclaims that match the specified selector -func (s *StoreToPersistentVolumeClaimLister) List(selector labels.Selector) (ret []*api.PersistentVolumeClaim, err error) { +func (s *StoreToPersistentVolumeClaimLister) List(selector labels.Selector) (ret []*v1.PersistentVolumeClaim, err error) { err = ListAll(s.Indexer, selector, func(m interface{}) { - ret = append(ret, m.(*api.PersistentVolumeClaim)) + ret = append(ret, m.(*v1.PersistentVolumeClaim)) }) return ret, err } @@ -277,14 +278,14 @@ type storeLimitRangesNamespacer struct { namespace string } -func (s storeLimitRangesNamespacer) List(selector labels.Selector) (ret []*api.LimitRange, err error) { +func (s storeLimitRangesNamespacer) List(selector labels.Selector) (ret []*v1.LimitRange, err error) { err = ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*api.LimitRange)) + ret = append(ret, m.(*v1.LimitRange)) }) return ret, err } -func (s storeLimitRangesNamespacer) Get(name string) (*api.LimitRange, error) { +func (s storeLimitRangesNamespacer) Get(name string) (*v1.LimitRange, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err @@ -292,7 +293,7 @@ func (s storeLimitRangesNamespacer) Get(name string) (*api.LimitRange, error) { if !exists { return nil, errors.NewNotFound(api.Resource("limitrange"), name) } - return obj.(*api.LimitRange), nil + return obj.(*v1.LimitRange), nil } // PersistentVolumeClaims returns all claims in a specified namespace. @@ -305,14 +306,14 @@ type storePersistentVolumeClaimsNamespacer struct { namespace string } -func (s storePersistentVolumeClaimsNamespacer) List(selector labels.Selector) (ret []*api.PersistentVolumeClaim, err error) { +func (s storePersistentVolumeClaimsNamespacer) List(selector labels.Selector) (ret []*v1.PersistentVolumeClaim, err error) { err = ListAllByNamespace(s.Indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*api.PersistentVolumeClaim)) + ret = append(ret, m.(*v1.PersistentVolumeClaim)) }) return ret, err } -func (s storePersistentVolumeClaimsNamespacer) Get(name string) (*api.PersistentVolumeClaim, error) { +func (s storePersistentVolumeClaimsNamespacer) Get(name string) (*v1.PersistentVolumeClaim, error) { obj, exists, err := s.Indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err @@ -320,7 +321,7 @@ func (s storePersistentVolumeClaimsNamespacer) Get(name string) (*api.Persistent if !exists { return nil, errors.NewNotFound(api.Resource("persistentvolumeclaims"), name) } - return obj.(*api.PersistentVolumeClaim), nil + return obj.(*v1.PersistentVolumeClaim), nil } // IndexerToNamespaceLister gives an Indexer List method @@ -329,14 +330,14 @@ type IndexerToNamespaceLister struct { } // List returns a list of namespaces -func (i *IndexerToNamespaceLister) List(selector labels.Selector) (ret []*api.Namespace, err error) { +func (i *IndexerToNamespaceLister) List(selector labels.Selector) (ret []*v1.Namespace, err error) { err = ListAll(i.Indexer, selector, func(m interface{}) { - ret = append(ret, m.(*api.Namespace)) + ret = append(ret, m.(*v1.Namespace)) }) return ret, err } -func (i *IndexerToNamespaceLister) Get(name string) (*api.Namespace, error) { +func (i *IndexerToNamespaceLister) Get(name string) (*v1.Namespace, error) { obj, exists, err := i.Indexer.GetByKey(name) if err != nil { return nil, err @@ -344,5 +345,5 @@ func (i *IndexerToNamespaceLister) Get(name string) (*api.Namespace, error) { if !exists { return nil, errors.NewNotFound(api.Resource("namespace"), name) } - return obj.(*api.Namespace), nil + return obj.(*v1.Namespace), nil } diff --git a/pkg/client/cache/listers_extensions.go b/pkg/client/cache/listers_extensions.go index 539657765d1..922c2943fd8 100644 --- a/pkg/client/cache/listers_extensions.go +++ b/pkg/client/cache/listers_extensions.go @@ -19,10 +19,11 @@ package cache import ( "fmt" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + extensionsinternal "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/labels" ) @@ -71,7 +72,7 @@ func (s storeDeploymentsNamespacer) Get(name string) (*extensions.Deployment, er return nil, err } if !exists { - return nil, errors.NewNotFound(extensions.Resource("deployment"), name) + return nil, errors.NewNotFound(extensionsinternal.Resource("deployment"), name) } return obj.(*extensions.Deployment), nil } @@ -107,7 +108,7 @@ func (s *StoreToDeploymentLister) GetDeploymentsForReplicaSet(rs *extensions.Rep // GetDeploymentsForDeployments returns a list of deployments managing a pod. Returns an error only if no matching deployments are found. // TODO eliminate shallow copies -func (s *StoreToDeploymentLister) GetDeploymentsForPod(pod *api.Pod) (deployments []*extensions.Deployment, err error) { +func (s *StoreToDeploymentLister) GetDeploymentsForPod(pod *v1.Pod) (deployments []*extensions.Deployment, err error) { if len(pod.Labels) == 0 { err = fmt.Errorf("no deployments found for Pod %v because it has no labels", pod.Name) return @@ -172,13 +173,13 @@ func (s storeReplicaSetsNamespacer) Get(name string) (*extensions.ReplicaSet, er return nil, err } if !exists { - return nil, errors.NewNotFound(extensions.Resource("replicaset"), name) + return nil, errors.NewNotFound(extensionsinternal.Resource("replicaset"), name) } return obj.(*extensions.ReplicaSet), nil } // GetPodReplicaSets returns a list of ReplicaSets managing a pod. Returns an error only if no matching ReplicaSets are found. -func (s *StoreToReplicaSetLister) GetPodReplicaSets(pod *api.Pod) (rss []*extensions.ReplicaSet, err error) { +func (s *StoreToReplicaSetLister) GetPodReplicaSets(pod *v1.Pod) (rss []*extensions.ReplicaSet, err error) { if len(pod.Labels) == 0 { err = fmt.Errorf("no ReplicaSets found for pod %v because it has no labels", pod.Name) return diff --git a/pkg/client/cache/listers_rbac.go b/pkg/client/cache/listers_rbac.go index 2b1cf8bb2a8..fb7769a881c 100644 --- a/pkg/client/cache/listers_rbac.go +++ b/pkg/client/cache/listers_rbac.go @@ -18,7 +18,7 @@ package cache import ( "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/apis/rbac" + rbac "k8s.io/kubernetes/pkg/apis/rbac" "k8s.io/kubernetes/pkg/labels" ) diff --git a/pkg/client/cache/listers_test.go b/pkg/client/cache/listers_test.go index 6b7e5937478..a904e89c842 100644 --- a/pkg/client/cache/listers_test.go +++ b/pkg/client/cache/listers_test.go @@ -19,10 +19,10 @@ package cache import ( "testing" - "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/sets" ) @@ -31,7 +31,7 @@ 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}}) + store.Add(&v1.Node{ObjectMeta: v1.ObjectMeta{Name: id}}) } sml := StoreToNodeLister{store} @@ -50,44 +50,44 @@ func TestStoreToNodeLister(t *testing.T) { func TestStoreToNodeConditionLister(t *testing.T) { store := NewStore(MetaNamespaceKeyFunc) - nodes := []*api.Node{ + nodes := []*v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + ObjectMeta: v1.ObjectMeta{Name: "foo"}, + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, }, { - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionFalse, }, }, }, }, { - ObjectMeta: api.ObjectMeta{Name: "bar"}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + ObjectMeta: v1.ObjectMeta{Name: "bar"}, + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeOutOfDisk, - Status: api.ConditionTrue, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionTrue, }, }, }, }, { - ObjectMeta: api.ObjectMeta{Name: "baz"}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + ObjectMeta: v1.ObjectMeta{Name: "baz"}, + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionFalse, + Type: v1.NodeReady, + Status: v1.ConditionFalse, }, { - Type: api.NodeOutOfDisk, - Status: api.ConditionUnknown, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionUnknown, }, }, }, @@ -97,9 +97,9 @@ func TestStoreToNodeConditionLister(t *testing.T) { store.Add(n) } - predicate := func(node *api.Node) bool { + predicate := func(node *v1.Node) bool { for _, cond := range node.Status.Conditions { - if cond.Type == api.NodeOutOfDisk && cond.Status == api.ConditionTrue { + if cond.Type == v1.NodeOutOfDisk && cond.Status == v1.ConditionTrue { return false } } @@ -126,65 +126,65 @@ func TestStoreToNodeConditionLister(t *testing.T) { func TestStoreToReplicationControllerLister(t *testing.T) { testCases := []struct { description string - inRCs []*api.ReplicationController - list func(StoreToReplicationControllerLister) ([]*api.ReplicationController, error) + inRCs []*v1.ReplicationController + list func(StoreToReplicationControllerLister) ([]*v1.ReplicationController, error) outRCNames sets.String expectErr bool onlyIfIndexedByNamespace bool }{ { description: "Verify we can search all namespaces", - inRCs: []*api.ReplicationController{ + inRCs: []*v1.ReplicationController{ { - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"}, + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: "bar"}, }, { - ObjectMeta: api.ObjectMeta{Name: "hmm", Namespace: "hmm"}, + ObjectMeta: v1.ObjectMeta{Name: "hmm", Namespace: "hmm"}, }, }, - list: func(lister StoreToReplicationControllerLister) ([]*api.ReplicationController, error) { - return lister.ReplicationControllers(api.NamespaceAll).List(labels.Set{}.AsSelectorPreValidated()) + list: func(lister StoreToReplicationControllerLister) ([]*v1.ReplicationController, error) { + return lister.ReplicationControllers(v1.NamespaceAll).List(labels.Set{}.AsSelectorPreValidated()) }, outRCNames: sets.NewString("hmm", "foo"), }, { description: "Verify we can search a specific namespace", - inRCs: []*api.ReplicationController{ + inRCs: []*v1.ReplicationController{ { - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"}, + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: "bar"}, }, { - ObjectMeta: api.ObjectMeta{Name: "hmm", Namespace: "hmm"}, + ObjectMeta: v1.ObjectMeta{Name: "hmm", Namespace: "hmm"}, }, }, - list: func(lister StoreToReplicationControllerLister) ([]*api.ReplicationController, error) { + list: func(lister StoreToReplicationControllerLister) ([]*v1.ReplicationController, error) { return lister.ReplicationControllers("hmm").List(labels.Set{}.AsSelectorPreValidated()) }, outRCNames: sets.NewString("hmm"), }, { description: "Basic listing with all labels and no selectors", - inRCs: []*api.ReplicationController{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}, + inRCs: []*v1.ReplicationController{ + {ObjectMeta: v1.ObjectMeta{Name: "basic"}}, }, - list: func(lister StoreToReplicationControllerLister) ([]*api.ReplicationController, error) { + list: func(lister StoreToReplicationControllerLister) ([]*v1.ReplicationController, error) { return lister.List(labels.Everything()) }, outRCNames: sets.NewString("basic"), }, { description: "No pod labels", - inRCs: []*api.ReplicationController{ + inRCs: []*v1.ReplicationController{ { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, - Spec: api.ReplicationControllerSpec{ + ObjectMeta: v1.ObjectMeta{Name: "basic", Namespace: "ns"}, + Spec: v1.ReplicationControllerSpec{ Selector: map[string]string{"foo": "baz"}, }, }, }, - list: func(lister StoreToReplicationControllerLister) ([]*api.ReplicationController, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "pod1", Namespace: "ns"}, + list: func(lister StoreToReplicationControllerLister) ([]*v1.ReplicationController, error) { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "pod1", Namespace: "ns"}, } return lister.GetPodControllers(pod) }, @@ -193,14 +193,14 @@ func TestStoreToReplicationControllerLister(t *testing.T) { }, { description: "No RC selectors", - inRCs: []*api.ReplicationController{ + inRCs: []*v1.ReplicationController{ { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, + ObjectMeta: v1.ObjectMeta{Name: "basic", Namespace: "ns"}, }, }, - list: func(lister StoreToReplicationControllerLister) ([]*api.ReplicationController, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + list: func(lister StoreToReplicationControllerLister) ([]*v1.ReplicationController, error) { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", Namespace: "ns", Labels: map[string]string{"foo": "bar"}, @@ -213,23 +213,23 @@ func TestStoreToReplicationControllerLister(t *testing.T) { }, { description: "Matching labels to selectors and namespace", - inRCs: []*api.ReplicationController{ + inRCs: []*v1.ReplicationController{ { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.ReplicationControllerSpec{ + ObjectMeta: v1.ObjectMeta{Name: "foo"}, + Spec: v1.ReplicationControllerSpec{ Selector: map[string]string{"foo": "bar"}, }, }, { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "ns"}, - Spec: api.ReplicationControllerSpec{ + ObjectMeta: v1.ObjectMeta{Name: "bar", Namespace: "ns"}, + Spec: v1.ReplicationControllerSpec{ Selector: map[string]string{"foo": "bar"}, }, }, }, - list: func(lister StoreToReplicationControllerLister) ([]*api.ReplicationController, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + list: func(lister StoreToReplicationControllerLister) ([]*v1.ReplicationController, error) { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", Labels: map[string]string{"foo": "bar"}, Namespace: "ns", @@ -290,7 +290,7 @@ func TestStoreToReplicaSetLister(t *testing.T) { // Basic listing with all labels and no selectors { inRSs: []*extensions.ReplicaSet{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}, + {ObjectMeta: v1.ObjectMeta{Name: "basic"}}, }, list: func() ([]*extensions.ReplicaSet, error) { return lister.List(labels.Everything()) @@ -301,15 +301,15 @@ func TestStoreToReplicaSetLister(t *testing.T) { { inRSs: []*extensions.ReplicaSet{ { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, + ObjectMeta: v1.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"}, + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "pod1", Namespace: "ns"}, } return lister.GetPodReplicaSets(pod) }, @@ -320,12 +320,12 @@ func TestStoreToReplicaSetLister(t *testing.T) { { inRSs: []*extensions.ReplicaSet{ { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, + ObjectMeta: v1.ObjectMeta{Name: "basic", Namespace: "ns"}, }, }, list: func() ([]*extensions.ReplicaSet, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", Namespace: "ns", Labels: map[string]string{"foo": "bar"}, @@ -340,21 +340,21 @@ func TestStoreToReplicaSetLister(t *testing.T) { { inRSs: []*extensions.ReplicaSet{ { - ObjectMeta: api.ObjectMeta{Name: "foo"}, + ObjectMeta: v1.ObjectMeta{Name: "foo"}, Spec: extensions.ReplicaSetSpec{ Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, }, }, { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "ns"}, + ObjectMeta: v1.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{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", Labels: map[string]string{"foo": "bar"}, Namespace: "ns", @@ -402,7 +402,7 @@ func TestStoreToDaemonSetLister(t *testing.T) { // Basic listing { inDSs: []*extensions.DaemonSet{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}, + {ObjectMeta: v1.ObjectMeta{Name: "basic"}}, }, list: func() ([]extensions.DaemonSet, error) { list, err := lister.List() @@ -413,9 +413,9 @@ func TestStoreToDaemonSetLister(t *testing.T) { // Listing multiple daemon sets { inDSs: []*extensions.DaemonSet{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}, - {ObjectMeta: api.ObjectMeta{Name: "complex"}}, - {ObjectMeta: api.ObjectMeta{Name: "complex2"}}, + {ObjectMeta: v1.ObjectMeta{Name: "basic"}}, + {ObjectMeta: v1.ObjectMeta{Name: "complex"}}, + {ObjectMeta: v1.ObjectMeta{Name: "complex2"}}, }, list: func() ([]extensions.DaemonSet, error) { list, err := lister.List() @@ -427,15 +427,15 @@ func TestStoreToDaemonSetLister(t *testing.T) { { inDSs: []*extensions.DaemonSet{ { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, + ObjectMeta: v1.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"}, + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "pod1", Namespace: "ns"}, } return lister.GetPodDaemonSets(pod) }, @@ -446,12 +446,12 @@ func TestStoreToDaemonSetLister(t *testing.T) { { inDSs: []*extensions.DaemonSet{ { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, + ObjectMeta: v1.ObjectMeta{Name: "basic", Namespace: "ns"}, }, }, list: func() ([]extensions.DaemonSet, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", Namespace: "ns", Labels: map[string]string{"foo": "bar"}, @@ -466,21 +466,21 @@ func TestStoreToDaemonSetLister(t *testing.T) { { inDSs: []*extensions.DaemonSet{ { - ObjectMeta: api.ObjectMeta{Name: "foo"}, + ObjectMeta: v1.ObjectMeta{Name: "foo"}, Spec: extensions.DaemonSetSpec{ Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, }, }, { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "ns"}, + ObjectMeta: v1.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{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", Labels: map[string]string{"foo": "bar"}, Namespace: "ns", @@ -527,25 +527,25 @@ func TestStoreToPodLister(t *testing.T) { for _, store := range stores { ids := []string{"foo", "bar", "baz"} for _, id := range ids { - store.Add(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + store.Add(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: "other", Name: id, Labels: map[string]string{"name": id}, }, }) } - store.Add(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + store.Add(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "quux", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, Labels: map[string]string{"name": "quux"}, }, }) spl := StoreToPodLister{store} // Verify that we can always look up by Namespace. - defaultPods, err := spl.Pods(api.NamespaceDefault).List(labels.Set{}.AsSelectorPreValidated()) + defaultPods, err := spl.Pods(v1.NamespaceDefault).List(labels.Set{}.AsSelectorPreValidated()) if err != nil { t.Errorf("Unexpected error: %v", err) } else if e, a := 1, len(defaultPods); e != a { @@ -583,17 +583,17 @@ func TestStoreToPodLister(t *testing.T) { func TestStoreToServiceLister(t *testing.T) { store := NewIndexer(MetaNamespaceKeyFunc, Indexers{NamespaceIndex: MetaNamespaceIndexFunc}) - store.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.ServiceSpec{ + store.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{Name: "foo"}, + Spec: v1.ServiceSpec{ Selector: map[string]string{}, }, }) - store.Add(&api.Service{ObjectMeta: api.ObjectMeta{Name: "bar"}}) + store.Add(&v1.Service{ObjectMeta: v1.ObjectMeta{Name: "bar"}}) ssl := StoreToServiceLister{store} - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "foopod", Labels: map[string]string{"role": "foo"}, }, diff --git a/pkg/client/cache/listwatch.go b/pkg/client/cache/listwatch.go index 3956ccb1e25..9622e9f9870 100644 --- a/pkg/client/cache/listwatch.go +++ b/pkg/client/cache/listwatch.go @@ -21,6 +21,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/meta" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/runtime" @@ -31,16 +32,16 @@ import ( type ListerWatcher interface { // List should return a list type object; the Items field will be extracted, and the // ResourceVersion field will be used to start the watch in the right place. - List(options api.ListOptions) (runtime.Object, error) + List(options v1.ListOptions) (runtime.Object, error) // Watch should begin a watch at the specified version. - Watch(options api.ListOptions) (watch.Interface, error) + Watch(options v1.ListOptions) (watch.Interface, error) } // ListFunc knows how to list resources -type ListFunc func(options api.ListOptions) (runtime.Object, error) +type ListFunc func(options v1.ListOptions) (runtime.Object, error) // WatchFunc knows how to watch resources -type WatchFunc func(options api.ListOptions) (watch.Interface, error) +type WatchFunc func(options v1.ListOptions) (watch.Interface, error) // ListWatch knows how to list and watch a set of apiserver resources. It satisfies the ListerWatcher interface. // It is a convenience function for users of NewReflector, etc. @@ -57,7 +58,7 @@ type Getter interface { // NewListWatchFromClient creates a new ListWatch from the specified client, resource, namespace and field selector. func NewListWatchFromClient(c Getter, resource string, namespace string, fieldSelector fields.Selector) *ListWatch { - listFunc := func(options api.ListOptions) (runtime.Object, error) { + listFunc := func(options v1.ListOptions) (runtime.Object, error) { return c.Get(). Namespace(namespace). Resource(resource). @@ -66,7 +67,7 @@ func NewListWatchFromClient(c Getter, resource string, namespace string, fieldSe Do(). Get() } - watchFunc := func(options api.ListOptions) (watch.Interface, error) { + watchFunc := func(options v1.ListOptions) (watch.Interface, error) { return c.Get(). Prefix("watch"). Namespace(namespace). @@ -78,7 +79,7 @@ func NewListWatchFromClient(c Getter, resource string, namespace string, fieldSe return &ListWatch{ListFunc: listFunc, WatchFunc: watchFunc} } -func timeoutFromListOptions(options api.ListOptions) time.Duration { +func timeoutFromListOptions(options v1.ListOptions) time.Duration { if options.TimeoutSeconds != nil { return time.Duration(*options.TimeoutSeconds) * time.Second } @@ -86,12 +87,12 @@ func timeoutFromListOptions(options api.ListOptions) time.Duration { } // List a set of apiserver resources -func (lw *ListWatch) List(options api.ListOptions) (runtime.Object, error) { +func (lw *ListWatch) List(options v1.ListOptions) (runtime.Object, error) { return lw.ListFunc(options) } // Watch a set of apiserver resources -func (lw *ListWatch) Watch(options api.ListOptions) (watch.Interface, error) { +func (lw *ListWatch) Watch(options v1.ListOptions) (watch.Interface, error) { return lw.WatchFunc(options) } @@ -101,7 +102,7 @@ func ListWatchUntil(timeout time.Duration, lw ListerWatcher, conditions ...watch return nil, nil } - list, err := lw.List(api.ListOptions{}) + list, err := lw.List(v1.ListOptions{}) if err != nil { return nil, err } @@ -153,7 +154,7 @@ func ListWatchUntil(timeout time.Duration, lw ListerWatcher, conditions ...watch } currResourceVersion := metaObj.GetResourceVersion() - watchInterface, err := lw.Watch(api.ListOptions{ResourceVersion: currResourceVersion}) + watchInterface, err := lw.Watch(v1.ListOptions{ResourceVersion: currResourceVersion}) if err != nil { return nil, err } diff --git a/pkg/client/cache/listwatch_test.go b/pkg/client/cache/listwatch_test.go index 1766bcf43eb..3c5663daf50 100644 --- a/pkg/client/cache/listwatch_test.go +++ b/pkg/client/cache/listwatch_test.go @@ -22,9 +22,9 @@ import ( "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/apimachinery/registered" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/client/restclient" @@ -60,7 +60,7 @@ func buildLocation(resourcePath string, query url.Values) string { } func TestListWatchesCanList(t *testing.T) { - fieldSelectorQueryParamName := unversioned.FieldSelectorQueryParam(registered.GroupOrDie(api.GroupName).GroupVersion.String()) + fieldSelectorQueryParamName := unversioned.FieldSelectorQueryParam(registered.GroupOrDie(v1.GroupName).GroupVersion.String()) table := []struct { location string resource string @@ -69,18 +69,18 @@ func TestListWatchesCanList(t *testing.T) { }{ // Node { - location: testapi.Default.ResourcePath("nodes", api.NamespaceAll, ""), + location: testapi.Default.ResourcePath("nodes", v1.NamespaceAll, ""), resource: "nodes", - namespace: api.NamespaceAll, + namespace: v1.NamespaceAll, fieldSelector: parseSelectorOrDie(""), }, // pod with "assigned" field selector. { location: buildLocation( - testapi.Default.ResourcePath("pods", api.NamespaceAll, ""), + testapi.Default.ResourcePath("pods", v1.NamespaceAll, ""), buildQueryValues(url.Values{fieldSelectorQueryParamName: []string{"spec.host="}})), resource: "pods", - namespace: api.NamespaceAll, + namespace: v1.NamespaceAll, fieldSelector: fields.Set{"spec.host": ""}.AsSelector(), }, // pod in namespace "foo" @@ -101,16 +101,16 @@ func TestListWatchesCanList(t *testing.T) { } server := httptest.NewServer(&handler) defer server.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) lw := NewListWatchFromClient(client.Core().RESTClient(), item.resource, item.namespace, item.fieldSelector) // This test merely tests that the correct request is made. - lw.List(api.ListOptions{}) + lw.List(v1.ListOptions{}) handler.ValidateRequest(t, item.location, "GET", nil) } } func TestListWatchesCanWatch(t *testing.T) { - fieldSelectorQueryParamName := unversioned.FieldSelectorQueryParam(registered.GroupOrDie(api.GroupName).GroupVersion.String()) + fieldSelectorQueryParamName := unversioned.FieldSelectorQueryParam(registered.GroupOrDie(v1.GroupName).GroupVersion.String()) table := []struct { rv string location string @@ -121,30 +121,30 @@ func TestListWatchesCanWatch(t *testing.T) { // Node { location: buildLocation( - testapi.Default.ResourcePathWithPrefix("watch", "nodes", api.NamespaceAll, ""), + testapi.Default.ResourcePathWithPrefix("watch", "nodes", v1.NamespaceAll, ""), buildQueryValues(url.Values{})), rv: "", resource: "nodes", - namespace: api.NamespaceAll, + namespace: v1.NamespaceAll, fieldSelector: parseSelectorOrDie(""), }, { location: buildLocation( - testapi.Default.ResourcePathWithPrefix("watch", "nodes", api.NamespaceAll, ""), + testapi.Default.ResourcePathWithPrefix("watch", "nodes", v1.NamespaceAll, ""), buildQueryValues(url.Values{"resourceVersion": []string{"42"}})), rv: "42", resource: "nodes", - namespace: api.NamespaceAll, + namespace: v1.NamespaceAll, fieldSelector: parseSelectorOrDie(""), }, // pod with "assigned" field selector. { location: buildLocation( - testapi.Default.ResourcePathWithPrefix("watch", "pods", api.NamespaceAll, ""), + testapi.Default.ResourcePathWithPrefix("watch", "pods", v1.NamespaceAll, ""), buildQueryValues(url.Values{fieldSelectorQueryParamName: []string{"spec.host="}, "resourceVersion": []string{"0"}})), rv: "0", resource: "pods", - namespace: api.NamespaceAll, + namespace: v1.NamespaceAll, fieldSelector: fields.Set{"spec.host": ""}.AsSelector(), }, // pod with namespace foo and assigned field selector @@ -167,10 +167,10 @@ func TestListWatchesCanWatch(t *testing.T) { } server := httptest.NewServer(&handler) defer server.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) lw := NewListWatchFromClient(client.Core().RESTClient(), item.resource, item.namespace, item.fieldSelector) // This test merely tests that the correct request is made. - lw.Watch(api.ListOptions{ResourceVersion: item.rv}) + lw.Watch(v1.ListOptions{ResourceVersion: item.rv}) handler.ValidateRequest(t, item.location, "GET", nil) } } @@ -180,22 +180,22 @@ type lw struct { watch watch.Interface } -func (w lw) List(options api.ListOptions) (runtime.Object, error) { +func (w lw) List(options v1.ListOptions) (runtime.Object, error) { return w.list, nil } -func (w lw) Watch(options api.ListOptions) (watch.Interface, error) { +func (w lw) Watch(options v1.ListOptions) (watch.Interface, error) { return w.watch, nil } func TestListWatchUntil(t *testing.T) { fw := watch.NewFake() go func() { - var obj *api.Pod + var obj *v1.Pod fw.Modify(obj) }() listwatch := lw{ - list: &api.PodList{Items: []api.Pod{{}}}, + list: &v1.PodList{Items: []v1.Pod{{}}}, watch: fw, } @@ -221,7 +221,7 @@ func TestListWatchUntil(t *testing.T) { if lastEvent.Type != watch.Modified { t.Fatalf("expected MODIFIED event type, got %v", lastEvent.Type) } - if got, isPod := lastEvent.Object.(*api.Pod); !isPod { + if got, isPod := lastEvent.Object.(*v1.Pod); !isPod { t.Fatalf("expected a pod event, got %#v", got) } } diff --git a/pkg/client/cache/mutation_detector_test.go b/pkg/client/cache/mutation_detector_test.go index 3a5d70c1c93..a7c5fee15b5 100644 --- a/pkg/client/cache/mutation_detector_test.go +++ b/pkg/client/cache/mutation_detector_test.go @@ -22,7 +22,7 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/watch" ) @@ -30,15 +30,15 @@ import ( func TestMutationDetector(t *testing.T) { fakeWatch := watch.NewFake() lw := &testLW{ - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return fakeWatch, nil }, - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return &api.PodList{}, nil + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return &v1.PodList{}, nil }, } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "anything", Labels: map[string]string{"check": "foo"}, }, @@ -48,7 +48,7 @@ func TestMutationDetector(t *testing.T) { addReceived := make(chan bool) mutationFound := make(chan bool) - informer := NewSharedInformer(lw, &api.Pod{}, 1*time.Second).(*sharedIndexInformer) + informer := NewSharedInformer(lw, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) informer.cacheMutationDetector = &defaultCacheMutationDetector{ name: "name", period: 1 * time.Second, diff --git a/pkg/client/cache/reflector.go b/pkg/client/cache/reflector.go index 8a0d05ab479..8c8aee3a7b0 100644 --- a/pkg/client/cache/reflector.go +++ b/pkg/client/cache/reflector.go @@ -34,9 +34,9 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" apierrs "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/meta" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/runtime" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/wait" @@ -239,7 +239,7 @@ func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error { // Explicitly set "0" as resource version - it's fine for the List() // to be served from cache and potentially be delayed relative to // etcd contents. Reflector framework will catch up via Watch() eventually. - options := api.ListOptions{ResourceVersion: "0"} + options := v1.ListOptions{ResourceVersion: "0"} list, err := r.listerWatcher.List(options) if err != nil { return fmt.Errorf("%s: Failed to list %v: %v", r.name, r.expectedType, err) @@ -278,7 +278,7 @@ func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error { for { timemoutseconds := int64(minWatchTimeout.Seconds() * (rand.Float64() + 1.0)) - options = api.ListOptions{ + options = v1.ListOptions{ ResourceVersion: resourceVersion, // We want to avoid situations of hanging watchers. Stop any wachers that do not // receive any events within the timeout window. diff --git a/pkg/client/cache/reflector_test.go b/pkg/client/cache/reflector_test.go index 470787676d4..eabe810a159 100644 --- a/pkg/client/cache/reflector_test.go +++ b/pkg/client/cache/reflector_test.go @@ -24,8 +24,8 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/watch" @@ -34,27 +34,27 @@ import ( var nevererrc chan error type testLW struct { - ListFunc func(options api.ListOptions) (runtime.Object, error) - WatchFunc func(options api.ListOptions) (watch.Interface, error) + ListFunc func(options v1.ListOptions) (runtime.Object, error) + WatchFunc func(options v1.ListOptions) (watch.Interface, error) } -func (t *testLW) List(options api.ListOptions) (runtime.Object, error) { +func (t *testLW) List(options v1.ListOptions) (runtime.Object, error) { return t.ListFunc(options) } -func (t *testLW) Watch(options api.ListOptions) (watch.Interface, error) { +func (t *testLW) Watch(options v1.ListOptions) (watch.Interface, error) { return t.WatchFunc(options) } func TestCloseWatchChannelOnError(t *testing.T) { - r := NewReflector(&testLW{}, &api.Pod{}, NewStore(MetaNamespaceKeyFunc), 0) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar"}} + r := NewReflector(&testLW{}, &v1.Pod{}, NewStore(MetaNamespaceKeyFunc), 0) + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "bar"}} fw := watch.NewFake() r.listerWatcher = &testLW{ - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return fw, nil }, - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}, nil + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return &v1.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}, nil }, } go r.ListAndWatch(wait.NeverStop) @@ -73,20 +73,20 @@ func TestCloseWatchChannelOnError(t *testing.T) { func TestRunUntil(t *testing.T) { stopCh := make(chan struct{}) store := NewStore(MetaNamespaceKeyFunc) - r := NewReflector(&testLW{}, &api.Pod{}, store, 0) + r := NewReflector(&testLW{}, &v1.Pod{}, store, 0) fw := watch.NewFake() r.listerWatcher = &testLW{ - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return fw, nil }, - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}, nil + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return &v1.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"}}) + fw.Add(&v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "bar"}}) close(stopCh) select { case _, ok := <-fw.ResultChan(): @@ -101,7 +101,7 @@ func TestRunUntil(t *testing.T) { func TestReflectorResyncChan(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &api.Pod{}, s, time.Millisecond) + g := NewReflector(&testLW{}, &v1.Pod{}, s, time.Millisecond) a, _ := g.resyncChan() b := time.After(wait.ForeverTestTimeout) select { @@ -114,7 +114,7 @@ func TestReflectorResyncChan(t *testing.T) { func BenchmarkReflectorResyncChanMany(b *testing.B) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &api.Pod{}, s, 25*time.Millisecond) + g := NewReflector(&testLW{}, &v1.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++ { @@ -126,7 +126,7 @@ func BenchmarkReflectorResyncChanMany(b *testing.B) { func TestReflectorWatchHandlerError(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &api.Pod{}, s, 0) + g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) fw := watch.NewFake() go func() { fw.Stop() @@ -140,15 +140,15 @@ func TestReflectorWatchHandlerError(t *testing.T) { func TestReflectorWatchHandler(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &api.Pod{}, s, 0) + g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) fw := watch.NewFake() - s.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}) - s.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar"}}) + s.Add(&v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo"}}) + s.Add(&v1.Pod{ObjectMeta: v1.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.Add(&v1.Service{ObjectMeta: v1.ObjectMeta{Name: "rejected"}}) + fw.Delete(&v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo"}}) + fw.Modify(&v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "bar", ResourceVersion: "55"}}) + fw.Add(&v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "baz", ResourceVersion: "32"}}) fw.Stop() }() var resumeRV string @@ -157,12 +157,12 @@ func TestReflectorWatchHandler(t *testing.T) { t.Errorf("unexpected error %v", err) } - mkPod := func(id string, rv string) *api.Pod { - return &api.Pod{ObjectMeta: api.ObjectMeta{Name: id, ResourceVersion: rv}} + mkPod := func(id string, rv string) *v1.Pod { + return &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: id, ResourceVersion: rv}} } table := []struct { - Pod *api.Pod + Pod *v1.Pod exists bool }{ {mkPod("foo", ""), false}, @@ -178,7 +178,7 @@ func TestReflectorWatchHandler(t *testing.T) { if !exists { continue } - if e, a := item.Pod.ResourceVersion, obj.(*api.Pod).ResourceVersion; e != a { + if e, a := item.Pod.ResourceVersion, obj.(*v1.Pod).ResourceVersion; e != a { t.Errorf("%v: expected %v, got %v", item.Pod, e, a) } } @@ -196,7 +196,7 @@ func TestReflectorWatchHandler(t *testing.T) { func TestReflectorStopWatch(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &api.Pod{}, s, 0) + g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) fw := watch.NewFake() var resumeRV string stopWatch := make(chan struct{}, 1) @@ -215,7 +215,7 @@ func TestReflectorListAndWatch(t *testing.T) { // inject an error. expectedRVs := []string{"1", "3"} lw := &testLW{ - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { rv := options.ResourceVersion fw := watch.NewFake() if e, a := expectedRVs[0], rv; e != a { @@ -227,12 +227,12 @@ func TestReflectorListAndWatch(t *testing.T) { go func() { createdFakes <- fw }() return fw, nil }, - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}, nil + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return &v1.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}, nil }, } s := NewFIFO(MetaNamespaceKeyFunc) - r := NewReflector(lw, &api.Pod{}, s, 0) + r := NewReflector(lw, &v1.Pod{}, s, 0) go r.ListAndWatch(wait.NeverStop) ids := []string{"foo", "bar", "baz", "qux", "zoo"} @@ -242,7 +242,7 @@ func TestReflectorListAndWatch(t *testing.T) { fw = <-createdFakes } sendingRV := strconv.FormatUint(uint64(i+2), 10) - fw.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: id, ResourceVersion: sendingRV}}) + fw.Add(&v1.Pod{ObjectMeta: v1.ObjectMeta{Name: id, ResourceVersion: sendingRV}}) if sendingRV == "3" { // Inject a failure. fw.Stop() @@ -252,7 +252,7 @@ func TestReflectorListAndWatch(t *testing.T) { // Verify we received the right ids with the right resource versions. for i, id := range ids { - pod := Pop(s).(*api.Pod) + pod := Pop(s).(*v1.Pod) if e, a := id, pod.Name; e != a { t.Errorf("%v: Expected %v, got %v", i, e, a) } @@ -267,18 +267,18 @@ func TestReflectorListAndWatch(t *testing.T) { } func TestReflectorListAndWatchWithErrors(t *testing.T) { - mkPod := func(id string, rv string) *api.Pod { - return &api.Pod{ObjectMeta: api.ObjectMeta{Name: id, ResourceVersion: rv}} + mkPod := func(id string, rv string) *v1.Pod { + return &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: id, ResourceVersion: rv}} } - mkList := func(rv string, pods ...*api.Pod) *api.PodList { - list := &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: rv}} + mkList := func(rv string, pods ...*v1.Pod) *v1.PodList { + list := &v1.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: rv}} for _, pod := range pods { list.Items = append(list.Items, *pod) } return list } table := []struct { - list *api.PodList + list *v1.PodList listErr error events []watch.Event watchErr error @@ -317,7 +317,7 @@ func TestReflectorListAndWatchWithErrors(t *testing.T) { current := s.List() checkMap := map[string]string{} for _, item := range current { - pod := item.(*api.Pod) + pod := item.(*v1.Pod) checkMap[pod.Name] = pod.ResourceVersion } for _, pod := range item.list.Items { @@ -331,7 +331,7 @@ func TestReflectorListAndWatchWithErrors(t *testing.T) { } watchRet, watchErr := item.events, item.watchErr lw := &testLW{ - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if watchErr != nil { return nil, watchErr } @@ -345,11 +345,11 @@ func TestReflectorListAndWatchWithErrors(t *testing.T) { }() return fw, nil }, - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return item.list, item.listErr }, } - r := NewReflector(lw, &api.Pod{}, s, 0) + r := NewReflector(lw, &v1.Pod{}, s, 0) r.ListAndWatch(wait.NeverStop) } } @@ -369,16 +369,16 @@ func TestReflectorResync(t *testing.T) { } lw := &testLW{ - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { fw := watch.NewFake() return fw, nil }, - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "0"}}, nil + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return &v1.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "0"}}, nil }, } resyncPeriod := 1 * time.Millisecond - r := NewReflector(lw, &api.Pod{}, s, resyncPeriod) + r := NewReflector(lw, &v1.Pod{}, s, resyncPeriod) if err := r.ListAndWatch(stopCh); err != nil { // error from Resync is not propaged up to here. t.Errorf("expected error %v", err) diff --git a/pkg/client/clientset_generated/internalclientset/typed/core/internalversion/BUILD b/pkg/client/clientset_generated/internalclientset/typed/core/internalversion/BUILD index 6ac76125649..6a1f9ab3db4 100644 --- a/pkg/client/clientset_generated/internalclientset/typed/core/internalversion/BUILD +++ b/pkg/client/clientset_generated/internalclientset/typed/core/internalversion/BUILD @@ -41,6 +41,7 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/fields:go_default_library", diff --git a/pkg/client/clientset_generated/internalclientset/typed/core/internalversion/event_expansion.go b/pkg/client/clientset_generated/internalclientset/typed/core/internalversion/event_expansion.go index 2d316aaed3e..569a47a78fb 100644 --- a/pkg/client/clientset_generated/internalclientset/typed/core/internalversion/event_expansion.go +++ b/pkg/client/clientset_generated/internalclientset/typed/core/internalversion/event_expansion.go @@ -20,6 +20,7 @@ import ( "fmt" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/runtime" ) @@ -148,14 +149,47 @@ type EventSinkImpl struct { Interface EventInterface } -func (e *EventSinkImpl) Create(event *api.Event) (*api.Event, error) { - return e.Interface.CreateWithEventNamespace(event) +func (e *EventSinkImpl) Create(event *v1.Event) (*v1.Event, error) { + internalEvent := &api.Event{} + err := v1.Convert_v1_Event_To_api_Event(event, internalEvent, nil) + if err != nil { + return nil, err + } + _, err = e.Interface.CreateWithEventNamespace(internalEvent) + if err != nil { + return nil, err + } + return event, nil } -func (e *EventSinkImpl) Update(event *api.Event) (*api.Event, error) { - return e.Interface.UpdateWithEventNamespace(event) +func (e *EventSinkImpl) Update(event *v1.Event) (*v1.Event, error) { + internalEvent := &api.Event{} + err := v1.Convert_v1_Event_To_api_Event(event, internalEvent, nil) + if err != nil { + return nil, err + } + _, err = e.Interface.UpdateWithEventNamespace(internalEvent) + if err != nil { + return nil, err + } + return event, nil } -func (e *EventSinkImpl) Patch(event *api.Event, data []byte) (*api.Event, error) { - return e.Interface.PatchWithEventNamespace(event, data) +func (e *EventSinkImpl) Patch(event *v1.Event, data []byte) (*v1.Event, error) { + internalEvent := &api.Event{} + err := v1.Convert_v1_Event_To_api_Event(event, internalEvent, nil) + if err != nil { + return nil, err + } + internalEvent, err = e.Interface.PatchWithEventNamespace(internalEvent, data) + if err != nil { + return nil, err + } + externalEvent := &v1.Event{} + err = v1.Convert_api_Event_To_v1_Event(internalEvent, externalEvent, nil) + if err != nil { + // Patch succeeded, no need to report the failed conversion + return event, nil + } + return externalEvent, nil } diff --git a/pkg/client/conditions/BUILD b/pkg/client/conditions/BUILD new file mode 100644 index 00000000000..b8789ade21e --- /dev/null +++ b/pkg/client/conditions/BUILD @@ -0,0 +1,23 @@ +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +load( + "@io_bazel_rules_go//go:def.bzl", + "go_binary", + "go_library", + "go_test", + "cgo_library", +) + +go_library( + name = "go_default_library", + srcs = ["conditions.go"], + tags = ["automanaged"], + deps = [ + "//pkg/api/errors:go_default_library", + "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/watch:go_default_library", + ], +) diff --git a/pkg/client/conditions/conditions.go b/pkg/client/conditions/conditions.go new file mode 100644 index 00000000000..8d304b48a89 --- /dev/null +++ b/pkg/client/conditions/conditions.go @@ -0,0 +1,164 @@ +/* +Copyright 2014 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package conditions + +import ( + "fmt" + + "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/watch" +) + +// ErrPodCompleted is returned by PodRunning or PodContainerRunning to indicate that +// the pod has already reached completed state. +var ErrPodCompleted = fmt.Errorf("pod ran to completion") + +// ErrContainerTerminated is returned by PodContainerRunning in the intermediate +// state where the pod indicates it's still running, but its container is already terminated +var ErrContainerTerminated = fmt.Errorf("container terminated") + +// PodRunning returns true if the pod is running, false if the pod has not yet reached running state, +// returns ErrPodCompleted if the pod has run to completion, or an error in any other case. +func PodRunning(event watch.Event) (bool, error) { + switch event.Type { + case watch.Deleted: + return false, errors.NewNotFound(unversioned.GroupResource{Resource: "pods"}, "") + } + switch t := event.Object.(type) { + case *v1.Pod: + switch t.Status.Phase { + case v1.PodRunning: + return true, nil + case v1.PodFailed, v1.PodSucceeded: + return false, ErrPodCompleted + } + } + return false, nil +} + +// PodCompleted returns true if the pod has run to completion, false if the pod has not yet +// reached running state, or an error in any other case. +func PodCompleted(event watch.Event) (bool, error) { + switch event.Type { + case watch.Deleted: + return false, errors.NewNotFound(unversioned.GroupResource{Resource: "pods"}, "") + } + switch t := event.Object.(type) { + case *v1.Pod: + switch t.Status.Phase { + case v1.PodFailed, v1.PodSucceeded: + return true, nil + } + } + return false, nil +} + +// PodRunningAndReady returns true if the pod is running and ready, false if the pod has not +// yet reached those states, returns ErrPodCompleted if the pod has run to completion, or +// an error in any other case. +func PodRunningAndReady(event watch.Event) (bool, error) { + switch event.Type { + case watch.Deleted: + return false, errors.NewNotFound(unversioned.GroupResource{Resource: "pods"}, "") + } + switch t := event.Object.(type) { + case *v1.Pod: + switch t.Status.Phase { + case v1.PodFailed, v1.PodSucceeded: + return false, ErrPodCompleted + case v1.PodRunning: + return v1.IsPodReady(t), nil + } + } + return false, nil +} + +// PodNotPending returns true if the pod has left the pending state, false if it has not, +// or an error in any other case (such as if the pod was deleted). +func PodNotPending(event watch.Event) (bool, error) { + switch event.Type { + case watch.Deleted: + return false, errors.NewNotFound(unversioned.GroupResource{Resource: "pods"}, "") + } + switch t := event.Object.(type) { + case *v1.Pod: + switch t.Status.Phase { + case v1.PodPending: + return false, nil + default: + return true, nil + } + } + return false, nil +} + +// PodContainerRunning returns false until the named container has ContainerStatus running (at least once), +// and will return an error if the pod is deleted, runs to completion, or the container pod is not available. +func PodContainerRunning(containerName string) watch.ConditionFunc { + return func(event watch.Event) (bool, error) { + switch event.Type { + case watch.Deleted: + return false, errors.NewNotFound(unversioned.GroupResource{Resource: "pods"}, "") + } + switch t := event.Object.(type) { + case *v1.Pod: + switch t.Status.Phase { + case v1.PodRunning, v1.PodPending: + case v1.PodFailed, v1.PodSucceeded: + return false, ErrPodCompleted + default: + return false, nil + } + for _, s := range t.Status.ContainerStatuses { + if s.Name != containerName { + continue + } + if s.State.Terminated != nil { + return false, ErrContainerTerminated + } + return s.State.Running != nil, nil + } + for _, s := range t.Status.InitContainerStatuses { + if s.Name != containerName { + continue + } + if s.State.Terminated != nil { + return false, ErrContainerTerminated + } + return s.State.Running != nil, nil + } + return false, nil + } + return false, nil + } +} + +// ServiceAccountHasSecrets returns true if the service account has at least one secret, +// false if it does not, or an error. +func ServiceAccountHasSecrets(event watch.Event) (bool, error) { + switch event.Type { + case watch.Deleted: + return false, errors.NewNotFound(unversioned.GroupResource{Resource: "serviceaccounts"}, "") + } + switch t := event.Object.(type) { + case *v1.ServiceAccount: + return len(t.Secrets) > 0, nil + } + return false, nil +} diff --git a/pkg/client/leaderelection/BUILD b/pkg/client/leaderelection/BUILD index a539ba56172..8ceffa3df0c 100644 --- a/pkg/client/leaderelection/BUILD +++ b/pkg/client/leaderelection/BUILD @@ -32,10 +32,10 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/leaderelection/resourcelock:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/testing/core:go_default_library", diff --git a/pkg/client/leaderelection/leaderelection_test.go b/pkg/client/leaderelection/leaderelection_test.go index 52ff99befe1..422b9179da8 100644 --- a/pkg/client/leaderelection/leaderelection_test.go +++ b/pkg/client/leaderelection/leaderelection_test.go @@ -26,10 +26,10 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - fakeclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + fakeclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" rl "k8s.io/kubernetes/pkg/client/leaderelection/resourcelock" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/testing/core" @@ -67,7 +67,7 @@ func TestTryAcquireOrRenew(t *testing.T) { { verb: "create", reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, action.(core.CreateAction).GetObject().(*api.Endpoints), nil + return true, action.(core.CreateAction).GetObject().(*v1.Endpoints), nil }, }, }, @@ -83,8 +83,8 @@ func TestTryAcquireOrRenew(t *testing.T) { { verb: "get", reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + return true, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Namespace: action.GetNamespace(), Name: action.(core.GetAction).GetName(), }, @@ -94,7 +94,7 @@ func TestTryAcquireOrRenew(t *testing.T) { { verb: "update", reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, action.(core.CreateAction).GetObject().(*api.Endpoints), nil + return true, action.(core.CreateAction).GetObject().(*v1.Endpoints), nil }, }, }, @@ -112,8 +112,8 @@ func TestTryAcquireOrRenew(t *testing.T) { { verb: "get", reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + return true, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Namespace: action.GetNamespace(), Name: action.(core.GetAction).GetName(), Annotations: map[string]string{ @@ -126,7 +126,7 @@ func TestTryAcquireOrRenew(t *testing.T) { { verb: "update", reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, action.(core.CreateAction).GetObject().(*api.Endpoints), nil + return true, action.(core.CreateAction).GetObject().(*v1.Endpoints), nil }, }, }, @@ -146,8 +146,8 @@ func TestTryAcquireOrRenew(t *testing.T) { { verb: "get", reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + return true, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Namespace: action.GetNamespace(), Name: action.(core.GetAction).GetName(), Annotations: map[string]string{ @@ -172,8 +172,8 @@ func TestTryAcquireOrRenew(t *testing.T) { { verb: "get", reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + return true, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Namespace: action.GetNamespace(), Name: action.(core.GetAction).GetName(), Annotations: map[string]string{ @@ -186,7 +186,7 @@ func TestTryAcquireOrRenew(t *testing.T) { { verb: "update", reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, action.(core.CreateAction).GetObject().(*api.Endpoints), nil + return true, action.(core.CreateAction).GetObject().(*v1.Endpoints), nil }, }, }, @@ -205,7 +205,7 @@ func TestTryAcquireOrRenew(t *testing.T) { var reportedLeader string lock := rl.EndpointsLock{ - EndpointsMeta: api.ObjectMeta{Namespace: "foo", Name: "bar"}, + EndpointsMeta: v1.ObjectMeta{Namespace: "foo", Name: "bar"}, LockConfig: rl.ResourceLockConfig{ Identity: "baz", EventRecorder: &record.FakeRecorder{}, diff --git a/pkg/client/leaderelection/resourcelock/BUILD b/pkg/client/leaderelection/resourcelock/BUILD index 3daed466a5b..3e1077b516f 100644 --- a/pkg/client/leaderelection/resourcelock/BUILD +++ b/pkg/client/leaderelection/resourcelock/BUILD @@ -18,9 +18,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/record:go_default_library", ], ) diff --git a/pkg/client/leaderelection/resourcelock/endpointslock.go b/pkg/client/leaderelection/resourcelock/endpointslock.go index 56749661df0..9ebd12af5c4 100644 --- a/pkg/client/leaderelection/resourcelock/endpointslock.go +++ b/pkg/client/leaderelection/resourcelock/endpointslock.go @@ -21,17 +21,17 @@ import ( "errors" "fmt" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" ) type EndpointsLock struct { // EndpointsMeta should contain a Name and a Namespace of an // Endpoints object that the LeaderElector will attempt to lead. - EndpointsMeta api.ObjectMeta + EndpointsMeta v1.ObjectMeta Client clientset.Interface LockConfig ResourceLockConfig - e *api.Endpoints + e *v1.Endpoints } func (el *EndpointsLock) Get() (*LeaderElectionRecord, error) { @@ -58,8 +58,8 @@ func (el *EndpointsLock) Create(ler LeaderElectionRecord) error { if err != nil { return err } - el.e, err = el.Client.Core().Endpoints(el.EndpointsMeta.Namespace).Create(&api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + el.e, err = el.Client.Core().Endpoints(el.EndpointsMeta.Namespace).Create(&v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: el.EndpointsMeta.Name, Namespace: el.EndpointsMeta.Namespace, Annotations: map[string]string{ @@ -87,7 +87,7 @@ func (el *EndpointsLock) Update(ler LeaderElectionRecord) error { // RecordEvent in leader election while adding meta-data func (el *EndpointsLock) RecordEvent(s string) { events := fmt.Sprintf("%v %v", el.LockConfig.Identity, s) - el.LockConfig.EventRecorder.Eventf(&api.Endpoints{ObjectMeta: el.e.ObjectMeta}, api.EventTypeNormal, "LeaderElection", events) + el.LockConfig.EventRecorder.Eventf(&v1.Endpoints{ObjectMeta: el.e.ObjectMeta}, v1.EventTypeNormal, "LeaderElection", events) } // Describe is used to convert details on current resource lock diff --git a/pkg/client/listers/batch/v1/BUILD b/pkg/client/listers/batch/v1/BUILD index b7174eafc61..77698b69e4f 100644 --- a/pkg/client/listers/batch/v1/BUILD +++ b/pkg/client/listers/batch/v1/BUILD @@ -15,10 +15,13 @@ go_library( srcs = [ "expansion_generated.go", "job.go", + "job_expansion.go", ], tags = ["automanaged"], deps = [ "//pkg/api/errors:go_default_library", + "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/batch:go_default_library", "//pkg/apis/batch/v1:go_default_library", "//pkg/client/cache:go_default_library", diff --git a/pkg/client/listers/batch/v1/expansion_generated.go b/pkg/client/listers/batch/v1/expansion_generated.go index 14ac2777652..c9652cbfe9a 100644 --- a/pkg/client/listers/batch/v1/expansion_generated.go +++ b/pkg/client/listers/batch/v1/expansion_generated.go @@ -17,11 +17,3 @@ limitations under the License. // This file was automatically generated by lister-gen with arguments: --input-dirs=[k8s.io/kubernetes/pkg/api,k8s.io/kubernetes/pkg/api/v1,k8s.io/kubernetes/pkg/apis/abac,k8s.io/kubernetes/pkg/apis/abac/v0,k8s.io/kubernetes/pkg/apis/abac/v1beta1,k8s.io/kubernetes/pkg/apis/apps,k8s.io/kubernetes/pkg/apis/apps/v1beta1,k8s.io/kubernetes/pkg/apis/authentication,k8s.io/kubernetes/pkg/apis/authentication/v1beta1,k8s.io/kubernetes/pkg/apis/authorization,k8s.io/kubernetes/pkg/apis/authorization/v1beta1,k8s.io/kubernetes/pkg/apis/autoscaling,k8s.io/kubernetes/pkg/apis/autoscaling/v1,k8s.io/kubernetes/pkg/apis/batch,k8s.io/kubernetes/pkg/apis/batch/v1,k8s.io/kubernetes/pkg/apis/batch/v2alpha1,k8s.io/kubernetes/pkg/apis/certificates,k8s.io/kubernetes/pkg/apis/certificates/v1alpha1,k8s.io/kubernetes/pkg/apis/componentconfig,k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1,k8s.io/kubernetes/pkg/apis/extensions,k8s.io/kubernetes/pkg/apis/extensions/v1beta1,k8s.io/kubernetes/pkg/apis/imagepolicy,k8s.io/kubernetes/pkg/apis/imagepolicy/v1alpha1,k8s.io/kubernetes/pkg/apis/policy,k8s.io/kubernetes/pkg/apis/policy/v1alpha1,k8s.io/kubernetes/pkg/apis/policy/v1beta1,k8s.io/kubernetes/pkg/apis/rbac,k8s.io/kubernetes/pkg/apis/rbac/v1alpha1,k8s.io/kubernetes/pkg/apis/storage,k8s.io/kubernetes/pkg/apis/storage/v1beta1] package v1 - -// JobListerExpansion allows custom methods to be added to -// JobLister. -type JobListerExpansion interface{} - -// JobNamespaceListerExpansion allows custom methods to be added to -// JobNamespaeLister. -type JobNamespaceListerExpansion interface{} diff --git a/pkg/client/listers/batch/v1/job_expansion.go b/pkg/client/listers/batch/v1/job_expansion.go new file mode 100644 index 00000000000..cfded28c34a --- /dev/null +++ b/pkg/client/listers/batch/v1/job_expansion.go @@ -0,0 +1,64 @@ +/* +Copyright 2016 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1 + +import ( + "fmt" + + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + batch "k8s.io/kubernetes/pkg/apis/batch/v1" + "k8s.io/kubernetes/pkg/labels" +) + +// JobListerExpansion allows custom methods to be added to +// JobLister. +type JobListerExpansion interface { + // GetPodJobs returns a list of jobs managing a pod. An error is returned only + // if no matching jobs are found. + GetPodJobs(pod *v1.Pod) (jobs []batch.Job, err error) +} + +// GetPodJobs returns a list of jobs managing a pod. An error is returned only +// if no matching jobs are found. +func (l *jobLister) GetPodJobs(pod *v1.Pod) (jobs []batch.Job, err error) { + if len(pod.Labels) == 0 { + err = fmt.Errorf("no jobs found for pod %v because it has no labels", pod.Name) + return + } + + var list []*batch.Job + list, err = l.Jobs(pod.Namespace).List(labels.Everything()) + if err != nil { + return + } + for _, job := range list { + selector, _ := unversioned.LabelSelectorAsSelector(job.Spec.Selector) + if !selector.Matches(labels.Set(pod.Labels)) { + continue + } + jobs = append(jobs, *job) + } + if len(jobs) == 0 { + err = fmt.Errorf("could not find jobs for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) + } + return +} + +// JobNamespaceListerExpansion allows custom methods to be added to +// JobNamespaceLister. +type JobNamespaceListerExpansion interface{} diff --git a/pkg/client/record/BUILD b/pkg/client/record/BUILD index 6679d725c17..37161fcc6f7 100644 --- a/pkg/client/record/BUILD +++ b/pkg/client/record/BUILD @@ -20,9 +20,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/runtime:go_default_library", "//pkg/util/clock:go_default_library", @@ -44,10 +44,10 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/install:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/runtime:go_default_library", "//pkg/util/clock:go_default_library", diff --git a/pkg/client/record/event.go b/pkg/client/record/event.go index 55873a73d94..e3daba2af60 100644 --- a/pkg/client/record/event.go +++ b/pkg/client/record/event.go @@ -21,9 +21,9 @@ import ( "math/rand" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/clock" @@ -46,9 +46,9 @@ const maxQueuedEvents = 1000 // It is assumed that EventSink will return the same sorts of errors as // pkg/client's REST client. type EventSink interface { - Create(event *api.Event) (*api.Event, error) - Update(event *api.Event) (*api.Event, error) - Patch(oldEvent *api.Event, data []byte) (*api.Event, error) + Create(event *v1.Event) (*v1.Event, error) + Update(event *v1.Event) (*v1.Event, error) + Patch(oldEvent *v1.Event, data []byte) (*v1.Event, error) } // EventRecorder knows how to record events on behalf of an EventSource. @@ -78,7 +78,7 @@ type EventBroadcaster interface { // StartEventWatcher starts sending events received from this EventBroadcaster to the given // event handler function. The return value can be ignored or used to stop recording, if // desired. - StartEventWatcher(eventHandler func(*api.Event)) watch.Interface + StartEventWatcher(eventHandler func(*v1.Event)) watch.Interface // StartRecordingToSink starts sending events received from this EventBroadcaster to the given // sink. The return value can be ignored or used to stop recording, if desired. @@ -90,7 +90,7 @@ type EventBroadcaster interface { // NewRecorder returns an EventRecorder that can be used to send events to this EventBroadcaster // with the event source set to the given event source. - NewRecorder(source api.EventSource) EventRecorder + NewRecorder(source v1.EventSource) EventRecorder } // Creates a new event broadcaster. @@ -116,12 +116,12 @@ func (eventBroadcaster *eventBroadcasterImpl) StartRecordingToSink(sink EventSin randGen := rand.New(rand.NewSource(time.Now().UnixNano())) eventCorrelator := NewEventCorrelator(clock.RealClock{}) return eventBroadcaster.StartEventWatcher( - func(event *api.Event) { + func(event *v1.Event) { recordToSink(sink, event, eventCorrelator, randGen, eventBroadcaster.sleepDuration) }) } -func recordToSink(sink EventSink, event *api.Event, eventCorrelator *EventCorrelator, randGen *rand.Rand, sleepDuration time.Duration) { +func recordToSink(sink EventSink, event *v1.Event, eventCorrelator *EventCorrelator, randGen *rand.Rand, sleepDuration time.Duration) { // Make a copy before modification, because there could be multiple listeners. // Events are safe to copy like this. eventCopy := *event @@ -167,8 +167,8 @@ func isKeyNotFoundError(err error) bool { // was successfully recorded or discarded, false if it should be retried. // If updateExistingEvent is false, it creates a new event, otherwise it updates // existing event. -func recordEvent(sink EventSink, event *api.Event, patch []byte, updateExistingEvent bool, eventCorrelator *EventCorrelator) bool { - var newEvent *api.Event +func recordEvent(sink EventSink, event *v1.Event, patch []byte, updateExistingEvent bool, eventCorrelator *EventCorrelator) bool { + var newEvent *v1.Event var err error if updateExistingEvent { newEvent, err = sink.Patch(event, patch) @@ -213,14 +213,14 @@ func recordEvent(sink EventSink, event *api.Event, patch []byte, updateExistingE // The return value can be ignored or used to stop recording, if desired. func (eventBroadcaster *eventBroadcasterImpl) StartLogging(logf func(format string, args ...interface{})) watch.Interface { return eventBroadcaster.StartEventWatcher( - func(e *api.Event) { + func(e *v1.Event) { logf("Event(%#v): type: '%v' reason: '%v' %v", e.InvolvedObject, e.Type, e.Reason, e.Message) }) } // StartEventWatcher starts sending events received from this EventBroadcaster to the given event handler function. // The return value can be ignored or used to stop recording, if desired. -func (eventBroadcaster *eventBroadcasterImpl) StartEventWatcher(eventHandler func(*api.Event)) watch.Interface { +func (eventBroadcaster *eventBroadcasterImpl) StartEventWatcher(eventHandler func(*v1.Event)) watch.Interface { watcher := eventBroadcaster.Watch() go func() { defer utilruntime.HandleCrash() @@ -229,7 +229,7 @@ func (eventBroadcaster *eventBroadcasterImpl) StartEventWatcher(eventHandler fun if !open { return } - event, ok := watchEvent.Object.(*api.Event) + event, ok := watchEvent.Object.(*v1.Event) if !ok { // This is all local, so there's no reason this should // ever happen. @@ -242,18 +242,18 @@ func (eventBroadcaster *eventBroadcasterImpl) StartEventWatcher(eventHandler fun } // NewRecorder returns an EventRecorder that records events with the given event source. -func (eventBroadcaster *eventBroadcasterImpl) NewRecorder(source api.EventSource) EventRecorder { +func (eventBroadcaster *eventBroadcasterImpl) NewRecorder(source v1.EventSource) EventRecorder { return &recorderImpl{source, eventBroadcaster.Broadcaster, clock.RealClock{}} } type recorderImpl struct { - source api.EventSource + source v1.EventSource *watch.Broadcaster clock clock.Clock } func (recorder *recorderImpl) generateEvent(object runtime.Object, timestamp unversioned.Time, eventtype, reason, message string) { - ref, err := api.GetReference(object) + ref, err := v1.GetReference(object) if err != nil { glog.Errorf("Could not construct reference to: '%#v' due to: '%v'. Will not report event: '%v' '%v' '%v'", object, err, eventtype, reason, message) return @@ -276,7 +276,7 @@ func (recorder *recorderImpl) generateEvent(object runtime.Object, timestamp unv func validateEventType(eventtype string) bool { switch eventtype { - case api.EventTypeNormal, api.EventTypeWarning: + case v1.EventTypeNormal, v1.EventTypeWarning: return true } return false @@ -294,14 +294,14 @@ func (recorder *recorderImpl) PastEventf(object runtime.Object, timestamp unvers recorder.generateEvent(object, timestamp, eventtype, reason, fmt.Sprintf(messageFmt, args...)) } -func (recorder *recorderImpl) makeEvent(ref *api.ObjectReference, eventtype, reason, message string) *api.Event { +func (recorder *recorderImpl) makeEvent(ref *v1.ObjectReference, eventtype, reason, message string) *v1.Event { t := unversioned.Time{Time: recorder.clock.Now()} namespace := ref.Namespace if namespace == "" { - namespace = api.NamespaceDefault + namespace = v1.NamespaceDefault } - return &api.Event{ - ObjectMeta: api.ObjectMeta{ + return &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: fmt.Sprintf("%v.%x", ref.Name, t.UnixNano()), Namespace: namespace, }, diff --git a/pkg/client/record/event_test.go b/pkg/client/record/event_test.go index c10dde47f47..fa50936f399 100644 --- a/pkg/client/record/event_test.go +++ b/pkg/client/record/event_test.go @@ -25,10 +25,10 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" _ "k8s.io/kubernetes/pkg/api/install" // To register api.Pod used in tests below "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/restclient" k8sruntime "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/clock" @@ -36,13 +36,13 @@ import ( ) 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) + OnCreate func(e *v1.Event) (*v1.Event, error) + OnUpdate func(e *v1.Event) (*v1.Event, error) + OnPatch func(e *v1.Event, p []byte) (*v1.Event, error) } // CreateEvent records the event for testing. -func (t *testEventSink) Create(e *api.Event) (*api.Event, error) { +func (t *testEventSink) Create(e *v1.Event) (*v1.Event, error) { if t.OnCreate != nil { return t.OnCreate(e) } @@ -50,7 +50,7 @@ func (t *testEventSink) Create(e *api.Event) (*api.Event, error) { } // UpdateEvent records the event for testing. -func (t *testEventSink) Update(e *api.Event) (*api.Event, error) { +func (t *testEventSink) Update(e *v1.Event) (*v1.Event, error) { if t.OnUpdate != nil { return t.OnUpdate(e) } @@ -58,27 +58,27 @@ func (t *testEventSink) Update(e *api.Event) (*api.Event, error) { } // PatchEvent records the event for testing. -func (t *testEventSink) Patch(e *api.Event, p []byte) (*api.Event, error) { +func (t *testEventSink) Patch(e *v1.Event, p []byte) (*v1.Event, error) { if t.OnPatch != nil { return t.OnPatch(e, p) } return e, nil } -type OnCreateFunc func(*api.Event) (*api.Event, error) +type OnCreateFunc func(*v1.Event) (*v1.Event, error) -func OnCreateFactory(testCache map[string]*api.Event, createEvent chan<- *api.Event) OnCreateFunc { - return func(event *api.Event) (*api.Event, error) { +func OnCreateFactory(testCache map[string]*v1.Event, createEvent chan<- *v1.Event) OnCreateFunc { + return func(event *v1.Event) (*v1.Event, error) { testCache[getEventKey(event)] = event createEvent <- event return event, nil } } -type OnPatchFunc func(*api.Event, []byte) (*api.Event, error) +type OnPatchFunc func(*v1.Event, []byte) (*v1.Event, error) -func OnPatchFactory(testCache map[string]*api.Event, patchEvent chan<- *api.Event) OnPatchFunc { - return func(event *api.Event, patch []byte) (*api.Event, error) { +func OnPatchFactory(testCache map[string]*v1.Event, patchEvent chan<- *v1.Event) OnPatchFunc { + return func(event *v1.Event, patch []byte) (*v1.Event, error) { cachedEvent, found := testCache[getEventKey(event)] if !found { return nil, fmt.Errorf("unexpected error: couldn't find Event in testCache.") @@ -91,7 +91,7 @@ func OnPatchFactory(testCache map[string]*api.Event, patchEvent chan<- *api.Even if err != nil { return nil, fmt.Errorf("unexpected error: %v", err) } - patchedObj := &api.Event{} + patchedObj := &v1.Event{} err = json.Unmarshal(patched, patchedObj) if err != nil { return nil, fmt.Errorf("unexpected error: %v", err) @@ -102,24 +102,24 @@ func OnPatchFactory(testCache map[string]*api.Event, patchEvent chan<- *api.Even } func TestEventf(t *testing.T) { - testPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + testPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ SelfLink: "/api/version/pods/foo", Name: "foo", Namespace: "baz", UID: "bar", }, } - testPod2 := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + testPod2 := &v1.Pod{ + ObjectMeta: v1.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]") + testRef, err := v1.GetPartialReference(testPod, "spec.containers[2]") + testRef2, err := v1.GetPartialReference(testPod2, "spec.containers[3]") if err != nil { t.Fatal(err) } @@ -129,22 +129,22 @@ func TestEventf(t *testing.T) { reason string messageFmt string elements []interface{} - expect *api.Event + expect *v1.Event expectLog string expectUpdate bool }{ { obj: testRef, - eventtype: api.EventTypeNormal, + eventtype: v1.EventTypeNormal, reason: "Started", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -154,25 +154,25 @@ func TestEventf(t *testing.T) { }, Reason: "Started", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 1, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Killed", messageFmt: "some other verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -181,25 +181,25 @@ func TestEventf(t *testing.T) { }, Reason: "Killed", Message: "some other verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 1, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Started", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -209,25 +209,25 @@ func TestEventf(t *testing.T) { }, Reason: "Started", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 2, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Started", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -237,25 +237,25 @@ func TestEventf(t *testing.T) { }, Reason: "Started", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 1, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Started", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -265,25 +265,25 @@ func TestEventf(t *testing.T) { }, Reason: "Started", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 3, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Stopped", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -293,25 +293,25 @@ func TestEventf(t *testing.T) { }, Reason: "Stopped", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 1, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Stopped", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -321,23 +321,23 @@ func TestEventf(t *testing.T) { }, Reason: "Stopped", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 2, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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{} + testCache := map[string]*v1.Event{} logCalled := make(chan struct{}) - createEvent := make(chan *api.Event) - updateEvent := make(chan *api.Event) - patchEvent := make(chan *api.Event) + createEvent := make(chan *v1.Event) + updateEvent := make(chan *v1.Event) + patchEvent := make(chan *v1.Event) testEvents := testEventSink{ OnCreate: OnCreateFactory(testCache, createEvent), - OnUpdate: func(event *api.Event) (*api.Event, error) { + OnUpdate: func(event *v1.Event) (*v1.Event, error) { updateEvent <- event return event, nil }, @@ -347,7 +347,7 @@ func TestEventf(t *testing.T) { sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents) clock := clock.NewFakeClock(time.Now()) - recorder := recorderWithFakeClock(api.EventSource{Component: "eventTest"}, eventBroadcaster, clock) + recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock) for index, item := range table { clock.Step(1 * time.Second) logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) { @@ -373,7 +373,7 @@ func TestEventf(t *testing.T) { sinkWatcher.Stop() } -func recorderWithFakeClock(eventSource api.EventSource, eventBroadcaster EventBroadcaster, clock clock.Clock) EventRecorder { +func recorderWithFakeClock(eventSource v1.EventSource, eventBroadcaster EventBroadcaster, clock clock.Clock) EventRecorder { return &recorderImpl{eventSource, eventBroadcaster.(*eventBroadcasterImpl).Broadcaster, clock} } @@ -417,7 +417,7 @@ func TestWriteEventError(t *testing.T) { for caseName, ent := range table { attempts := 0 sink := &testEventSink{ - OnCreate: func(event *api.Event) (*api.Event, error) { + OnCreate: func(event *v1.Event) (*v1.Event, error) { attempts++ if attempts < ent.timesToSendError { return nil, ent.err @@ -425,7 +425,7 @@ func TestWriteEventError(t *testing.T) { return event, nil }, } - ev := &api.Event{} + ev := &v1.Event{} recordToSink(sink, ev, eventCorrelator, randGen, 0) if attempts != ent.attemptsWanted { t.Errorf("case %v: wanted %d, got %d attempts", caseName, ent.attemptsWanted, attempts) @@ -437,23 +437,23 @@ func TestUpdateExpiredEvent(t *testing.T) { eventCorrelator := NewEventCorrelator(clock.RealClock{}) randGen := rand.New(rand.NewSource(time.Now().UnixNano())) - var createdEvent *api.Event + var createdEvent *v1.Event sink := &testEventSink{ - OnPatch: func(*api.Event, []byte) (*api.Event, error) { + OnPatch: func(*v1.Event, []byte) (*v1.Event, error) { return nil, &errors.StatusError{ ErrStatus: unversioned.Status{ Code: http.StatusNotFound, Reason: unversioned.StatusReasonNotFound, }} }, - OnCreate: func(event *api.Event) (*api.Event, error) { + OnCreate: func(event *v1.Event) (*v1.Event, error) { createdEvent = event return event, nil }, } - ev := &api.Event{} + ev := &v1.Event{} ev.ResourceVersion = "updated-resource-version" ev.Count = 2 recordToSink(sink, ev, eventCorrelator, randGen, 0) @@ -475,7 +475,7 @@ func TestLotsOfEvents(t *testing.T) { // 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) { + OnCreate: func(event *v1.Event) (*v1.Event, error) { num, err := strconv.Atoi(event.Message) if err != nil { t.Error(err) @@ -495,8 +495,8 @@ func TestLotsOfEvents(t *testing.T) { logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) { loggerCalled <- struct{}{} }) - recorder := eventBroadcaster.NewRecorder(api.EventSource{Component: "eventTest"}) - ref := &api.ObjectReference{ + recorder := eventBroadcaster.NewRecorder(v1.EventSource{Component: "eventTest"}) + ref := &v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -505,7 +505,7 @@ func TestLotsOfEvents(t *testing.T) { } 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)) + go recorder.Eventf(ref, v1.EventTypeNormal, "Reason-"+string(i), strconv.Itoa(i)) } // Make sure no events were dropped by either of the listeners. for i := 0; i < maxQueuedEvents; i++ { @@ -523,14 +523,14 @@ func TestLotsOfEvents(t *testing.T) { } func TestEventfNoNamespace(t *testing.T) { - testPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + testPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ SelfLink: "/api/version/pods/foo", Name: "foo", UID: "bar", }, } - testRef, err := api.GetPartialReference(testPod, "spec.containers[2]") + testRef, err := v1.GetPartialReference(testPod, "spec.containers[2]") if err != nil { t.Fatal(err) } @@ -540,22 +540,22 @@ func TestEventfNoNamespace(t *testing.T) { reason string messageFmt string elements []interface{} - expect *api.Event + expect *v1.Event expectLog string expectUpdate bool }{ { obj: testRef, - eventtype: api.EventTypeNormal, + eventtype: v1.EventTypeNormal, reason: "Started", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "default", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "", @@ -565,23 +565,23 @@ func TestEventfNoNamespace(t *testing.T) { }, Reason: "Started", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 1, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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{} + testCache := map[string]*v1.Event{} logCalled := make(chan struct{}) - createEvent := make(chan *api.Event) - updateEvent := make(chan *api.Event) - patchEvent := make(chan *api.Event) + createEvent := make(chan *v1.Event) + updateEvent := make(chan *v1.Event) + patchEvent := make(chan *v1.Event) testEvents := testEventSink{ OnCreate: OnCreateFactory(testCache, createEvent), - OnUpdate: func(event *api.Event) (*api.Event, error) { + OnUpdate: func(event *v1.Event) (*v1.Event, error) { updateEvent <- event return event, nil }, @@ -591,7 +591,7 @@ func TestEventfNoNamespace(t *testing.T) { sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents) clock := clock.NewFakeClock(time.Now()) - recorder := recorderWithFakeClock(api.EventSource{Component: "eventTest"}, eventBroadcaster, clock) + recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock) for index, item := range table { clock.Step(1 * time.Second) @@ -620,24 +620,24 @@ func TestEventfNoNamespace(t *testing.T) { } func TestMultiSinkCache(t *testing.T) { - testPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + testPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ SelfLink: "/api/version/pods/foo", Name: "foo", Namespace: "baz", UID: "bar", }, } - testPod2 := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + testPod2 := &v1.Pod{ + ObjectMeta: v1.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]") + testRef, err := v1.GetPartialReference(testPod, "spec.containers[2]") + testRef2, err := v1.GetPartialReference(testPod2, "spec.containers[3]") if err != nil { t.Fatal(err) } @@ -647,22 +647,22 @@ func TestMultiSinkCache(t *testing.T) { reason string messageFmt string elements []interface{} - expect *api.Event + expect *v1.Event expectLog string expectUpdate bool }{ { obj: testRef, - eventtype: api.EventTypeNormal, + eventtype: v1.EventTypeNormal, reason: "Started", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -672,25 +672,25 @@ func TestMultiSinkCache(t *testing.T) { }, Reason: "Started", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 1, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Killed", messageFmt: "some other verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -699,25 +699,25 @@ func TestMultiSinkCache(t *testing.T) { }, Reason: "Killed", Message: "some other verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 1, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Started", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -727,25 +727,25 @@ func TestMultiSinkCache(t *testing.T) { }, Reason: "Started", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 2, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Started", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -755,25 +755,25 @@ func TestMultiSinkCache(t *testing.T) { }, Reason: "Started", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 1, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Started", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -783,25 +783,25 @@ func TestMultiSinkCache(t *testing.T) { }, Reason: "Started", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 3, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Stopped", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -811,25 +811,25 @@ func TestMultiSinkCache(t *testing.T) { }, Reason: "Stopped", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 1, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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, + eventtype: v1.EventTypeNormal, reason: "Stopped", messageFmt: "some verbose message: %v", elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ + expect: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: "baz", }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", @@ -839,35 +839,35 @@ func TestMultiSinkCache(t *testing.T) { }, Reason: "Stopped", Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, + Source: v1.EventSource{Component: "eventTest"}, Count: 2, - Type: api.EventTypeNormal, + Type: v1.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`, + expectLog: `Event(v1.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) + testCache := map[string]*v1.Event{} + createEvent := make(chan *v1.Event) + updateEvent := make(chan *v1.Event) + patchEvent := make(chan *v1.Event) testEvents := testEventSink{ OnCreate: OnCreateFactory(testCache, createEvent), - OnUpdate: func(event *api.Event) (*api.Event, error) { + OnUpdate: func(event *v1.Event) (*v1.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) + testCache2 := map[string]*v1.Event{} + createEvent2 := make(chan *v1.Event) + updateEvent2 := make(chan *v1.Event) + patchEvent2 := make(chan *v1.Event) testEvents2 := testEventSink{ OnCreate: OnCreateFactory(testCache2, createEvent2), - OnUpdate: func(event *api.Event) (*api.Event, error) { + OnUpdate: func(event *v1.Event) (*v1.Event, error) { updateEvent2 <- event return event, nil }, @@ -876,7 +876,7 @@ func TestMultiSinkCache(t *testing.T) { eventBroadcaster := NewBroadcasterForTests(0) clock := clock.NewFakeClock(time.Now()) - recorder := recorderWithFakeClock(api.EventSource{Component: "eventTest"}, eventBroadcaster, clock) + recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock) sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents) for index, item := range table { diff --git a/pkg/client/record/events_cache.go b/pkg/client/record/events_cache.go index 8ff65776cb1..5b1d84a42c8 100644 --- a/pkg/client/record/events_cache.go +++ b/pkg/client/record/events_cache.go @@ -25,8 +25,8 @@ import ( "github.com/golang/groupcache/lru" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/clock" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/strategicpatch" @@ -42,7 +42,7 @@ const ( ) // getEventKey builds unique event key based on source, involvedObject, reason, message -func getEventKey(event *api.Event) string { +func getEventKey(event *v1.Event) string { return strings.Join([]string{ event.Source.Component, event.Source.Host, @@ -59,10 +59,10 @@ func getEventKey(event *api.Event) string { } // EventFilterFunc is a function that returns true if the event should be skipped -type EventFilterFunc func(event *api.Event) bool +type EventFilterFunc func(event *v1.Event) bool // DefaultEventFilterFunc returns false for all incoming events -func DefaultEventFilterFunc(event *api.Event) bool { +func DefaultEventFilterFunc(event *v1.Event) bool { return false } @@ -70,10 +70,10 @@ func DefaultEventFilterFunc(event *api.Event) bool { // It returns a tuple of the following: // aggregateKey - key the identifies the aggregate group to bucket this event // localKey - key that makes this event in the local group -type EventAggregatorKeyFunc func(event *api.Event) (aggregateKey string, localKey string) +type EventAggregatorKeyFunc func(event *v1.Event) (aggregateKey string, localKey string) // EventAggregatorByReasonFunc aggregates events by exact match on event.Source, event.InvolvedObject, event.Type and event.Reason -func EventAggregatorByReasonFunc(event *api.Event) (string, string) { +func EventAggregatorByReasonFunc(event *v1.Event) (string, string) { return strings.Join([]string{ event.Source.Component, event.Source.Host, @@ -89,10 +89,10 @@ func EventAggregatorByReasonFunc(event *api.Event) (string, string) { } // EventAggregatorMessageFunc is responsible for producing an aggregation message -type EventAggregatorMessageFunc func(event *api.Event) string +type EventAggregatorMessageFunc func(event *v1.Event) string // EventAggregratorByReasonMessageFunc returns an aggregate message by prefixing the incoming message -func EventAggregatorByReasonMessageFunc(event *api.Event) string { +func EventAggregatorByReasonMessageFunc(event *v1.Event) string { return "(events with common reason combined)" } @@ -142,7 +142,7 @@ type aggregateRecord struct { } // EventAggregate identifies similar events and groups into a common event if required -func (e *EventAggregator) EventAggregate(newEvent *api.Event) (*api.Event, error) { +func (e *EventAggregator) EventAggregate(newEvent *v1.Event) (*v1.Event, error) { aggregateKey, localKey := e.keyFunc(newEvent) now := unversioned.NewTime(e.clock.Now()) record := aggregateRecord{localKeys: sets.NewString(), lastTimestamp: now} @@ -171,8 +171,8 @@ func (e *EventAggregator) EventAggregate(newEvent *api.Event) (*api.Event, error record.localKeys.PopAny() // create a new aggregate event - eventCopy := &api.Event{ - ObjectMeta: api.ObjectMeta{ + eventCopy := &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: fmt.Sprintf("%v.%x", newEvent.InvolvedObject.Name, now.UnixNano()), Namespace: newEvent.Namespace, }, @@ -216,7 +216,7 @@ func newEventLogger(lruCacheEntries int, clock clock.Clock) *eventLogger { } // eventObserve records the event, and determines if its frequency should update -func (e *eventLogger) eventObserve(newEvent *api.Event) (*api.Event, []byte, error) { +func (e *eventLogger) eventObserve(newEvent *v1.Event) (*v1.Event, []byte, error) { var ( patch []byte err error @@ -261,7 +261,7 @@ func (e *eventLogger) eventObserve(newEvent *api.Event) (*api.Event, []byte, err } // updateState updates its internal tracking information based on latest server state -func (e *eventLogger) updateState(event *api.Event) { +func (e *eventLogger) updateState(event *v1.Event) { key := getEventKey(event) e.Lock() defer e.Unlock() @@ -305,7 +305,7 @@ type EventCorrelator struct { // EventCorrelateResult is the result of a Correlate type EventCorrelateResult struct { // the event after correlation - Event *api.Event + Event *v1.Event // if provided, perform a strategic patch when updating the record on the server Patch []byte // if true, do no further processing of the event @@ -342,7 +342,7 @@ func NewEventCorrelator(clock clock.Clock) *EventCorrelator { } // EventCorrelate filters, aggregates, counts, and de-duplicates all incoming events -func (c *EventCorrelator) EventCorrelate(newEvent *api.Event) (*EventCorrelateResult, error) { +func (c *EventCorrelator) EventCorrelate(newEvent *v1.Event) (*EventCorrelateResult, error) { if c.filterFunc(newEvent) { return &EventCorrelateResult{Skip: true}, nil } @@ -355,6 +355,6 @@ func (c *EventCorrelator) EventCorrelate(newEvent *api.Event) (*EventCorrelateRe } // UpdateState based on the latest observed state from server -func (c *EventCorrelator) UpdateState(event *api.Event) { +func (c *EventCorrelator) UpdateState(event *v1.Event) { c.logger.updateState(event) } diff --git a/pkg/client/record/events_cache_test.go b/pkg/client/record/events_cache_test.go index 0a9d15265ba..7b7b5036a78 100644 --- a/pkg/client/record/events_cache_test.go +++ b/pkg/client/record/events_cache_test.go @@ -22,14 +22,14 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/clock" "k8s.io/kubernetes/pkg/util/diff" ) -func makeObjectReference(kind, name, namespace string) api.ObjectReference { - return api.ObjectReference{ +func makeObjectReference(kind, name, namespace string) v1.ObjectReference { + return v1.ObjectReference{ Kind: kind, Name: name, Namespace: namespace, @@ -38,34 +38,34 @@ func makeObjectReference(kind, name, namespace string) api.ObjectReference { } } -func makeEvent(reason, message string, involvedObject api.ObjectReference) api.Event { +func makeEvent(reason, message string, involvedObject v1.ObjectReference) v1.Event { eventTime := unversioned.Now() - event := api.Event{ + event := v1.Event{ Reason: reason, Message: message, InvolvedObject: involvedObject, - Source: api.EventSource{ + Source: v1.EventSource{ Component: "kubelet", Host: "kublet.node1", }, Count: 1, FirstTimestamp: eventTime, LastTimestamp: eventTime, - Type: api.EventTypeNormal, + Type: v1.EventTypeNormal, } return event } -func makeEvents(num int, template api.Event) []api.Event { - events := []api.Event{} +func makeEvents(num int, template v1.Event) []v1.Event { + events := []v1.Event{} for i := 0; i < num; i++ { events = append(events, template) } return events } -func makeUniqueEvents(num int) []api.Event { - events := []api.Event{} +func makeUniqueEvents(num int) []v1.Event { + events := []v1.Event{} kind := "Pod" for i := 0; i < num; i++ { reason := strings.Join([]string{"reason", string(i)}, "-") @@ -78,7 +78,7 @@ func makeUniqueEvents(num int) []api.Event { return events } -func makeSimilarEvents(num int, template api.Event, messagePrefix string) []api.Event { +func makeSimilarEvents(num int, template v1.Event, messagePrefix string) []v1.Event { events := makeEvents(num, template) for i := range events { events[i].Message = strings.Join([]string{messagePrefix, string(i), events[i].Message}, "-") @@ -86,12 +86,12 @@ func makeSimilarEvents(num int, template api.Event, messagePrefix string) []api. return events } -func setCount(event api.Event, count int) api.Event { +func setCount(event v1.Event, count int) v1.Event { event.Count = int32(count) return event } -func validateEvent(messagePrefix string, actualEvent *api.Event, expectedEvent *api.Event, t *testing.T) (*api.Event, error) { +func validateEvent(messagePrefix string, actualEvent *v1.Event, expectedEvent *v1.Event, t *testing.T) (*v1.Event, error) { recvEvent := *actualEvent expectCompression := expectedEvent.Count > 1 t.Logf("%v - expectedEvent.Count is %d\n", messagePrefix, expectedEvent.Count) @@ -172,13 +172,13 @@ func TestEventCorrelator(t *testing.T) { 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 + previousEvents []v1.Event + newEvent v1.Event + expectedEvent v1.Event intervalSeconds int }{ "create-a-single-event": { - previousEvents: []api.Event{}, + previousEvents: []v1.Event{}, newEvent: firstEvent, expectedEvent: setCount(firstEvent, 1), intervalSeconds: 5, diff --git a/pkg/client/testing/cache/BUILD b/pkg/client/testing/cache/BUILD index 0546d8cccf4..f993d85516b 100644 --- a/pkg/client/testing/cache/BUILD +++ b/pkg/client/testing/cache/BUILD @@ -17,6 +17,7 @@ go_library( deps = [ "//pkg/api:go_default_library", "//pkg/api/meta:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/runtime:go_default_library", "//pkg/types:go_default_library", "//pkg/watch:go_default_library", @@ -30,6 +31,7 @@ go_test( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/watch:go_default_library", ], ) diff --git a/pkg/client/testing/cache/fake_controller_source.go b/pkg/client/testing/cache/fake_controller_source.go index ee00c0586e1..a45defd54cb 100644 --- a/pkg/client/testing/cache/fake_controller_source.go +++ b/pkg/client/testing/cache/fake_controller_source.go @@ -24,6 +24,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/meta" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/watch" @@ -161,7 +162,7 @@ func (f *FakeControllerSource) getListItemsLocked() ([]runtime.Object, error) { } // List returns a list object, with its resource version set. -func (f *FakeControllerSource) List(options api.ListOptions) (runtime.Object, error) { +func (f *FakeControllerSource) List(options v1.ListOptions) (runtime.Object, error) { f.lock.RLock() defer f.lock.RUnlock() list, err := f.getListItemsLocked() @@ -182,14 +183,14 @@ func (f *FakeControllerSource) List(options api.ListOptions) (runtime.Object, er } // List returns a list object, with its resource version set. -func (f *FakePVControllerSource) List(options api.ListOptions) (runtime.Object, error) { +func (f *FakePVControllerSource) List(options v1.ListOptions) (runtime.Object, error) { f.lock.RLock() defer f.lock.RUnlock() list, err := f.FakeControllerSource.getListItemsLocked() if err != nil { return nil, err } - listObj := &api.PersistentVolumeList{} + listObj := &v1.PersistentVolumeList{} if err := meta.SetList(listObj, list); err != nil { return nil, err } @@ -203,14 +204,14 @@ func (f *FakePVControllerSource) List(options api.ListOptions) (runtime.Object, } // List returns a list object, with its resource version set. -func (f *FakePVCControllerSource) List(options api.ListOptions) (runtime.Object, error) { +func (f *FakePVCControllerSource) List(options v1.ListOptions) (runtime.Object, error) { f.lock.RLock() defer f.lock.RUnlock() list, err := f.FakeControllerSource.getListItemsLocked() if err != nil { return nil, err } - listObj := &api.PersistentVolumeClaimList{} + listObj := &v1.PersistentVolumeClaimList{} if err := meta.SetList(listObj, list); err != nil { return nil, err } @@ -225,7 +226,7 @@ func (f *FakePVCControllerSource) List(options api.ListOptions) (runtime.Object, // Watch returns a watch, which will be pre-populated with all changes // after resourceVersion. -func (f *FakeControllerSource) Watch(options api.ListOptions) (watch.Interface, error) { +func (f *FakeControllerSource) Watch(options v1.ListOptions) (watch.Interface, error) { f.lock.RLock() defer f.lock.RUnlock() rc, err := strconv.Atoi(options.ResourceVersion) diff --git a/pkg/client/testing/cache/fake_controller_source_test.go b/pkg/client/testing/cache/fake_controller_source_test.go index 0256e46159c..2f9efade5dd 100644 --- a/pkg/client/testing/cache/fake_controller_source_test.go +++ b/pkg/client/testing/cache/fake_controller_source_test.go @@ -21,6 +21,7 @@ import ( "testing" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/watch" ) @@ -33,7 +34,7 @@ func consume(t *testing.T, w watch.Interface, rvs []string, done *sync.WaitGroup t.Errorf("%#v: unexpected channel close, wanted %v", rvs, rv) return } - gotRV := got.Object.(*api.Pod).ObjectMeta.ResourceVersion + gotRV := got.Object.(*v1.Pod).ObjectMeta.ResourceVersion if e, a := rv, gotRV; e != a { t.Errorf("wanted %v, got %v", e, a) } else { @@ -48,9 +49,9 @@ func consume(t *testing.T, w watch.Interface, rvs []string, done *sync.WaitGroup } func TestRCNumber(t *testing.T) { - pod := func(name string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := func(name string) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, } @@ -64,13 +65,13 @@ func TestRCNumber(t *testing.T) { source.Modify(pod("foo")) source.Modify(pod("foo")) - w, err := source.Watch(api.ListOptions{ResourceVersion: "1"}) + w, err := source.Watch(v1.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{}) + list, err := source.List(v1.ListOptions{}) if err != nil { t.Fatalf("Unexpected error: %v", err) } @@ -78,13 +79,13 @@ func TestRCNumber(t *testing.T) { t.Errorf("wanted %v, got %v", e, a) } - w2, err := source.Watch(api.ListOptions{ResourceVersion: "2"}) + w2, err := source.Watch(v1.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"}) + w3, err := source.Watch(v1.ListOptions{ResourceVersion: "3"}) if err != nil { t.Fatalf("Unexpected error: %v", err) } diff --git a/pkg/cloudprovider/BUILD b/pkg/cloudprovider/BUILD index 7860acc401c..9a53ca14764 100644 --- a/pkg/cloudprovider/BUILD +++ b/pkg/cloudprovider/BUILD @@ -19,7 +19,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//vendor:github.com/golang/glog", ], diff --git a/pkg/cloudprovider/cloud.go b/pkg/cloudprovider/cloud.go index 6ed104ff15b..06c9674bfc4 100644 --- a/pkg/cloudprovider/cloud.go +++ b/pkg/cloudprovider/cloud.go @@ -21,7 +21,7 @@ import ( "fmt" "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" ) @@ -53,7 +53,7 @@ type Clusters interface { // TODO(#6812): Use a shorter name that's less likely to be longer than cloud // providers' name length limits. -func GetLoadBalancerName(service *api.Service) string { +func GetLoadBalancerName(service *v1.Service) string { //GCE requires that the name of a load balancer starts with a lower case letter. ret := "a" + string(service.UID) ret = strings.Replace(ret, "-", "", -1) @@ -81,26 +81,26 @@ type LoadBalancer interface { // TODO: Break this up into different interfaces (LB, etc) when we have more than one type of service // GetLoadBalancer returns whether the specified load balancer exists, and // if so, what its status is. - // Implementations must treat the *api.Service parameter as read-only and not modify it. + // Implementations must treat the *v1.Service parameter as read-only and not modify it. // Parameter 'clusterName' is the name of the cluster as presented to kube-controller-manager - GetLoadBalancer(clusterName string, service *api.Service) (status *api.LoadBalancerStatus, exists bool, err error) + GetLoadBalancer(clusterName string, service *v1.Service) (status *v1.LoadBalancerStatus, exists bool, err error) // EnsureLoadBalancer creates a new load balancer 'name', or updates the existing one. Returns the status of the balancer - // Implementations must treat the *api.Service parameter as read-only and not modify it. + // Implementations must treat the *v1.Service parameter as read-only and not modify it. // Parameter 'clusterName' is the name of the cluster as presented to kube-controller-manager - EnsureLoadBalancer(clusterName string, service *api.Service, nodeNames []string) (*api.LoadBalancerStatus, error) + EnsureLoadBalancer(clusterName string, service *v1.Service, nodeNames []string) (*v1.LoadBalancerStatus, error) // UpdateLoadBalancer updates hosts under the specified load balancer. - // Implementations must treat the *api.Service parameter as read-only and not modify it. + // Implementations must treat the *v1.Service parameter as read-only and not modify it. // Parameter 'clusterName' is the name of the cluster as presented to kube-controller-manager - UpdateLoadBalancer(clusterName string, service *api.Service, nodeNames []string) error + UpdateLoadBalancer(clusterName string, service *v1.Service, nodeNames []string) error // EnsureLoadBalancerDeleted deletes the specified load balancer if it // exists, returning nil if the load balancer specified either didn't exist or // was successfully deleted. // This construction is useful because many cloud providers' load balancers // have multiple underlying components, meaning a Get could say that the LB // doesn't exist even if some part of it is still laying around. - // Implementations must treat the *api.Service parameter as read-only and not modify it. + // Implementations must treat the *v1.Service parameter as read-only and not modify it. // Parameter 'clusterName' is the name of the cluster as presented to kube-controller-manager - EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error + EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error } // Instances is an abstract, pluggable interface for sets of instances. @@ -109,7 +109,7 @@ type Instances interface { // TODO(roberthbailey): This currently is only used in such a way that it // returns the address of the calling instance. We should do a rename to // make this clearer. - NodeAddresses(name types.NodeName) ([]api.NodeAddress, error) + NodeAddresses(name types.NodeName) ([]v1.NodeAddress, error) // ExternalID returns the cloud provider ID of the node with the specified NodeName. // Note that if the instance does not exist or is no longer running, we must return ("", cloudprovider.InstanceNotFound) ExternalID(nodeName types.NodeName) (string, error) diff --git a/pkg/cloudprovider/providers/aws/BUILD b/pkg/cloudprovider/providers/aws/BUILD index 29e7062722d..ca7eea3aefa 100644 --- a/pkg/cloudprovider/providers/aws/BUILD +++ b/pkg/cloudprovider/providers/aws/BUILD @@ -25,9 +25,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/api/service:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/service:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/credentialprovider/aws:go_default_library", "//pkg/types:go_default_library", @@ -57,8 +57,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/sets:go_default_library", "//vendor:github.com/aws/aws-sdk-go/aws", diff --git a/pkg/cloudprovider/providers/aws/aws.go b/pkg/cloudprovider/providers/aws/aws.go index 3bea88ab5b8..dff6afedd6e 100644 --- a/pkg/cloudprovider/providers/aws/aws.go +++ b/pkg/cloudprovider/providers/aws/aws.go @@ -41,9 +41,9 @@ import ( "github.com/aws/aws-sdk-go/service/elb" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/service" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/api/v1/service" "k8s.io/kubernetes/pkg/cloudprovider" aws_credentials "k8s.io/kubernetes/pkg/credentialprovider/aws" "k8s.io/kubernetes/pkg/types" @@ -878,17 +878,17 @@ func (c *Cloud) Routes() (cloudprovider.Routes, bool) { } // NodeAddresses is an implementation of Instances.NodeAddresses. -func (c *Cloud) NodeAddresses(name types.NodeName) ([]api.NodeAddress, error) { +func (c *Cloud) NodeAddresses(name types.NodeName) ([]v1.NodeAddress, error) { if c.selfAWSInstance.nodeName == name || len(name) == 0 { - addresses := []api.NodeAddress{} + addresses := []v1.NodeAddress{} internalIP, err := c.metadata.GetMetadata("local-ipv4") if err != nil { return nil, err } - addresses = append(addresses, api.NodeAddress{Type: api.NodeInternalIP, Address: internalIP}) + addresses = append(addresses, v1.NodeAddress{Type: v1.NodeInternalIP, Address: internalIP}) // Legacy compatibility: the private ip was the legacy host ip - addresses = append(addresses, api.NodeAddress{Type: api.NodeLegacyHostIP, Address: internalIP}) + addresses = append(addresses, v1.NodeAddress{Type: v1.NodeLegacyHostIP, Address: internalIP}) externalIP, err := c.metadata.GetMetadata("public-ipv4") if err != nil { @@ -896,7 +896,7 @@ func (c *Cloud) NodeAddresses(name types.NodeName) ([]api.NodeAddress, error) { // 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}) + addresses = append(addresses, v1.NodeAddress{Type: v1.NodeExternalIP, Address: externalIP}) } return addresses, nil @@ -906,7 +906,7 @@ func (c *Cloud) NodeAddresses(name types.NodeName) ([]api.NodeAddress, error) { return nil, fmt.Errorf("getInstanceByNodeName failed for %q with %v", name, err) } - addresses := []api.NodeAddress{} + addresses := []v1.NodeAddress{} if !isNilOrEmpty(instance.PrivateIpAddress) { ipAddress := *instance.PrivateIpAddress @@ -914,10 +914,10 @@ func (c *Cloud) NodeAddresses(name types.NodeName) ([]api.NodeAddress, error) { 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()}) + addresses = append(addresses, v1.NodeAddress{Type: v1.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()}) + addresses = append(addresses, v1.NodeAddress{Type: v1.NodeLegacyHostIP, Address: ip.String()}) } // TODO: Other IP addresses (multiple ips)? @@ -927,7 +927,7 @@ func (c *Cloud) NodeAddresses(name types.NodeName) ([]api.NodeAddress, error) { 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()}) + addresses = append(addresses, v1.NodeAddress{Type: v1.NodeExternalIP, Address: ip.String()}) } return addresses, nil @@ -1042,7 +1042,7 @@ func (c *Cloud) getAllZones() (sets.String, error) { // We don't currently cache this; it is currently used only in volume // creation which is expected to be a comparatively rare occurrence. - // TODO: Caching / expose api.Nodes to the cloud provider? + // TODO: Caching / expose v1.Nodes to the cloud provider? // TODO: We could also query for subnets, I think filters := []*ec2.Filter{newEc2Filter("instance-state-name", "running")} @@ -2464,7 +2464,7 @@ func getPortSets(annotation string) (ports *portSets) { // buildListener creates a new listener from the given port, adding an SSL certificate // if indicated by the appropriate annotations. -func buildListener(port api.ServicePort, annotations map[string]string, sslPorts *portSets) (*elb.Listener, error) { +func buildListener(port v1.ServicePort, annotations map[string]string, sslPorts *portSets) (*elb.Listener, error) { loadBalancerPort := int64(port.Port) portName := strings.ToLower(port.Name) instancePort := int64(port.NodePort) @@ -2499,12 +2499,12 @@ func buildListener(port api.ServicePort, annotations map[string]string, sslPorts } // EnsureLoadBalancer implements LoadBalancer.EnsureLoadBalancer -func (c *Cloud) EnsureLoadBalancer(clusterName string, apiService *api.Service, hosts []string) (*api.LoadBalancerStatus, error) { +func (c *Cloud) EnsureLoadBalancer(clusterName string, apiService *v1.Service, hosts []string) (*v1.LoadBalancerStatus, error) { annotations := apiService.Annotations glog.V(2).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v, %v, %v)", clusterName, apiService.Namespace, apiService.Name, c.region, apiService.Spec.LoadBalancerIP, apiService.Spec.Ports, hosts, annotations) - if apiService.Spec.SessionAffinity != api.ServiceAffinityNone { + if apiService.Spec.SessionAffinity != v1.ServiceAffinityNone { // ELB supports sticky sessions, but only when configured for HTTP/HTTPS return nil, fmt.Errorf("unsupported load balancer affinity: %v", apiService.Spec.SessionAffinity) } @@ -2517,7 +2517,7 @@ func (c *Cloud) EnsureLoadBalancer(clusterName string, apiService *api.Service, listeners := []*elb.Listener{} portList := getPortSets(annotations[ServiceAnnotationLoadBalancerSSLPorts]) for _, port := range apiService.Spec.Ports { - if port.Protocol != api.ProtocolTCP { + if port.Protocol != v1.ProtocolTCP { return nil, fmt.Errorf("Only TCP LoadBalancer is supported for AWS ELB") } if port.NodePort == 0 { @@ -2773,7 +2773,7 @@ func (c *Cloud) EnsureLoadBalancer(clusterName string, apiService *api.Service, } // GetLoadBalancer is an implementation of LoadBalancer.GetLoadBalancer -func (c *Cloud) GetLoadBalancer(clusterName string, service *api.Service) (*api.LoadBalancerStatus, bool, error) { +func (c *Cloud) GetLoadBalancer(clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error) { loadBalancerName := cloudprovider.GetLoadBalancerName(service) lb, err := c.describeLoadBalancer(loadBalancerName) if err != nil { @@ -2788,13 +2788,13 @@ func (c *Cloud) GetLoadBalancer(clusterName string, service *api.Service) (*api. return status, true, nil } -func toStatus(lb *elb.LoadBalancerDescription) *api.LoadBalancerStatus { - status := &api.LoadBalancerStatus{} +func toStatus(lb *elb.LoadBalancerDescription) *v1.LoadBalancerStatus { + status := &v1.LoadBalancerStatus{} if !isNilOrEmpty(lb.DNSName) { - var ingress api.LoadBalancerIngress + var ingress v1.LoadBalancerIngress ingress.Hostname = orEmpty(lb.DNSName) - status.Ingress = []api.LoadBalancerIngress{ingress} + status.Ingress = []v1.LoadBalancerIngress{ingress} } return status @@ -2989,7 +2989,7 @@ func (c *Cloud) updateInstanceSecurityGroupsForLoadBalancer(lb *elb.LoadBalancer } // EnsureLoadBalancerDeleted implements LoadBalancer.EnsureLoadBalancerDeleted. -func (c *Cloud) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { +func (c *Cloud) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) lb, err := c.describeLoadBalancer(loadBalancerName) if err != nil { @@ -3085,7 +3085,7 @@ func (c *Cloud) EnsureLoadBalancerDeleted(clusterName string, service *api.Servi } // UpdateLoadBalancer implements LoadBalancer.UpdateLoadBalancer -func (c *Cloud) UpdateLoadBalancer(clusterName string, service *api.Service, hosts []string) error { +func (c *Cloud) UpdateLoadBalancer(clusterName string, service *v1.Service, hosts []string) error { hostSet := sets.NewString(hosts...) instances, err := c.getInstancesByNodeNamesCached(hostSet) if err != nil { diff --git a/pkg/cloudprovider/providers/aws/aws_test.go b/pkg/cloudprovider/providers/aws/aws_test.go index 7a9c99bcc42..7f81aad2090 100644 --- a/pkg/cloudprovider/providers/aws/aws_test.go +++ b/pkg/cloudprovider/providers/aws/aws_test.go @@ -28,8 +28,8 @@ import ( "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/sets" "github.com/stretchr/testify/assert" @@ -624,7 +624,7 @@ func TestList(t *testing.T) { } } -func testHasNodeAddress(t *testing.T, addrs []api.NodeAddress, addressType api.NodeAddressType, address string) { +func testHasNodeAddress(t *testing.T, addrs []v1.NodeAddress, addressType v1.NodeAddressType, address string) { for _, addr := range addrs { if addr.Type == addressType && addr.Address == address { return @@ -697,9 +697,9 @@ func TestNodeAddresses(t *testing.T) { 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") + testHasNodeAddress(t, addrs3, v1.NodeInternalIP, "192.168.0.1") + testHasNodeAddress(t, addrs3, v1.NodeLegacyHostIP, "192.168.0.1") + testHasNodeAddress(t, addrs3, v1.NodeExternalIP, "1.2.3.4") // Fetch from metadata aws4, fakeServices := mockInstancesResp(&instance0, []*ec2.Instance{&instance0}) @@ -710,8 +710,8 @@ func TestNodeAddresses(t *testing.T) { 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") + testHasNodeAddress(t, addrs4, v1.NodeInternalIP, "192.168.0.2") + testHasNodeAddress(t, addrs4, v1.NodeExternalIP, "2.3.4.5") } func TestGetRegion(t *testing.T) { @@ -1192,7 +1192,7 @@ func TestDescribeLoadBalancerOnDelete(t *testing.T) { c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices) awsServices.elb.expectDescribeLoadBalancers("aid") - c.EnsureLoadBalancerDeleted(TestClusterName, &api.Service{ObjectMeta: api.ObjectMeta{Name: "myservice", UID: "id"}}) + c.EnsureLoadBalancerDeleted(TestClusterName, &v1.Service{ObjectMeta: v1.ObjectMeta{Name: "myservice", UID: "id"}}) } func TestDescribeLoadBalancerOnUpdate(t *testing.T) { @@ -1200,7 +1200,7 @@ func TestDescribeLoadBalancerOnUpdate(t *testing.T) { c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices) awsServices.elb.expectDescribeLoadBalancers("aid") - c.UpdateLoadBalancer(TestClusterName, &api.Service{ObjectMeta: api.ObjectMeta{Name: "myservice", UID: "id"}}, []string{}) + c.UpdateLoadBalancer(TestClusterName, &v1.Service{ObjectMeta: v1.ObjectMeta{Name: "myservice", UID: "id"}}, []string{}) } func TestDescribeLoadBalancerOnGet(t *testing.T) { @@ -1208,7 +1208,7 @@ func TestDescribeLoadBalancerOnGet(t *testing.T) { c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices) awsServices.elb.expectDescribeLoadBalancers("aid") - c.GetLoadBalancer(TestClusterName, &api.Service{ObjectMeta: api.ObjectMeta{Name: "myservice", UID: "id"}}) + c.GetLoadBalancer(TestClusterName, &v1.Service{ObjectMeta: v1.ObjectMeta{Name: "myservice", UID: "id"}}) } func TestDescribeLoadBalancerOnEnsure(t *testing.T) { @@ -1216,7 +1216,7 @@ func TestDescribeLoadBalancerOnEnsure(t *testing.T) { c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices) awsServices.elb.expectDescribeLoadBalancers("aid") - c.EnsureLoadBalancer(TestClusterName, &api.Service{ObjectMeta: api.ObjectMeta{Name: "myservice", UID: "id"}}, []string{}) + c.EnsureLoadBalancer(TestClusterName, &v1.Service{ObjectMeta: v1.ObjectMeta{Name: "myservice", UID: "id"}}, []string{}) } func TestBuildListener(t *testing.T) { @@ -1317,11 +1317,11 @@ func TestBuildListener(t *testing.T) { annotations[ServiceAnnotationLoadBalancerCertificate] = test.certAnnotation } ports := getPortSets(test.sslPortAnnotation) - l, err := buildListener(api.ServicePort{ + l, err := buildListener(v1.ServicePort{ NodePort: int32(test.instancePort), Port: int32(test.lbPort), Name: test.portName, - Protocol: api.Protocol("tcp"), + Protocol: v1.Protocol("tcp"), }, annotations, ports) if test.expectError { if err == nil { diff --git a/pkg/cloudprovider/providers/aws/volumes.go b/pkg/cloudprovider/providers/aws/volumes.go index f0ed233892e..c9d11ef8a7b 100644 --- a/pkg/cloudprovider/providers/aws/volumes.go +++ b/pkg/cloudprovider/providers/aws/volumes.go @@ -18,9 +18,10 @@ package aws import ( "fmt" - "github.com/aws/aws-sdk-go/aws" "net/url" "strings" + + "github.com/aws/aws-sdk-go/aws" ) // awsVolumeID represents the ID of the volume in the AWS API, e.g. vol-12345678a diff --git a/pkg/cloudprovider/providers/azure/BUILD b/pkg/cloudprovider/providers/azure/BUILD index 6db03860d80..e7f23256b5f 100644 --- a/pkg/cloudprovider/providers/azure/BUILD +++ b/pkg/cloudprovider/providers/azure/BUILD @@ -27,8 +27,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/api/service:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/service:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/types:go_default_library", "//pkg/util/errors:go_default_library", @@ -51,8 +51,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/api/service:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/service:go_default_library", "//pkg/types:go_default_library", "//vendor:github.com/Azure/azure-sdk-for-go/arm/compute", "//vendor:github.com/Azure/azure-sdk-for-go/arm/network", diff --git a/pkg/cloudprovider/providers/azure/azure_instances.go b/pkg/cloudprovider/providers/azure/azure_instances.go index a03c5dd9b05..46178b4298e 100644 --- a/pkg/cloudprovider/providers/azure/azure_instances.go +++ b/pkg/cloudprovider/providers/azure/azure_instances.go @@ -20,7 +20,7 @@ import ( "fmt" "regexp" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "github.com/Azure/azure-sdk-for-go/arm/compute" @@ -28,15 +28,15 @@ import ( ) // NodeAddresses returns the addresses of the specified instance. -func (az *Cloud) NodeAddresses(name types.NodeName) ([]api.NodeAddress, error) { +func (az *Cloud) NodeAddresses(name types.NodeName) ([]v1.NodeAddress, error) { ip, err := az.getIPForMachine(name) if err != nil { return nil, err } - return []api.NodeAddress{ - {Type: api.NodeInternalIP, Address: ip}, - {Type: api.NodeHostName, Address: string(name)}, + return []v1.NodeAddress{ + {Type: v1.NodeInternalIP, Address: ip}, + {Type: v1.NodeHostName, Address: string(name)}, }, nil } diff --git a/pkg/cloudprovider/providers/azure/azure_loadbalancer.go b/pkg/cloudprovider/providers/azure/azure_loadbalancer.go index bd26a41c528..8c43e1968ac 100644 --- a/pkg/cloudprovider/providers/azure/azure_loadbalancer.go +++ b/pkg/cloudprovider/providers/azure/azure_loadbalancer.go @@ -21,8 +21,8 @@ import ( "strconv" "strings" - "k8s.io/kubernetes/pkg/api" - serviceapi "k8s.io/kubernetes/pkg/api/service" + "k8s.io/kubernetes/pkg/api/v1" + serviceapi "k8s.io/kubernetes/pkg/api/v1/service" utilerrors "k8s.io/kubernetes/pkg/util/errors" "github.com/Azure/azure-sdk-for-go/arm/network" @@ -33,7 +33,7 @@ import ( // GetLoadBalancer returns whether the specified load balancer exists, and // if so, what its status is. -func (az *Cloud) GetLoadBalancer(clusterName string, service *api.Service) (status *api.LoadBalancerStatus, exists bool, err error) { +func (az *Cloud) GetLoadBalancer(clusterName string, service *v1.Service) (status *v1.LoadBalancerStatus, exists bool, err error) { lbName := getLoadBalancerName(clusterName) pipName := getPublicIPName(clusterName, service) serviceName := getServiceName(service) @@ -56,13 +56,13 @@ func (az *Cloud) GetLoadBalancer(clusterName string, service *api.Service) (stat return nil, false, nil } - return &api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{{IP: *pip.Properties.IPAddress}}, + return &v1.LoadBalancerStatus{ + Ingress: []v1.LoadBalancerIngress{{IP: *pip.Properties.IPAddress}}, }, true, nil } // EnsureLoadBalancer creates a new load balancer 'name', or updates the existing one. Returns the status of the balancer -func (az *Cloud) EnsureLoadBalancer(clusterName string, service *api.Service, nodeNames []string) (*api.LoadBalancerStatus, error) { +func (az *Cloud) EnsureLoadBalancer(clusterName string, service *v1.Service, nodeNames []string) (*v1.LoadBalancerStatus, error) { lbName := getLoadBalancerName(clusterName) pipName := getPublicIPName(clusterName, service) serviceName := getServiceName(service) @@ -135,13 +135,13 @@ func (az *Cloud) EnsureLoadBalancer(clusterName string, service *api.Service, no } glog.V(2).Infof("ensure(%s): FINISH - %s", serviceName, *pip.Properties.IPAddress) - return &api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{{IP: *pip.Properties.IPAddress}}, + return &v1.LoadBalancerStatus{ + Ingress: []v1.LoadBalancerIngress{{IP: *pip.Properties.IPAddress}}, }, nil } // UpdateLoadBalancer updates hosts under the specified load balancer. -func (az *Cloud) UpdateLoadBalancer(clusterName string, service *api.Service, nodeNames []string) error { +func (az *Cloud) UpdateLoadBalancer(clusterName string, service *v1.Service, nodeNames []string) error { _, err := az.EnsureLoadBalancer(clusterName, service, nodeNames) return err } @@ -152,7 +152,7 @@ func (az *Cloud) UpdateLoadBalancer(clusterName string, service *api.Service, no // This construction is useful because many cloud providers' load balancers // have multiple underlying components, meaning a Get could say that the LB // doesn't exist even if some part of it is still laying around. -func (az *Cloud) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { +func (az *Cloud) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error { lbName := getLoadBalancerName(clusterName) pipName := getPublicIPName(clusterName, service) serviceName := getServiceName(service) @@ -160,7 +160,7 @@ func (az *Cloud) EnsureLoadBalancerDeleted(clusterName string, service *api.Serv glog.V(2).Infof("delete(%s): START clusterName=%q lbName=%q", serviceName, clusterName, lbName) // reconcile logic is capable of fully reconcile, so we can use this to delete - service.Spec.Ports = []api.ServicePort{} + service.Spec.Ports = []v1.ServicePort{} lb, existsLb, err := az.getAzureLoadBalancer(lbName) if err != nil { @@ -259,7 +259,7 @@ func (az *Cloud) ensurePublicIPDeleted(serviceName, pipName string) error { // This ensures load balancer exists and the frontend ip config is setup. // This also reconciles the Service's Ports with the LoadBalancer config. // This entails adding rules/probes for expected Ports and removing stale rules/ports. -func (az *Cloud) reconcileLoadBalancer(lb network.LoadBalancer, pip *network.PublicIPAddress, clusterName string, service *api.Service, nodeNames []string) (network.LoadBalancer, bool, error) { +func (az *Cloud) reconcileLoadBalancer(lb network.LoadBalancer, pip *network.PublicIPAddress, clusterName string, service *v1.Service, nodeNames []string) (network.LoadBalancer, bool, error) { lbName := getLoadBalancerName(clusterName) serviceName := getServiceName(service) lbFrontendIPConfigName := getFrontendIPConfigName(service) @@ -471,7 +471,7 @@ func (az *Cloud) reconcileLoadBalancer(lb network.LoadBalancer, pip *network.Pub // This reconciles the Network Security Group similar to how the LB is reconciled. // This entails adding required, missing SecurityRules and removing stale rules. -func (az *Cloud) reconcileSecurityGroup(sg network.SecurityGroup, clusterName string, service *api.Service) (network.SecurityGroup, bool, error) { +func (az *Cloud) reconcileSecurityGroup(sg network.SecurityGroup, clusterName string, service *v1.Service) (network.SecurityGroup, bool, error) { serviceName := getServiceName(service) wantLb := len(service.Spec.Ports) > 0 diff --git a/pkg/cloudprovider/providers/azure/azure_test.go b/pkg/cloudprovider/providers/azure/azure_test.go index d48a3e43129..246ec62755b 100644 --- a/pkg/cloudprovider/providers/azure/azure_test.go +++ b/pkg/cloudprovider/providers/azure/azure_test.go @@ -21,8 +21,8 @@ import ( "strings" "testing" - "k8s.io/kubernetes/pkg/api" - serviceapi "k8s.io/kubernetes/pkg/api/service" + "k8s.io/kubernetes/pkg/api/v1" + serviceapi "k8s.io/kubernetes/pkg/api/v1/service" "k8s.io/kubernetes/pkg/types" "github.com/Azure/azure-sdk-for-go/arm/compute" @@ -229,20 +229,20 @@ func getTestPublicIP() network.PublicIPAddress { return pip } -func getTestService(identifier string, requestedPorts ...int32) api.Service { - ports := []api.ServicePort{} +func getTestService(identifier string, requestedPorts ...int32) v1.Service { + ports := []v1.ServicePort{} for _, port := range requestedPorts { - ports = append(ports, api.ServicePort{ + ports = append(ports, v1.ServicePort{ Name: fmt.Sprintf("port-%d", port), - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, Port: port, NodePort: getBackendPort(port), }) } - svc := api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeLoadBalancer, + svc := v1.Service{ + Spec: v1.ServiceSpec{ + Type: v1.ServiceTypeLoadBalancer, Ports: ports, }, } @@ -253,7 +253,7 @@ func getTestService(identifier string, requestedPorts ...int32) api.Service { return svc } -func getTestLoadBalancer(services ...api.Service) network.LoadBalancer { +func getTestLoadBalancer(services ...v1.Service) network.LoadBalancer { rules := []network.LoadBalancingRule{} probes := []network.Probe{} @@ -286,14 +286,14 @@ func getTestLoadBalancer(services ...api.Service) network.LoadBalancer { return lb } -func getServiceSourceRanges(service *api.Service) []string { +func getServiceSourceRanges(service *v1.Service) []string { if len(service.Spec.LoadBalancerSourceRanges) == 0 { return []string{"Internet"} } return service.Spec.LoadBalancerSourceRanges } -func getTestSecurityGroup(services ...api.Service) network.SecurityGroup { +func getTestSecurityGroup(services ...v1.Service) network.SecurityGroup { rules := []network.SecurityRule{} for _, service := range services { @@ -322,7 +322,7 @@ func getTestSecurityGroup(services ...api.Service) network.SecurityGroup { return sg } -func validateLoadBalancer(t *testing.T, loadBalancer network.LoadBalancer, services ...api.Service) { +func validateLoadBalancer(t *testing.T, loadBalancer network.LoadBalancer, services ...v1.Service) { expectedRuleCount := 0 for _, svc := range services { for _, wantedRule := range svc.Spec.Ports { @@ -381,7 +381,7 @@ func validateLoadBalancer(t *testing.T, loadBalancer network.LoadBalancer, servi } } -func validateSecurityGroup(t *testing.T, securityGroup network.SecurityGroup, services ...api.Service) { +func validateSecurityGroup(t *testing.T, securityGroup network.SecurityGroup, services ...v1.Service) { expectedRuleCount := 0 for _, svc := range services { for _, wantedRule := range svc.Spec.Ports { @@ -455,7 +455,7 @@ func TestSecurityRulePriorityFailsIfExhausted(t *testing.T) { } func TestProtocolTranslationTCP(t *testing.T) { - proto := api.ProtocolTCP + proto := v1.ProtocolTCP transportProto, securityGroupProto, probeProto, err := getProtocolsFromKubernetesProtocol(proto) if err != nil { t.Error(err) @@ -473,7 +473,7 @@ func TestProtocolTranslationTCP(t *testing.T) { } func TestProtocolTranslationUDP(t *testing.T) { - proto := api.ProtocolUDP + proto := v1.ProtocolUDP _, _, _, err := getProtocolsFromKubernetesProtocol(proto) if err == nil { t.Error("Expected an error. UDP is unsupported.") diff --git a/pkg/cloudprovider/providers/azure/azure_util.go b/pkg/cloudprovider/providers/azure/azure_util.go index c020671042b..ff9cbe48df8 100644 --- a/pkg/cloudprovider/providers/azure/azure_util.go +++ b/pkg/cloudprovider/providers/azure/azure_util.go @@ -20,7 +20,7 @@ import ( "fmt" "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "github.com/Azure/azure-sdk-for-go/arm/compute" @@ -122,9 +122,9 @@ func getLastSegment(ID string) (string, error) { // returns the equivalent LoadBalancerRule, SecurityRule and LoadBalancerProbe // protocol types for the given Kubernetes protocol type. -func getProtocolsFromKubernetesProtocol(protocol api.Protocol) (network.TransportProtocol, network.SecurityRuleProtocol, network.ProbeProtocol, error) { +func getProtocolsFromKubernetesProtocol(protocol v1.Protocol) (network.TransportProtocol, network.SecurityRuleProtocol, network.ProbeProtocol, error) { switch protocol { - case api.ProtocolTCP: + case v1.ProtocolTCP: return network.TransportProtocolTCP, network.TCP, network.ProbeProtocolTCP, nil default: return "", "", "", fmt.Errorf("Only TCP is supported for Azure LoadBalancers") @@ -168,31 +168,31 @@ func getBackendPoolName(clusterName string) string { return clusterName } -func getRuleName(service *api.Service, port api.ServicePort) string { +func getRuleName(service *v1.Service, port v1.ServicePort) string { return fmt.Sprintf("%s-%s-%d-%d", getRulePrefix(service), port.Protocol, port.Port, port.NodePort) } // This returns a human-readable version of the Service used to tag some resources. // This is only used for human-readable convenience, and not to filter. -func getServiceName(service *api.Service) string { +func getServiceName(service *v1.Service) string { return fmt.Sprintf("%s/%s", service.Namespace, service.Name) } // This returns a prefix for loadbalancer/security rules. -func getRulePrefix(service *api.Service) string { +func getRulePrefix(service *v1.Service) string { return cloudprovider.GetLoadBalancerName(service) } -func serviceOwnsRule(service *api.Service, rule string) bool { +func serviceOwnsRule(service *v1.Service, rule string) bool { prefix := getRulePrefix(service) return strings.HasPrefix(strings.ToUpper(rule), strings.ToUpper(prefix)) } -func getFrontendIPConfigName(service *api.Service) string { +func getFrontendIPConfigName(service *v1.Service) string { return cloudprovider.GetLoadBalancerName(service) } -func getPublicIPName(clusterName string, service *api.Service) string { +func getPublicIPName(clusterName string, service *v1.Service) string { return fmt.Sprintf("%s-%s", clusterName, cloudprovider.GetLoadBalancerName(service)) } diff --git a/pkg/cloudprovider/providers/cloudstack/BUILD b/pkg/cloudprovider/providers/cloudstack/BUILD index 5fb01a420b1..fae8ddf5a4b 100644 --- a/pkg/cloudprovider/providers/cloudstack/BUILD +++ b/pkg/cloudprovider/providers/cloudstack/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//vendor:github.com/golang/glog", "//vendor:github.com/xanzy/go-cloudstack/cloudstack", @@ -31,5 +31,5 @@ go_test( srcs = ["cloudstack_test.go"], library = "go_default_library", tags = ["automanaged"], - deps = ["//pkg/api:go_default_library"], + deps = ["//pkg/api/v1:go_default_library"], ) diff --git a/pkg/cloudprovider/providers/cloudstack/cloudstack_loadbalancer.go b/pkg/cloudprovider/providers/cloudstack/cloudstack_loadbalancer.go index 63e5b713ce1..1e24fe10073 100644 --- a/pkg/cloudprovider/providers/cloudstack/cloudstack_loadbalancer.go +++ b/pkg/cloudprovider/providers/cloudstack/cloudstack_loadbalancer.go @@ -22,7 +22,7 @@ import ( "github.com/golang/glog" "github.com/xanzy/go-cloudstack/cloudstack" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" ) @@ -40,7 +40,7 @@ type loadBalancer struct { } // GetLoadBalancer returns whether the specified load balancer exists, and if so, what its status is. -func (cs *CSCloud) GetLoadBalancer(clusterName string, service *api.Service) (*api.LoadBalancerStatus, bool, error) { +func (cs *CSCloud) GetLoadBalancer(clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error) { glog.V(4).Infof("GetLoadBalancer(%v, %v, %v)", clusterName, service.Namespace, service.Name) // Get the load balancer details and existing rules. @@ -56,14 +56,14 @@ func (cs *CSCloud) GetLoadBalancer(clusterName string, service *api.Service) (*a glog.V(4).Infof("Found a load balancer associated with IP %v", lb.ipAddr) - status := &api.LoadBalancerStatus{} - status.Ingress = append(status.Ingress, api.LoadBalancerIngress{IP: lb.ipAddr}) + status := &v1.LoadBalancerStatus{} + status.Ingress = append(status.Ingress, v1.LoadBalancerIngress{IP: lb.ipAddr}) return status, true, nil } // EnsureLoadBalancer creates a new load balancer, or updates the existing one. Returns the status of the balancer. -func (cs *CSCloud) EnsureLoadBalancer(clusterName string, service *api.Service, hosts []string) (status *api.LoadBalancerStatus, err error) { +func (cs *CSCloud) EnsureLoadBalancer(clusterName string, service *v1.Service, hosts []string) (status *v1.LoadBalancerStatus, err error) { glog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v)", clusterName, service.Namespace, service.Name, service.Spec.LoadBalancerIP, service.Spec.Ports, hosts) if len(service.Spec.Ports) == 0 { @@ -78,9 +78,9 @@ func (cs *CSCloud) EnsureLoadBalancer(clusterName string, service *api.Service, // Set the load balancer algorithm. switch service.Spec.SessionAffinity { - case api.ServiceAffinityNone: + case v1.ServiceAffinityNone: lb.algorithm = "roundrobin" - case api.ServiceAffinityClientIP: + case v1.ServiceAffinityClientIP: lb.algorithm = "source" default: return nil, fmt.Errorf("unsupported load balancer affinity: %v", service.Spec.SessionAffinity) @@ -158,14 +158,14 @@ func (cs *CSCloud) EnsureLoadBalancer(clusterName string, service *api.Service, } } - status = &api.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: lb.ipAddr}} + status = &v1.LoadBalancerStatus{} + status.Ingress = []v1.LoadBalancerIngress{{IP: lb.ipAddr}} return status, nil } // UpdateLoadBalancer updates hosts under the specified load balancer. -func (cs *CSCloud) UpdateLoadBalancer(clusterName string, service *api.Service, hosts []string) error { +func (cs *CSCloud) UpdateLoadBalancer(clusterName string, service *v1.Service, hosts []string) error { glog.V(4).Infof("UpdateLoadBalancer(%v, %v, %v, %v)", clusterName, service.Namespace, service.Name, hosts) // Get the load balancer details and existing rules. @@ -211,7 +211,7 @@ func (cs *CSCloud) UpdateLoadBalancer(clusterName string, service *api.Service, // EnsureLoadBalancerDeleted deletes the specified load balancer if it exists, returning // nil if the load balancer specified either didn't exist or was successfully deleted. -func (cs *CSCloud) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { +func (cs *CSCloud) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error { glog.V(4).Infof("EnsureLoadBalancerDeleted(%v, %v, %v)", clusterName, service.Namespace, service.Name) // Get the load balancer details and existing rules. @@ -238,7 +238,7 @@ func (cs *CSCloud) EnsureLoadBalancerDeleted(clusterName string, service *api.Se } // getLoadBalancer retrieves the IP address and ID and all the existing rules it can find. -func (cs *CSCloud) getLoadBalancer(service *api.Service) (*loadBalancer, error) { +func (cs *CSCloud) getLoadBalancer(service *v1.Service) (*loadBalancer, error) { lb := &loadBalancer{ CloudStackClient: cs.client, name: cloudprovider.GetLoadBalancerName(service), @@ -403,7 +403,7 @@ func (lb *loadBalancer) releaseLoadBalancerIP() error { // checkLoadBalancerRule checks if the rule already exists and if it does, if it can be updated. If // it does exist but cannot be updated, it will delete the existing rule so it can be created again. -func (lb *loadBalancer) checkLoadBalancerRule(lbRuleName string, port api.ServicePort) (bool, bool, error) { +func (lb *loadBalancer) checkLoadBalancerRule(lbRuleName string, port v1.ServicePort) (bool, bool, error) { lbRule, ok := lb.rules[lbRuleName] if !ok { return false, false, nil @@ -434,7 +434,7 @@ func (lb *loadBalancer) updateLoadBalancerRule(lbRuleName string) error { } // createLoadBalancerRule creates a new load balancer rule and returns it's ID. -func (lb *loadBalancer) createLoadBalancerRule(lbRuleName string, port api.ServicePort) (*cloudstack.LoadBalancerRule, error) { +func (lb *loadBalancer) createLoadBalancerRule(lbRuleName string, port v1.ServicePort) (*cloudstack.LoadBalancerRule, error) { p := lb.LoadBalancer.NewCreateLoadBalancerRuleParams( lb.algorithm, lbRuleName, @@ -446,9 +446,9 @@ func (lb *loadBalancer) createLoadBalancerRule(lbRuleName string, port api.Servi p.SetPublicipid(lb.ipAddrID) switch port.Protocol { - case api.ProtocolTCP: + case v1.ProtocolTCP: p.SetProtocol("TCP") - case api.ProtocolUDP: + case v1.ProtocolUDP: p.SetProtocol("UDP") default: return nil, fmt.Errorf("unsupported load balancer protocol: %v", port.Protocol) diff --git a/pkg/cloudprovider/providers/cloudstack/cloudstack_test.go b/pkg/cloudprovider/providers/cloudstack/cloudstack_test.go index 8cb147d92f6..25f6795b07d 100644 --- a/pkg/cloudprovider/providers/cloudstack/cloudstack_test.go +++ b/pkg/cloudprovider/providers/cloudstack/cloudstack_test.go @@ -22,7 +22,7 @@ import ( "strings" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) const testClusterName = "testCluster" @@ -111,7 +111,7 @@ func TestLoadBalancer(t *testing.T) { t.Fatalf("LoadBalancer() returned false") } - _, exists, err := lb.GetLoadBalancer(testClusterName, &api.Service{ObjectMeta: api.ObjectMeta{Name: "noexist"}}) + _, exists, err := lb.GetLoadBalancer(testClusterName, &v1.Service{ObjectMeta: v1.ObjectMeta{Name: "noexist"}}) if err != nil { t.Fatalf("GetLoadBalancer(\"noexist\") returned error: %s", err) } diff --git a/pkg/cloudprovider/providers/fake/BUILD b/pkg/cloudprovider/providers/fake/BUILD index 3e27423c9b7..e43f91d842b 100644 --- a/pkg/cloudprovider/providers/fake/BUILD +++ b/pkg/cloudprovider/providers/fake/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/types:go_default_library", ], diff --git a/pkg/cloudprovider/providers/fake/fake.go b/pkg/cloudprovider/providers/fake/fake.go index 56b7b073ff5..e4bed45df32 100644 --- a/pkg/cloudprovider/providers/fake/fake.go +++ b/pkg/cloudprovider/providers/fake/fake.go @@ -23,7 +23,7 @@ import ( "regexp" "sync" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" ) @@ -35,12 +35,12 @@ type FakeBalancer struct { Name string Region string LoadBalancerIP string - Ports []api.ServicePort + Ports []v1.ServicePort Hosts []string } type FakeUpdateBalancerCall struct { - Service *api.Service + Service *v1.Service Hosts []string } @@ -49,11 +49,11 @@ type FakeCloud struct { Exists bool Err error Calls []string - Addresses []api.NodeAddress + Addresses []v1.NodeAddress ExtID map[types.NodeName]string InstanceTypes map[types.NodeName]string Machines []types.NodeName - NodeResources *api.NodeResources + NodeResources *v1.NodeResources ClusterList []string MasterName string ExternalIP net.IP @@ -122,16 +122,16 @@ func (f *FakeCloud) Routes() (cloudprovider.Routes, bool) { } // GetLoadBalancer is a stub implementation of LoadBalancer.GetLoadBalancer. -func (f *FakeCloud) GetLoadBalancer(clusterName string, service *api.Service) (*api.LoadBalancerStatus, bool, error) { - status := &api.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: f.ExternalIP.String()}} +func (f *FakeCloud) GetLoadBalancer(clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error) { + status := &v1.LoadBalancerStatus{} + status.Ingress = []v1.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(clusterName string, service *api.Service, hosts []string) (*api.LoadBalancerStatus, error) { +func (f *FakeCloud) EnsureLoadBalancer(clusterName string, service *v1.Service, hosts []string) (*v1.LoadBalancerStatus, error) { f.addCall("create") if f.Balancers == nil { f.Balancers = make(map[string]FakeBalancer) @@ -148,15 +148,15 @@ func (f *FakeCloud) EnsureLoadBalancer(clusterName string, service *api.Service, f.Balancers[name] = FakeBalancer{name, region, spec.LoadBalancerIP, spec.Ports, hosts} - status := &api.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: f.ExternalIP.String()}} + status := &v1.LoadBalancerStatus{} + status.Ingress = []v1.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(clusterName string, service *api.Service, hosts []string) error { +func (f *FakeCloud) UpdateLoadBalancer(clusterName string, service *v1.Service, hosts []string) error { f.addCall("update") f.UpdateCalls = append(f.UpdateCalls, FakeUpdateBalancerCall{service, hosts}) return f.Err @@ -164,7 +164,7 @@ func (f *FakeCloud) UpdateLoadBalancer(clusterName string, service *api.Service, // EnsureLoadBalancerDeleted is a test-spy implementation of LoadBalancer.EnsureLoadBalancerDeleted. // It adds an entry "delete" into the internal method call record. -func (f *FakeCloud) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { +func (f *FakeCloud) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error { f.addCall("delete") return f.Err } @@ -180,7 +180,7 @@ func (f *FakeCloud) CurrentNodeName(hostname string) (types.NodeName, error) { // 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 types.NodeName) ([]api.NodeAddress, error) { +func (f *FakeCloud) NodeAddresses(instance types.NodeName) ([]v1.NodeAddress, error) { f.addCall("node-addresses") return f.Addresses, f.Err } diff --git a/pkg/cloudprovider/providers/gce/BUILD b/pkg/cloudprovider/providers/gce/BUILD index c8098b12a48..52d263fcc29 100644 --- a/pkg/cloudprovider/providers/gce/BUILD +++ b/pkg/cloudprovider/providers/gce/BUILD @@ -19,9 +19,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/api/service:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/service:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/types:go_default_library", "//pkg/util/errors:go_default_library", diff --git a/pkg/cloudprovider/providers/gce/gce.go b/pkg/cloudprovider/providers/gce/gce.go index c56dd43b6b0..a4063718b27 100644 --- a/pkg/cloudprovider/providers/gce/gce.go +++ b/pkg/cloudprovider/providers/gce/gce.go @@ -30,9 +30,9 @@ import ( "gopkg.in/gcfg.v1" - "k8s.io/kubernetes/pkg/api" - apiservice "k8s.io/kubernetes/pkg/api/service" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + apiservice "k8s.io/kubernetes/pkg/api/v1/service" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" utilerrors "k8s.io/kubernetes/pkg/util/errors" @@ -527,12 +527,12 @@ func (gce *GCECloud) waitForZoneOp(op *compute.Operation, zone string) error { } // GetLoadBalancer is an implementation of LoadBalancer.GetLoadBalancer -func (gce *GCECloud) GetLoadBalancer(clusterName string, service *api.Service) (*api.LoadBalancerStatus, bool, error) { +func (gce *GCECloud) GetLoadBalancer(clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error) { loadBalancerName := cloudprovider.GetLoadBalancerName(service) fwd, err := gce.service.ForwardingRules.Get(gce.projectID, gce.region, loadBalancerName).Do() if err == nil { - status := &api.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: fwd.IPAddress}} + status := &v1.LoadBalancerStatus{} + status.Ingress = []v1.LoadBalancerIngress{{IP: fwd.IPAddress}} return status, true, nil } @@ -554,7 +554,7 @@ func isHTTPErrorCode(err error, code int) bool { // Due to an interesting series of design decisions, this handles both creating // new load balancers and updating existing load balancers, recognizing when // each is needed. -func (gce *GCECloud) EnsureLoadBalancer(clusterName string, apiService *api.Service, hostNames []string) (*api.LoadBalancerStatus, error) { +func (gce *GCECloud) EnsureLoadBalancer(clusterName string, apiService *v1.Service, hostNames []string) (*v1.LoadBalancerStatus, error) { if len(hostNames) == 0 { return nil, fmt.Errorf("Cannot EnsureLoadBalancer() with no hosts") } @@ -832,8 +832,8 @@ func (gce *GCECloud) EnsureLoadBalancer(clusterName string, apiService *api.Serv glog.Infof("EnsureLoadBalancer(%v(%v)): created forwarding rule, IP %s", loadBalancerName, serviceName, ipAddress) } - status := &api.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: ipAddress}} + status := &v1.LoadBalancerStatus{} + status.Ingress = []v1.LoadBalancerIngress{{IP: ipAddress}} return status, nil } @@ -889,7 +889,7 @@ func (gce *GCECloud) ensureHttpHealthCheck(name, path string, port int32) (hc *c // IP is being requested. // Returns whether the forwarding rule exists, whether it needs to be updated, // what its IP address is (if it exists), and any error we encountered. -func (gce *GCECloud) forwardingRuleNeedsUpdate(name, region string, loadBalancerIP string, ports []api.ServicePort) (exists bool, needsUpdate bool, ipAddress string, err error) { +func (gce *GCECloud) forwardingRuleNeedsUpdate(name, region string, loadBalancerIP string, ports []v1.ServicePort) (exists bool, needsUpdate bool, ipAddress string, err error) { fwd, err := gce.service.ForwardingRules.Get(gce.projectID, region, name).Do() if err != nil { if isHTTPErrorCode(err, http.StatusNotFound) { @@ -926,13 +926,13 @@ func (gce *GCECloud) forwardingRuleNeedsUpdate(name, region string, loadBalancer return true, false, fwd.IPAddress, nil } -func loadBalancerPortRange(ports []api.ServicePort) (string, error) { +func loadBalancerPortRange(ports []v1.ServicePort) (string, error) { if len(ports) == 0 { return "", fmt.Errorf("no ports specified for GCE load balancer") } // The service controller verified all the protocols match on the ports, just check and use the first one - if ports[0].Protocol != api.ProtocolTCP && ports[0].Protocol != api.ProtocolUDP { + if ports[0].Protocol != v1.ProtocolTCP && ports[0].Protocol != v1.ProtocolUDP { return "", fmt.Errorf("Invalid protocol %s, only TCP and UDP are supported", string(ports[0].Protocol)) } @@ -951,7 +951,7 @@ func loadBalancerPortRange(ports []api.ServicePort) (string, error) { // Doesn't check whether the hosts have changed, since host updating is handled // separately. -func (gce *GCECloud) targetPoolNeedsUpdate(name, region string, affinityType api.ServiceAffinity) (exists bool, needsUpdate bool, err error) { +func (gce *GCECloud) targetPoolNeedsUpdate(name, region string, affinityType v1.ServiceAffinity) (exists bool, needsUpdate bool, err error) { tp, err := gce.service.TargetPools.Get(gce.projectID, region, name).Do() if err != nil { if isHTTPErrorCode(err, http.StatusNotFound) { @@ -977,11 +977,11 @@ func (gce *GCECloud) targetPoolNeedsUpdate(name, region string, affinityType api } // translate from what K8s supports to what the cloud provider supports for session affinity. -func translateAffinityType(affinityType api.ServiceAffinity) string { +func translateAffinityType(affinityType v1.ServiceAffinity) string { switch affinityType { - case api.ServiceAffinityClientIP: + case v1.ServiceAffinityClientIP: return gceAffinityTypeClientIP - case api.ServiceAffinityNone: + case v1.ServiceAffinityNone: return gceAffinityTypeNone default: glog.Errorf("Unexpected affinity type: %v", affinityType) @@ -989,7 +989,7 @@ func translateAffinityType(affinityType api.ServiceAffinity) string { } } -func (gce *GCECloud) firewallNeedsUpdate(name, serviceName, region, ipAddress string, ports []api.ServicePort, sourceRanges netsets.IPNet) (exists bool, needsUpdate bool, err error) { +func (gce *GCECloud) firewallNeedsUpdate(name, serviceName, region, ipAddress string, ports []v1.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) { @@ -1050,7 +1050,7 @@ func slicesEqual(x, y []string) bool { return true } -func (gce *GCECloud) createForwardingRule(name, serviceName, region, ipAddress string, ports []api.ServicePort) error { +func (gce *GCECloud) createForwardingRule(name, serviceName, region, ipAddress string, ports []v1.ServicePort) error { portRange, err := loadBalancerPortRange(ports) if err != nil { return err @@ -1077,7 +1077,7 @@ func (gce *GCECloud) createForwardingRule(name, serviceName, region, ipAddress s return nil } -func (gce *GCECloud) createTargetPool(name, serviceName, region string, hosts []*gceInstance, affinityType api.ServiceAffinity, hc *compute.HttpHealthCheck) error { +func (gce *GCECloud) createTargetPool(name, serviceName, region string, hosts []*gceInstance, affinityType v1.ServiceAffinity, hc *compute.HttpHealthCheck) error { var instances []string for _, host := range hosts { instances = append(instances, makeHostURL(gce.projectID, host.Zone, host.Name)) @@ -1114,7 +1114,7 @@ func (gce *GCECloud) createTargetPool(name, serviceName, region string, hosts [] return nil } -func (gce *GCECloud) createFirewall(name, region, desc string, sourceRanges netsets.IPNet, ports []api.ServicePort, hosts []*gceInstance) error { +func (gce *GCECloud) createFirewall(name, region, desc string, sourceRanges netsets.IPNet, ports []v1.ServicePort, hosts []*gceInstance) error { firewall, err := gce.firewallObject(name, region, desc, sourceRanges, ports, hosts) if err != nil { return err @@ -1132,7 +1132,7 @@ func (gce *GCECloud) createFirewall(name, region, desc string, sourceRanges nets return nil } -func (gce *GCECloud) updateFirewall(name, region, desc string, sourceRanges netsets.IPNet, ports []api.ServicePort, hosts []*gceInstance) error { +func (gce *GCECloud) updateFirewall(name, region, desc string, sourceRanges netsets.IPNet, ports []v1.ServicePort, hosts []*gceInstance) error { firewall, err := gce.firewallObject(name, region, desc, sourceRanges, ports, hosts) if err != nil { return err @@ -1150,7 +1150,7 @@ func (gce *GCECloud) updateFirewall(name, region, desc string, sourceRanges nets return nil } -func (gce *GCECloud) firewallObject(name, region, desc string, sourceRanges netsets.IPNet, ports []api.ServicePort, hosts []*gceInstance) (*compute.Firewall, error) { +func (gce *GCECloud) firewallObject(name, region, desc string, sourceRanges netsets.IPNet, ports []v1.ServicePort, hosts []*gceInstance) (*compute.Firewall, error) { allowedPorts := make([]string, len(ports)) for ix := range ports { allowedPorts[ix] = strconv.Itoa(int(ports[ix].Port)) @@ -1331,7 +1331,7 @@ func (gce *GCECloud) ensureStaticIP(name, serviceName, region, existingIP string } // UpdateLoadBalancer is an implementation of LoadBalancer.UpdateLoadBalancer. -func (gce *GCECloud) UpdateLoadBalancer(clusterName string, service *api.Service, hostNames []string) error { +func (gce *GCECloud) UpdateLoadBalancer(clusterName string, service *v1.Service, hostNames []string) error { hosts, err := gce.getInstancesByNames(hostNames) if err != nil { return err @@ -1402,7 +1402,7 @@ func (gce *GCECloud) updateTargetPool(loadBalancerName string, existing sets.Str } // EnsureLoadBalancerDeleted is an implementation of LoadBalancer.EnsureLoadBalancerDeleted. -func (gce *GCECloud) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { +func (gce *GCECloud) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) glog.V(2).Infof("EnsureLoadBalancerDeleted(%v, %v, %v, %v, %v)", clusterName, service.Namespace, service.Name, loadBalancerName, gce.region) @@ -1555,15 +1555,15 @@ func (gce *GCECloud) CreateFirewall(name, desc string, sourceRanges netsets.IPNe return err } // TODO: This completely breaks modularity in the cloudprovider but the methods - // shared with the TCPLoadBalancer take api.ServicePorts. - svcPorts := []api.ServicePort{} + // shared with the TCPLoadBalancer take v1.ServicePorts. + svcPorts := []v1.ServicePort{} // TODO: Currently the only consumer of this method is the GCE L7 // loadbalancer controller, which never needs a protocol other than TCP. // We should pipe through a mapping of port:protocol and default to TCP // if UDP ports are required. This means the method signature will change // forcing downstream clients to refactor interfaces. for _, p := range ports { - svcPorts = append(svcPorts, api.ServicePort{Port: int32(p), Protocol: api.ProtocolTCP}) + svcPorts = append(svcPorts, v1.ServicePort{Port: int32(p), Protocol: v1.ProtocolTCP}) } hosts, err := gce.getInstancesByNames(hostNames) if err != nil { @@ -1589,15 +1589,15 @@ func (gce *GCECloud) UpdateFirewall(name, desc string, sourceRanges netsets.IPNe return err } // TODO: This completely breaks modularity in the cloudprovider but the methods - // shared with the TCPLoadBalancer take api.ServicePorts. - svcPorts := []api.ServicePort{} + // shared with the TCPLoadBalancer take v1.ServicePorts. + svcPorts := []v1.ServicePort{} // TODO: Currently the only consumer of this method is the GCE L7 // loadbalancer controller, which never needs a protocol other than TCP. // We should pipe through a mapping of port:protocol and default to TCP // if UDP ports are required. This means the method signature will change, // forcing downstream clients to refactor interfaces. for _, p := range ports { - svcPorts = append(svcPorts, api.ServicePort{Port: int32(p), Protocol: api.ProtocolTCP}) + svcPorts = append(svcPorts, v1.ServicePort{Port: int32(p), Protocol: v1.ProtocolTCP}) } hosts, err := gce.getInstancesByNames(hostNames) if err != nil { @@ -2171,7 +2171,7 @@ func (gce *GCECloud) AddSSHKeyToAllInstances(user string, keyData []byte) error } // NodeAddresses is an implementation of Instances.NodeAddresses. -func (gce *GCECloud) NodeAddresses(_ types.NodeName) ([]api.NodeAddress, error) { +func (gce *GCECloud) NodeAddresses(_ types.NodeName) ([]v1.NodeAddress, error) { internalIP, err := metadata.Get("instance/network-interfaces/0/ip") if err != nil { return nil, fmt.Errorf("couldn't get internal IP: %v", err) @@ -2180,9 +2180,9 @@ func (gce *GCECloud) NodeAddresses(_ types.NodeName) ([]api.NodeAddress, error) if err != nil { return nil, fmt.Errorf("couldn't get external IP: %v", err) } - return []api.NodeAddress{ - {Type: api.NodeInternalIP, Address: internalIP}, - {Type: api.NodeExternalIP, Address: externalIP}, + return []v1.NodeAddress{ + {Type: v1.NodeInternalIP, Address: internalIP}, + {Type: v1.NodeExternalIP, Address: externalIP}, }, nil } diff --git a/pkg/cloudprovider/providers/mesos/BUILD b/pkg/cloudprovider/providers/mesos/BUILD index 294e9b2deb8..e012e29ebec 100644 --- a/pkg/cloudprovider/providers/mesos/BUILD +++ b/pkg/cloudprovider/providers/mesos/BUILD @@ -20,8 +20,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/types:go_default_library", "//pkg/util/net:go_default_library", diff --git a/pkg/cloudprovider/providers/mesos/client.go b/pkg/cloudprovider/providers/mesos/client.go index 84b506fc7a2..cfb207b6f09 100644 --- a/pkg/cloudprovider/providers/mesos/client.go +++ b/pkg/cloudprovider/providers/mesos/client.go @@ -31,8 +31,8 @@ import ( "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" + "k8s.io/kubernetes/pkg/api/v1" utilnet "k8s.io/kubernetes/pkg/util/net" ) @@ -52,7 +52,7 @@ type mesosClient struct { type slaveNode struct { hostname string kubeletRunning bool - resources *api.NodeResources + resources *v1.NodeResources } type mesosState struct { @@ -315,12 +315,12 @@ func parseMesosState(blob []byte) (*mesosState, error) { continue } node := &slaveNode{hostname: slave.Hostname} - cap := api.ResourceList{} + cap := v1.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) + cap[v1.ResourceCPU] = *resource.NewQuantity(int64(cpuNum), resource.DecimalSI) } else { log.Warningf("unexpected slave cpu resource type %T: %v", cpu, cpu) } @@ -329,7 +329,7 @@ func parseMesosState(blob []byte) (*mesosState, error) { } if mem, found := slave.Resources["mem"]; found { if memNum, ok := mem.(float64); ok { - cap[api.ResourceMemory] = *resource.NewQuantity(int64(memNum), resource.BinarySI) + cap[v1.ResourceMemory] = *resource.NewQuantity(int64(memNum), resource.BinarySI) } else { log.Warningf("unexpected slave mem resource type %T: %v", mem, mem) } @@ -338,7 +338,7 @@ func parseMesosState(blob []byte) (*mesosState, error) { } } if len(cap) > 0 { - node.resources = &api.NodeResources{ + node.resources = &v1.NodeResources{ Capacity: cap, } log.V(4).Infof("node %q reporting capacity %v", node.hostname, cap) diff --git a/pkg/cloudprovider/providers/mesos/mesos.go b/pkg/cloudprovider/providers/mesos/mesos.go index 1fbaa04dcc8..4facb9ecdce 100644 --- a/pkg/cloudprovider/providers/mesos/mesos.go +++ b/pkg/cloudprovider/providers/mesos/mesos.go @@ -28,7 +28,7 @@ import ( log "github.com/golang/glog" "github.com/mesos/mesos-go/detector" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" ) @@ -284,15 +284,15 @@ func (c *MesosCloud) ListWithoutKubelet() ([]string, error) { } // NodeAddresses returns the addresses of the instance with the specified nodeName. -func (c *MesosCloud) NodeAddresses(nodeName types.NodeName) ([]api.NodeAddress, error) { +func (c *MesosCloud) NodeAddresses(nodeName types.NodeName) ([]v1.NodeAddress, error) { name := mapNodeNameToHostname(nodeName) ip, err := ipAddress(name) if err != nil { return nil, err } - return []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: ip.String()}, - {Type: api.NodeInternalIP, Address: ip.String()}, - {Type: api.NodeExternalIP, Address: ip.String()}, + return []v1.NodeAddress{ + {Type: v1.NodeLegacyHostIP, Address: ip.String()}, + {Type: v1.NodeInternalIP, Address: ip.String()}, + {Type: v1.NodeExternalIP, Address: ip.String()}, }, nil } diff --git a/pkg/cloudprovider/providers/openstack/BUILD b/pkg/cloudprovider/providers/openstack/BUILD index 5e4ffa5dc3a..cf2bfdc94ef 100644 --- a/pkg/cloudprovider/providers/openstack/BUILD +++ b/pkg/cloudprovider/providers/openstack/BUILD @@ -21,9 +21,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", - "//pkg/api/service:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/service:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", @@ -65,7 +65,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/util/rand:go_default_library", "//vendor:github.com/rackspace/gophercloud", ], diff --git a/pkg/cloudprovider/providers/openstack/openstack.go b/pkg/cloudprovider/providers/openstack/openstack.go index 7ba6ab7cda3..b86e67ba1ee 100644 --- a/pkg/cloudprovider/providers/openstack/openstack.go +++ b/pkg/cloudprovider/providers/openstack/openstack.go @@ -36,7 +36,7 @@ import ( "github.com/rackspace/gophercloud/pagination" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" ) @@ -261,13 +261,13 @@ func getServerByName(client *gophercloud.ServiceClient, name types.NodeName) (*s return &serverList[0], nil } -func getAddressesByName(client *gophercloud.ServiceClient, name types.NodeName) ([]api.NodeAddress, error) { +func getAddressesByName(client *gophercloud.ServiceClient, name types.NodeName) ([]v1.NodeAddress, error) { srv, err := getServerByName(client, name) if err != nil { return nil, err } - addrs := []api.NodeAddress{} + addrs := []v1.NodeAddress{} for network, netblob := range srv.Addresses { list, ok := netblob.([]interface{}) @@ -276,7 +276,7 @@ func getAddressesByName(client *gophercloud.ServiceClient, name types.NodeName) } for _, item := range list { - var addressType api.NodeAddressType + var addressType v1.NodeAddressType props, ok := item.(map[string]interface{}) if !ok { @@ -285,9 +285,9 @@ func getAddressesByName(client *gophercloud.ServiceClient, name types.NodeName) extIPType, ok := props["OS-EXT-IPS:type"] if (ok && extIPType == "floating") || (!ok && network == "public") { - addressType = api.NodeExternalIP + addressType = v1.NodeExternalIP } else { - addressType = api.NodeInternalIP + addressType = v1.NodeInternalIP } tmp, ok := props["addr"] @@ -299,8 +299,8 @@ func getAddressesByName(client *gophercloud.ServiceClient, name types.NodeName) continue } - api.AddToNodeAddresses(&addrs, - api.NodeAddress{ + v1.AddToNodeAddresses(&addrs, + v1.NodeAddress{ Type: addressType, Address: addr, }, @@ -310,18 +310,18 @@ func getAddressesByName(client *gophercloud.ServiceClient, name types.NodeName) // AccessIPs are usually duplicates of "public" addresses. if srv.AccessIPv4 != "" { - api.AddToNodeAddresses(&addrs, - api.NodeAddress{ - Type: api.NodeExternalIP, + v1.AddToNodeAddresses(&addrs, + v1.NodeAddress{ + Type: v1.NodeExternalIP, Address: srv.AccessIPv4, }, ) } if srv.AccessIPv6 != "" { - api.AddToNodeAddresses(&addrs, - api.NodeAddress{ - Type: api.NodeExternalIP, + v1.AddToNodeAddresses(&addrs, + v1.NodeAddress{ + Type: v1.NodeExternalIP, Address: srv.AccessIPv6, }, ) @@ -339,7 +339,7 @@ func getAddressByName(client *gophercloud.ServiceClient, name types.NodeName) (s } for _, addr := range addrs { - if addr.Type == api.NodeInternalIP { + if addr.Type == v1.NodeInternalIP { return addr.Address, nil } } diff --git a/pkg/cloudprovider/providers/openstack/openstack_instances.go b/pkg/cloudprovider/providers/openstack/openstack_instances.go index 71d1d3309be..40df290f8d9 100644 --- a/pkg/cloudprovider/providers/openstack/openstack_instances.go +++ b/pkg/cloudprovider/providers/openstack/openstack_instances.go @@ -26,15 +26,15 @@ import ( "github.com/rackspace/gophercloud/openstack/compute/v2/servers" "github.com/rackspace/gophercloud/pagination" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" ) type Instances struct { compute *gophercloud.ServiceClient - flavor_to_resource map[string]*api.NodeResources // keyed by flavor id + flavor_to_resource map[string]*v1.NodeResources // keyed by flavor id } // Instances returns an implementation of Instances for OpenStack. @@ -51,17 +51,17 @@ func (os *OpenStack) Instances() (cloudprovider.Instances, bool) { pager := flavors.ListDetail(compute, nil) - flavor_to_resource := make(map[string]*api.NodeResources) + flavor_to_resource := make(map[string]*v1.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), + rsrc := v1.NodeResources{ + Capacity: v1.ResourceList{ + v1.ResourceCPU: *resource.NewQuantity(int64(flavor.VCPUs), resource.DecimalSI), + v1.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), @@ -126,7 +126,7 @@ func (i *Instances) AddSSHKeyToAllInstances(user string, keyData []byte) error { return errors.New("unimplemented") } -func (i *Instances) NodeAddresses(name types.NodeName) ([]api.NodeAddress, error) { +func (i *Instances) NodeAddresses(name types.NodeName) ([]v1.NodeAddress, error) { glog.V(4).Infof("NodeAddresses(%v) called", name) addrs, err := getAddressesByName(i.compute, name) diff --git a/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go b/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go index caa917af6df..e35834b25ad 100644 --- a/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go +++ b/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go @@ -39,8 +39,8 @@ import ( neutron_ports "github.com/rackspace/gophercloud/openstack/networking/v2/ports" "github.com/rackspace/gophercloud/pagination" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/service" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/api/v1/service" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" ) @@ -282,7 +282,7 @@ func getListenersByLoadBalancerID(client *gophercloud.ServiceClient, id string) } // get listener for a port or nil if does not exist -func getListenerForPort(existingListeners []listeners.Listener, port api.ServicePort) *listeners.Listener { +func getListenerForPort(existingListeners []listeners.Listener, port v1.ServicePort) *listeners.Listener { for _, l := range existingListeners { if l.Protocol == string(port.Protocol) && l.ProtocolPort == int(port.Port) { return &l @@ -418,7 +418,7 @@ func popMember(members []v2_pools.Member, addr string, port int) []v2_pools.Memb return members } -func getSecurityGroupName(clusterName string, service *api.Service) string { +func getSecurityGroupName(clusterName string, service *v1.Service) string { return fmt.Sprintf("lb-sg-%s-%v", clusterName, service.Name) } @@ -521,7 +521,7 @@ func createNodeSecurityGroup(client *gophercloud.ServiceClient, nodeSecurityGrou return nil } -func (lbaas *LbaasV2) createLoadBalancer(service *api.Service, name string) (*loadbalancers.LoadBalancer, error) { +func (lbaas *LbaasV2) createLoadBalancer(service *v1.Service, name string) (*loadbalancers.LoadBalancer, error) { createOpts := loadbalancers.CreateOpts{ Name: name, Description: fmt.Sprintf("Kubernetes external service %s", name), @@ -549,7 +549,7 @@ func stringInArray(x string, list []string) bool { return false } -func (lbaas *LbaasV2) GetLoadBalancer(clusterName string, service *api.Service) (*api.LoadBalancerStatus, bool, error) { +func (lbaas *LbaasV2) GetLoadBalancer(clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error) { loadBalancerName := cloudprovider.GetLoadBalancerName(service) loadbalancer, err := getLoadbalancerByName(lbaas.network, loadBalancerName) if err == ErrNotFound { @@ -559,8 +559,8 @@ func (lbaas *LbaasV2) GetLoadBalancer(clusterName string, service *api.Service) return nil, false, err } - status := &api.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: loadbalancer.VipAddress}} + status := &v1.LoadBalancerStatus{} + status.Ingress = []v1.LoadBalancerIngress{{IP: loadbalancer.VipAddress}} return status, true, err } @@ -570,7 +570,7 @@ func (lbaas *LbaasV2) GetLoadBalancer(clusterName string, service *api.Service) // a list of regions (from config) and query/create loadbalancers in // each region. -func (lbaas *LbaasV2) EnsureLoadBalancer(clusterName string, apiService *api.Service, nodeNames []string) (*api.LoadBalancerStatus, error) { +func (lbaas *LbaasV2) EnsureLoadBalancer(clusterName string, apiService *v1.Service, nodeNames []string) (*v1.LoadBalancerStatus, error) { glog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v, %v)", clusterName, apiService.Namespace, apiService.Name, apiService.Spec.LoadBalancerIP, apiService.Spec.Ports, nodeNames, apiService.Annotations) ports := apiService.Spec.Ports @@ -581,7 +581,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(clusterName string, apiService *api.Ser // Check for TCP protocol on each port // TODO: Convert all error messages to use an event recorder for _, port := range ports { - if port.Protocol != api.ProtocolTCP { + if port.Protocol != v1.ProtocolTCP { return nil, fmt.Errorf("Only TCP LoadBalancer is supported for openstack load balancers") } } @@ -595,12 +595,12 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(clusterName string, apiService *api.Ser return nil, fmt.Errorf("Source range restrictions are not supported for openstack load balancers without managing security groups") } - affinity := api.ServiceAffinityNone + affinity := v1.ServiceAffinityNone var persistence *v2_pools.SessionPersistence switch affinity { - case api.ServiceAffinityNone: + case v1.ServiceAffinityNone: persistence = nil - case api.ServiceAffinityClientIP: + case v1.ServiceAffinityClientIP: persistence = &v2_pools.SessionPersistence{Type: "SOURCE_IP"} default: return nil, fmt.Errorf("unsupported load balancer affinity: %v", affinity) @@ -794,9 +794,9 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(clusterName string, apiService *api.Ser glog.V(2).Infof("Deleted obsolete listener: %s", listener.ID) } - status := &api.LoadBalancerStatus{} + status := &v1.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: loadbalancer.VipAddress}} + status.Ingress = []v1.LoadBalancerIngress{{IP: loadbalancer.VipAddress}} port, err := getPortByIP(lbaas.network, loadbalancer.VipAddress) if err != nil { @@ -818,7 +818,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(clusterName string, apiService *api.Ser } } if floatIP != nil { - status.Ingress = append(status.Ingress, api.LoadBalancerIngress{IP: floatIP.FloatingIP}) + status.Ingress = append(status.Ingress, v1.LoadBalancerIngress{IP: floatIP.FloatingIP}) } if lbaas.opts.ManageSecurityGroups { @@ -939,7 +939,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(clusterName string, apiService *api.Ser return status, nil } -func (lbaas *LbaasV2) UpdateLoadBalancer(clusterName string, service *api.Service, nodeNames []string) error { +func (lbaas *LbaasV2) UpdateLoadBalancer(clusterName string, service *v1.Service, nodeNames []string) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) glog.V(4).Infof("UpdateLoadBalancer(%v, %v, %v)", clusterName, loadBalancerName, nodeNames) @@ -1086,7 +1086,7 @@ func (lbaas *LbaasV2) UpdateLoadBalancer(clusterName string, service *api.Servic return nil } -func (lbaas *LbaasV2) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { +func (lbaas *LbaasV2) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) glog.V(4).Infof("EnsureLoadBalancerDeleted(%v, %v)", clusterName, loadBalancerName) @@ -1256,7 +1256,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancerDeleted(clusterName string, service *api return nil } -func (lb *LbaasV1) GetLoadBalancer(clusterName string, service *api.Service) (*api.LoadBalancerStatus, bool, error) { +func (lb *LbaasV1) GetLoadBalancer(clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error) { loadBalancerName := cloudprovider.GetLoadBalancerName(service) vip, err := getVipByName(lb.network, loadBalancerName) if err == ErrNotFound { @@ -1266,8 +1266,8 @@ func (lb *LbaasV1) GetLoadBalancer(clusterName string, service *api.Service) (*a return nil, false, err } - status := &api.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: vip.Address}} + status := &v1.LoadBalancerStatus{} + status.Ingress = []v1.LoadBalancerIngress{{IP: vip.Address}} return status, true, err } @@ -1277,7 +1277,7 @@ func (lb *LbaasV1) GetLoadBalancer(clusterName string, service *api.Service) (*a // a list of regions (from config) and query/create loadbalancers in // each region. -func (lb *LbaasV1) EnsureLoadBalancer(clusterName string, apiService *api.Service, nodeNames []string) (*api.LoadBalancerStatus, error) { +func (lb *LbaasV1) EnsureLoadBalancer(clusterName string, apiService *v1.Service, nodeNames []string) (*v1.LoadBalancerStatus, error) { glog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v, %v)", clusterName, apiService.Namespace, apiService.Name, apiService.Spec.LoadBalancerIP, apiService.Spec.Ports, nodeNames, apiService.Annotations) ports := apiService.Spec.Ports @@ -1289,16 +1289,16 @@ func (lb *LbaasV1) EnsureLoadBalancer(clusterName string, apiService *api.Servic // 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 { + if ports[0].Protocol != v1.ProtocolTCP { return nil, fmt.Errorf("Only TCP LoadBalancer is supported for openstack load balancers") } affinity := apiService.Spec.SessionAffinity var persistence *vips.SessionPersistence switch affinity { - case api.ServiceAffinityNone: + case v1.ServiceAffinityNone: persistence = nil - case api.ServiceAffinityClientIP: + case v1.ServiceAffinityClientIP: persistence = &vips.SessionPersistence{Type: "SOURCE_IP"} default: return nil, fmt.Errorf("unsupported load balancer affinity: %v", affinity) @@ -1405,9 +1405,9 @@ func (lb *LbaasV1) EnsureLoadBalancer(clusterName string, apiService *api.Servic return nil, err } - status := &api.LoadBalancerStatus{} + status := &v1.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: vip.Address}} + status.Ingress = []v1.LoadBalancerIngress{{IP: vip.Address}} if lb.opts.FloatingNetworkId != "" { floatIPOpts := floatingips.CreateOpts{ @@ -1419,14 +1419,14 @@ func (lb *LbaasV1) EnsureLoadBalancer(clusterName string, apiService *api.Servic return nil, err } - status.Ingress = append(status.Ingress, api.LoadBalancerIngress{IP: floatIP.FloatingIP}) + status.Ingress = append(status.Ingress, v1.LoadBalancerIngress{IP: floatIP.FloatingIP}) } return status, nil } -func (lb *LbaasV1) UpdateLoadBalancer(clusterName string, service *api.Service, nodeNames []string) error { +func (lb *LbaasV1) UpdateLoadBalancer(clusterName string, service *v1.Service, nodeNames []string) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) glog.V(4).Infof("UpdateLoadBalancer(%v, %v, %v)", clusterName, loadBalancerName, nodeNames) @@ -1488,7 +1488,7 @@ func (lb *LbaasV1) UpdateLoadBalancer(clusterName string, service *api.Service, return nil } -func (lb *LbaasV1) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { +func (lb *LbaasV1) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) glog.V(4).Infof("EnsureLoadBalancerDeleted(%v, %v)", clusterName, loadBalancerName) diff --git a/pkg/cloudprovider/providers/openstack/openstack_test.go b/pkg/cloudprovider/providers/openstack/openstack_test.go index bf8b7864acb..df656a9c73d 100644 --- a/pkg/cloudprovider/providers/openstack/openstack_test.go +++ b/pkg/cloudprovider/providers/openstack/openstack_test.go @@ -25,7 +25,7 @@ import ( "k8s.io/kubernetes/pkg/util/rand" "github.com/rackspace/gophercloud" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) const volumeAvailableStatus = "available" @@ -226,7 +226,7 @@ func TestLoadBalancer(t *testing.T) { t.Fatalf("LoadBalancer() returned false - perhaps your stack doesn't support Neutron?") } - _, exists, err := lb.GetLoadBalancer(testClusterName, &api.Service{ObjectMeta: api.ObjectMeta{Name: "noexist"}}) + _, exists, err := lb.GetLoadBalancer(testClusterName, &v1.Service{ObjectMeta: v1.ObjectMeta{Name: "noexist"}}) if err != nil { t.Fatalf("GetLoadBalancer(\"noexist\") returned error: %s", err) } diff --git a/pkg/cloudprovider/providers/ovirt/BUILD b/pkg/cloudprovider/providers/ovirt/BUILD index 8d53099d717..b32fb70889b 100644 --- a/pkg/cloudprovider/providers/ovirt/BUILD +++ b/pkg/cloudprovider/providers/ovirt/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["ovirt.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/types:go_default_library", "//vendor:gopkg.in/gcfg.v1", diff --git a/pkg/cloudprovider/providers/ovirt/ovirt.go b/pkg/cloudprovider/providers/ovirt/ovirt.go index 5bc2f28fb25..ddeb6e7fc5a 100644 --- a/pkg/cloudprovider/providers/ovirt/ovirt.go +++ b/pkg/cloudprovider/providers/ovirt/ovirt.go @@ -31,7 +31,7 @@ import ( "gopkg.in/gcfg.v1" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" ) @@ -151,7 +151,7 @@ func (v *OVirtCloud) Routes() (cloudprovider.Routes, bool) { } // NodeAddresses returns the NodeAddresses of the instance with the specified nodeName. -func (v *OVirtCloud) NodeAddresses(nodeName types.NodeName) ([]api.NodeAddress, error) { +func (v *OVirtCloud) NodeAddresses(nodeName types.NodeName) ([]v1.NodeAddress, error) { name := mapNodeNameToInstanceName(nodeName) instance, err := v.fetchInstance(name) if err != nil { @@ -173,10 +173,10 @@ func (v *OVirtCloud) NodeAddresses(nodeName types.NodeName) ([]api.NodeAddress, address = resolved[0] } - return []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: address.String()}, - {Type: api.NodeInternalIP, Address: address.String()}, - {Type: api.NodeExternalIP, Address: address.String()}, + return []v1.NodeAddress{ + {Type: v1.NodeLegacyHostIP, Address: address.String()}, + {Type: v1.NodeInternalIP, Address: address.String()}, + {Type: v1.NodeExternalIP, Address: address.String()}, }, nil } diff --git a/pkg/cloudprovider/providers/photon/BUILD b/pkg/cloudprovider/providers/photon/BUILD index f0fcbc78f90..9d24f66cf6d 100644 --- a/pkg/cloudprovider/providers/photon/BUILD +++ b/pkg/cloudprovider/providers/photon/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["photon.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/types:go_default_library", "//vendor:github.com/golang/glog", diff --git a/pkg/cloudprovider/providers/photon/photon.go b/pkg/cloudprovider/providers/photon/photon.go index 89d4e738d51..e4b18e4bd7d 100644 --- a/pkg/cloudprovider/providers/photon/photon.go +++ b/pkg/cloudprovider/providers/photon/photon.go @@ -26,16 +26,17 @@ package photon import ( "errors" "fmt" - "github.com/golang/glog" - "github.com/vmware/photon-controller-go-sdk/photon" - "gopkg.in/gcfg.v1" "io" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/cloudprovider" - k8stypes "k8s.io/kubernetes/pkg/types" "log" "os/exec" "strings" + + "github.com/golang/glog" + "github.com/vmware/photon-controller-go-sdk/photon" + "gopkg.in/gcfg.v1" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/cloudprovider" + k8stypes "k8s.io/kubernetes/pkg/types" ) const ( @@ -284,8 +285,8 @@ func (pc *PCCloud) List(filter string) ([]k8stypes.NodeName, error) { } // NodeAddresses is an implementation of Instances.NodeAddresses. -func (pc *PCCloud) NodeAddresses(nodeName k8stypes.NodeName) ([]api.NodeAddress, error) { - addrs := []api.NodeAddress{} +func (pc *PCCloud) NodeAddresses(nodeName k8stypes.NodeName) ([]v1.NodeAddress, error) { + addrs := []v1.NodeAddress{} name := string(nodeName) var vmID string @@ -326,10 +327,10 @@ func (pc *PCCloud) NodeAddresses(nodeName k8stypes.NodeName) ([]api.NodeAddress, if val, ok := network["ipAddress"]; ok && val != nil { ipAddr := val.(string) if ipAddr != "-" { - api.AddToNodeAddresses(&addrs, - api.NodeAddress{ + v1.AddToNodeAddresses(&addrs, + v1.NodeAddress{ // TODO: figure out the type of the IP - Type: api.NodeInternalIP, + Type: v1.NodeInternalIP, Address: ipAddr, }, ) diff --git a/pkg/cloudprovider/providers/rackspace/BUILD b/pkg/cloudprovider/providers/rackspace/BUILD index bdea9f2deb7..0081dff4d31 100644 --- a/pkg/cloudprovider/providers/rackspace/BUILD +++ b/pkg/cloudprovider/providers/rackspace/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["rackspace.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/types:go_default_library", "//vendor:github.com/golang/glog", diff --git a/pkg/cloudprovider/providers/rackspace/rackspace.go b/pkg/cloudprovider/providers/rackspace/rackspace.go index 10548cae55a..c2852a0ac3f 100644 --- a/pkg/cloudprovider/providers/rackspace/rackspace.go +++ b/pkg/cloudprovider/providers/rackspace/rackspace.go @@ -40,7 +40,7 @@ import ( "github.com/rackspace/gophercloud/rackspace/compute/v2/servers" "github.com/rackspace/gophercloud/rackspace/compute/v2/volumeattach" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" ) @@ -397,7 +397,7 @@ func getAddressByName(api *gophercloud.ServiceClient, name string) (string, erro return getAddressByServer(srv) } -func (i *Instances) NodeAddresses(nodeName types.NodeName) ([]api.NodeAddress, error) { +func (i *Instances) NodeAddresses(nodeName types.NodeName) ([]v1.NodeAddress, error) { glog.V(2).Infof("NodeAddresses(%v) called", nodeName) serverName := mapNodeNameToServerName(nodeName) ip, err := probeNodeAddress(i.compute, serverName) @@ -409,10 +409,10 @@ func (i *Instances) NodeAddresses(nodeName types.NodeName) ([]api.NodeAddress, e // net.ParseIP().String() is to maintain compatibility with the old code parsedIP := net.ParseIP(ip).String() - return []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: parsedIP}, - {Type: api.NodeInternalIP, Address: parsedIP}, - {Type: api.NodeExternalIP, Address: parsedIP}, + return []v1.NodeAddress{ + {Type: v1.NodeLegacyHostIP, Address: parsedIP}, + {Type: v1.NodeInternalIP, Address: parsedIP}, + {Type: v1.NodeExternalIP, Address: parsedIP}, }, nil } diff --git a/pkg/cloudprovider/providers/vsphere/BUILD b/pkg/cloudprovider/providers/vsphere/BUILD index a835a303109..727b6916bb2 100644 --- a/pkg/cloudprovider/providers/vsphere/BUILD +++ b/pkg/cloudprovider/providers/vsphere/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["vsphere.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/types:go_default_library", "//pkg/util/runtime:go_default_library", diff --git a/pkg/cloudprovider/providers/vsphere/vsphere.go b/pkg/cloudprovider/providers/vsphere/vsphere.go index 804931a96bb..3438a708690 100644 --- a/pkg/cloudprovider/providers/vsphere/vsphere.go +++ b/pkg/cloudprovider/providers/vsphere/vsphere.go @@ -42,7 +42,7 @@ import ( "github.com/vmware/govmomi/vim25/types" "golang.org/x/net/context" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" k8stypes "k8s.io/kubernetes/pkg/types" k8runtime "k8s.io/kubernetes/pkg/util/runtime" @@ -492,8 +492,8 @@ func (i *Instances) List(filter string) ([]k8stypes.NodeName, error) { } // NodeAddresses is an implementation of Instances.NodeAddresses. -func (i *Instances) NodeAddresses(nodeName k8stypes.NodeName) ([]api.NodeAddress, error) { - addrs := []api.NodeAddress{} +func (i *Instances) NodeAddresses(nodeName k8stypes.NodeName) ([]v1.NodeAddress, error) { + addrs := []v1.NodeAddress{} // Create context ctx, cancel := context.WithCancel(context.Background()) @@ -512,15 +512,15 @@ func (i *Instances) NodeAddresses(nodeName k8stypes.NodeName) ([]api.NodeAddress // retrieve VM's ip(s) for _, v := range mvm.Guest.Net { - var addressType api.NodeAddressType + var addressType v1.NodeAddressType if i.cfg.Network.PublicNetwork == v.Network { - addressType = api.NodeExternalIP + addressType = v1.NodeExternalIP } else { - addressType = api.NodeInternalIP + addressType = v1.NodeInternalIP } for _, ip := range v.IpAddress { - api.AddToNodeAddresses(&addrs, - api.NodeAddress{ + v1.AddToNodeAddresses(&addrs, + v1.NodeAddress{ Type: addressType, Address: ip, }, diff --git a/pkg/controller/BUILD b/pkg/controller/BUILD index 26d93d511f0..8648d892793 100644 --- a/pkg/controller/BUILD +++ b/pkg/controller/BUILD @@ -25,13 +25,15 @@ go_library( "//pkg/api/errors:go_default_library", "//pkg/api/meta:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/api/validation:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/restclient:go_default_library", + "//pkg/conversion:go_default_library", "//pkg/fields:go_default_library", "//pkg/labels:go_default_library", "//pkg/runtime:go_default_library", @@ -55,9 +57,10 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/testapi:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/runtime:go_default_library", diff --git a/pkg/controller/certificates/BUILD b/pkg/controller/certificates/BUILD index 8a421f833bc..599d24f0990 100644 --- a/pkg/controller/certificates/BUILD +++ b/pkg/controller/certificates/BUILD @@ -19,11 +19,11 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/apis/certificates:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/certificates/v1alpha1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/controller:go_default_library", "//pkg/runtime:go_default_library", diff --git a/pkg/controller/certificates/controller.go b/pkg/controller/certificates/controller.go index f8f771638b9..dc6cb8b18be 100644 --- a/pkg/controller/certificates/controller.go +++ b/pkg/controller/certificates/controller.go @@ -22,11 +22,11 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/certificates" + "k8s.io/kubernetes/pkg/api/v1" + certificates "k8s.io/kubernetes/pkg/apis/certificates/v1alpha1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/runtime" @@ -62,7 +62,7 @@ func NewCertificateController(kubeClient clientset.Interface, syncPeriod time.Du // Send events to the apiserver eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(glog.Infof) - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.Core().Events("")}) // Configure cfssl signer // TODO: support non-default policy and remote/pkcs11 signing @@ -84,10 +84,10 @@ func NewCertificateController(kubeClient clientset.Interface, syncPeriod time.Du // Manage the addition/update of certificate requests cc.csrStore.Store, cc.csrController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return cc.kubeClient.Certificates().CertificateSigningRequests().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return cc.kubeClient.Certificates().CertificateSigningRequests().Watch(options) }, }, @@ -240,7 +240,7 @@ func (cc *CertificateController) maybeAutoApproveCSR(csr *certificates.Certifica return csr, nil } - x509cr, err := certutil.ParseCSR(csr) + x509cr, err := certutil.ParseCSRV1alpha1(csr) if err != nil { utilruntime.HandleError(fmt.Errorf("unable to parse csr %q: %v", csr.Name, err)) return csr, nil diff --git a/pkg/controller/certificates/controller_utils.go b/pkg/controller/certificates/controller_utils.go index ca3e7f44a22..242573c937b 100644 --- a/pkg/controller/certificates/controller_utils.go +++ b/pkg/controller/certificates/controller_utils.go @@ -16,7 +16,7 @@ limitations under the License. package certificates -import "k8s.io/kubernetes/pkg/apis/certificates" +import certificates "k8s.io/kubernetes/pkg/apis/certificates/v1alpha1" // IsCertificateRequestApproved returns true if a certificate request has the // "Approved" condition and no "Denied" conditions; false otherwise. diff --git a/pkg/controller/client_builder.go b/pkg/controller/client_builder.go index 88f9c97c1ed..f37de8499bd 100644 --- a/pkg/controller/client_builder.go +++ b/pkg/controller/client_builder.go @@ -22,9 +22,10 @@ import ( "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/runtime" @@ -76,7 +77,7 @@ type SAControllerClientBuilder struct { // CoreClient is used to provision service accounts if needed and watch for their associated tokens // to construct a controller client - CoreClient unversionedcore.CoreInterface + CoreClient v1core.CoreV1Interface // Namespace is the namespace used to host the service accounts that will back the // controllers. It must be highly privileged namespace which normal users cannot inspect. @@ -96,26 +97,26 @@ func (b SAControllerClientBuilder) Config(name string) (*restclient.Config, erro // check to see if the namespace exists. If it isn't a NotFound, just try to create the SA. // It'll probably fail, but perhaps that will have a better message. if _, err := b.CoreClient.Namespaces().Get(b.Namespace); apierrors.IsNotFound(err) { - _, err = b.CoreClient.Namespaces().Create(&api.Namespace{ObjectMeta: api.ObjectMeta{Name: b.Namespace}}) + _, err = b.CoreClient.Namespaces().Create(&v1.Namespace{ObjectMeta: v1.ObjectMeta{Name: b.Namespace}}) if err != nil && !apierrors.IsAlreadyExists(err) { return nil, err } } sa, err = b.CoreClient.ServiceAccounts(b.Namespace).Create( - &api.ServiceAccount{ObjectMeta: api.ObjectMeta{Namespace: b.Namespace, Name: name}}) + &v1.ServiceAccount{ObjectMeta: v1.ObjectMeta{Namespace: b.Namespace, Name: name}}) if err != nil { return nil, err } } lw := &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - options.FieldSelector = fields.SelectorFromSet(map[string]string{api.SecretTypeField: string(api.SecretTypeServiceAccountToken)}) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + options.FieldSelector = fields.SelectorFromSet(map[string]string{api.SecretTypeField: string(v1.SecretTypeServiceAccountToken)}).String() return b.CoreClient.Secrets(b.Namespace).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - options.FieldSelector = fields.SelectorFromSet(map[string]string{api.SecretTypeField: string(api.SecretTypeServiceAccountToken)}) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + options.FieldSelector = fields.SelectorFromSet(map[string]string{api.SecretTypeField: string(v1.SecretTypeServiceAccountToken)}).String() return b.CoreClient.Secrets(b.Namespace).Watch(options) }, } @@ -128,13 +129,13 @@ func (b SAControllerClientBuilder) Config(name string) (*restclient.Config, erro return false, fmt.Errorf("error watching") case watch.Added, watch.Modified: - secret := event.Object.(*api.Secret) + secret := event.Object.(*v1.Secret) if !serviceaccount.IsServiceAccountToken(secret, sa) || - len(secret.Data[api.ServiceAccountTokenKey]) == 0 { + len(secret.Data[v1.ServiceAccountTokenKey]) == 0 { return false, nil } // TODO maybe verify the token is valid - clientConfig.BearerToken = string(secret.Data[api.ServiceAccountTokenKey]) + clientConfig.BearerToken = string(secret.Data[v1.ServiceAccountTokenKey]) restclient.AddUserAgent(clientConfig, serviceaccount.MakeUsername(b.Namespace, name)) return true, nil diff --git a/pkg/controller/controller_ref_manager.go b/pkg/controller/controller_ref_manager.go index 52a8667f209..637f5d92b50 100644 --- a/pkg/controller/controller_ref_manager.go +++ b/pkg/controller/controller_ref_manager.go @@ -21,15 +21,15 @@ import ( "strings" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" ) type PodControllerRefManager struct { podControl PodControlInterface - controllerObject api.ObjectMeta + controllerObject v1.ObjectMeta controllerSelector labels.Selector controllerKind unversioned.GroupVersionKind } @@ -38,7 +38,7 @@ type PodControllerRefManager struct { // methods to manage the controllerRef of pods. func NewPodControllerRefManager( podControl PodControlInterface, - controllerObject api.ObjectMeta, + controllerObject v1.ObjectMeta, controllerSelector labels.Selector, controllerKind unversioned.GroupVersionKind, ) *PodControllerRefManager { @@ -53,10 +53,10 @@ func NewPodControllerRefManager( // controllerRef pointing to other object are ignored) 3. controlledDoesNotMatch // are the pods that have a controllerRef pointing to the controller, but their // labels no longer match the selector. -func (m *PodControllerRefManager) Classify(pods []*api.Pod) ( - matchesAndControlled []*api.Pod, - matchesNeedsController []*api.Pod, - controlledDoesNotMatch []*api.Pod) { +func (m *PodControllerRefManager) Classify(pods []*v1.Pod) ( + matchesAndControlled []*v1.Pod, + matchesNeedsController []*v1.Pod, + controlledDoesNotMatch []*v1.Pod) { for i := range pods { pod := pods[i] if !IsPodActive(pod) { @@ -91,7 +91,7 @@ func (m *PodControllerRefManager) Classify(pods []*api.Pod) ( // getControllerOf returns the controllerRef if controllee has a controller, // otherwise returns nil. -func getControllerOf(controllee api.ObjectMeta) *api.OwnerReference { +func getControllerOf(controllee v1.ObjectMeta) *v1.OwnerReference { for _, owner := range controllee.OwnerReferences { // controlled by other controller if owner.Controller != nil && *owner.Controller == true { @@ -103,7 +103,7 @@ func getControllerOf(controllee api.ObjectMeta) *api.OwnerReference { // AdoptPod sends a patch to take control of the pod. It returns the error if // the patching fails. -func (m *PodControllerRefManager) AdoptPod(pod *api.Pod) error { +func (m *PodControllerRefManager) AdoptPod(pod *v1.Pod) error { // we should not adopt any pods if the controller is about to be deleted if m.controllerObject.DeletionTimestamp != nil { return fmt.Errorf("cancel the adopt attempt for pod %s because the controlller is being deleted", @@ -118,7 +118,7 @@ func (m *PodControllerRefManager) AdoptPod(pod *api.Pod) error { // ReleasePod sends a patch to free the pod from the control of the controller. // It returns the error if the patching fails. 404 and 422 errors are ignored. -func (m *PodControllerRefManager) ReleasePod(pod *api.Pod) error { +func (m *PodControllerRefManager) ReleasePod(pod *v1.Pod) error { glog.V(2).Infof("patching pod %s_%s to remove its controllerRef to %s/%s:%s", pod.Namespace, pod.Name, m.controllerKind.GroupVersion(), m.controllerKind.Kind, m.controllerObject.Name) deleteOwnerRefPatch := fmt.Sprintf(`{"metadata":{"ownerReferences":[{"$patch":"delete","uid":"%s"}],"uid":"%s"}}`, m.controllerObject.UID, pod.UID) diff --git a/pkg/controller/controller_utils.go b/pkg/controller/controller_utils.go index 11f871a8b0f..dca41821518 100644 --- a/pkg/controller/controller_utils.go +++ b/pkg/controller/controller_utils.go @@ -26,11 +26,13 @@ import ( "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/api/validation" - "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/record" + "k8s.io/kubernetes/pkg/conversion" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/clock" @@ -363,11 +365,11 @@ const ( // 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 + CreatePods(namespace string, template *v1.PodTemplateSpec, object runtime.Object) error // CreatePodsOnNode creates a new pod according to the spec on the specified node. - CreatePodsOnNode(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object) error + CreatePodsOnNode(nodeName, namespace string, template *v1.PodTemplateSpec, object runtime.Object) error // CreatePodsWithControllerRef creates new pods according to the spec, and sets object as the pod's controller. - CreatePodsWithControllerRef(namespace string, template *api.PodTemplateSpec, object runtime.Object, controllerRef *api.OwnerReference) error + CreatePodsWithControllerRef(namespace string, template *v1.PodTemplateSpec, object runtime.Object, controllerRef *v1.OwnerReference) error // DeletePod deletes the pod identified by podID. DeletePod(namespace string, podID string, object runtime.Object) error // PatchPod patches the pod. @@ -382,7 +384,7 @@ type RealPodControl struct { var _ PodControlInterface = &RealPodControl{} -func getPodsLabelSet(template *api.PodTemplateSpec) labels.Set { +func getPodsLabelSet(template *v1.PodTemplateSpec) labels.Set { desiredLabels := make(labels.Set) for k, v := range template.Labels { desiredLabels[k] = v @@ -390,18 +392,18 @@ func getPodsLabelSet(template *api.PodTemplateSpec) labels.Set { return desiredLabels } -func getPodsFinalizers(template *api.PodTemplateSpec) []string { +func getPodsFinalizers(template *v1.PodTemplateSpec) []string { desiredFinalizers := make([]string, len(template.Finalizers)) copy(desiredFinalizers, template.Finalizers) return desiredFinalizers } -func getPodsAnnotationSet(template *api.PodTemplateSpec, object runtime.Object) (labels.Set, error) { +func getPodsAnnotationSet(template *v1.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) + createdByRef, err := v1.GetReference(object) if err != nil { return desiredAnnotations, fmt.Errorf("unable to get controller reference: %v", err) } @@ -409,15 +411,15 @@ func getPodsAnnotationSet(template *api.PodTemplateSpec, object runtime.Object) // 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"}) + codec := api.Codecs.LegacyCodec(unversioned.GroupVersion{Group: v1.GroupName, Version: "v1"}) - createdByRefJson, err := runtime.Encode(codec, &api.SerializedReference{ + createdByRefJson, err := runtime.Encode(codec, &v1.SerializedReference{ Reference: *createdByRef, }) if err != nil { return desiredAnnotations, fmt.Errorf("unable to serialize controller reference: %v", err) } - desiredAnnotations[api.CreatedByAnnotation] = string(createdByRefJson) + desiredAnnotations[v1.CreatedByAnnotation] = string(createdByRefJson) return desiredAnnotations, nil } @@ -430,11 +432,11 @@ func getPodsPrefix(controllerName string) string { return prefix } -func (r RealPodControl) CreatePods(namespace string, template *api.PodTemplateSpec, object runtime.Object) error { +func (r RealPodControl) CreatePods(namespace string, template *v1.PodTemplateSpec, object runtime.Object) error { return r.createPods("", namespace, template, object, nil) } -func (r RealPodControl) CreatePodsWithControllerRef(namespace string, template *api.PodTemplateSpec, controllerObject runtime.Object, controllerRef *api.OwnerReference) error { +func (r RealPodControl) CreatePodsWithControllerRef(namespace string, template *v1.PodTemplateSpec, controllerObject runtime.Object, controllerRef *v1.OwnerReference) error { if controllerRef == nil { return fmt.Errorf("controllerRef is nil") } @@ -450,7 +452,7 @@ func (r RealPodControl) CreatePodsWithControllerRef(namespace string, template * return r.createPods("", namespace, template, controllerObject, controllerRef) } -func (r RealPodControl) CreatePodsOnNode(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object) error { +func (r RealPodControl) CreatePodsOnNode(nodeName, namespace string, template *v1.PodTemplateSpec, object runtime.Object) error { return r.createPods(nodeName, namespace, template, object, nil) } @@ -459,7 +461,7 @@ func (r RealPodControl) PatchPod(namespace, name string, data []byte) error { return err } -func GetPodFromTemplate(template *api.PodTemplateSpec, parentObject runtime.Object, controllerRef *api.OwnerReference) (*api.Pod, error) { +func GetPodFromTemplate(template *v1.PodTemplateSpec, parentObject runtime.Object, controllerRef *v1.OwnerReference) (*v1.Pod, error) { desiredLabels := getPodsLabelSet(template) desiredFinalizers := getPodsFinalizers(template) desiredAnnotations, err := getPodsAnnotationSet(template, parentObject) @@ -472,8 +474,8 @@ func GetPodFromTemplate(template *api.PodTemplateSpec, parentObject runtime.Obje } prefix := getPodsPrefix(accessor.GetName()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: desiredLabels, Annotations: desiredAnnotations, GenerateName: prefix, @@ -483,13 +485,15 @@ func GetPodFromTemplate(template *api.PodTemplateSpec, parentObject runtime.Obje if controllerRef != nil { pod.OwnerReferences = append(pod.OwnerReferences, *controllerRef) } - if err := api.Scheme.Convert(&template.Spec, &pod.Spec, nil); err != nil { - return nil, fmt.Errorf("unable to convert pod template: %v", err) + clone, err := conversion.NewCloner().DeepCopy(&template.Spec) + if err != nil { + return nil, err } + pod.Spec = *clone.(*v1.PodSpec) return pod, nil } -func (r RealPodControl) createPods(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object, controllerRef *api.OwnerReference) error { +func (r RealPodControl) createPods(nodeName, namespace string, template *v1.PodTemplateSpec, object runtime.Object, controllerRef *v1.OwnerReference) error { pod, err := GetPodFromTemplate(template, object, controllerRef) if err != nil { return err @@ -501,7 +505,7 @@ func (r RealPodControl) createPods(nodeName, namespace string, template *api.Pod 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, FailedCreatePodReason, "Error creating: %v", err) + r.Recorder.Eventf(object, v1.EventTypeWarning, FailedCreatePodReason, "Error creating: %v", err) return fmt.Errorf("unable to create pods: %v", err) } else { accessor, err := meta.Accessor(object) @@ -510,7 +514,7 @@ func (r RealPodControl) createPods(nodeName, namespace string, template *api.Pod return nil } glog.V(4).Infof("Controller %v created pod %v", accessor.GetName(), newPod.Name) - r.Recorder.Eventf(object, api.EventTypeNormal, SuccessfulCreatePodReason, "Created pod: %v", newPod.Name) + r.Recorder.Eventf(object, v1.EventTypeNormal, SuccessfulCreatePodReason, "Created pod: %v", newPod.Name) } return nil } @@ -522,18 +526,18 @@ func (r RealPodControl) DeletePod(namespace string, podID string, object runtime } glog.V(2).Infof("Controller %v deleting pod %v/%v", accessor.GetName(), namespace, podID) if err := r.KubeClient.Core().Pods(namespace).Delete(podID, nil); err != nil { - r.Recorder.Eventf(object, api.EventTypeWarning, FailedDeletePodReason, "Error deleting: %v", err) + r.Recorder.Eventf(object, v1.EventTypeWarning, FailedDeletePodReason, "Error deleting: %v", err) return fmt.Errorf("unable to delete pods: %v", err) } else { - r.Recorder.Eventf(object, api.EventTypeNormal, SuccessfulDeletePodReason, "Deleted pod: %v", podID) + r.Recorder.Eventf(object, v1.EventTypeNormal, SuccessfulDeletePodReason, "Deleted pod: %v", podID) } return nil } type FakePodControl struct { sync.Mutex - Templates []api.PodTemplateSpec - ControllerRefs []api.OwnerReference + Templates []v1.PodTemplateSpec + ControllerRefs []v1.OwnerReference DeletePodName []string Patches [][]byte Err error @@ -551,7 +555,7 @@ func (f *FakePodControl) PatchPod(namespace, name string, data []byte) error { return nil } -func (f *FakePodControl) CreatePods(namespace string, spec *api.PodTemplateSpec, object runtime.Object) error { +func (f *FakePodControl) CreatePods(namespace string, spec *v1.PodTemplateSpec, object runtime.Object) error { f.Lock() defer f.Unlock() f.Templates = append(f.Templates, *spec) @@ -561,7 +565,7 @@ func (f *FakePodControl) CreatePods(namespace string, spec *api.PodTemplateSpec, return nil } -func (f *FakePodControl) CreatePodsWithControllerRef(namespace string, spec *api.PodTemplateSpec, object runtime.Object, controllerRef *api.OwnerReference) error { +func (f *FakePodControl) CreatePodsWithControllerRef(namespace string, spec *v1.PodTemplateSpec, object runtime.Object, controllerRef *v1.OwnerReference) error { f.Lock() defer f.Unlock() f.Templates = append(f.Templates, *spec) @@ -572,7 +576,7 @@ func (f *FakePodControl) CreatePodsWithControllerRef(namespace string, spec *api return nil } -func (f *FakePodControl) CreatePodsOnNode(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object) error { +func (f *FakePodControl) CreatePodsOnNode(nodeName, namespace string, template *v1.PodTemplateSpec, object runtime.Object) error { f.Lock() defer f.Unlock() f.Templates = append(f.Templates, *template) @@ -596,13 +600,13 @@ func (f *FakePodControl) Clear() { f.Lock() defer f.Unlock() f.DeletePodName = []string{} - f.Templates = []api.PodTemplateSpec{} - f.ControllerRefs = []api.OwnerReference{} + f.Templates = []v1.PodTemplateSpec{} + f.ControllerRefs = []v1.OwnerReference{} f.Patches = [][]byte{} } // ByLogging allows custom sorting of pods so the best one can be picked for getting its logs. -type ByLogging []*api.Pod +type ByLogging []*v1.Pod func (s ByLogging) Len() int { return len(s) } func (s ByLogging) Swap(i, j int) { s[i], s[j] = s[j], s[i] } @@ -613,18 +617,18 @@ func (s ByLogging) Less(i, j int) bool { return len(s[i].Spec.NodeName) > 0 } // 2. PodRunning < PodUnknown < PodPending - m := map[api.PodPhase]int{api.PodRunning: 0, api.PodUnknown: 1, api.PodPending: 2} + m := map[v1.PodPhase]int{v1.PodRunning: 0, v1.PodUnknown: 1, v1.PodPending: 2} if m[s[i].Status.Phase] != m[s[j].Status.Phase] { return m[s[i].Status.Phase] < m[s[j].Status.Phase] } // 3. ready < not ready - if api.IsPodReady(s[i]) != api.IsPodReady(s[j]) { - return api.IsPodReady(s[i]) + if v1.IsPodReady(s[i]) != v1.IsPodReady(s[j]) { + return v1.IsPodReady(s[i]) } // TODO: take availability into account when we push minReadySeconds information from deployment into pods, // see https://github.com/kubernetes/kubernetes/issues/22065 // 4. Been ready for more time < less time < empty time - if api.IsPodReady(s[i]) && api.IsPodReady(s[j]) && !podReadyTime(s[i]).Equal(podReadyTime(s[j])) { + if v1.IsPodReady(s[i]) && v1.IsPodReady(s[j]) && !podReadyTime(s[i]).Equal(podReadyTime(s[j])) { return afterOrZero(podReadyTime(s[j]), podReadyTime(s[i])) } // 5. Pods with containers with higher restart counts < lower restart counts @@ -639,7 +643,7 @@ func (s ByLogging) Less(i, j int) bool { } // ActivePods type allows custom sorting of pods so a controller can pick the best ones to delete. -type ActivePods []*api.Pod +type ActivePods []*v1.Pod func (s ActivePods) Len() int { return len(s) } func (s ActivePods) Swap(i, j int) { s[i], s[j] = s[j], s[i] } @@ -651,20 +655,20 @@ func (s ActivePods) Less(i, j int) bool { 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} + m := map[v1.PodPhase]int{v1.PodPending: 0, v1.PodUnknown: 1, v1.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]) + if v1.IsPodReady(s[i]) != v1.IsPodReady(s[j]) { + return !v1.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])) { + if v1.IsPodReady(s[i]) && v1.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 @@ -687,11 +691,11 @@ func afterOrZero(t1, t2 unversioned.Time) bool { return t1.After(t2.Time) } -func podReadyTime(pod *api.Pod) unversioned.Time { - if api.IsPodReady(pod) { +func podReadyTime(pod *v1.Pod) unversioned.Time { + if v1.IsPodReady(pod) { for _, c := range pod.Status.Conditions { // we only care about pod ready conditions - if c.Type == api.PodReady && c.Status == api.ConditionTrue { + if c.Type == v1.PodReady && c.Status == v1.ConditionTrue { return c.LastTransitionTime } } @@ -699,7 +703,7 @@ func podReadyTime(pod *api.Pod) unversioned.Time { return unversioned.Time{} } -func maxContainerRestarts(pod *api.Pod) int { +func maxContainerRestarts(pod *v1.Pod) int { maxRestarts := 0 for _, c := range pod.Status.ContainerStatuses { maxRestarts = integer.IntMax(maxRestarts, int(c.RestartCount)) @@ -708,8 +712,8 @@ func maxContainerRestarts(pod *api.Pod) int { } // FilterActivePods returns pods that have not terminated. -func FilterActivePods(pods []*api.Pod) []*api.Pod { - var result []*api.Pod +func FilterActivePods(pods []*v1.Pod) []*v1.Pod { + var result []*v1.Pod for _, p := range pods { if IsPodActive(p) { result = append(result, p) @@ -721,9 +725,9 @@ func FilterActivePods(pods []*api.Pod) []*api.Pod { return result } -func IsPodActive(p *api.Pod) bool { - return api.PodSucceeded != p.Status.Phase && - api.PodFailed != p.Status.Phase && +func IsPodActive(p *v1.Pod) bool { + return v1.PodSucceeded != p.Status.Phase && + v1.PodFailed != p.Status.Phase && p.DeletionTimestamp == nil } @@ -733,7 +737,7 @@ func FilterActiveReplicaSets(replicaSets []*extensions.ReplicaSet) []*extensions for i := range replicaSets { rs := replicaSets[i] - if rs != nil && rs.Spec.Replicas > 0 { + if rs != nil && *(rs.Spec.Replicas) > 0 { active = append(active, replicaSets[i]) } } @@ -744,12 +748,12 @@ func FilterActiveReplicaSets(replicaSets []*extensions.ReplicaSet) []*extensions // It's used so we consistently use the same key scheme in this module. // It does exactly what cache.MetaNamespaceKeyFunc would have done // except there's not possibility for error since we know the exact type. -func PodKey(pod *api.Pod) string { +func PodKey(pod *v1.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 +type ControllersByCreationTimestamp []*v1.ReplicationController func (o ControllersByCreationTimestamp) Len() int { return len(o) } func (o ControllersByCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] } @@ -779,10 +783,10 @@ type ReplicaSetsBySizeOlder []*extensions.ReplicaSet func (o ReplicaSetsBySizeOlder) Len() int { return len(o) } func (o ReplicaSetsBySizeOlder) Swap(i, j int) { o[i], o[j] = o[j], o[i] } func (o ReplicaSetsBySizeOlder) Less(i, j int) bool { - if o[i].Spec.Replicas == o[j].Spec.Replicas { + if *(o[i].Spec.Replicas) == *(o[j].Spec.Replicas) { return ReplicaSetsByCreationTimestamp(o).Less(i, j) } - return o[i].Spec.Replicas > o[j].Spec.Replicas + return *(o[i].Spec.Replicas) > *(o[j].Spec.Replicas) } // ReplicaSetsBySizeNewer sorts a list of ReplicaSet by size in descending order, using their creation timestamp or name as a tie breaker. @@ -792,8 +796,8 @@ type ReplicaSetsBySizeNewer []*extensions.ReplicaSet func (o ReplicaSetsBySizeNewer) Len() int { return len(o) } func (o ReplicaSetsBySizeNewer) Swap(i, j int) { o[i], o[j] = o[j], o[i] } func (o ReplicaSetsBySizeNewer) Less(i, j int) bool { - if o[i].Spec.Replicas == o[j].Spec.Replicas { + if *(o[i].Spec.Replicas) == *(o[j].Spec.Replicas) { return ReplicaSetsByCreationTimestamp(o).Less(j, i) } - return o[i].Spec.Replicas > o[j].Spec.Replicas + return *(o[i].Spec.Replicas) > *(o[j].Spec.Replicas) } diff --git a/pkg/controller/controller_utils_test.go b/pkg/controller/controller_utils_test.go index 5aa86e4d594..a802e705f25 100644 --- a/pkg/controller/controller_utils_test.go +++ b/pkg/controller/controller_utils_test.go @@ -17,6 +17,7 @@ limitations under the License. package controller import ( + "encoding/json" "fmt" "math/rand" "net/http/httptest" @@ -29,9 +30,10 @@ import ( "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/apimachinery/registered" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/runtime" @@ -52,36 +54,36 @@ func NewFakeControllerExpectationsLookup(ttl time.Duration) (*ControllerExpectat return &ControllerExpectations{ttlStore}, fakeClock } -func newReplicationController(replicas int) *api.ReplicationController { - rc := &api.ReplicationController{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ +func newReplicationController(replicas int) *v1.ReplicationController { + rc := &v1.ReplicationController{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + ObjectMeta: v1.ObjectMeta{ UID: uuid.NewUUID(), Name: "foobar", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, ResourceVersion: "18", }, - Spec: api.ReplicationControllerSpec{ - Replicas: int32(replicas), + Spec: v1.ReplicationControllerSpec{ + Replicas: func() *int32 { i := int32(replicas); return &i }(), Selector: map[string]string{"foo": "bar"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{ "name": "foo", "type": "production", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Image: "foo/bar", - TerminationMessagePath: api.TerminationMessagePathDefault, - ImagePullPolicy: api.PullIfNotPresent, + TerminationMessagePath: v1.TerminationMessagePathDefault, + ImagePullPolicy: v1.PullIfNotPresent, SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), }, }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSDefault, + RestartPolicy: v1.RestartPolicyAlways, + DNSPolicy: v1.DNSDefault, NodeSelector: map[string]string{ "baz": "blah", }, @@ -93,23 +95,23 @@ func newReplicationController(replicas int) *api.ReplicationController { } // create count pods with the given phase for the given rc (same selectors and namespace), and add them to the store. -func newPodList(store cache.Store, count int, status api.PodPhase, rc *api.ReplicationController) *api.PodList { - pods := []api.Pod{} +func newPodList(store cache.Store, count int, status v1.PodPhase, rc *v1.ReplicationController) *v1.PodList { + pods := []v1.Pod{} for i := 0; i < count; i++ { - newPod := api.Pod{ - ObjectMeta: api.ObjectMeta{ + newPod := v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: fmt.Sprintf("pod%d", i), Labels: rc.Spec.Selector, Namespace: rc.Namespace, }, - Status: api.PodStatus{Phase: status}, + Status: v1.PodStatus{Phase: status}, } if store != nil { store.Add(&newPod) } pods = append(pods, newPod) } - return &api.PodList{ + return &v1.PodList{ Items: pods, } } @@ -187,7 +189,7 @@ func TestControllerExpectations(t *testing.T) { func TestUIDExpectations(t *testing.T) { uidExp := NewUIDTrackingControllerExpectations(NewControllerExpectations()) - rcList := []*api.ReplicationController{ + rcList := []*v1.ReplicationController{ newReplicationController(2), newReplicationController(1), newReplicationController(0), @@ -200,7 +202,7 @@ func TestUIDExpectations(t *testing.T) { rcName := fmt.Sprintf("rc-%v", i) rc.Name = rcName rc.Spec.Selector[rcName] = rcName - podList := newPodList(nil, 5, api.PodRunning, rc) + podList := newPodList(nil, 5, v1.PodRunning, rc) rcKey, err := KeyFunc(rc) if err != nil { t.Fatalf("Couldn't get key for object %#v: %v", rc, err) @@ -237,15 +239,15 @@ func TestUIDExpectations(t *testing.T) { } func TestCreatePods(t *testing.T) { - ns := api.NamespaceDefault - body := runtime.EncodeOrDie(testapi.Default.Codec(), &api.Pod{ObjectMeta: api.ObjectMeta{Name: "empty_pod"}}) + ns := v1.NamespaceDefault + body := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "empty_pod"}}) fakeHandler := utiltesting.FakeHandler{ StatusCode: 200, ResponseBody: string(body), } testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) podControl := RealPodControl{ KubeClient: clientset, @@ -259,15 +261,16 @@ func TestCreatePods(t *testing.T) { t.Fatalf("unexpected error: %v", err) } - expectedPod := api.Pod{ - ObjectMeta: api.ObjectMeta{ + expectedPod := v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: controllerSpec.Spec.Template.Labels, GenerateName: fmt.Sprintf("%s-", controllerSpec.Name), }, Spec: controllerSpec.Spec.Template.Spec, } - fakeHandler.ValidateRequest(t, testapi.Default.ResourcePath("pods", api.NamespaceDefault, ""), "POST", nil) - actualPod, err := runtime.Decode(testapi.Default.Codec(), []byte(fakeHandler.RequestBody)) + fakeHandler.ValidateRequest(t, testapi.Default.ResourcePath("pods", v1.NamespaceDefault, ""), "POST", nil) + var actualPod = &v1.Pod{} + err := json.Unmarshal([]byte(fakeHandler.RequestBody), actualPod) if err != nil { t.Fatalf("Unexpected error: %v", err) } @@ -280,15 +283,15 @@ func TestCreatePods(t *testing.T) { func TestActivePodFiltering(t *testing.T) { // This rc is not needed by the test, only the newPodList to give the pods labels/a namespace. rc := newReplicationController(0) - podList := newPodList(nil, 5, api.PodRunning, rc) - podList.Items[0].Status.Phase = api.PodSucceeded - podList.Items[1].Status.Phase = api.PodFailed + podList := newPodList(nil, 5, v1.PodRunning, rc) + podList.Items[0].Status.Phase = v1.PodSucceeded + podList.Items[1].Status.Phase = v1.PodFailed expectedNames := sets.NewString() for _, pod := range podList.Items[2:] { expectedNames.Insert(pod.Name) } - var podPointers []*api.Pod + var podPointers []*v1.Pod for i := range podList.Items { podPointers = append(podPointers, &podList.Items[i]) } @@ -306,55 +309,55 @@ func TestSortingActivePods(t *testing.T) { numPods := 9 // This rc is not needed by the test, only the newPodList to give the pods labels/a namespace. rc := newReplicationController(0) - podList := newPodList(nil, numPods, api.PodRunning, rc) + podList := newPodList(nil, numPods, v1.PodRunning, rc) - pods := make([]*api.Pod, len(podList.Items)) + pods := make([]*v1.Pod, len(podList.Items)) for i := range podList.Items { pods[i] = &podList.Items[i] } // pods[0] is not scheduled yet. pods[0].Spec.NodeName = "" - pods[0].Status.Phase = api.PodPending + pods[0].Status.Phase = v1.PodPending // pods[1] is scheduled but pending. pods[1].Spec.NodeName = "bar" - pods[1].Status.Phase = api.PodPending + pods[1].Status.Phase = v1.PodPending // pods[2] is unknown. pods[2].Spec.NodeName = "foo" - pods[2].Status.Phase = api.PodUnknown + pods[2].Status.Phase = v1.PodUnknown // pods[3] is running but not ready. pods[3].Spec.NodeName = "foo" - pods[3].Status.Phase = api.PodRunning + pods[3].Status.Phase = v1.PodRunning // pods[4] is running and ready but without LastTransitionTime. now := unversioned.Now() pods[4].Spec.NodeName = "foo" - pods[4].Status.Phase = api.PodRunning - pods[4].Status.Conditions = []api.PodCondition{{Type: api.PodReady, Status: api.ConditionTrue}} - pods[4].Status.ContainerStatuses = []api.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} + pods[4].Status.Phase = v1.PodRunning + pods[4].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue}} + pods[4].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} // pods[5] is running and ready and with LastTransitionTime. pods[5].Spec.NodeName = "foo" - pods[5].Status.Phase = api.PodRunning - pods[5].Status.Conditions = []api.PodCondition{{Type: api.PodReady, Status: api.ConditionTrue, LastTransitionTime: now}} - pods[5].Status.ContainerStatuses = []api.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} + pods[5].Status.Phase = v1.PodRunning + pods[5].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: now}} + pods[5].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} // pods[6] is running ready for a longer time than pods[5]. then := unversioned.Time{Time: now.AddDate(0, -1, 0)} pods[6].Spec.NodeName = "foo" - pods[6].Status.Phase = api.PodRunning - pods[6].Status.Conditions = []api.PodCondition{{Type: api.PodReady, Status: api.ConditionTrue, LastTransitionTime: then}} - pods[6].Status.ContainerStatuses = []api.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} + pods[6].Status.Phase = v1.PodRunning + pods[6].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}} + pods[6].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} // pods[7] has lower container restart count than pods[6]. pods[7].Spec.NodeName = "foo" - pods[7].Status.Phase = api.PodRunning - pods[7].Status.Conditions = []api.PodCondition{{Type: api.PodReady, Status: api.ConditionTrue, LastTransitionTime: then}} - pods[7].Status.ContainerStatuses = []api.ContainerStatus{{RestartCount: 2}, {RestartCount: 1}} + pods[7].Status.Phase = v1.PodRunning + pods[7].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}} + pods[7].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 2}, {RestartCount: 1}} pods[7].CreationTimestamp = now // pods[8] is older than pods[7]. pods[8].Spec.NodeName = "foo" - pods[8].Status.Phase = api.PodRunning - pods[8].Status.Conditions = []api.PodCondition{{Type: api.PodReady, Status: api.ConditionTrue, LastTransitionTime: then}} - pods[8].Status.ContainerStatuses = []api.ContainerStatus{{RestartCount: 2}, {RestartCount: 1}} + pods[8].Status.Phase = v1.PodRunning + pods[8].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}} + pods[8].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 2}, {RestartCount: 1}} pods[8].CreationTimestamp = then - getOrder := func(pods []*api.Pod) []string { + getOrder := func(pods []*v1.Pod) []string { names := make([]string, len(pods)) for i := range pods { names[i] = pods[i].Name @@ -366,7 +369,7 @@ func TestSortingActivePods(t *testing.T) { for i := 0; i < 20; i++ { idx := rand.Perm(numPods) - randomizedPods := make([]*api.Pod, numPods) + randomizedPods := make([]*v1.Pod, numPods) for j := 0; j < numPods; j++ { randomizedPods[j] = pods[idx[j]] } diff --git a/pkg/controller/cronjob/BUILD b/pkg/controller/cronjob/BUILD index 28c985fa3c9..ce396af5a74 100644 --- a/pkg/controller/cronjob/BUILD +++ b/pkg/controller/cronjob/BUILD @@ -23,11 +23,11 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/batch:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/batch/v2alpha1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", - "//pkg/controller/job:go_default_library", "//pkg/labels:go_default_library", "//pkg/runtime:go_default_library", "//pkg/types:go_default_library", @@ -49,9 +49,9 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/batch:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/batch/v2alpha1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/types:go_default_library", ], diff --git a/pkg/controller/cronjob/controller.go b/pkg/controller/cronjob/controller.go index aeeca3946c1..7ec35a1315f 100644 --- a/pkg/controller/cronjob/controller.go +++ b/pkg/controller/cronjob/controller.go @@ -34,14 +34,13 @@ import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/batch" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + "k8s.io/kubernetes/pkg/api/v1" + batch "k8s.io/kubernetes/pkg/apis/batch/v2alpha1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" - "k8s.io/kubernetes/pkg/controller/job" "k8s.io/kubernetes/pkg/runtime" utilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/metrics" @@ -63,7 +62,7 @@ func NewCronJobController(kubeClient clientset.Interface) *CronJobController { eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(glog.Infof) // TODO: remove the wrapper when every clients have moved to use the clientset. - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.Core().Events("")}) if kubeClient != nil && kubeClient.Core().RESTClient().GetRateLimiter() != nil { metrics.RegisterMetricAndTrackRateLimiterUsage("cronjob_controller", kubeClient.Core().RESTClient().GetRateLimiter()) @@ -74,7 +73,7 @@ func NewCronJobController(kubeClient clientset.Interface) *CronJobController { jobControl: realJobControl{KubeClient: kubeClient}, sjControl: &realSJControl{KubeClient: kubeClient}, podControl: &realPodControl{KubeClient: kubeClient}, - recorder: eventBroadcaster.NewRecorder(api.EventSource{Component: "cronjob-controller"}), + recorder: eventBroadcaster.NewRecorder(v1.EventSource{Component: "cronjob-controller"}), } return jm @@ -97,7 +96,7 @@ func (jm *CronJobController) Run(stopCh <-chan struct{}) { // SyncAll lists all the CronJobs and Jobs and reconciles them. func (jm *CronJobController) SyncAll() { - sjl, err := jm.kubeClient.Batch().CronJobs(api.NamespaceAll).List(api.ListOptions{}) + sjl, err := jm.kubeClient.BatchV2alpha1().CronJobs(v1.NamespaceAll).List(v1.ListOptions{}) if err != nil { glog.Errorf("Error listing cronjobs: %v", err) return @@ -105,7 +104,7 @@ func (jm *CronJobController) SyncAll() { sjs := sjl.Items glog.V(4).Infof("Found %d cronjobs", len(sjs)) - jl, err := jm.kubeClient.Batch().Jobs(api.NamespaceAll).List(api.ListOptions{}) + jl, err := jm.kubeClient.BatchV2alpha1().Jobs(v1.NamespaceAll).List(v1.ListOptions{}) if err != nil { glog.Errorf("Error listing jobs") return @@ -131,8 +130,8 @@ func SyncOne(sj batch.CronJob, js []batch.Job, now time.Time, jc jobControlInter for i := range js { j := js[i] found := inActiveList(sj, j.ObjectMeta.UID) - if !found && !job.IsJobFinished(&j) { - recorder.Eventf(&sj, api.EventTypeWarning, "UnexpectedJob", "Saw a job that the controller did not create or forgot: %v", j.Name) + if !found && !IsJobFinished(&j) { + recorder.Eventf(&sj, v1.EventTypeWarning, "UnexpectedJob", "Saw a job that the controller did not create or forgot: %v", j.Name) // We found an unfinished job that has us as the parent, but it is not in our Active list. // This could happen if we crashed right after creating the Job and before updating the status, // or if our jobs list is newer than our sj status after a relist, or if someone intentionally created @@ -143,10 +142,10 @@ func SyncOne(sj batch.CronJob, js []batch.Job, now time.Time, jc jobControlInter // user has permission to create a job within a namespace, then they have permission to make any scheduledJob // in the same namespace "adopt" that job. ReplicaSets and their Pods work the same way. // TBS: how to update sj.Status.LastScheduleTime if the adopted job is newer than any we knew about? - } else if found && job.IsJobFinished(&j) { + } else if found && IsJobFinished(&j) { deleteFromActiveList(&sj, j.ObjectMeta.UID) // TODO: event to call out failure vs success. - recorder.Eventf(&sj, api.EventTypeNormal, "SawCompletedJob", "Saw completed job: %v", j.Name) + recorder.Eventf(&sj, v1.EventTypeNormal, "SawCompletedJob", "Saw completed job: %v", j.Name) } } updatedSJ, err := sjc.UpdateStatus(&sj) @@ -209,7 +208,7 @@ func SyncOne(sj batch.CronJob, js []batch.Job, now time.Time, jc jobControlInter glog.V(4).Infof("Deleting job %s of %s that was still running at next scheduled start time", j.Name, nameForLog) job, err := jc.GetJob(j.Namespace, j.Name) if err != nil { - recorder.Eventf(&sj, api.EventTypeWarning, "FailedGet", "Get job: %v", err) + recorder.Eventf(&sj, v1.EventTypeWarning, "FailedGet", "Get job: %v", err) return } // scale job down to 0 @@ -218,16 +217,16 @@ func SyncOne(sj batch.CronJob, js []batch.Job, now time.Time, jc jobControlInter job.Spec.Parallelism = &zero job, err = jc.UpdateJob(job.Namespace, job) if err != nil { - recorder.Eventf(&sj, api.EventTypeWarning, "FailedUpdate", "Update job: %v", err) + recorder.Eventf(&sj, v1.EventTypeWarning, "FailedUpdate", "Update job: %v", err) return } } // remove all pods... selector, _ := unversioned.LabelSelectorAsSelector(job.Spec.Selector) - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} podList, err := pc.ListPods(job.Namespace, options) if err != nil { - recorder.Eventf(&sj, api.EventTypeWarning, "FailedList", "List job-pods: %v", err) + recorder.Eventf(&sj, v1.EventTypeWarning, "FailedList", "List job-pods: %v", err) } errList := []error{} for _, pod := range podList.Items { @@ -240,18 +239,18 @@ func SyncOne(sj batch.CronJob, js []batch.Job, now time.Time, jc jobControlInter } } if len(errList) != 0 { - recorder.Eventf(&sj, api.EventTypeWarning, "FailedDelete", "Deleted job-pods: %v", utilerrors.NewAggregate(errList)) + recorder.Eventf(&sj, v1.EventTypeWarning, "FailedDelete", "Deleted job-pods: %v", utilerrors.NewAggregate(errList)) return } // ... the job itself... if err := jc.DeleteJob(job.Namespace, job.Name); err != nil { - recorder.Eventf(&sj, api.EventTypeWarning, "FailedDelete", "Deleted job: %v", err) + recorder.Eventf(&sj, v1.EventTypeWarning, "FailedDelete", "Deleted job: %v", err) glog.Errorf("Error deleting job %s from %s: %v", job.Name, nameForLog, err) return } // ... and its reference from active list deleteFromActiveList(&sj, job.ObjectMeta.UID) - recorder.Eventf(&sj, api.EventTypeNormal, "SuccessfulDelete", "Deleted job %v", j.Name) + recorder.Eventf(&sj, v1.EventTypeNormal, "SuccessfulDelete", "Deleted job %v", j.Name) } } @@ -262,11 +261,11 @@ func SyncOne(sj batch.CronJob, js []batch.Job, now time.Time, jc jobControlInter } jobResp, err := jc.CreateJob(sj.Namespace, jobReq) if err != nil { - recorder.Eventf(&sj, api.EventTypeWarning, "FailedCreate", "Error creating job: %v", err) + recorder.Eventf(&sj, v1.EventTypeWarning, "FailedCreate", "Error creating job: %v", err) return } glog.V(4).Infof("Created Job %s for %s", jobResp.Name, nameForLog) - recorder.Eventf(&sj, api.EventTypeNormal, "SuccessfulCreate", "Created job %v", jobResp.Name) + recorder.Eventf(&sj, v1.EventTypeNormal, "SuccessfulCreate", "Created job %v", jobResp.Name) // ------------------------------------------------------------------ // @@ -293,6 +292,6 @@ func SyncOne(sj batch.CronJob, js []batch.Job, now time.Time, jc jobControlInter return } -func getRef(object runtime.Object) (*api.ObjectReference, error) { - return api.GetReference(object) +func getRef(object runtime.Object) (*v1.ObjectReference, error) { + return v1.GetReference(object) } diff --git a/pkg/controller/cronjob/controller_test.go b/pkg/controller/cronjob/controller_test.go index 1c0f5e99640..28042a15e0c 100644 --- a/pkg/controller/cronjob/controller_test.go +++ b/pkg/controller/cronjob/controller_test.go @@ -20,9 +20,9 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/batch" + "k8s.io/kubernetes/pkg/api/v1" + batch "k8s.io/kubernetes/pkg/apis/batch/v2alpha1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/types" ) @@ -75,7 +75,7 @@ func justAfterThePriorHour() time.Time { // returns a cronJob with some fields filled in. func cronJob() batch.CronJob { return batch.CronJob{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "mycronjob", Namespace: "snazzycats", UID: types.UID("1a2b3c"), @@ -86,7 +86,7 @@ func cronJob() batch.CronJob { Schedule: "* * * * ?", ConcurrencyPolicy: batch.AllowConcurrent, JobTemplate: batch.JobTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"a": "b"}, Annotations: map[string]string{"x": "y"}, }, @@ -101,14 +101,14 @@ func jobSpec() batch.JobSpec { return batch.JobSpec{ Parallelism: &one, Completions: &one, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{ "foo": "bar", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Image: "foo/bar"}, }, }, @@ -118,10 +118,10 @@ func jobSpec() batch.JobSpec { func newJob(UID string) batch.Job { return batch.Job{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: types.UID(UID), Name: "foobar", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, SelfLink: "/apis/batch/v1/namespaces/snazzycats/jobs/myjob", }, Spec: jobSpec(), @@ -213,7 +213,7 @@ func TestSyncOne_RunOrNot(t *testing.T) { job.UID = "1234" job.Namespace = "" if tc.stillActive { - sj.Status.Active = []api.ObjectReference{{UID: job.UID}} + sj.Status.Active = []v1.ObjectReference{{UID: job.UID}} js = append(js, *job) } } else { @@ -271,7 +271,7 @@ func TestSyncOne_RunOrNot(t *testing.T) { // TestSyncOne_Status tests sj.UpdateStatus in SyncOne func TestSyncOne_Status(t *testing.T) { finishedJob := newJob("1") - finishedJob.Status.Conditions = append(finishedJob.Status.Conditions, batch.JobCondition{Type: batch.JobComplete, Status: api.ConditionTrue}) + finishedJob.Status.Conditions = append(finishedJob.Status.Conditions, batch.JobCondition{Type: batch.JobComplete, Status: v1.ConditionTrue}) unexpectedJob := newJob("2") testCases := map[string]struct { @@ -360,7 +360,7 @@ func TestSyncOne_Status(t *testing.T) { if err != nil { t.Errorf("%s: test setup error: failed to get job's ref: %v.", name, err) } - sj.Status.Active = []api.ObjectReference{*ref} + sj.Status.Active = []v1.ObjectReference{*ref} jobs = append(jobs, finishedJob) } if tc.hasUnexpectedJob { diff --git a/pkg/controller/cronjob/injection.go b/pkg/controller/cronjob/injection.go index 6cda81ace3d..f62d44fde1f 100644 --- a/pkg/controller/cronjob/injection.go +++ b/pkg/controller/cronjob/injection.go @@ -20,9 +20,9 @@ import ( "fmt" "sync" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/batch" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + batch "k8s.io/kubernetes/pkg/apis/batch/v2alpha1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/labels" ) @@ -41,7 +41,7 @@ type realSJControl struct { var _ sjControlInterface = &realSJControl{} func (c *realSJControl) UpdateStatus(sj *batch.CronJob) (*batch.CronJob, error) { - return c.KubeClient.Batch().CronJobs(sj.Namespace).UpdateStatus(sj) + return c.KubeClient.BatchV2alpha1().CronJobs(sj.Namespace).UpdateStatus(sj) } // fakeSJControl is the default implementation of sjControlInterface. @@ -97,19 +97,19 @@ func copyAnnotations(template *batch.JobTemplateSpec) labels.Set { } func (r realJobControl) GetJob(namespace, name string) (*batch.Job, error) { - return r.KubeClient.Batch().Jobs(namespace).Get(name) + return r.KubeClient.BatchV2alpha1().Jobs(namespace).Get(name) } func (r realJobControl) UpdateJob(namespace string, job *batch.Job) (*batch.Job, error) { - return r.KubeClient.Batch().Jobs(namespace).Update(job) + return r.KubeClient.BatchV2alpha1().Jobs(namespace).Update(job) } func (r realJobControl) CreateJob(namespace string, job *batch.Job) (*batch.Job, error) { - return r.KubeClient.Batch().Jobs(namespace).Create(job) + return r.KubeClient.BatchV2alpha1().Jobs(namespace).Create(job) } func (r realJobControl) DeleteJob(namespace string, name string) error { - return r.KubeClient.Batch().Jobs(namespace).Delete(name, nil) + return r.KubeClient.BatchV2alpha1().Jobs(namespace).Delete(name, nil) } type fakeJobControl struct { @@ -176,7 +176,7 @@ func (f *fakeJobControl) Clear() { // created as an interface to allow testing. type podControlInterface interface { // ListPods list pods - ListPods(namespace string, opts api.ListOptions) (*api.PodList, error) + ListPods(namespace string, opts v1.ListOptions) (*v1.PodList, error) // DeleteJob deletes the pod identified by name. // TODO: delete by UID? DeletePod(namespace string, name string) error @@ -190,7 +190,7 @@ type realPodControl struct { var _ podControlInterface = &realPodControl{} -func (r realPodControl) ListPods(namespace string, opts api.ListOptions) (*api.PodList, error) { +func (r realPodControl) ListPods(namespace string, opts v1.ListOptions) (*v1.PodList, error) { return r.KubeClient.Core().Pods(namespace).List(opts) } @@ -200,17 +200,17 @@ func (r realPodControl) DeletePod(namespace string, name string) error { type fakePodControl struct { sync.Mutex - Pods []api.Pod + Pods []v1.Pod DeletePodName []string Err error } var _ podControlInterface = &fakePodControl{} -func (f *fakePodControl) ListPods(namespace string, opts api.ListOptions) (*api.PodList, error) { +func (f *fakePodControl) ListPods(namespace string, opts v1.ListOptions) (*v1.PodList, error) { f.Lock() defer f.Unlock() - return &api.PodList{Items: f.Pods}, nil + return &v1.PodList{Items: f.Pods}, nil } func (f *fakePodControl) DeletePod(namespace string, name string) error { diff --git a/pkg/controller/cronjob/utils.go b/pkg/controller/cronjob/utils.go index ebdfd199ee1..8f913a47c60 100644 --- a/pkg/controller/cronjob/utils.go +++ b/pkg/controller/cronjob/utils.go @@ -26,7 +26,8 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/batch" + "k8s.io/kubernetes/pkg/api/v1" + batch "k8s.io/kubernetes/pkg/apis/batch/v2alpha1" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/types" ) @@ -46,7 +47,7 @@ func deleteFromActiveList(sj *batch.CronJob, uid types.UID) { if sj == nil { return } - newActive := []api.ObjectReference{} + newActive := []v1.ObjectReference{} for _, j := range sj.Status.Active { if j.UID != uid { newActive = append(newActive, j) @@ -57,12 +58,12 @@ func deleteFromActiveList(sj *batch.CronJob, uid types.UID) { // getParentUIDFromJob extracts UID of job's parent and whether it was found func getParentUIDFromJob(j batch.Job) (types.UID, bool) { - creatorRefJson, found := j.ObjectMeta.Annotations[api.CreatedByAnnotation] + creatorRefJson, found := j.ObjectMeta.Annotations[v1.CreatedByAnnotation] if !found { glog.V(4).Infof("Job with no created-by annotation, name %s namespace %s", j.Name, j.Namespace) return types.UID(""), false } - var sr api.SerializedReference + var sr v1.SerializedReference err := json.Unmarshal([]byte(creatorRefJson), &sr) if err != nil { glog.V(4).Infof("Job with unparsable created-by annotation, name %s namespace %s: %v", j.Name, j.Namespace, err) @@ -181,12 +182,12 @@ func getJobFromTemplate(sj *batch.CronJob, scheduledTime time.Time) (*batch.Job, if err != nil { return nil, err } - annotations[api.CreatedByAnnotation] = string(createdByRefJson) + annotations[v1.CreatedByAnnotation] = string(createdByRefJson) // We want job names for a given nominal start time to have a deterministic name to avoid the same job being created twice name := fmt.Sprintf("%s-%d", sj.Name, getTimeHash(scheduledTime)) job := &batch.Job{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Labels: labels, Annotations: annotations, Name: name, @@ -205,7 +206,7 @@ func getTimeHash(scheduledTime time.Time) int64 { // makeCreatedByRefJson makes a json string with an object reference for use in "created-by" annotation value func makeCreatedByRefJson(object runtime.Object) (string, error) { - createdByRef, err := api.GetReference(object) + createdByRef, err := v1.GetReference(object) if err != nil { return "", fmt.Errorf("unable to get controller reference: %v", err) } @@ -213,9 +214,9 @@ func makeCreatedByRefJson(object runtime.Object) (string, error) { // 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"}) + codec := api.Codecs.LegacyCodec(unversioned.GroupVersion{Group: v1.GroupName, Version: "v1"}) - createdByRefJson, err := runtime.Encode(codec, &api.SerializedReference{ + createdByRefJson, err := runtime.Encode(codec, &v1.SerializedReference{ Reference: *createdByRef, }) if err != nil { @@ -223,3 +224,12 @@ func makeCreatedByRefJson(object runtime.Object) (string, error) { } return string(createdByRefJson), nil } + +func IsJobFinished(j *batch.Job) bool { + for _, c := range j.Status.Conditions { + if (c.Type == batch.JobComplete || c.Type == batch.JobFailed) && c.Status == v1.ConditionTrue { + return true + } + } + return false +} diff --git a/pkg/controller/cronjob/utils_test.go b/pkg/controller/cronjob/utils_test.go index 2d02bffc04e..8a9e57b683a 100644 --- a/pkg/controller/cronjob/utils_test.go +++ b/pkg/controller/cronjob/utils_test.go @@ -22,9 +22,9 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/batch" + "k8s.io/kubernetes/pkg/api/v1" + batch "k8s.io/kubernetes/pkg/apis/batch/v2alpha1" "k8s.io/kubernetes/pkg/types" //"k8s.io/kubernetes/pkg/controller" // "k8s.io/kubernetes/pkg/util/rand" @@ -38,7 +38,7 @@ func TestGetJobFromTemplate(t *testing.T) { var no bool = false sj := batch.CronJob{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "mycronjob", Namespace: "snazzycats", UID: types.UID("1a2b3c"), @@ -48,21 +48,21 @@ func TestGetJobFromTemplate(t *testing.T) { Schedule: "* * * * ?", ConcurrencyPolicy: batch.AllowConcurrent, JobTemplate: batch.JobTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"a": "b"}, Annotations: map[string]string{"x": "y"}, }, Spec: batch.JobSpec{ ActiveDeadlineSeconds: &one, ManualSelector: &no, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{ "foo": "bar", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Image: "foo/bar"}, }, }, @@ -86,7 +86,7 @@ func TestGetJobFromTemplate(t *testing.T) { if len(job.ObjectMeta.Annotations) != 2 { t.Errorf("Wrong number of annotations") } - v, ok := job.ObjectMeta.Annotations[api.CreatedByAnnotation] + v, ok := job.ObjectMeta.Annotations[v1.CreatedByAnnotation] if !ok { t.Errorf("Missing created-by annotation") } @@ -102,22 +102,22 @@ func TestGetJobFromTemplate(t *testing.T) { func TestGetParentUIDFromJob(t *testing.T) { j := &batch.Job{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "foobar", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, Spec: batch.JobSpec{ Selector: &unversioned.LabelSelector{ MatchLabels: map[string]string{"foo": "bar"}, }, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{ "foo": "bar", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Image: "foo/bar"}, }, }, @@ -126,7 +126,7 @@ func TestGetParentUIDFromJob(t *testing.T) { Status: batch.JobStatus{ Conditions: []batch.JobCondition{{ Type: batch.JobComplete, - Status: api.ConditionTrue, + Status: v1.ConditionTrue, }}, }, } @@ -140,7 +140,7 @@ func TestGetParentUIDFromJob(t *testing.T) { } { // Case 2: Has UID annotation - j.ObjectMeta.Annotations = map[string]string{api.CreatedByAnnotation: `{"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"CronJob","namespace":"default","name":"pi","uid":"5ef034e0-1890-11e6-8935-42010af0003e","apiVersion":"extensions","resourceVersion":"427339"}}`} + j.ObjectMeta.Annotations = map[string]string{v1.CreatedByAnnotation: `{"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"CronJob","namespace":"default","name":"pi","uid":"5ef034e0-1890-11e6-8935-42010af0003e","apiVersion":"extensions","resourceVersion":"427339"}}`} expectedUID := types.UID("5ef034e0-1890-11e6-8935-42010af0003e") @@ -158,9 +158,9 @@ func TestGroupJobsByParent(t *testing.T) { uid1 := types.UID("11111111-1111-1111-1111-111111111111") uid2 := types.UID("22222222-2222-2222-2222-222222222222") uid3 := types.UID("33333333-3333-3333-3333-333333333333") - createdBy1 := map[string]string{api.CreatedByAnnotation: `{"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"CronJob","namespace":"x","name":"pi","uid":"11111111-1111-1111-1111-111111111111","apiVersion":"extensions","resourceVersion":"111111"}}`} - createdBy2 := map[string]string{api.CreatedByAnnotation: `{"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"CronJob","namespace":"x","name":"pi","uid":"22222222-2222-2222-2222-222222222222","apiVersion":"extensions","resourceVersion":"222222"}}`} - createdBy3 := map[string]string{api.CreatedByAnnotation: `{"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"CronJob","namespace":"y","name":"pi","uid":"33333333-3333-3333-3333-333333333333","apiVersion":"extensions","resourceVersion":"333333"}}`} + createdBy1 := map[string]string{v1.CreatedByAnnotation: `{"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"CronJob","namespace":"x","name":"pi","uid":"11111111-1111-1111-1111-111111111111","apiVersion":"extensions","resourceVersion":"111111"}}`} + createdBy2 := map[string]string{v1.CreatedByAnnotation: `{"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"CronJob","namespace":"x","name":"pi","uid":"22222222-2222-2222-2222-222222222222","apiVersion":"extensions","resourceVersion":"222222"}}`} + createdBy3 := map[string]string{v1.CreatedByAnnotation: `{"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"CronJob","namespace":"y","name":"pi","uid":"33333333-3333-3333-3333-333333333333","apiVersion":"extensions","resourceVersion":"333333"}}`} noCreatedBy := map[string]string{} { @@ -176,7 +176,7 @@ func TestGroupJobsByParent(t *testing.T) { { // Case 2: there is one controller with no job. sjs := []batch.CronJob{ - {ObjectMeta: api.ObjectMeta{Name: "e", Namespace: "x", UID: uid1}}, + {ObjectMeta: v1.ObjectMeta{Name: "e", Namespace: "x", UID: uid1}}, } js := []batch.Job{} jobsBySj := groupJobsByParent(sjs, js) @@ -188,10 +188,10 @@ func TestGroupJobsByParent(t *testing.T) { { // Case 3: there is one controller with one job it created. sjs := []batch.CronJob{ - {ObjectMeta: api.ObjectMeta{Name: "e", Namespace: "x", UID: uid1}}, + {ObjectMeta: v1.ObjectMeta{Name: "e", Namespace: "x", UID: uid1}}, } js := []batch.Job{ - {ObjectMeta: api.ObjectMeta{Name: "a", Namespace: "x", Annotations: createdBy1}}, + {ObjectMeta: v1.ObjectMeta{Name: "a", Namespace: "x", Annotations: createdBy1}}, } jobsBySj := groupJobsByParent(sjs, js) @@ -211,18 +211,18 @@ func TestGroupJobsByParent(t *testing.T) { // Case 4: Two namespaces, one has two jobs from one controller, other has 3 jobs from two controllers. // There are also two jobs with no created-by annotation. js := []batch.Job{ - {ObjectMeta: api.ObjectMeta{Name: "a", Namespace: "x", Annotations: createdBy1}}, - {ObjectMeta: api.ObjectMeta{Name: "b", Namespace: "x", Annotations: createdBy2}}, - {ObjectMeta: api.ObjectMeta{Name: "c", Namespace: "x", Annotations: createdBy1}}, - {ObjectMeta: api.ObjectMeta{Name: "d", Namespace: "x", Annotations: noCreatedBy}}, - {ObjectMeta: api.ObjectMeta{Name: "a", Namespace: "y", Annotations: createdBy3}}, - {ObjectMeta: api.ObjectMeta{Name: "b", Namespace: "y", Annotations: createdBy3}}, - {ObjectMeta: api.ObjectMeta{Name: "d", Namespace: "y", Annotations: noCreatedBy}}, + {ObjectMeta: v1.ObjectMeta{Name: "a", Namespace: "x", Annotations: createdBy1}}, + {ObjectMeta: v1.ObjectMeta{Name: "b", Namespace: "x", Annotations: createdBy2}}, + {ObjectMeta: v1.ObjectMeta{Name: "c", Namespace: "x", Annotations: createdBy1}}, + {ObjectMeta: v1.ObjectMeta{Name: "d", Namespace: "x", Annotations: noCreatedBy}}, + {ObjectMeta: v1.ObjectMeta{Name: "a", Namespace: "y", Annotations: createdBy3}}, + {ObjectMeta: v1.ObjectMeta{Name: "b", Namespace: "y", Annotations: createdBy3}}, + {ObjectMeta: v1.ObjectMeta{Name: "d", Namespace: "y", Annotations: noCreatedBy}}, } sjs := []batch.CronJob{ - {ObjectMeta: api.ObjectMeta{Name: "e", Namespace: "x", UID: uid1}}, - {ObjectMeta: api.ObjectMeta{Name: "f", Namespace: "x", UID: uid2}}, - {ObjectMeta: api.ObjectMeta{Name: "g", Namespace: "y", UID: uid3}}, + {ObjectMeta: v1.ObjectMeta{Name: "e", Namespace: "x", UID: uid1}}, + {ObjectMeta: v1.ObjectMeta{Name: "f", Namespace: "x", UID: uid2}}, + {ObjectMeta: v1.ObjectMeta{Name: "g", Namespace: "y", UID: uid3}}, } jobsBySj := groupJobsByParent(sjs, js) @@ -270,9 +270,9 @@ func TestGetRecentUnmetScheduleTimes(t *testing.T) { } sj := batch.CronJob{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "mycronjob", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, UID: types.UID("1a2b3c"), }, Spec: batch.CronJobSpec{ diff --git a/pkg/controller/daemon/BUILD b/pkg/controller/daemon/BUILD index 7e594c2dbda..7484407b821 100644 --- a/pkg/controller/daemon/BUILD +++ b/pkg/controller/daemon/BUILD @@ -18,13 +18,13 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/controller:go_default_library", "//pkg/controller/informers:go_default_library", @@ -46,14 +46,14 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/testapi:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/controller:go_default_library", "//pkg/controller/informers:go_default_library", diff --git a/pkg/controller/daemon/daemoncontroller.go b/pkg/controller/daemon/daemoncontroller.go index bcf7c5cd494..ed0eef1b483 100644 --- a/pkg/controller/daemon/daemoncontroller.go +++ b/pkg/controller/daemon/daemoncontroller.go @@ -23,13 +23,13 @@ import ( "sync" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" - unversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" + unversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/informers" @@ -95,17 +95,17 @@ func NewDaemonSetsController(daemonSetInformer informers.DaemonSetInformer, podI eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(glog.Infof) // TODO: remove the wrapper when every clients have moved to use the clientset. - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.Core().Events("")}) if kubeClient != nil && kubeClient.Core().RESTClient().GetRateLimiter() != nil { metrics.RegisterMetricAndTrackRateLimiterUsage("daemon_controller", kubeClient.Core().RESTClient().GetRateLimiter()) } dsc := &DaemonSetsController{ kubeClient: kubeClient, - eventRecorder: eventBroadcaster.NewRecorder(api.EventSource{Component: "daemonset-controller"}), + eventRecorder: eventBroadcaster.NewRecorder(v1.EventSource{Component: "daemonset-controller"}), podControl: controller.RealPodControl{ KubeClient: kubeClient, - Recorder: eventBroadcaster.NewRecorder(api.EventSource{Component: "daemon-set"}), + Recorder: eventBroadcaster.NewRecorder(v1.EventSource{Component: "daemon-set"}), }, burstReplicas: BurstReplicas, expectations: controller.NewControllerExpectations(), @@ -239,7 +239,7 @@ func (dsc *DaemonSetsController) enqueueDaemonSet(ds *extensions.DaemonSet) { dsc.queue.Add(key) } -func (dsc *DaemonSetsController) getPodDaemonSet(pod *api.Pod) *extensions.DaemonSet { +func (dsc *DaemonSetsController) getPodDaemonSet(pod *v1.Pod) *extensions.DaemonSet { // look up in the cache, if cached and the cache is valid, just return cached value if obj, cached := dsc.lookupCache.GetMatchingObject(pod); cached { ds, ok := obj.(*extensions.DaemonSet) @@ -272,7 +272,7 @@ func (dsc *DaemonSetsController) getPodDaemonSet(pod *api.Pod) *extensions.Daemo } // isCacheValid check if the cache is valid -func (dsc *DaemonSetsController) isCacheValid(pod *api.Pod, cachedDS *extensions.DaemonSet) bool { +func (dsc *DaemonSetsController) isCacheValid(pod *v1.Pod, cachedDS *extensions.DaemonSet) bool { _, exists, err := dsc.dsStore.Get(cachedDS) // ds has been deleted or updated, cache is invalid if err != nil || !exists || !isDaemonSetMatch(pod, cachedDS) { @@ -283,7 +283,7 @@ func (dsc *DaemonSetsController) isCacheValid(pod *api.Pod, cachedDS *extensions // isDaemonSetMatch take a Pod and DaemonSet, return whether the Pod and DaemonSet are matching // TODO(mqliang): This logic is a copy from GetPodDaemonSets(), remove the duplication -func isDaemonSetMatch(pod *api.Pod, ds *extensions.DaemonSet) bool { +func isDaemonSetMatch(pod *v1.Pod, ds *extensions.DaemonSet) bool { if ds.Namespace != pod.Namespace { return false } @@ -301,7 +301,7 @@ func isDaemonSetMatch(pod *api.Pod, ds *extensions.DaemonSet) bool { } func (dsc *DaemonSetsController) addPod(obj interface{}) { - pod := obj.(*api.Pod) + pod := obj.(*v1.Pod) glog.V(4).Infof("Pod %s added.", pod.Name) if ds := dsc.getPodDaemonSet(pod); ds != nil { dsKey, err := controller.KeyFunc(ds) @@ -316,10 +316,10 @@ func (dsc *DaemonSetsController) addPod(obj interface{}) { // When a pod is updated, figure out what sets manage it and wake them // up. If the labels of the pod have changed we need to awaken both the old -// and new set. old and cur must be *api.Pod types. +// and new set. old and cur must be *v1.Pod types. func (dsc *DaemonSetsController) updatePod(old, cur interface{}) { - curPod := cur.(*api.Pod) - oldPod := old.(*api.Pod) + curPod := cur.(*v1.Pod) + oldPod := old.(*v1.Pod) if curPod.ResourceVersion == oldPod.ResourceVersion { // Periodic resync will send update events for all known pods. // Two different versions of the same pod will always have different RVs. @@ -342,7 +342,7 @@ func (dsc *DaemonSetsController) updatePod(old, cur interface{}) { } func (dsc *DaemonSetsController) deletePod(obj interface{}) { - pod, ok := obj.(*api.Pod) + pod, ok := obj.(*v1.Pod) // When a delete is dropped, the relist will notice a pod in the store not // in the list, leading to the insertion of a tombstone object which contains // the deleted key/value. Note that this value might be stale. If the pod @@ -354,7 +354,7 @@ func (dsc *DaemonSetsController) deletePod(obj interface{}) { glog.Errorf("Couldn't get object from tombstone %#v", obj) return } - pod, ok = tombstone.Obj.(*api.Pod) + pod, ok = tombstone.Obj.(*v1.Pod) if !ok { glog.Errorf("Tombstone contained object that is not a pod %#v", obj) return @@ -379,7 +379,7 @@ func (dsc *DaemonSetsController) addNode(obj interface{}) { glog.V(4).Infof("Error enqueueing daemon sets: %v", err) return } - node := obj.(*api.Node) + node := obj.(*v1.Node) for i := range dsList.Items { ds := &dsList.Items[i] shouldEnqueue := dsc.nodeShouldRunDaemonPod(node, ds) @@ -390,8 +390,8 @@ func (dsc *DaemonSetsController) addNode(obj interface{}) { } func (dsc *DaemonSetsController) updateNode(old, cur interface{}) { - oldNode := old.(*api.Node) - curNode := cur.(*api.Node) + oldNode := old.(*v1.Node) + curNode := cur.(*v1.Node) if reflect.DeepEqual(oldNode.Labels, curNode.Labels) { // If node labels didn't change, we can ignore this update. return @@ -412,8 +412,8 @@ func (dsc *DaemonSetsController) updateNode(old, cur interface{}) { } // getNodesToDaemonSetPods returns a map from nodes to daemon pods (corresponding to ds) running on the nodes. -func (dsc *DaemonSetsController) getNodesToDaemonPods(ds *extensions.DaemonSet) (map[string][]*api.Pod, error) { - nodeToDaemonPods := make(map[string][]*api.Pod) +func (dsc *DaemonSetsController) getNodesToDaemonPods(ds *extensions.DaemonSet) (map[string][]*v1.Pod, error) { + nodeToDaemonPods := make(map[string][]*v1.Pod) selector, err := unversioned.LabelSelectorAsSelector(ds.Spec.Selector) if err != nil { return nil, err @@ -585,7 +585,7 @@ func (dsc *DaemonSetsController) updateDaemonSetStatus(ds *extensions.DaemonSet) // Sort the daemon pods by creation time, so the the oldest is first. daemonPods, _ := nodeToDaemonPods[node.Name] sort.Sort(podByCreationTimestamp(daemonPods)) - if api.IsPodReady(daemonPods[0]) { + if v1.IsPodReady(daemonPods[0]) { numberReady++ } } @@ -623,7 +623,7 @@ func (dsc *DaemonSetsController) syncDaemonSet(key string) error { everything := unversioned.LabelSelector{} if reflect.DeepEqual(ds.Spec.Selector, &everything) { - dsc.eventRecorder.Eventf(ds, api.EventTypeWarning, "SelectingAll", "This daemon set is selecting all pods. A non-empty selector is required.") + dsc.eventRecorder.Eventf(ds, v1.EventTypeWarning, "SelectingAll", "This daemon set is selecting all pods. A non-empty selector is required.") return nil } @@ -644,7 +644,7 @@ func (dsc *DaemonSetsController) syncDaemonSet(key string) error { return dsc.updateDaemonSetStatus(ds) } -func (dsc *DaemonSetsController) nodeShouldRunDaemonPod(node *api.Node, ds *extensions.DaemonSet) bool { +func (dsc *DaemonSetsController) nodeShouldRunDaemonPod(node *v1.Node, ds *extensions.DaemonSet) bool { // If the daemon set specifies a node name, check that it matches with node.Name. if !(ds.Spec.Template.Spec.NodeName == "" || ds.Spec.Template.Spec.NodeName == node.Name) { return false @@ -652,23 +652,23 @@ func (dsc *DaemonSetsController) nodeShouldRunDaemonPod(node *api.Node, ds *exte // TODO: Move it to the predicates for _, c := range node.Status.Conditions { - if c.Type == api.NodeOutOfDisk && c.Status == api.ConditionTrue { + if c.Type == v1.NodeOutOfDisk && c.Status == v1.ConditionTrue { return false } } - newPod := &api.Pod{Spec: ds.Spec.Template.Spec, ObjectMeta: ds.Spec.Template.ObjectMeta} + newPod := &v1.Pod{Spec: ds.Spec.Template.Spec, ObjectMeta: ds.Spec.Template.ObjectMeta} newPod.Namespace = ds.Namespace newPod.Spec.NodeName = node.Name - pods := []*api.Pod{} + pods := []*v1.Pod{} for _, m := range dsc.podStore.Indexer.List() { - pod := m.(*api.Pod) + pod := m.(*v1.Pod) if pod.Spec.NodeName != node.Name { continue } - if pod.Status.Phase == api.PodSucceeded || pod.Status.Phase == api.PodFailed { + if pod.Status.Phase == v1.PodSucceeded || pod.Status.Phase == v1.PodFailed { continue } // ignore pods that belong to the daemonset when taking into account whether @@ -689,10 +689,10 @@ func (dsc *DaemonSetsController) nodeShouldRunDaemonPod(node *api.Node, ds *exte glog.V(4).Infof("GeneralPredicates failed on ds '%s/%s' for reason: %v", ds.ObjectMeta.Namespace, ds.ObjectMeta.Name, r.GetReason()) switch reason := r.(type) { case *predicates.InsufficientResourceError: - dsc.eventRecorder.Eventf(ds, api.EventTypeNormal, "FailedPlacement", "failed to place pod on %q: %s", node.ObjectMeta.Name, reason.Error()) + dsc.eventRecorder.Eventf(ds, v1.EventTypeNormal, "FailedPlacement", "failed to place pod on %q: %s", node.ObjectMeta.Name, reason.Error()) case *predicates.PredicateFailureError: if reason == predicates.ErrPodNotFitsHostPorts { - dsc.eventRecorder.Eventf(ds, api.EventTypeNormal, "FailedPlacement", "failed to place pod on %q: host port conflict", node.ObjectMeta.Name) + dsc.eventRecorder.Eventf(ds, v1.EventTypeNormal, "FailedPlacement", "failed to place pod on %q: host port conflict", node.ObjectMeta.Name) } } } @@ -712,7 +712,7 @@ func (o byCreationTimestamp) Less(i, j int) bool { return o[i].CreationTimestamp.Before(o[j].CreationTimestamp) } -type podByCreationTimestamp []*api.Pod +type podByCreationTimestamp []*v1.Pod func (o podByCreationTimestamp) Len() int { return len(o) } func (o podByCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] } diff --git a/pkg/controller/daemon/daemoncontroller_test.go b/pkg/controller/daemon/daemoncontroller_test.go index f9f26da2239..b0f4e7f472d 100644 --- a/pkg/controller/daemon/daemoncontroller_test.go +++ b/pkg/controller/daemon/daemoncontroller_test.go @@ -20,14 +20,14 @@ import ( "fmt" "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/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/informers" @@ -55,46 +55,46 @@ func getKey(ds *extensions.DaemonSet, t *testing.T) string { func newDaemonSet(name string) *extensions.DaemonSet { return &extensions.DaemonSet{ TypeMeta: unversioned.TypeMeta{APIVersion: testapi.Extensions.GroupVersion().String()}, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: name, - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, Spec: extensions.DaemonSetSpec{ Selector: &unversioned.LabelSelector{MatchLabels: simpleDaemonSetLabel}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: simpleDaemonSetLabel, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Image: "foo/bar", - TerminationMessagePath: api.TerminationMessagePathDefault, - ImagePullPolicy: api.PullIfNotPresent, + TerminationMessagePath: v1.TerminationMessagePathDefault, + ImagePullPolicy: v1.PullIfNotPresent, SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), }, }, - DNSPolicy: api.DNSDefault, + DNSPolicy: v1.DNSDefault, }, }, }, } } -func newNode(name string, label map[string]string) *api.Node { - return &api.Node{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ +func newNode(name string, label map[string]string) *v1.Node { + return &v1.Node{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: label, - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ - {Type: api.NodeReady, Status: api.ConditionTrue}, + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ + {Type: v1.NodeReady, Status: v1.ConditionTrue}, }, - Allocatable: api.ResourceList{ - api.ResourcePods: resource.MustParse("100"), + Allocatable: v1.ResourceList{ + v1.ResourcePods: resource.MustParse("100"), }, }, } @@ -106,28 +106,28 @@ func addNodes(nodeStore cache.Store, startIndex, numNodes int, label map[string] } } -func newPod(podName string, nodeName string, label map[string]string) *api.Pod { - pod := &api.Pod{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ +func newPod(podName string, nodeName string, label map[string]string) *v1.Pod { + pod := &v1.Pod{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + ObjectMeta: v1.ObjectMeta{ GenerateName: podName, Labels: label, - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: nodeName, - Containers: []api.Container{ + Containers: []v1.Container{ { Image: "foo/bar", - TerminationMessagePath: api.TerminationMessagePathDefault, - ImagePullPolicy: api.PullIfNotPresent, + TerminationMessagePath: v1.TerminationMessagePathDefault, + ImagePullPolicy: v1.PullIfNotPresent, SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), }, }, - DNSPolicy: api.DNSDefault, + DNSPolicy: v1.DNSDefault, }, } - api.GenerateName(api.SimpleNameGenerator, &pod.ObjectMeta) + v1.GenerateName(v1.SimpleNameGenerator, &pod.ObjectMeta) return pod } @@ -138,8 +138,8 @@ func addPods(podStore cache.Store, nodeName string, label map[string]string, num } func newTestController() (*DaemonSetsController, *controller.FakePodControl) { - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) - informerFactory := informers.NewSharedInformerFactory(clientset, controller.NoResyncPeriodFunc()) + clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) + informerFactory := informers.NewSharedInformerFactory(clientset, nil, controller.NoResyncPeriodFunc()) manager := NewDaemonSetsController(informerFactory.DaemonSets(), informerFactory.Pods(), informerFactory.Nodes(), clientset, 0) informerFactory.Start(wait.NeverStop) @@ -212,8 +212,8 @@ func TestOneNodeDaemonLaunchesPod(t *testing.T) { func TestNotReadNodeDaemonDoesNotLaunchPod(t *testing.T) { manager, podControl := newTestController() node := newNode("not-ready", nil) - node.Status.Conditions = []api.NodeCondition{ - {Type: api.NodeReady, Status: api.ConditionFalse}, + node.Status.Conditions = []v1.NodeCondition{ + {Type: v1.NodeReady, Status: v1.ConditionFalse}, } manager.nodeStore.Add(node) ds := newDaemonSet("foo") @@ -225,29 +225,29 @@ func TestNotReadNodeDaemonDoesNotLaunchPod(t *testing.T) { func TestOutOfDiskNodeDaemonDoesNotLaunchPod(t *testing.T) { manager, podControl := newTestController() node := newNode("not-enough-disk", nil) - node.Status.Conditions = []api.NodeCondition{{Type: api.NodeOutOfDisk, Status: api.ConditionTrue}} + node.Status.Conditions = []v1.NodeCondition{{Type: v1.NodeOutOfDisk, Status: v1.ConditionTrue}} manager.nodeStore.Add(node) ds := newDaemonSet("foo") manager.dsStore.Add(ds) syncAndValidateDaemonSets(t, manager, ds, podControl, 0, 0) } -func resourcePodSpec(nodeName, memory, cpu string) api.PodSpec { - return api.PodSpec{ +func resourcePodSpec(nodeName, memory, cpu string) v1.PodSpec { + return v1.PodSpec{ NodeName: nodeName, - Containers: []api.Container{{ - Resources: api.ResourceRequirements{ + Containers: []v1.Container{{ + Resources: v1.ResourceRequirements{ Requests: allocatableResources(memory, cpu), }, }}, } } -func allocatableResources(memory, cpu string) api.ResourceList { - return api.ResourceList{ - api.ResourceMemory: resource.MustParse(memory), - api.ResourceCPU: resource.MustParse(cpu), - api.ResourcePods: resource.MustParse("100"), +func allocatableResources(memory, cpu string) v1.ResourceList { + return v1.ResourceList{ + v1.ResourceMemory: resource.MustParse(memory), + v1.ResourceCPU: resource.MustParse(cpu), + v1.ResourcePods: resource.MustParse("100"), } } @@ -258,7 +258,7 @@ func TestInsufficentCapacityNodeDaemonDoesNotLaunchPod(t *testing.T) { node := newNode("too-much-mem", nil) node.Status.Allocatable = allocatableResources("100M", "200m") manager.nodeStore.Add(node) - manager.podStore.Indexer.Add(&api.Pod{ + manager.podStore.Indexer.Add(&v1.Pod{ Spec: podSpec, }) ds := newDaemonSet("foo") @@ -273,9 +273,9 @@ func TestSufficentCapacityWithTerminatedPodsDaemonLaunchesPod(t *testing.T) { node := newNode("too-much-mem", nil) node.Status.Allocatable = allocatableResources("100M", "200m") manager.nodeStore.Add(node) - manager.podStore.Indexer.Add(&api.Pod{ + manager.podStore.Indexer.Add(&v1.Pod{ Spec: podSpec, - Status: api.PodStatus{Phase: api.PodSucceeded}, + Status: v1.PodStatus{Phase: v1.PodSucceeded}, }) ds := newDaemonSet("foo") ds.Spec.Template.Spec = podSpec @@ -290,7 +290,7 @@ func TestSufficentCapacityNodeDaemonLaunchesPod(t *testing.T) { node := newNode("not-too-much-mem", nil) node.Status.Allocatable = allocatableResources("200M", "200m") manager.nodeStore.Add(node) - manager.podStore.Indexer.Add(&api.Pod{ + manager.podStore.Indexer.Add(&v1.Pod{ Spec: podSpec, }) ds := newDaemonSet("foo") @@ -306,7 +306,7 @@ func TestDontDoAnythingIfBeingDeleted(t *testing.T) { node := newNode("not-too-much-mem", nil) node.Status.Allocatable = allocatableResources("200M", "200m") manager.nodeStore.Add(node) - manager.podStore.Indexer.Add(&api.Pod{ + manager.podStore.Indexer.Add(&v1.Pod{ Spec: podSpec, }) ds := newDaemonSet("foo") @@ -319,10 +319,10 @@ func TestDontDoAnythingIfBeingDeleted(t *testing.T) { // DaemonSets should not place onto nodes that would cause port conflicts func TestPortConflictNodeDaemonDoesNotLaunchPod(t *testing.T) { - podSpec := api.PodSpec{ + podSpec := v1.PodSpec{ NodeName: "port-conflict", - Containers: []api.Container{{ - Ports: []api.ContainerPort{{ + Containers: []v1.Container{{ + Ports: []v1.ContainerPort{{ HostPort: 666, }}, }}, @@ -330,7 +330,7 @@ func TestPortConflictNodeDaemonDoesNotLaunchPod(t *testing.T) { manager, podControl := newTestController() node := newNode("port-conflict", nil) manager.nodeStore.Add(node) - manager.podStore.Indexer.Add(&api.Pod{ + manager.podStore.Indexer.Add(&v1.Pod{ Spec: podSpec, }) @@ -345,10 +345,10 @@ func TestPortConflictNodeDaemonDoesNotLaunchPod(t *testing.T) { // // Issue: https://github.com/kubernetes/kubernetes/issues/22309 func TestPortConflictWithSameDaemonPodDoesNotDeletePod(t *testing.T) { - podSpec := api.PodSpec{ + podSpec := v1.PodSpec{ NodeName: "port-conflict", - Containers: []api.Container{{ - Ports: []api.ContainerPort{{ + Containers: []v1.Container{{ + Ports: []v1.ContainerPort{{ HostPort: 666, }}, }}, @@ -356,10 +356,10 @@ func TestPortConflictWithSameDaemonPodDoesNotDeletePod(t *testing.T) { manager, podControl := newTestController() node := newNode("port-conflict", nil) manager.nodeStore.Add(node) - manager.podStore.Indexer.Add(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + manager.podStore.Indexer.Add(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: simpleDaemonSetLabel, - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, Spec: podSpec, }) @@ -371,18 +371,18 @@ func TestPortConflictWithSameDaemonPodDoesNotDeletePod(t *testing.T) { // DaemonSets should place onto nodes that would not cause port conflicts func TestNoPortConflictNodeDaemonLaunchesPod(t *testing.T) { - podSpec1 := api.PodSpec{ + podSpec1 := v1.PodSpec{ NodeName: "no-port-conflict", - Containers: []api.Container{{ - Ports: []api.ContainerPort{{ + Containers: []v1.Container{{ + Ports: []v1.ContainerPort{{ HostPort: 6661, }}, }}, } - podSpec2 := api.PodSpec{ + podSpec2 := v1.PodSpec{ NodeName: "no-port-conflict", - Containers: []api.Container{{ - Ports: []api.ContainerPort{{ + Containers: []v1.Container{{ + Ports: []v1.ContainerPort{{ HostPort: 6662, }}, }}, @@ -390,7 +390,7 @@ func TestNoPortConflictNodeDaemonLaunchesPod(t *testing.T) { manager, podControl := newTestController() node := newNode("no-port-conflict", nil) manager.nodeStore.Add(node) - manager.podStore.Indexer.Add(&api.Pod{ + manager.podStore.Indexer.Add(&v1.Pod{ Spec: podSpec1, }) ds := newDaemonSet("foo") @@ -406,12 +406,12 @@ func TestPodIsNotDeletedByDaemonsetWithEmptyLabelSelector(t *testing.T) { manager, podControl := newTestController() manager.nodeStore.Store.Add(newNode("node1", nil)) // Create pod not controlled by a daemonset. - manager.podStore.Indexer.Add(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + manager.podStore.Indexer.Add(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"bang": "boom"}, - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: "node1", }, }) @@ -554,7 +554,7 @@ func TestNodeAffinityDaemonLaunchesPods(t *testing.T) { addNodes(manager.nodeStore.Store, 4, 3, simpleNodeLabel) daemon := newDaemonSet("foo") affinity := map[string]string{ - api.AffinityAnnotationKey: fmt.Sprintf(` + v1.AffinityAnnotationKey: fmt.Sprintf(` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -586,7 +586,7 @@ func TestNumberReadyStatus(t *testing.T) { selector, _ := unversioned.LabelSelectorAsSelector(daemon.Spec.Selector) daemonPods, _ := manager.podStore.Pods(daemon.Namespace).List(selector) for _, pod := range daemonPods { - condition := api.PodCondition{Type: api.PodReady, Status: api.ConditionTrue} + condition := v1.PodCondition{Type: v1.PodReady, Status: v1.ConditionTrue} pod.Status.Conditions = append(pod.Status.Conditions, condition) } diff --git a/pkg/controller/deployment/BUILD b/pkg/controller/deployment/BUILD index c50ebd0d620..135ad889c88 100644 --- a/pkg/controller/deployment/BUILD +++ b/pkg/controller/deployment/BUILD @@ -25,10 +25,11 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/retry:go_default_library", "//pkg/controller:go_default_library", @@ -58,11 +59,11 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/apis/extensions:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/controller:go_default_library", diff --git a/pkg/controller/deployment/deployment_controller.go b/pkg/controller/deployment/deployment_controller.go index 17986c7891f..7a8fe1eb748 100644 --- a/pkg/controller/deployment/deployment_controller.go +++ b/pkg/controller/deployment/deployment_controller.go @@ -29,10 +29,11 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/deployment/util" @@ -91,14 +92,14 @@ func NewDeploymentController(dInformer informers.DeploymentInformer, rsInformer eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(glog.Infof) // TODO: remove the wrapper when every clients have moved to use the clientset. - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: client.Core().Events("")}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: client.Core().Events("")}) if client != nil && client.Core().RESTClient().GetRateLimiter() != nil { metrics.RegisterMetricAndTrackRateLimiterUsage("deployment_controller", client.Core().RESTClient().GetRateLimiter()) } dc := &DeploymentController{ client: client, - eventRecorder: eventBroadcaster.NewRecorder(api.EventSource{Component: "deployment-controller"}), + eventRecorder: eventBroadcaster.NewRecorder(v1.EventSource{Component: "deployment-controller"}), queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "deployment"), } @@ -333,7 +334,7 @@ func (dc *DeploymentController) syncDeployment(key string) error { everything := unversioned.LabelSelector{} if reflect.DeepEqual(d.Spec.Selector, &everything) { - dc.eventRecorder.Eventf(d, api.EventTypeWarning, "SelectingAll", "This deployment is selecting all pods. A non-empty selector is required.") + dc.eventRecorder.Eventf(d, v1.EventTypeWarning, "SelectingAll", "This deployment is selecting all pods. A non-empty selector is required.") if d.Status.ObservedGeneration < d.Generation { d.Status.ObservedGeneration = d.Generation dc.client.Extensions().Deployments(d.Namespace).UpdateStatus(d) @@ -347,7 +348,7 @@ func (dc *DeploymentController) syncDeployment(key string) error { // Handle overlapping deployments by deterministically avoid syncing deployments that fight over ReplicaSets. if err = dc.handleOverlap(d); err != nil { - dc.eventRecorder.Eventf(d, api.EventTypeWarning, "SelectorOverlap", err.Error()) + dc.eventRecorder.Eventf(d, v1.EventTypeWarning, "SelectorOverlap", err.Error()) return nil } diff --git a/pkg/controller/deployment/deployment_controller_test.go b/pkg/controller/deployment/deployment_controller_test.go index 03f40b13e5e..3ff88f1c1ae 100644 --- a/pkg/controller/deployment/deployment_controller_test.go +++ b/pkg/controller/deployment/deployment_controller_test.go @@ -20,11 +20,11 @@ import ( "fmt" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/controller" @@ -41,15 +41,15 @@ var ( func rs(name string, replicas int, selector map[string]string, timestamp unversioned.Time) *extensions.ReplicaSet { return &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: name, CreationTimestamp: timestamp, - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, Spec: extensions.ReplicaSetSpec{ - Replicas: int32(replicas), + Replicas: func() *int32 { i := int32(replicas); return &i }(), Selector: &unversioned.LabelSelector{MatchLabels: selector}, - Template: api.PodTemplateSpec{}, + Template: v1.PodTemplateSpec{}, }, } } @@ -65,24 +65,27 @@ func newRSWithStatus(name string, specReplicas, statusReplicas int, selector map func newDeployment(name string, replicas int, revisionHistoryLimit *int32, maxSurge, maxUnavailable *intstr.IntOrString, selector map[string]string) *extensions.Deployment { d := extensions.Deployment{ TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(extensions.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: uuid.NewUUID(), Name: name, - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, Spec: extensions.DeploymentSpec{ Strategy: extensions.DeploymentStrategy{ - Type: extensions.RollingUpdateDeploymentStrategyType, - RollingUpdate: &extensions.RollingUpdateDeployment{}, + Type: extensions.RollingUpdateDeploymentStrategyType, + RollingUpdate: &extensions.RollingUpdateDeployment{ + MaxUnavailable: func() *intstr.IntOrString { i := intstr.FromInt(0); return &i }(), + MaxSurge: func() *intstr.IntOrString { i := intstr.FromInt(0); return &i }(), + }, }, - Replicas: int32(replicas), + Replicas: func() *int32 { i := int32(replicas); return &i }(), Selector: &unversioned.LabelSelector{MatchLabels: selector}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: selector, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Image: "foo/bar", }, @@ -93,22 +96,22 @@ func newDeployment(name string, replicas int, revisionHistoryLimit *int32, maxSu }, } if maxSurge != nil { - d.Spec.Strategy.RollingUpdate.MaxSurge = *maxSurge + d.Spec.Strategy.RollingUpdate.MaxSurge = maxSurge } if maxUnavailable != nil { - d.Spec.Strategy.RollingUpdate.MaxUnavailable = *maxUnavailable + d.Spec.Strategy.RollingUpdate.MaxUnavailable = maxUnavailable } return &d } func newReplicaSet(d *extensions.Deployment, name string, replicas int) *extensions.ReplicaSet { return &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: name, - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, Spec: extensions.ReplicaSetSpec{ - Replicas: int32(replicas), + Replicas: func() *int32 { i := int32(replicas); return &i }(), Template: d.Spec.Template, }, } @@ -130,7 +133,7 @@ type fixture struct { // Objects to put in the store. dLister []*extensions.Deployment rsLister []*extensions.ReplicaSet - podLister []*api.Pod + podLister []*v1.Pod // Actions expected to happen on the client. Objects from here are also // preloaded into NewSimpleFake. @@ -161,7 +164,7 @@ func newFixture(t *testing.T) *fixture { func (f *fixture) run(deploymentName string) { f.client = fake.NewSimpleClientset(f.objects...) - informers := informers.NewSharedInformerFactory(f.client, controller.NoResyncPeriodFunc()) + informers := informers.NewSharedInformerFactory(f.client, nil, controller.NoResyncPeriodFunc()) c := NewDeploymentController(informers.Deployments(), informers.ReplicaSets(), informers.Pods(), f.client) c.eventRecorder = &record.FakeRecorder{} c.dListerSynced = alwaysReady @@ -234,7 +237,7 @@ func TestSyncDeploymentDontDoAnythingDuringDeletion(t *testing.T) { // issue: https://github.com/kubernetes/kubernetes/issues/23218 func TestDeploymentController_dontSyncDeploymentsWithEmptyPodSelector(t *testing.T) { fake := &fake.Clientset{} - informers := informers.NewSharedInformerFactory(fake, controller.NoResyncPeriodFunc()) + informers := informers.NewSharedInformerFactory(fake, nil, controller.NoResyncPeriodFunc()) controller := NewDeploymentController(informers.Deployments(), informers.ReplicaSets(), informers.Pods(), fake) controller.eventRecorder = &record.FakeRecorder{} controller.dListerSynced = alwaysReady diff --git a/pkg/controller/deployment/progress.go b/pkg/controller/deployment/progress.go index f2dd458e633..f53339b62ce 100644 --- a/pkg/controller/deployment/progress.go +++ b/pkg/controller/deployment/progress.go @@ -20,8 +20,8 @@ import ( "fmt" "reflect" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/controller/deployment/util" ) @@ -95,14 +95,14 @@ func (dc *DeploymentController) syncRolloutStatus(allRSs []*extensions.ReplicaSe // Update the deployment conditions with a message for the new replica set that // was successfully deployed. If the condition already exists, we ignore this update. msg := fmt.Sprintf("Replica set %q has successfully progressed.", newRS.Name) - condition := util.NewDeploymentCondition(extensions.DeploymentProgressing, api.ConditionTrue, util.NewRSAvailableReason, msg) + condition := util.NewDeploymentCondition(extensions.DeploymentProgressing, v1.ConditionTrue, util.NewRSAvailableReason, msg) util.SetDeploymentCondition(&newStatus, *condition) case util.DeploymentProgressing(d, &newStatus): // If there is any progress made, continue by not checking if the deployment failed. This // behavior emulates the rolling updater progressDeadline check. msg := fmt.Sprintf("Replica set %q is progressing.", newRS.Name) - condition := util.NewDeploymentCondition(extensions.DeploymentProgressing, api.ConditionTrue, util.ReplicaSetUpdatedReason, msg) + condition := util.NewDeploymentCondition(extensions.DeploymentProgressing, v1.ConditionTrue, util.ReplicaSetUpdatedReason, msg) // Update the current Progressing condition or add a new one if it doesn't exist. // If a Progressing condition with status=true already exists, we should update // everything but lastTransitionTime. SetDeploymentCondition already does that but @@ -111,7 +111,7 @@ func (dc *DeploymentController) syncRolloutStatus(allRSs []*extensions.ReplicaSe // update with the same reason and change just lastUpdateTime iff we notice any // progress. That's why we handle it here. if currentCond != nil { - if currentCond.Status == api.ConditionTrue { + if currentCond.Status == v1.ConditionTrue { condition.LastTransitionTime = currentCond.LastTransitionTime } util.RemoveDeploymentCondition(&newStatus, extensions.DeploymentProgressing) @@ -122,7 +122,7 @@ func (dc *DeploymentController) syncRolloutStatus(allRSs []*extensions.ReplicaSe // Update the deployment with a timeout condition. If the condition already exists, // we ignore this update. msg := fmt.Sprintf("Replica set %q has timed out progressing.", newRS.Name) - condition := util.NewDeploymentCondition(extensions.DeploymentProgressing, api.ConditionFalse, util.TimedOutReason, msg) + condition := util.NewDeploymentCondition(extensions.DeploymentProgressing, v1.ConditionFalse, util.TimedOutReason, msg) util.SetDeploymentCondition(&newStatus, *condition) } } diff --git a/pkg/controller/deployment/recreate.go b/pkg/controller/deployment/recreate.go index 5255e930c85..6b81063632d 100644 --- a/pkg/controller/deployment/recreate.go +++ b/pkg/controller/deployment/recreate.go @@ -19,7 +19,7 @@ package deployment import ( "fmt" - "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/retry" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/util/wait" @@ -82,7 +82,7 @@ func (dc *DeploymentController) scaleDownOldReplicaSetsForRecreate(oldRSs []*ext for i := range oldRSs { rs := oldRSs[i] // Scaling not required. - if rs.Spec.Replicas == 0 { + if *(rs.Spec.Replicas) == 0 { continue } scaledRS, updatedRS, err := dc.scaleReplicaSetAndRecordEvent(rs, 0, deployment) @@ -104,7 +104,7 @@ func (dc *DeploymentController) waitForInactiveReplicaSets(oldRSs []*extensions. rs := oldRSs[i] desiredGeneration := rs.Generation observedGeneration := rs.Status.ObservedGeneration - specReplicas := rs.Spec.Replicas + specReplicas := *(rs.Spec.Replicas) statusReplicas := rs.Status.Replicas if err := wait.ExponentialBackoff(retry.DefaultRetry, func() (bool, error) { @@ -113,13 +113,13 @@ func (dc *DeploymentController) waitForInactiveReplicaSets(oldRSs []*extensions. return false, err } - specReplicas = replicaSet.Spec.Replicas + specReplicas = *(replicaSet.Spec.Replicas) statusReplicas = replicaSet.Status.Replicas observedGeneration = replicaSet.Status.ObservedGeneration // TODO: We also need to wait for terminating replicas to actually terminate. // See https://github.com/kubernetes/kubernetes/issues/32567 - return observedGeneration >= desiredGeneration && replicaSet.Spec.Replicas == 0 && replicaSet.Status.Replicas == 0, nil + return observedGeneration >= desiredGeneration && *(replicaSet.Spec.Replicas) == 0 && replicaSet.Status.Replicas == 0, nil }); err != nil { if err == wait.ErrWaitTimeout { err = fmt.Errorf("replica set %q never became inactive: synced=%t, spec.replicas=%d, status.replicas=%d", @@ -133,6 +133,6 @@ func (dc *DeploymentController) waitForInactiveReplicaSets(oldRSs []*extensions. // scaleUpNewReplicaSetForRecreate scales up new replica set when deployment strategy is "Recreate" func (dc *DeploymentController) scaleUpNewReplicaSetForRecreate(newRS *extensions.ReplicaSet, deployment *extensions.Deployment) (bool, error) { - scaled, _, err := dc.scaleReplicaSetAndRecordEvent(newRS, deployment.Spec.Replicas, deployment) + scaled, _, err := dc.scaleReplicaSetAndRecordEvent(newRS, *(deployment.Spec.Replicas), deployment) return scaled, err } diff --git a/pkg/controller/deployment/rollback.go b/pkg/controller/deployment/rollback.go index bb5e91416a6..b04d67026c8 100644 --- a/pkg/controller/deployment/rollback.go +++ b/pkg/controller/deployment/rollback.go @@ -21,8 +21,8 @@ import ( "reflect" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" ) @@ -91,11 +91,11 @@ func (dc *DeploymentController) rollbackToTemplate(deployment *extensions.Deploy } func (dc *DeploymentController) emitRollbackWarningEvent(deployment *extensions.Deployment, reason, message string) { - dc.eventRecorder.Eventf(deployment, api.EventTypeWarning, reason, message) + dc.eventRecorder.Eventf(deployment, v1.EventTypeWarning, reason, message) } func (dc *DeploymentController) emitRollbackNormalEvent(deployment *extensions.Deployment, message string) { - dc.eventRecorder.Eventf(deployment, api.EventTypeNormal, deploymentutil.RollbackDone, message) + dc.eventRecorder.Eventf(deployment, v1.EventTypeNormal, deploymentutil.RollbackDone, message) } // updateDeploymentAndClearRollbackTo sets .spec.rollbackTo to nil and update the input deployment diff --git a/pkg/controller/deployment/rolling.go b/pkg/controller/deployment/rolling.go index 47d7d6f623f..1c41508336f 100644 --- a/pkg/controller/deployment/rolling.go +++ b/pkg/controller/deployment/rolling.go @@ -21,7 +21,7 @@ import ( "sort" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/controller" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" "k8s.io/kubernetes/pkg/util/integer" @@ -62,13 +62,13 @@ func (dc *DeploymentController) rolloutRolling(deployment *extensions.Deployment } func (dc *DeploymentController) reconcileNewReplicaSet(allRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet, deployment *extensions.Deployment) (bool, error) { - if newRS.Spec.Replicas == deployment.Spec.Replicas { + if *(newRS.Spec.Replicas) == *(deployment.Spec.Replicas) { // Scaling not required. return false, nil } - if newRS.Spec.Replicas > deployment.Spec.Replicas { + if *(newRS.Spec.Replicas) > *(deployment.Spec.Replicas) { // Scale down. - scaled, _, err := dc.scaleReplicaSetAndRecordEvent(newRS, deployment.Spec.Replicas, deployment) + scaled, _, err := dc.scaleReplicaSetAndRecordEvent(newRS, *(deployment.Spec.Replicas), deployment) return scaled, err } newReplicasCount, err := deploymentutil.NewRSNewReplicas(deployment, allRSs, newRS) @@ -120,8 +120,8 @@ func (dc *DeploymentController) reconcileOldReplicaSets(allRSs []*extensions.Rep // * The new replica set created must start with 0 replicas because allPodsCount is already at 13. // * However, newRSPodsUnavailable would also be 0, so the 2 old replica sets could be scaled down by 5 (13 - 8 - 0), which would then // allow the new replica set to be scaled up by 5. - minAvailable := deployment.Spec.Replicas - maxUnavailable - newRSUnavailablePodCount := newRS.Spec.Replicas - newRS.Status.AvailableReplicas + minAvailable := *(deployment.Spec.Replicas) - maxUnavailable + newRSUnavailablePodCount := *(newRS.Spec.Replicas) - newRS.Status.AvailableReplicas maxScaledDown := allPodsCount - minAvailable - newRSUnavailablePodCount if maxScaledDown <= 0 { return false, nil @@ -158,20 +158,20 @@ func (dc *DeploymentController) cleanupUnhealthyReplicas(oldRSs []*extensions.Re if totalScaledDown >= maxCleanupCount { break } - if targetRS.Spec.Replicas == 0 { + if *(targetRS.Spec.Replicas) == 0 { // cannot scale down this replica set. continue } glog.V(4).Infof("Found %d available pods in old RS %s/%s", targetRS.Status.AvailableReplicas, targetRS.Namespace, targetRS.Name) - if targetRS.Spec.Replicas == targetRS.Status.AvailableReplicas { + if *(targetRS.Spec.Replicas) == targetRS.Status.AvailableReplicas { // no unhealthy replicas found, no scaling required. continue } - scaledDownCount := int32(integer.IntMin(int(maxCleanupCount-totalScaledDown), int(targetRS.Spec.Replicas-targetRS.Status.AvailableReplicas))) - newReplicasCount := targetRS.Spec.Replicas - scaledDownCount - if newReplicasCount > targetRS.Spec.Replicas { - return nil, 0, fmt.Errorf("when cleaning up unhealthy replicas, got invalid request to scale down %s/%s %d -> %d", targetRS.Namespace, targetRS.Name, targetRS.Spec.Replicas, newReplicasCount) + scaledDownCount := int32(integer.IntMin(int(maxCleanupCount-totalScaledDown), int(*(targetRS.Spec.Replicas)-targetRS.Status.AvailableReplicas))) + newReplicasCount := *(targetRS.Spec.Replicas) - scaledDownCount + if newReplicasCount > *(targetRS.Spec.Replicas) { + return nil, 0, fmt.Errorf("when cleaning up unhealthy replicas, got invalid request to scale down %s/%s %d -> %d", targetRS.Namespace, targetRS.Name, *(targetRS.Spec.Replicas), newReplicasCount) } _, updatedOldRS, err := dc.scaleReplicaSetAndRecordEvent(targetRS, newReplicasCount, deployment) if err != nil { @@ -189,7 +189,7 @@ func (dc *DeploymentController) scaleDownOldReplicaSetsForRollingUpdate(allRSs [ maxUnavailable := deploymentutil.MaxUnavailable(*deployment) // Check if we can scale down. - minAvailable := deployment.Spec.Replicas - maxUnavailable + minAvailable := *(deployment.Spec.Replicas) - maxUnavailable // Find the number of available pods. availablePodCount := deploymentutil.GetAvailableReplicaCountForReplicaSets(allRSs) if availablePodCount <= minAvailable { @@ -207,15 +207,15 @@ func (dc *DeploymentController) scaleDownOldReplicaSetsForRollingUpdate(allRSs [ // No further scaling required. break } - if targetRS.Spec.Replicas == 0 { + if *(targetRS.Spec.Replicas) == 0 { // cannot scale down this ReplicaSet. continue } // Scale down. - scaleDownCount := int32(integer.IntMin(int(targetRS.Spec.Replicas), int(totalScaleDownCount-totalScaledDown))) - newReplicasCount := targetRS.Spec.Replicas - scaleDownCount - if newReplicasCount > targetRS.Spec.Replicas { - return 0, fmt.Errorf("when scaling down old RS, got invalid request to scale down %s/%s %d -> %d", targetRS.Namespace, targetRS.Name, targetRS.Spec.Replicas, newReplicasCount) + scaleDownCount := int32(integer.IntMin(int(*(targetRS.Spec.Replicas)), int(totalScaleDownCount-totalScaledDown))) + newReplicasCount := *(targetRS.Spec.Replicas) - scaleDownCount + if newReplicasCount > *(targetRS.Spec.Replicas) { + return 0, fmt.Errorf("when scaling down old RS, got invalid request to scale down %s/%s %d -> %d", targetRS.Namespace, targetRS.Name, *(targetRS.Spec.Replicas), newReplicasCount) } _, _, err := dc.scaleReplicaSetAndRecordEvent(targetRS, newReplicasCount, deployment) if err != nil { diff --git a/pkg/controller/deployment/rolling_test.go b/pkg/controller/deployment/rolling_test.go index bee1e453cf4..bb9fc165ea5 100644 --- a/pkg/controller/deployment/rolling_test.go +++ b/pkg/controller/deployment/rolling_test.go @@ -19,8 +19,8 @@ package deployment import ( "testing" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/util/intstr" @@ -110,7 +110,7 @@ func TestDeploymentController_reconcileNewReplicaSet(t *testing.T) { continue } updated := fake.Actions()[0].(core.UpdateAction).GetObject().(*extensions.ReplicaSet) - if e, a := test.expectedNewReplicas, int(updated.Spec.Replicas); e != a { + if e, a := test.expectedNewReplicas, int(*(updated.Spec.Replicas)); e != a { t.Errorf("expected update to %d replicas, got %d", e, a) } } @@ -372,7 +372,7 @@ func TestDeploymentController_scaleDownOldReplicaSetsForRollingUpdate(t *testing continue } updated := updateAction.GetObject().(*extensions.ReplicaSet) - if e, a := test.expectedOldReplicas, int(updated.Spec.Replicas); e != a { + if e, a := test.expectedOldReplicas, int(*(updated.Spec.Replicas)); e != a { t.Errorf("expected update to %d replicas, got %d", e, a) } } diff --git a/pkg/controller/deployment/sync.go b/pkg/controller/deployment/sync.go index 2e48e30024e..014363b2148 100644 --- a/pkg/controller/deployment/sync.go +++ b/pkg/controller/deployment/sync.go @@ -26,9 +26,11 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/controller" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" + "k8s.io/kubernetes/pkg/labels" utilerrors "k8s.io/kubernetes/pkg/util/errors" labelsutil "k8s.io/kubernetes/pkg/util/labels" podutil "k8s.io/kubernetes/pkg/util/pod" @@ -80,11 +82,11 @@ func (dc *DeploymentController) checkPausedConditions(d *extensions.Deployment) needsUpdate := false if d.Spec.Paused && !pausedCondExists { - condition := deploymentutil.NewDeploymentCondition(extensions.DeploymentProgressing, api.ConditionUnknown, deploymentutil.PausedDeployReason, "Deployment is paused") + condition := deploymentutil.NewDeploymentCondition(extensions.DeploymentProgressing, v1.ConditionUnknown, deploymentutil.PausedDeployReason, "Deployment is paused") deploymentutil.SetDeploymentCondition(&d.Status, *condition) needsUpdate = true } else if !d.Spec.Paused && pausedCondExists { - condition := deploymentutil.NewDeploymentCondition(extensions.DeploymentProgressing, api.ConditionUnknown, deploymentutil.ResumedDeployReason, "Deployment is resumed") + condition := deploymentutil.NewDeploymentCondition(extensions.DeploymentProgressing, v1.ConditionUnknown, deploymentutil.ResumedDeployReason, "Deployment is resumed") deploymentutil.SetDeploymentCondition(&d.Status, *condition) needsUpdate = true } @@ -126,10 +128,14 @@ func (dc *DeploymentController) getAllReplicaSetsAndSyncRevision(deployment *ext } // rsAndPodsWithHashKeySynced returns the RSes and pods the given deployment targets, with pod-template-hash information synced. -func (dc *DeploymentController) rsAndPodsWithHashKeySynced(deployment *extensions.Deployment) ([]*extensions.ReplicaSet, *api.PodList, error) { +func (dc *DeploymentController) rsAndPodsWithHashKeySynced(deployment *extensions.Deployment) ([]*extensions.ReplicaSet, *v1.PodList, error) { rsList, err := deploymentutil.ListReplicaSets(deployment, - func(namespace string, options api.ListOptions) ([]*extensions.ReplicaSet, error) { - return dc.rsLister.ReplicaSets(namespace).List(options.LabelSelector) + func(namespace string, options v1.ListOptions) ([]*extensions.ReplicaSet, error) { + parsed, err := labels.Parse(options.LabelSelector) + if err != nil { + return nil, err + } + return dc.rsLister.ReplicaSets(namespace).List(parsed) }) if err != nil { return nil, nil, fmt.Errorf("error listing ReplicaSets: %v", err) @@ -201,12 +207,16 @@ func (dc *DeploymentController) addHashKeyToRSAndPods(rs *extensions.ReplicaSet) if err != nil { return nil, fmt.Errorf("error in converting selector to label selector for replica set %s: %s", updatedRS.Name, err) } - options := api.ListOptions{LabelSelector: selector} - pods, err := dc.podLister.Pods(namespace).List(options.LabelSelector) + options := v1.ListOptions{LabelSelector: selector.String()} + parsed, err := labels.Parse(options.LabelSelector) + if err != nil { + return nil, err + } + pods, err := dc.podLister.Pods(namespace).List(parsed) if err != nil { return nil, fmt.Errorf("error in getting pod list for namespace %s and list options %+v: %s", namespace, options, err) } - podList := api.PodList{Items: make([]api.Pod, 0, len(pods))} + podList := v1.PodList{Items: make([]v1.Pod, 0, len(pods))} for i := range pods { podList.Items = append(podList.Items, *pods[i]) } @@ -253,11 +263,15 @@ func (dc *DeploymentController) addHashKeyToRSAndPods(rs *extensions.ReplicaSet) return updatedRS, nil } -func (dc *DeploymentController) listPods(deployment *extensions.Deployment) (*api.PodList, error) { +func (dc *DeploymentController) listPods(deployment *extensions.Deployment) (*v1.PodList, error) { return deploymentutil.ListPods(deployment, - func(namespace string, options api.ListOptions) (*api.PodList, error) { - pods, err := dc.podLister.Pods(namespace).List(options.LabelSelector) - result := api.PodList{Items: make([]api.Pod, 0, len(pods))} + func(namespace string, options v1.ListOptions) (*v1.PodList, error) { + parsed, err := labels.Parse(options.LabelSelector) + if err != nil { + return nil, err + } + pods, err := dc.podLister.Pods(namespace).List(parsed) + result := v1.PodList{Items: make([]v1.Pod, 0, len(pods))} for i := range pods { result.Items = append(result.Items, *pods[i]) } @@ -307,7 +321,7 @@ func (dc *DeploymentController) getNewReplicaSet(deployment *extensions.Deployme cond := deploymentutil.GetDeploymentCondition(deployment.Status, extensions.DeploymentProgressing) if deployment.Spec.ProgressDeadlineSeconds != nil && cond == nil { msg := fmt.Sprintf("Found new replica set %q", rsCopy.Name) - condition := deploymentutil.NewDeploymentCondition(extensions.DeploymentProgressing, api.ConditionTrue, deploymentutil.FoundNewRSReason, msg) + condition := deploymentutil.NewDeploymentCondition(extensions.DeploymentProgressing, v1.ConditionTrue, deploymentutil.FoundNewRSReason, msg) deploymentutil.SetDeploymentCondition(&deployment.Status, *condition) updateConditions = true } @@ -333,13 +347,13 @@ func (dc *DeploymentController) getNewReplicaSet(deployment *extensions.Deployme // Create new ReplicaSet newRS := extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ // Make the name deterministic, to ensure idempotence Name: deployment.Name + "-" + fmt.Sprintf("%d", podTemplateSpecHash), Namespace: namespace, }, Spec: extensions.ReplicaSetSpec{ - Replicas: 0, + Replicas: func(i int32) *int32 { return &i }(0), MinReadySeconds: deployment.Spec.MinReadySeconds, Selector: newRSSelector, Template: newRSTemplate, @@ -351,7 +365,7 @@ func (dc *DeploymentController) getNewReplicaSet(deployment *extensions.Deployme return nil, err } - newRS.Spec.Replicas = newReplicasCount + *(newRS.Spec.Replicas) = newReplicasCount // Set new replica set's annotation deploymentutil.SetNewReplicaSetAnnotations(deployment, &newRS, newRevision, false) createdRS, err := dc.client.Extensions().ReplicaSets(namespace).Create(&newRS) @@ -365,7 +379,7 @@ func (dc *DeploymentController) getNewReplicaSet(deployment *extensions.Deployme case err != nil: msg := fmt.Sprintf("Failed to create new replica set %q: %v", newRS.Name, err) if deployment.Spec.ProgressDeadlineSeconds != nil { - cond := deploymentutil.NewDeploymentCondition(extensions.DeploymentProgressing, api.ConditionFalse, deploymentutil.FailedRSCreateReason, msg) + cond := deploymentutil.NewDeploymentCondition(extensions.DeploymentProgressing, v1.ConditionFalse, deploymentutil.FailedRSCreateReason, msg) deploymentutil.SetDeploymentCondition(&deployment.Status, *cond) // We don't really care about this error at this point, since we have a bigger issue to report. // TODO: Update the rest of the Deployment status, too. We may need to do this every time we @@ -375,17 +389,17 @@ func (dc *DeploymentController) getNewReplicaSet(deployment *extensions.Deployme // these reasons as well. Related issue: https://github.com/kubernetes/kubernetes/issues/18568 _, _ = dc.client.Extensions().Deployments(deployment.ObjectMeta.Namespace).UpdateStatus(deployment) } - dc.eventRecorder.Eventf(deployment, api.EventTypeWarning, deploymentutil.FailedRSCreateReason, msg) + dc.eventRecorder.Eventf(deployment, v1.EventTypeWarning, deploymentutil.FailedRSCreateReason, msg) return nil, err } if newReplicasCount > 0 { - dc.eventRecorder.Eventf(deployment, api.EventTypeNormal, "ScalingReplicaSet", "Scaled up replica set %s to %d", createdRS.Name, newReplicasCount) + dc.eventRecorder.Eventf(deployment, v1.EventTypeNormal, "ScalingReplicaSet", "Scaled up replica set %s to %d", createdRS.Name, newReplicasCount) } deploymentutil.SetDeploymentRevision(deployment, newRevision) if deployment.Spec.ProgressDeadlineSeconds != nil { msg := fmt.Sprintf("Created new replica set %q", createdRS.Name) - condition := deploymentutil.NewDeploymentCondition(extensions.DeploymentProgressing, api.ConditionTrue, deploymentutil.NewReplicaSetReason, msg) + condition := deploymentutil.NewDeploymentCondition(extensions.DeploymentProgressing, v1.ConditionTrue, deploymentutil.NewReplicaSetReason, msg) deploymentutil.SetDeploymentCondition(&deployment.Status, *condition) } _, err = dc.client.Extensions().Deployments(deployment.Namespace).UpdateStatus(deployment) @@ -401,10 +415,10 @@ func (dc *DeploymentController) scale(deployment *extensions.Deployment, newRS * // If there is only one active replica set then we should scale that up to the full count of the // deployment. If there is no active replica set, then we should scale up the newest replica set. if activeOrLatest := deploymentutil.FindActiveOrLatest(newRS, oldRSs); activeOrLatest != nil { - if activeOrLatest.Spec.Replicas == deployment.Spec.Replicas { + if *(activeOrLatest.Spec.Replicas) == *(deployment.Spec.Replicas) { return nil } - _, _, err := dc.scaleReplicaSetAndRecordEvent(activeOrLatest, deployment.Spec.Replicas, deployment) + _, _, err := dc.scaleReplicaSetAndRecordEvent(activeOrLatest, *(deployment.Spec.Replicas), deployment) return err } @@ -427,8 +441,8 @@ func (dc *DeploymentController) scale(deployment *extensions.Deployment, newRS * allRSsReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs) allowedSize := int32(0) - if deployment.Spec.Replicas > 0 { - allowedSize = deployment.Spec.Replicas + deploymentutil.MaxSurge(*deployment) + if *(deployment.Spec.Replicas) > 0 { + allowedSize = *(deployment.Spec.Replicas) + deploymentutil.MaxSurge(*deployment) } // Number of additional replicas that can be either added or removed from the total @@ -465,10 +479,10 @@ func (dc *DeploymentController) scale(deployment *extensions.Deployment, newRS * if deploymentReplicasToAdd != 0 { proportion := deploymentutil.GetProportion(rs, *deployment, deploymentReplicasToAdd, deploymentReplicasAdded) - nameToSize[rs.Name] = rs.Spec.Replicas + proportion + nameToSize[rs.Name] = *(rs.Spec.Replicas) + proportion deploymentReplicasAdded += proportion } else { - nameToSize[rs.Name] = rs.Spec.Replicas + nameToSize[rs.Name] = *(rs.Spec.Replicas) } } @@ -497,11 +511,11 @@ func (dc *DeploymentController) scale(deployment *extensions.Deployment, newRS * func (dc *DeploymentController) scaleReplicaSetAndRecordEvent(rs *extensions.ReplicaSet, newScale int32, deployment *extensions.Deployment) (bool, *extensions.ReplicaSet, error) { // No need to scale - if rs.Spec.Replicas == newScale { + if *(rs.Spec.Replicas) == newScale { return false, rs, nil } var scalingOperation string - if rs.Spec.Replicas < newScale { + if *(rs.Spec.Replicas) < newScale { scalingOperation = "up" } else { scalingOperation = "down" @@ -517,14 +531,14 @@ func (dc *DeploymentController) scaleReplicaSet(rs *extensions.ReplicaSet, newSc } rsCopy := objCopy.(*extensions.ReplicaSet) - sizeNeedsUpdate := rsCopy.Spec.Replicas != newScale - annotationsNeedUpdate := deploymentutil.SetReplicasAnnotations(rsCopy, deployment.Spec.Replicas, deployment.Spec.Replicas+deploymentutil.MaxSurge(*deployment)) + sizeNeedsUpdate := *(rsCopy.Spec.Replicas) != newScale + annotationsNeedUpdate := deploymentutil.SetReplicasAnnotations(rsCopy, *(deployment.Spec.Replicas), *(deployment.Spec.Replicas)+deploymentutil.MaxSurge(*deployment)) if sizeNeedsUpdate || annotationsNeedUpdate { - rsCopy.Spec.Replicas = newScale + *(rsCopy.Spec.Replicas) = newScale rs, err = dc.client.Extensions().ReplicaSets(rsCopy.Namespace).Update(rsCopy) if err == nil && sizeNeedsUpdate { - dc.eventRecorder.Eventf(deployment, api.EventTypeNormal, "ScalingReplicaSet", "Scaled %s replica set %s to %d", scalingOperation, rs.Name, newScale) + dc.eventRecorder.Eventf(deployment, v1.EventTypeNormal, "ScalingReplicaSet", "Scaled %s replica set %s to %d", scalingOperation, rs.Name, newScale) } } return rs, err @@ -549,7 +563,7 @@ func (dc *DeploymentController) cleanupDeployment(oldRSs []*extensions.ReplicaSe for i := int32(0); i < diff; i++ { rs := oldRSs[i] // Avoid delete replica set with non-zero replica counts - if rs.Status.Replicas != 0 || rs.Spec.Replicas != 0 || rs.Generation > rs.Status.ObservedGeneration { + if rs.Status.Replicas != 0 || *(rs.Spec.Replicas) != 0 || rs.Generation > rs.Status.ObservedGeneration { continue } if err := dc.client.Extensions().ReplicaSets(rs.Namespace).Delete(rs.Name, nil); err != nil && !errors.IsNotFound(err) { @@ -579,11 +593,11 @@ func (dc *DeploymentController) calculateStatus(allRSs []*extensions.ReplicaSet, availableReplicas := deploymentutil.GetAvailableReplicaCountForReplicaSets(allRSs) totalReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs) - if availableReplicas >= deployment.Spec.Replicas-deploymentutil.MaxUnavailable(*deployment) { - minAvailability := deploymentutil.NewDeploymentCondition(extensions.DeploymentAvailable, api.ConditionTrue, deploymentutil.MinimumReplicasAvailable, "Deployment has minimum availability.") + if availableReplicas >= *(deployment.Spec.Replicas)-deploymentutil.MaxUnavailable(*deployment) { + minAvailability := deploymentutil.NewDeploymentCondition(extensions.DeploymentAvailable, v1.ConditionTrue, deploymentutil.MinimumReplicasAvailable, "Deployment has minimum availability.") deploymentutil.SetDeploymentCondition(&deployment.Status, *minAvailability) } else { - noMinAvailability := deploymentutil.NewDeploymentCondition(extensions.DeploymentAvailable, api.ConditionFalse, deploymentutil.MinimumReplicasUnavailable, "Deployment does not have minimum availability.") + noMinAvailability := deploymentutil.NewDeploymentCondition(extensions.DeploymentAvailable, v1.ConditionFalse, deploymentutil.MinimumReplicasUnavailable, "Deployment does not have minimum availability.") deploymentutil.SetDeploymentCondition(&deployment.Status, *noMinAvailability) } @@ -611,7 +625,7 @@ func (dc *DeploymentController) isScalingEvent(d *extensions.Deployment) (bool, if !ok { continue } - if desired != d.Spec.Replicas { + if desired != *(d.Spec.Replicas) { return true, nil } } diff --git a/pkg/controller/deployment/sync_test.go b/pkg/controller/deployment/sync_test.go index 42c9b23de32..6baae690905 100644 --- a/pkg/controller/deployment/sync_test.go +++ b/pkg/controller/deployment/sync_test.go @@ -21,8 +21,8 @@ import ( "time" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/record" testclient "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/controller" @@ -261,7 +261,7 @@ func TestScale(t *testing.T) { } if test.newRS != nil { - desiredReplicas := test.oldDeployment.Spec.Replicas + desiredReplicas := *(test.oldDeployment.Spec.Replicas) if desired, ok := test.desiredReplicasAnnotations[test.newRS.Name]; ok { desiredReplicas = desired } @@ -272,7 +272,7 @@ func TestScale(t *testing.T) { if rs == nil { continue } - desiredReplicas := test.oldDeployment.Spec.Replicas + desiredReplicas := *(test.oldDeployment.Spec.Replicas) if desired, ok := test.desiredReplicasAnnotations[rs.Name]; ok { desiredReplicas = desired } @@ -289,22 +289,22 @@ func TestScale(t *testing.T) { // no update action for it. nameToSize := make(map[string]int32) if test.newRS != nil { - nameToSize[test.newRS.Name] = test.newRS.Spec.Replicas + nameToSize[test.newRS.Name] = *(test.newRS.Spec.Replicas) } for i := range test.oldRSs { rs := test.oldRSs[i] - nameToSize[rs.Name] = rs.Spec.Replicas + nameToSize[rs.Name] = *(rs.Spec.Replicas) } // Get all the UPDATE actions and update nameToSize with all the updated sizes. for _, action := range fake.Actions() { rs := action.(testclient.UpdateAction).GetObject().(*extensions.ReplicaSet) if !test.wasntUpdated[rs.Name] { - nameToSize[rs.Name] = rs.Spec.Replicas + nameToSize[rs.Name] = *(rs.Spec.Replicas) } } - if test.expectedNew != nil && test.newRS != nil && test.expectedNew.Spec.Replicas != nameToSize[test.newRS.Name] { - t.Errorf("%s: expected new replicas: %d, got: %d", test.name, test.expectedNew.Spec.Replicas, nameToSize[test.newRS.Name]) + if test.expectedNew != nil && test.newRS != nil && *(test.expectedNew.Spec.Replicas) != nameToSize[test.newRS.Name] { + t.Errorf("%s: expected new replicas: %d, got: %d", test.name, *(test.expectedNew.Spec.Replicas), nameToSize[test.newRS.Name]) continue } if len(test.expectedOld) != len(test.oldRSs) { @@ -314,8 +314,8 @@ func TestScale(t *testing.T) { for n := range test.oldRSs { rs := test.oldRSs[n] expected := test.expectedOld[n] - if expected.Spec.Replicas != nameToSize[rs.Name] { - t.Errorf("%s: expected old (%s) replicas: %d, got: %d", test.name, rs.Name, expected.Spec.Replicas, nameToSize[rs.Name]) + if *(expected.Spec.Replicas) != nameToSize[rs.Name] { + t.Errorf("%s: expected old (%s) replicas: %d, got: %d", test.name, rs.Name, *(expected.Spec.Replicas), nameToSize[rs.Name]) } } } @@ -371,7 +371,7 @@ func TestDeploymentController_cleanupDeployment(t *testing.T) { for i := range tests { test := tests[i] fake := &fake.Clientset{} - informers := informers.NewSharedInformerFactory(fake, controller.NoResyncPeriodFunc()) + informers := informers.NewSharedInformerFactory(fake, nil, controller.NoResyncPeriodFunc()) controller := NewDeploymentController(informers.Deployments(), informers.ReplicaSets(), informers.Pods(), fake) controller.eventRecorder = &record.FakeRecorder{} diff --git a/pkg/controller/deployment/util/BUILD b/pkg/controller/deployment/util/BUILD index 22a5a92bdf4..f9af42154a2 100644 --- a/pkg/controller/deployment/util/BUILD +++ b/pkg/controller/deployment/util/BUILD @@ -19,8 +19,10 @@ go_library( "//pkg/api/annotations:go_default_library", "//pkg/api/meta:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/extensions:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/controller:go_default_library", "//pkg/labels:go_default_library", "//pkg/runtime:go_default_library", @@ -42,8 +44,9 @@ go_test( deps = [ "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/extensions:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/runtime:go_default_library", "//pkg/util/intstr:go_default_library", diff --git a/pkg/controller/deployment/util/deployment_util.go b/pkg/controller/deployment/util/deployment_util.go index b520eda5835..9d5165b8699 100644 --- a/pkg/controller/deployment/util/deployment_util.go +++ b/pkg/controller/deployment/util/deployment_util.go @@ -29,8 +29,10 @@ import ( "k8s.io/kubernetes/pkg/api/annotations" "k8s.io/kubernetes/pkg/api/meta" "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/api/v1" + internalextensions "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" @@ -108,7 +110,7 @@ const ( ) // NewDeploymentCondition creates a new deployment condition. -func NewDeploymentCondition(condType extensions.DeploymentConditionType, status api.ConditionStatus, reason, message string) *extensions.DeploymentCondition { +func NewDeploymentCondition(condType extensions.DeploymentConditionType, status v1.ConditionStatus, reason, message string) *extensions.DeploymentCondition { return &extensions.DeploymentCondition{ Type: condType, Status: status, @@ -130,6 +132,18 @@ func GetDeploymentCondition(status extensions.DeploymentStatus, condType extensi return nil } +// TODO: remove the duplicate +// GetDeploymentConditionInternal returns the condition with the provided type. +func GetDeploymentConditionInternal(status internalextensions.DeploymentStatus, condType internalextensions.DeploymentConditionType) *internalextensions.DeploymentCondition { + for i := range status.Conditions { + c := status.Conditions[i] + if c.Type == condType { + return &c + } + } + return nil +} + // SetDeploymentCondition updates the deployment to include the provided condition. If the condition that // we are about to add already exists and has the same status and reason then we are not going to update. func SetDeploymentCondition(status *extensions.DeploymentStatus, condition extensions.DeploymentCondition) { @@ -266,7 +280,7 @@ func SetNewReplicaSetAnnotations(deployment *extensions.Deployment, newRS *exten } } // If the new replica set is about to be created, we need to add replica annotations to it. - if !exists && SetReplicasAnnotations(newRS, deployment.Spec.Replicas, deployment.Spec.Replicas+MaxSurge(*deployment)) { + if !exists && SetReplicasAnnotations(newRS, *(deployment.Spec.Replicas), *(deployment.Spec.Replicas)+MaxSurge(*deployment)) { annotationChanged = true } return annotationChanged @@ -404,7 +418,7 @@ func MaxUnavailable(deployment extensions.Deployment) int32 { return int32(0) } // Error caught by validation - _, maxUnavailable, _ := ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas) + _, maxUnavailable, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas)) return maxUnavailable } @@ -413,7 +427,7 @@ func MinAvailable(deployment *extensions.Deployment) int32 { if !IsRollingUpdate(deployment) { return int32(0) } - return deployment.Spec.Replicas - MaxUnavailable(*deployment) + return *(deployment.Spec.Replicas) - MaxUnavailable(*deployment) } // MaxSurge returns the maximum surge pods a rolling deployment can take. @@ -422,7 +436,7 @@ func MaxSurge(deployment extensions.Deployment) int32 { return int32(0) } // Error caught by validation - maxSurge, _, _ := ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas) + maxSurge, _, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas)) return maxSurge } @@ -430,7 +444,7 @@ func MaxSurge(deployment extensions.Deployment) int32 { // of the parent deployment, 2. the replica count that needs be added on the replica sets of the // deployment, and 3. the total replicas added in the replica sets of the deployment so far. func GetProportion(rs *extensions.ReplicaSet, d extensions.Deployment, deploymentReplicasToAdd, deploymentReplicasAdded int32) int32 { - if rs == nil || rs.Spec.Replicas == 0 || deploymentReplicasToAdd == 0 || deploymentReplicasToAdd == deploymentReplicasAdded { + if rs == nil || *(rs.Spec.Replicas) == 0 || deploymentReplicasToAdd == 0 || deploymentReplicasToAdd == deploymentReplicasAdded { return int32(0) } @@ -453,11 +467,11 @@ func GetProportion(rs *extensions.ReplicaSet, d extensions.Deployment, deploymen // 1. a scaling event during a rollout or 2. when scaling a paused deployment. func getReplicaSetFraction(rs extensions.ReplicaSet, d extensions.Deployment) int32 { // If we are scaling down to zero then the fraction of this replica set is its whole size (negative) - if d.Spec.Replicas == int32(0) { - return -rs.Spec.Replicas + if *(d.Spec.Replicas) == int32(0) { + return -*(rs.Spec.Replicas) } - deploymentReplicas := d.Spec.Replicas + MaxSurge(d) + deploymentReplicas := *(d.Spec.Replicas) + MaxSurge(d) annotatedReplicas, ok := getMaxReplicasAnnotation(&rs) if !ok { // If we cannot find the annotation then fallback to the current deployment size. Note that this @@ -469,8 +483,8 @@ func getReplicaSetFraction(rs extensions.ReplicaSet, d extensions.Deployment) in // We should never proportionally scale up from zero which means rs.spec.replicas and annotatedReplicas // will never be zero here. - newRSsize := (float64(rs.Spec.Replicas * deploymentReplicas)) / float64(annotatedReplicas) - return integer.RoundToInt32(newRSsize) - rs.Spec.Replicas + newRSsize := (float64(*(rs.Spec.Replicas) * deploymentReplicas)) / float64(annotatedReplicas) + return integer.RoundToInt32(newRSsize) - *(rs.Spec.Replicas) } // GetAllReplicaSets returns the old and new replica sets targeted by the given Deployment. It gets PodList and ReplicaSetList from client interface. @@ -523,7 +537,7 @@ func GetNewReplicaSet(deployment *extensions.Deployment, c clientset.Interface) // listReplicaSets lists all RSes the given deployment targets with the given client interface. func listReplicaSets(deployment *extensions.Deployment, c clientset.Interface) ([]*extensions.ReplicaSet, error) { return ListReplicaSets(deployment, - func(namespace string, options api.ListOptions) ([]*extensions.ReplicaSet, error) { + func(namespace string, options v1.ListOptions) ([]*extensions.ReplicaSet, error) { rsList, err := c.Extensions().ReplicaSets(namespace).List(options) if err != nil { return nil, err @@ -537,16 +551,16 @@ func listReplicaSets(deployment *extensions.Deployment, c clientset.Interface) ( } // listReplicaSets lists all Pods the given deployment targets with the given client interface. -func listPods(deployment *extensions.Deployment, c clientset.Interface) (*api.PodList, error) { +func listPods(deployment *extensions.Deployment, c clientset.Interface) (*v1.PodList, error) { return ListPods(deployment, - func(namespace string, options api.ListOptions) (*api.PodList, error) { + func(namespace string, options v1.ListOptions) (*v1.PodList, error) { return c.Core().Pods(namespace).List(options) }) } // TODO: switch this to full namespacers -type rsListFunc func(string, api.ListOptions) ([]*extensions.ReplicaSet, error) -type podListFunc func(string, api.ListOptions) (*api.PodList, error) +type rsListFunc func(string, v1.ListOptions) ([]*extensions.ReplicaSet, error) +type podListFunc func(string, v1.ListOptions) (*v1.PodList, error) // ListReplicaSets returns a slice of RSes the given deployment targets. func ListReplicaSets(deployment *extensions.Deployment, getRSList rsListFunc) ([]*extensions.ReplicaSet, error) { @@ -558,18 +572,18 @@ func ListReplicaSets(deployment *extensions.Deployment, getRSList rsListFunc) ([ if err != nil { return nil, err } - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} return getRSList(namespace, options) } // ListPods returns a list of pods the given deployment targets. -func ListPods(deployment *extensions.Deployment, getPodList podListFunc) (*api.PodList, error) { +func ListPods(deployment *extensions.Deployment, getPodList podListFunc) (*v1.PodList, error) { namespace := deployment.Namespace selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { return nil, err } - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} return getPodList(namespace, options) } @@ -577,7 +591,7 @@ func ListPods(deployment *extensions.Deployment, getPodList podListFunc) (*api.P // We ignore pod-template-hash because the hash result would be different upon podTemplateSpec API changes // (e.g. the addition of a new field will cause the hash code to change) // Note that we assume input podTemplateSpecs contain non-empty labels -func equalIgnoreHash(template1, template2 api.PodTemplateSpec) (bool, error) { +func equalIgnoreHash(template1, template2 v1.PodTemplateSpec) (bool, error) { // First, compare template.Labels (ignoring hash) labels1, labels2 := template1.Labels, template2.Labels // The podTemplateSpec must have a non-empty label so that label selectors can find them. @@ -620,7 +634,7 @@ func FindNewReplicaSet(deployment *extensions.Deployment, rsList []*extensions.R // 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) { +func FindOldReplicaSets(deployment *extensions.Deployment, rsList []*extensions.ReplicaSet, podList *v1.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{} @@ -679,19 +693,19 @@ func WaitForPodsHashPopulated(c clientset.Interface, desiredGeneration int64, na return false, err } return rs.Status.ObservedGeneration >= desiredGeneration && - rs.Status.FullyLabeledReplicas == rs.Spec.Replicas, nil + rs.Status.FullyLabeledReplicas == *(rs.Spec.Replicas), 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) { +func LabelPodsWithHash(podList *v1.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 { + func(podToUpdate *v1.Pod) error { // Precondition: the pod doesn't contain the new hash in its label. if podToUpdate.Labels[extensions.DefaultDeploymentUniqueLabelKey] == hash { return errors.ErrPreconditionViolated @@ -713,9 +727,9 @@ func LabelPodsWithHash(podList *api.PodList, rs *extensions.ReplicaSet, c client } // GetNewReplicaSetTemplate 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) v1.PodTemplateSpec { // newRS will have the same template as in deployment spec, plus a unique label in some cases. - newRSTemplate := api.PodTemplateSpec{ + newRSTemplate := v1.PodTemplateSpec{ ObjectMeta: deployment.Spec.Template.ObjectMeta, Spec: deployment.Spec.Template.Spec, } @@ -726,8 +740,23 @@ func GetNewReplicaSetTemplate(deployment *extensions.Deployment) api.PodTemplate return newRSTemplate } +// TODO: remove the duplicate +// GetNewReplicaSetTemplateInternal returns the desired PodTemplateSpec for the new ReplicaSet corresponding to the given ReplicaSet. +func GetNewReplicaSetTemplateInternal(deployment *internalextensions.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, + Spec: deployment.Spec.Template.Spec, + } + newRSTemplate.ObjectMeta.Labels = labelsutil.CloneAndAddLabel( + deployment.Spec.Template.ObjectMeta.Labels, + internalextensions.DefaultDeploymentUniqueLabelKey, + podutil.GetInternalPodTemplateSpecHash(newRSTemplate)) + return newRSTemplate +} + // SetFromReplicaSetTemplate sets the desired PodTemplateSpec from a replica set template to the given deployment. -func SetFromReplicaSetTemplate(deployment *extensions.Deployment, template api.PodTemplateSpec) *extensions.Deployment { +func SetFromReplicaSetTemplate(deployment *extensions.Deployment, template v1.PodTemplateSpec) *extensions.Deployment { deployment.Spec.Template.ObjectMeta = template.ObjectMeta deployment.Spec.Template.Spec = template.Spec deployment.Spec.Template.ObjectMeta.Labels = labelsutil.CloneAndRemoveLabel( @@ -741,7 +770,7 @@ func GetReplicaCountForReplicaSets(replicaSets []*extensions.ReplicaSet) int32 { totalReplicas := int32(0) for _, rs := range replicaSets { if rs != nil { - totalReplicas += rs.Spec.Replicas + totalReplicas += *(rs.Spec.Replicas) } } return totalReplicas @@ -772,7 +801,7 @@ func GetAvailableReplicaCountForReplicaSets(replicaSets []*extensions.ReplicaSet // IsPodAvailable return true if the pod is available. // TODO: Remove this once we start using replica set status for calculating available pods // for a deployment. -func IsPodAvailable(pod *api.Pod, minReadySeconds int32, now time.Time) bool { +func IsPodAvailable(pod *v1.Pod, minReadySeconds int32, now time.Time) bool { if !controller.IsPodActive(pod) { return false } @@ -780,7 +809,7 @@ func IsPodAvailable(pod *api.Pod, minReadySeconds int32, now time.Time) bool { // If so, this pod is ready for _, c := range pod.Status.Conditions { // we only care about pod ready conditions - if c.Type == api.PodReady && c.Status == api.ConditionTrue { + if c.Type == v1.PodReady && c.Status == v1.ConditionTrue { glog.V(4).Infof("Comparing pod %s/%s ready condition last transition time %s + minReadySeconds %d with now %s.", pod.Namespace, pod.Name, c.LastTransitionTime.String(), minReadySeconds, now.String()) // 2 cases that this ready condition is valid (passed minReadySeconds, i.e. the pod is available): // 1. minReadySeconds == 0, or @@ -802,8 +831,8 @@ func IsRollingUpdate(deployment *extensions.Deployment) bool { // DeploymentComplete considers a deployment to be complete once its desired replicas equals its // updatedReplicas and it doesn't violate minimum availability. func DeploymentComplete(deployment *extensions.Deployment, newStatus *extensions.DeploymentStatus) bool { - return newStatus.UpdatedReplicas == deployment.Spec.Replicas && - newStatus.AvailableReplicas >= deployment.Spec.Replicas-MaxUnavailable(*deployment) + return newStatus.UpdatedReplicas == *(deployment.Spec.Replicas) && + newStatus.AvailableReplicas >= *(deployment.Spec.Replicas)-MaxUnavailable(*deployment) } // DeploymentProgressing reports progress for a deployment. Progress is estimated by comparing the @@ -857,24 +886,24 @@ 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, int(deployment.Spec.Replicas), true) + maxSurge, err := intstrutil.GetValueFromIntOrPercent(deployment.Spec.Strategy.RollingUpdate.MaxSurge, int(*(deployment.Spec.Replicas)), true) if err != nil { return 0, err } // Find the total number of pods currentPodCount := GetReplicaCountForReplicaSets(allRSs) - maxTotalPods := deployment.Spec.Replicas + int32(maxSurge) + maxTotalPods := *(deployment.Spec.Replicas) + int32(maxSurge) if currentPodCount >= maxTotalPods { // Cannot scale up. - return newRS.Spec.Replicas, nil + return *(newRS.Spec.Replicas), nil } // Scale up. scaleUpCount := maxTotalPods - currentPodCount // Do not exceed the number of desired replicas. - scaleUpCount = int32(integer.IntMin(int(scaleUpCount), int(deployment.Spec.Replicas-newRS.Spec.Replicas))) - return newRS.Spec.Replicas + scaleUpCount, nil + scaleUpCount = int32(integer.IntMin(int(scaleUpCount), int(*(deployment.Spec.Replicas)-*(newRS.Spec.Replicas)))) + return *(newRS.Spec.Replicas) + scaleUpCount, nil case extensions.RecreateDeploymentStrategyType: - return deployment.Spec.Replicas, nil + return *(deployment.Spec.Replicas), nil default: return 0, fmt.Errorf("deployment type %v isn't supported", deployment.Spec.Strategy.Type) } @@ -892,7 +921,7 @@ func IsSaturated(deployment *extensions.Deployment, rs *extensions.ReplicaSet) b if err != nil { return false } - return rs.Spec.Replicas == deployment.Spec.Replicas && int32(desired) == deployment.Spec.Replicas + return *(rs.Spec.Replicas) == *(deployment.Spec.Replicas) && int32(desired) == *(deployment.Spec.Replicas) } // WaitForObservedDeployment polls for deployment to be updated so that deployment.Status.ObservedGeneration >= desiredGeneration. @@ -908,6 +937,19 @@ func WaitForObservedDeployment(getDeploymentFunc func() (*extensions.Deployment, }) } +// TODO: remove the duplicate +// WaitForObservedInternalDeployment polls for deployment to be updated so that deployment.Status.ObservedGeneration >= desiredGeneration. +// Returns error if polling timesout. +func WaitForObservedDeploymentInternal(getDeploymentFunc func() (*internalextensions.Deployment, error), desiredGeneration int64, interval, timeout time.Duration) error { + 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: // diff --git a/pkg/controller/deployment/util/deployment_util_test.go b/pkg/controller/deployment/util/deployment_util_test.go index 722b12914de..1bc31a9ba2a 100644 --- a/pkg/controller/deployment/util/deployment_util_test.go +++ b/pkg/controller/deployment/util/deployment_util_test.go @@ -26,8 +26,9 @@ import ( "k8s.io/kubernetes/pkg/api" "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/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/intstr" @@ -74,22 +75,22 @@ func addUpdateRSReactor(fakeClient *fake.Clientset) *fake.Clientset { func addUpdatePodsReactor(fakeClient *fake.Clientset) *fake.Clientset { fakeClient.AddReactor("update", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) { - obj := action.(core.UpdateAction).GetObject().(*api.Pod) + obj := action.(core.UpdateAction).GetObject().(*v1.Pod) return true, obj, nil }) return fakeClient } -func newPod(now time.Time, ready bool, beforeSec int) api.Pod { - conditionStatus := api.ConditionFalse +func newPod(now time.Time, ready bool, beforeSec int) v1.Pod { + conditionStatus := v1.ConditionFalse if ready { - conditionStatus = api.ConditionTrue + conditionStatus = v1.ConditionTrue } - return api.Pod{ - Status: api.PodStatus{ - Conditions: []api.PodCondition{ + return v1.Pod{ + Status: v1.PodStatus{ + Conditions: []v1.PodCondition{ { - Type: api.PodReady, + Type: v1.PodReady, LastTransitionTime: unversioned.NewTime(now.Add(-1 * time.Duration(beforeSec) * time.Second)), Status: conditionStatus, }, @@ -99,27 +100,27 @@ func newPod(now time.Time, ready bool, beforeSec int) api.Pod { } // 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{ +func generatePodFromRS(rs extensions.ReplicaSet) v1.Pod { + return v1.Pod{ + ObjectMeta: v1.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{ +func generatePod(labels map[string]string, image string) v1.Pod { + return v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: labels, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: image, Image: image, - ImagePullPolicy: api.PullAlways, - TerminationMessagePath: api.TerminationMessagePathDefault, + ImagePullPolicy: v1.PullAlways, + TerminationMessagePath: v1.TerminationMessagePathDefault, }, }, }, @@ -128,24 +129,24 @@ func generatePod(labels map[string]string, image string) api.Pod { func generateRSWithLabel(labels map[string]string, image string) extensions.ReplicaSet { return extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ - Name: api.SimpleNameGenerator.GenerateName("replicaset"), + ObjectMeta: v1.ObjectMeta{ + Name: v1.SimpleNameGenerator.GenerateName("replicaset"), Labels: labels, }, Spec: extensions.ReplicaSetSpec{ - Replicas: 1, + Replicas: func(i int32) *int32 { return &i }(1), Selector: &unversioned.LabelSelector{MatchLabels: labels}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: labels, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: image, Image: image, - ImagePullPolicy: api.PullAlways, - TerminationMessagePath: api.TerminationMessagePathDefault, + ImagePullPolicy: v1.PullAlways, + TerminationMessagePath: v1.TerminationMessagePathDefault, }, }, }, @@ -158,11 +159,12 @@ func generateRSWithLabel(labels map[string]string, image string) extensions.Repl func generateRS(deployment extensions.Deployment) extensions.ReplicaSet { template := GetNewReplicaSetTemplate(&deployment) return extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ - Name: api.SimpleNameGenerator.GenerateName("replicaset"), + ObjectMeta: v1.ObjectMeta{ + Name: v1.SimpleNameGenerator.GenerateName("replicaset"), Labels: template.Labels, }, Spec: extensions.ReplicaSetSpec{ + Replicas: func() *int32 { i := int32(0); return &i }(), Template: template, Selector: &unversioned.LabelSelector{MatchLabels: template.Labels}, }, @@ -174,29 +176,29 @@ func generateDeployment(image string) extensions.Deployment { podLabels := map[string]string{"name": image} terminationSec := int64(30) return extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: image, }, Spec: extensions.DeploymentSpec{ - Replicas: 1, + Replicas: func(i int32) *int32 { return &i }(1), Selector: &unversioned.LabelSelector{MatchLabels: podLabels}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabels, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: image, Image: image, - ImagePullPolicy: api.PullAlways, - TerminationMessagePath: api.TerminationMessagePathDefault, + ImagePullPolicy: v1.PullAlways, + TerminationMessagePath: v1.TerminationMessagePathDefault, }, }, - DNSPolicy: api.DNSClusterFirst, + DNSPolicy: v1.DNSClusterFirst, TerminationGracePeriodSeconds: &terminationSec, - RestartPolicy: api.RestartPolicyAlways, - SecurityContext: &api.PodSecurityContext{}, + RestartPolicy: v1.RestartPolicyAlways, + SecurityContext: &v1.PodSecurityContext{}, }, }, }, @@ -215,7 +217,7 @@ func TestGetNewRC(t *testing.T) { { "No new ReplicaSet", []runtime.Object{ - &api.PodList{}, + &v1.PodList{}, &extensions.ReplicaSetList{ Items: []extensions.ReplicaSet{ generateRS(generateDeployment("foo")), @@ -228,7 +230,7 @@ func TestGetNewRC(t *testing.T) { { "Has new ReplicaSet", []runtime.Object{ - &api.PodList{}, + &v1.PodList{}, &extensions.ReplicaSetList{ Items: []extensions.ReplicaSet{ generateRS(generateDeployment("foo")), @@ -262,25 +264,25 @@ func TestGetNewRC(t *testing.T) { func TestGetOldRCs(t *testing.T) { newDeployment := generateDeployment("nginx") newRS := generateRS(newDeployment) - newRS.Status.FullyLabeledReplicas = newRS.Spec.Replicas + newRS.Status.FullyLabeledReplicas = *(newRS.Spec.Replicas) 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) - oldRS.Status.FullyLabeledReplicas = oldRS.Spec.Replicas + oldRS.Status.FullyLabeledReplicas = *(oldRS.Spec.Replicas) oldPod := generatePodFromRS(oldRS) oldDeployment2 := generateDeployment("nginx") oldDeployment2.Spec.Template.Spec.Containers[0].Name = "nginx-old-2" oldRS2 := generateRS(oldDeployment2) - oldRS2.Status.FullyLabeledReplicas = oldRS2.Spec.Replicas + oldRS2.Status.FullyLabeledReplicas = *(oldRS2.Spec.Replicas) 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") - existedRS.Status.FullyLabeledReplicas = existedRS.Spec.Replicas + existedRS.Status.FullyLabeledReplicas = *(existedRS.Spec.Replicas) tests := []struct { test string @@ -290,8 +292,8 @@ func TestGetOldRCs(t *testing.T) { { "No old ReplicaSets", []runtime.Object{ - &api.PodList{ - Items: []api.Pod{ + &v1.PodList{ + Items: []v1.Pod{ generatePod(newDeployment.Spec.Template.Labels, "foo"), generatePod(newDeployment.Spec.Template.Labels, "bar"), newPod, @@ -310,8 +312,8 @@ func TestGetOldRCs(t *testing.T) { { "Has old ReplicaSet", []runtime.Object{ - &api.PodList{ - Items: []api.Pod{ + &v1.PodList{ + Items: []v1.Pod{ oldPod, oldPod2, generatePod(map[string]string{"name": "bar"}, "bar"), @@ -359,14 +361,14 @@ func TestGetOldRCs(t *testing.T) { } } -func generatePodTemplateSpec(name, nodeName string, annotations, labels map[string]string) api.PodTemplateSpec { - return api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ +func generatePodTemplateSpec(name, nodeName string, annotations, labels map[string]string) v1.PodTemplateSpec { + return v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Name: name, Annotations: annotations, Labels: labels, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: nodeName, }, } @@ -375,7 +377,7 @@ func generatePodTemplateSpec(name, nodeName string, annotations, labels map[stri func TestEqualIgnoreHash(t *testing.T) { tests := []struct { test string - former, latter api.PodTemplateSpec + former, latter v1.PodTemplateSpec expected bool }{ { @@ -429,7 +431,7 @@ func TestEqualIgnoreHash(t *testing.T) { } for _, test := range tests { - runTest := func(t1, t2 api.PodTemplateSpec, reversed bool) { + runTest := func(t1, t2 v1.PodTemplateSpec, reversed bool) { // Set up t1Copy, err := api.Scheme.DeepCopy(t1) if err != nil { @@ -472,7 +474,7 @@ func TestFindNewReplicaSet(t *testing.T) { oldDeployment := generateDeployment("nginx") oldDeployment.Spec.Template.Spec.Containers[0].Name = "nginx-old-1" oldRS := generateRS(oldDeployment) - oldRS.Status.FullyLabeledReplicas = oldRS.Spec.Replicas + oldRS.Status.FullyLabeledReplicas = *(oldRS.Spec.Replicas) tests := []struct { test string @@ -508,7 +510,7 @@ func TestFindOldReplicaSets(t *testing.T) { oldDeployment := generateDeployment("nginx") oldDeployment.Spec.Template.Spec.Containers[0].Name = "nginx-old-1" oldRS := generateRS(oldDeployment) - oldRS.Status.FullyLabeledReplicas = oldRS.Spec.Replicas + oldRS.Status.FullyLabeledReplicas = *(oldRS.Spec.Replicas) newPod := generatePodFromRS(newRS) oldPod := generatePodFromRS(oldRS) @@ -516,15 +518,15 @@ func TestFindOldReplicaSets(t *testing.T) { test string deployment extensions.Deployment rsList []*extensions.ReplicaSet - podList *api.PodList + podList *v1.PodList expected []*extensions.ReplicaSet }{ { test: "Get old ReplicaSets", deployment: deployment, rsList: []*extensions.ReplicaSet{&newRS, &oldRS}, - podList: &api.PodList{ - Items: []api.Pod{ + podList: &v1.PodList{ + Items: []v1.Pod{ newPod, oldPod, }, @@ -535,8 +537,8 @@ func TestFindOldReplicaSets(t *testing.T) { test: "Get old ReplicaSets with no new ReplicaSet", deployment: deployment, rsList: []*extensions.ReplicaSet{&oldRS}, - podList: &api.PodList{ - Items: []api.Pod{ + podList: &v1.PodList{ + Items: []v1.Pod{ oldPod, }, }, @@ -546,8 +548,8 @@ func TestFindOldReplicaSets(t *testing.T) { test: "Get empty old ReplicaSets", deployment: deployment, rsList: []*extensions.ReplicaSet{&newRS}, - podList: &api.PodList{ - Items: []api.Pod{ + podList: &v1.PodList{ + Items: []v1.Pod{ newPod, }, }, @@ -584,10 +586,10 @@ func equal(rss1, rss2 []*extensions.ReplicaSet) bool { func TestGetReplicaCountForReplicaSets(t *testing.T) { rs1 := generateRS(generateDeployment("foo")) - rs1.Spec.Replicas = 1 + *(rs1.Spec.Replicas) = 1 rs1.Status.Replicas = 2 rs2 := generateRS(generateDeployment("bar")) - rs2.Spec.Replicas = 2 + *(rs2.Spec.Replicas) = 2 rs2.Status.Replicas = 3 tests := []struct { @@ -715,16 +717,16 @@ func TestNewRSNewReplicas(t *testing.T) { newDeployment := generateDeployment("nginx") newRC := generateRS(newDeployment) rs5 := generateRS(newDeployment) - rs5.Spec.Replicas = 5 + *(rs5.Spec.Replicas) = 5 for _, test := range tests { - newDeployment.Spec.Replicas = test.depReplicas + *(newDeployment.Spec.Replicas) = test.depReplicas newDeployment.Spec.Strategy = extensions.DeploymentStrategy{Type: test.strategyType} newDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{ - MaxUnavailable: intstr.FromInt(1), - MaxSurge: intstr.FromInt(test.maxSurge), + MaxUnavailable: func(i int) *intstr.IntOrString { x := intstr.FromInt(i); return &x }(1), + MaxSurge: func(i int) *intstr.IntOrString { x := intstr.FromInt(i); return &x }(test.maxSurge), } - newRC.Spec.Replicas = test.newRSReplicas + *(newRC.Spec.Replicas) = test.newRSReplicas rs, err := NewRSNewReplicas(&newDeployment, []*extensions.ReplicaSet{&rs5}, &newRC) if err != nil { t.Errorf("In test case %s, got unexpected error %v", test.test, err) @@ -739,7 +741,7 @@ var ( condProgressing = func() extensions.DeploymentCondition { return extensions.DeploymentCondition{ Type: extensions.DeploymentProgressing, - Status: api.ConditionFalse, + Status: v1.ConditionFalse, Reason: "ForSomeReason", } } @@ -747,7 +749,7 @@ var ( condProgressing2 = func() extensions.DeploymentCondition { return extensions.DeploymentCondition{ Type: extensions.DeploymentProgressing, - Status: api.ConditionTrue, + Status: v1.ConditionTrue, Reason: "BecauseItIs", } } @@ -755,7 +757,7 @@ var ( condAvailable = func() extensions.DeploymentCondition { return extensions.DeploymentCondition{ Type: extensions.DeploymentAvailable, - Status: api.ConditionTrue, + Status: v1.ConditionTrue, Reason: "AwesomeController", } } @@ -775,7 +777,7 @@ func TestGetCondition(t *testing.T) { status extensions.DeploymentStatus condType extensions.DeploymentConditionType - condStatus api.ConditionStatus + condStatus v1.ConditionStatus condReason string expected bool @@ -897,10 +899,11 @@ func TestDeploymentComplete(t *testing.T) { deployment := func(desired, current, updated, available, maxUnavailable int32) *extensions.Deployment { return &extensions.Deployment{ Spec: extensions.DeploymentSpec{ - Replicas: desired, + Replicas: &desired, Strategy: extensions.DeploymentStrategy{ RollingUpdate: &extensions.RollingUpdateDeployment{ - MaxUnavailable: intstr.FromInt(int(maxUnavailable)), + MaxUnavailable: func(i int) *intstr.IntOrString { x := intstr.FromInt(i); return &x }(int(maxUnavailable)), + MaxSurge: func() *intstr.IntOrString { x := intstr.FromInt(0); return &x }(), }, Type: extensions.RollingUpdateDeploymentStrategyType, }, @@ -1047,7 +1050,7 @@ func TestDeploymentTimedOut(t *testing.T) { timeFn := func(min, sec int) time.Time { return time.Date(2016, 1, 1, 0, min, sec, 0, time.UTC) } - deployment := func(condType extensions.DeploymentConditionType, status api.ConditionStatus, pds *int32, from time.Time) extensions.Deployment { + deployment := func(condType extensions.DeploymentConditionType, status v1.ConditionStatus, pds *int32, from time.Time) extensions.Deployment { return extensions.Deployment{ Spec: extensions.DeploymentSpec{ ProgressDeadlineSeconds: pds, @@ -1075,21 +1078,21 @@ func TestDeploymentTimedOut(t *testing.T) { { name: "no progressDeadlineSeconds specified - no timeout", - d: deployment(extensions.DeploymentProgressing, api.ConditionTrue, null, timeFn(1, 9)), + d: deployment(extensions.DeploymentProgressing, v1.ConditionTrue, null, timeFn(1, 9)), nowFn: func() time.Time { return timeFn(1, 20) }, expected: false, }, { name: "progressDeadlineSeconds: 10s, now - started => 00:01:20 - 00:01:09 => 11s", - d: deployment(extensions.DeploymentProgressing, api.ConditionTrue, &ten, timeFn(1, 9)), + d: deployment(extensions.DeploymentProgressing, v1.ConditionTrue, &ten, timeFn(1, 9)), nowFn: func() time.Time { return timeFn(1, 20) }, expected: true, }, { name: "progressDeadlineSeconds: 10s, now - started => 00:01:20 - 00:01:11 => 9s", - d: deployment(extensions.DeploymentProgressing, api.ConditionTrue, &ten, timeFn(1, 11)), + d: deployment(extensions.DeploymentProgressing, v1.ConditionTrue, &ten, timeFn(1, 11)), nowFn: func() time.Time { return timeFn(1, 20) }, expected: false, }, diff --git a/pkg/controller/disruption/BUILD b/pkg/controller/disruption/BUILD index a8b4f982b3d..0b2ba48769c 100644 --- a/pkg/controller/disruption/BUILD +++ b/pkg/controller/disruption/BUILD @@ -17,12 +17,13 @@ go_library( deps = [ "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/extensions:go_default_library", - "//pkg/apis/policy:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", + "//pkg/apis/policy/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/policy/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/policy/v1beta1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/controller:go_default_library", "//pkg/runtime:go_default_library", @@ -44,9 +45,10 @@ go_test( deps = [ "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/apis/extensions:go_default_library", - "//pkg/apis/policy:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", + "//pkg/apis/policy/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/client/record:go_default_library", "//pkg/controller:go_default_library", diff --git a/pkg/controller/disruption/disruption.go b/pkg/controller/disruption/disruption.go index 45ff073d30c..805663794d2 100644 --- a/pkg/controller/disruption/disruption.go +++ b/pkg/controller/disruption/disruption.go @@ -23,12 +23,13 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/apis/policy" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + policy "k8s.io/kubernetes/pkg/apis/policy/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" - policyclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/policy/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" + policyclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/policy/v1beta1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/runtime" @@ -58,7 +59,7 @@ const DeletionTimeout = 2 * 60 * time.Second type updater func(*policy.PodDisruptionBudget) error type DisruptionController struct { - kubeClient internalclientset.Interface + kubeClient clientset.Interface pdbStore cache.Store pdbController *cache.Controller @@ -98,9 +99,9 @@ type controllerAndScale struct { // podControllerFinder is a function type that maps a pod to a list of // controllers and their scale. -type podControllerFinder func(*api.Pod) ([]controllerAndScale, error) +type podControllerFinder func(*v1.Pod) ([]controllerAndScale, error) -func NewDisruptionController(podInformer cache.SharedIndexInformer, kubeClient internalclientset.Interface) *DisruptionController { +func NewDisruptionController(podInformer cache.SharedIndexInformer, kubeClient clientset.Interface) *DisruptionController { dc := &DisruptionController{ kubeClient: kubeClient, podController: podInformer.GetController(), @@ -108,7 +109,7 @@ func NewDisruptionController(podInformer cache.SharedIndexInformer, kubeClient i recheckQueue: workqueue.NewNamedDelayingQueue("disruption-recheck"), broadcaster: record.NewBroadcaster(), } - dc.recorder = dc.broadcaster.NewRecorder(api.EventSource{Component: "controllermanager"}) + dc.recorder = dc.broadcaster.NewRecorder(v1.EventSource{Component: "controllermanager"}) dc.getUpdater = func() updater { return dc.writePdbStatus } @@ -122,11 +123,11 @@ func NewDisruptionController(podInformer cache.SharedIndexInformer, kubeClient i dc.pdbStore, dc.pdbController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return dc.kubeClient.Policy().PodDisruptionBudgets(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return dc.kubeClient.Policy().PodDisruptionBudgets(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return dc.kubeClient.Policy().PodDisruptionBudgets(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return dc.kubeClient.Policy().PodDisruptionBudgets(v1.NamespaceAll).Watch(options) }, }, &policy.PodDisruptionBudget{}, @@ -141,14 +142,14 @@ func NewDisruptionController(podInformer cache.SharedIndexInformer, kubeClient i dc.rcIndexer, dc.rcController = cache.NewIndexerInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return dc.kubeClient.Core().ReplicationControllers(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return dc.kubeClient.Core().ReplicationControllers(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return dc.kubeClient.Core().ReplicationControllers(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return dc.kubeClient.Core().ReplicationControllers(v1.NamespaceAll).Watch(options) }, }, - &api.ReplicationController{}, + &v1.ReplicationController{}, 30*time.Second, cache.ResourceEventHandlerFuncs{}, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, @@ -158,11 +159,11 @@ func NewDisruptionController(podInformer cache.SharedIndexInformer, kubeClient i dc.rsLister.Indexer, dc.rsController = cache.NewIndexerInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return dc.kubeClient.Extensions().ReplicaSets(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return dc.kubeClient.Extensions().ReplicaSets(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return dc.kubeClient.Extensions().ReplicaSets(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return dc.kubeClient.Extensions().ReplicaSets(v1.NamespaceAll).Watch(options) }, }, &extensions.ReplicaSet{}, @@ -174,11 +175,11 @@ func NewDisruptionController(podInformer cache.SharedIndexInformer, kubeClient i dc.dIndexer, dc.dController = cache.NewIndexerInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return dc.kubeClient.Extensions().Deployments(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return dc.kubeClient.Extensions().Deployments(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return dc.kubeClient.Extensions().Deployments(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return dc.kubeClient.Extensions().Deployments(v1.NamespaceAll).Watch(options) }, }, &extensions.Deployment{}, @@ -204,7 +205,7 @@ func (dc *DisruptionController) finders() []podControllerFinder { } // getPodReplicaSets finds replicasets which have no matching deployments. -func (dc *DisruptionController) getPodReplicaSets(pod *api.Pod) ([]controllerAndScale, error) { +func (dc *DisruptionController) getPodReplicaSets(pod *v1.Pod) ([]controllerAndScale, error) { cas := []controllerAndScale{} rss, err := dc.rsLister.GetPodReplicaSets(pod) // GetPodReplicaSets returns an error only if no ReplicaSets are found. We @@ -220,7 +221,7 @@ func (dc *DisruptionController) getPodReplicaSets(pod *api.Pod) ([]controllerAnd if err == nil { // A deployment was found, so this finder will not count this RS. continue } - controllerScale[rs.UID] = rs.Spec.Replicas + controllerScale[rs.UID] = *(rs.Spec.Replicas) } for uid, scale := range controllerScale { @@ -231,7 +232,7 @@ func (dc *DisruptionController) getPodReplicaSets(pod *api.Pod) ([]controllerAnd } // getPodDeployments finds deployments for any replicasets which are being managed by deployments. -func (dc *DisruptionController) getPodDeployments(pod *api.Pod) ([]controllerAndScale, error) { +func (dc *DisruptionController) getPodDeployments(pod *v1.Pod) ([]controllerAndScale, error) { cas := []controllerAndScale{} rss, err := dc.rsLister.GetPodReplicaSets(pod) // GetPodReplicaSets returns an error only if no ReplicaSets are found. We @@ -248,7 +249,7 @@ func (dc *DisruptionController) getPodDeployments(pod *api.Pod) ([]controllerAnd continue } for _, d := range ds { - controllerScale[d.UID] = d.Spec.Replicas + controllerScale[d.UID] = *(d.Spec.Replicas) } } @@ -259,12 +260,12 @@ func (dc *DisruptionController) getPodDeployments(pod *api.Pod) ([]controllerAnd return cas, nil } -func (dc *DisruptionController) getPodReplicationControllers(pod *api.Pod) ([]controllerAndScale, error) { +func (dc *DisruptionController) getPodReplicationControllers(pod *v1.Pod) ([]controllerAndScale, error) { cas := []controllerAndScale{} rcs, err := dc.rcLister.GetPodControllers(pod) if err == nil { for _, rc := range rcs { - cas = append(cas, controllerAndScale{UID: rc.UID, scale: rc.Spec.Replicas}) + cas = append(cas, controllerAndScale{UID: rc.UID, scale: *(rc.Spec.Replicas)}) } } return cas, nil @@ -274,7 +275,7 @@ func (dc *DisruptionController) Run(stopCh <-chan struct{}) { glog.V(0).Infof("Starting disruption controller") if dc.kubeClient != nil { glog.V(0).Infof("Sending events to api server.") - dc.broadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: dc.kubeClient.Core().Events("")}) + dc.broadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: dc.kubeClient.Core().Events("")}) } else { glog.V(0).Infof("No api server defined - no events will be sent to API server.") } @@ -310,7 +311,7 @@ func (dc *DisruptionController) removeDb(obj interface{}) { } func (dc *DisruptionController) addPod(obj interface{}) { - pod := obj.(*api.Pod) + pod := obj.(*v1.Pod) glog.V(4).Infof("addPod called on pod %q", pod.Name) pdb := dc.getPdbForPod(pod) if pdb == nil { @@ -322,7 +323,7 @@ func (dc *DisruptionController) addPod(obj interface{}) { } func (dc *DisruptionController) updatePod(old, cur interface{}) { - pod := cur.(*api.Pod) + pod := cur.(*v1.Pod) glog.V(4).Infof("updatePod called on pod %q", pod.Name) pdb := dc.getPdbForPod(pod) if pdb == nil { @@ -334,7 +335,7 @@ func (dc *DisruptionController) updatePod(old, cur interface{}) { } func (dc *DisruptionController) deletePod(obj interface{}) { - pod, ok := obj.(*api.Pod) + pod, ok := obj.(*v1.Pod) // When a delete is dropped, the relist will notice a pod in the store not // in the list, leading to the insertion of a tombstone object which contains // the deleted key/value. Note that this value might be stale. If the pod @@ -346,7 +347,7 @@ func (dc *DisruptionController) deletePod(obj interface{}) { glog.Errorf("Couldn't get object from tombstone %+v", obj) return } - pod, ok = tombstone.Obj.(*api.Pod) + pod, ok = tombstone.Obj.(*v1.Pod) if !ok { glog.Errorf("Tombstone contained object that is not a pod %+v", obj) return @@ -380,7 +381,7 @@ func (dc *DisruptionController) enqueuePdbForRecheck(pdb *policy.PodDisruptionBu dc.recheckQueue.AddAfter(key, delay) } -func (dc *DisruptionController) getPdbForPod(pod *api.Pod) *policy.PodDisruptionBudget { +func (dc *DisruptionController) getPdbForPod(pod *v1.Pod) *policy.PodDisruptionBudget { // GetPodPodDisruptionBudgets returns an error only if no // PodDisruptionBudgets are found. We don't return that as an error to the // caller. @@ -393,25 +394,25 @@ func (dc *DisruptionController) getPdbForPod(pod *api.Pod) *policy.PodDisruption if len(pdbs) > 1 { msg := fmt.Sprintf("Pod %q/%q matches multiple PodDisruptionBudgets. Chose %q arbitrarily.", pod.Namespace, pod.Name, pdbs[0].Name) glog.Warning(msg) - dc.recorder.Event(pod, api.EventTypeWarning, "MultiplePodDisruptionBudgets", msg) + dc.recorder.Event(pod, v1.EventTypeWarning, "MultiplePodDisruptionBudgets", msg) } return &pdbs[0] } -func (dc *DisruptionController) getPodsForPdb(pdb *policy.PodDisruptionBudget) ([]*api.Pod, error) { +func (dc *DisruptionController) getPodsForPdb(pdb *policy.PodDisruptionBudget) ([]*v1.Pod, error) { sel, err := unversioned.LabelSelectorAsSelector(pdb.Spec.Selector) if sel.Empty() { - return []*api.Pod{}, nil + return []*v1.Pod{}, nil } if err != nil { - return []*api.Pod{}, err + return []*v1.Pod{}, err } pods, err := dc.podLister.Pods(pdb.Namespace).List(sel) if err != nil { - return []*api.Pod{}, err + return []*v1.Pod{}, err } // TODO: Do we need to copy here? - result := make([]*api.Pod, 0, len(pods)) + result := make([]*v1.Pod, 0, len(pods)) for i := range pods { result = append(result, &(*pods[i])) } @@ -485,16 +486,16 @@ func (dc *DisruptionController) sync(key string) error { func (dc *DisruptionController) trySync(pdb *policy.PodDisruptionBudget) error { pods, err := dc.getPodsForPdb(pdb) if err != nil { - dc.recorder.Eventf(pdb, api.EventTypeWarning, "NoPods", "Failed to get pods: %v", err) + dc.recorder.Eventf(pdb, v1.EventTypeWarning, "NoPods", "Failed to get pods: %v", err) return err } if len(pods) == 0 { - dc.recorder.Eventf(pdb, api.EventTypeNormal, "NoPods", "No matching pods found") + dc.recorder.Eventf(pdb, v1.EventTypeNormal, "NoPods", "No matching pods found") } expectedCount, desiredHealthy, err := dc.getExpectedPodCount(pdb, pods) if err != nil { - dc.recorder.Eventf(pdb, api.EventTypeNormal, "ExpectedPods", "Failed to calculate the number of expected pods: %v", err) + dc.recorder.Eventf(pdb, v1.EventTypeNormal, "ExpectedPods", "Failed to calculate the number of expected pods: %v", err) return err } @@ -512,7 +513,7 @@ func (dc *DisruptionController) trySync(pdb *policy.PodDisruptionBudget) error { return err } -func (dc *DisruptionController) getExpectedPodCount(pdb *policy.PodDisruptionBudget, pods []*api.Pod) (expectedCount, desiredHealthy int32, err error) { +func (dc *DisruptionController) getExpectedPodCount(pdb *policy.PodDisruptionBudget, pods []*v1.Pod) (expectedCount, desiredHealthy int32, err error) { err = nil // TODO(davidopp): consider making the way expectedCount and rules about // permitted controller configurations (specifically, considering it an error @@ -554,11 +555,11 @@ func (dc *DisruptionController) getExpectedPodCount(pdb *policy.PodDisruptionBud } if controllerCount == 0 { err = fmt.Errorf("asked for percentage, but found no controllers for pod %q", pod.Name) - dc.recorder.Event(pdb, api.EventTypeWarning, "NoControllers", err.Error()) + dc.recorder.Event(pdb, v1.EventTypeWarning, "NoControllers", err.Error()) return } else if controllerCount > 1 { err = fmt.Errorf("pod %q has %v>1 controllers", pod.Name, controllerCount) - dc.recorder.Event(pdb, api.EventTypeWarning, "TooManyControllers", err.Error()) + dc.recorder.Event(pdb, v1.EventTypeWarning, "TooManyControllers", err.Error()) return } } @@ -581,7 +582,7 @@ func (dc *DisruptionController) getExpectedPodCount(pdb *policy.PodDisruptionBud return } -func countHealthyPods(pods []*api.Pod, disruptedPods map[string]unversioned.Time, currentTime time.Time) (currentHealthy int32) { +func countHealthyPods(pods []*v1.Pod, disruptedPods map[string]unversioned.Time, currentTime time.Time) (currentHealthy int32) { Pod: for _, pod := range pods { // Pod is beeing deleted. @@ -592,7 +593,7 @@ Pod: if disruptionTime, found := disruptedPods[pod.Name]; found && disruptionTime.Time.Add(DeletionTimeout).After(currentTime) { continue } - if api.IsPodReady(pod) { + if v1.IsPodReady(pod) { currentHealthy++ continue Pod } @@ -603,7 +604,7 @@ Pod: // Builds new PodDisruption map, possibly removing items that refer to non-existing, already deleted // or not-deleted at all items. Also returns an information when this check should be repeated. -func (dc *DisruptionController) buildDisruptedPodMap(pods []*api.Pod, pdb *policy.PodDisruptionBudget, currentTime time.Time) (map[string]unversioned.Time, *time.Time) { +func (dc *DisruptionController) buildDisruptedPodMap(pods []*v1.Pod, pdb *policy.PodDisruptionBudget, currentTime time.Time) (map[string]unversioned.Time, *time.Time) { disruptedPods := pdb.Status.DisruptedPods result := make(map[string]unversioned.Time) var recheckTime *time.Time @@ -625,7 +626,7 @@ func (dc *DisruptionController) buildDisruptedPodMap(pods []*api.Pod, pdb *polic if expectedDeletion.Before(currentTime) { glog.V(1).Infof("Pod %s/%s was expected to be deleted at %s but it wasn't, updating pdb %s/%s", pod.Namespace, pod.Name, disruptionTime.String(), pdb.Namespace, pdb.Name) - dc.recorder.Eventf(pod, api.EventTypeWarning, "NotDeleted", "Pod was expected by PDB %s/%s to be deleted but it wasn't", + dc.recorder.Eventf(pod, v1.EventTypeWarning, "NotDeleted", "Pod was expected by PDB %s/%s to be deleted but it wasn't", pdb.Namespace, pdb.Namespace) } else { if recheckTime == nil || expectedDeletion.Before(*recheckTime) { diff --git a/pkg/controller/disruption/disruption_test.go b/pkg/controller/disruption/disruption_test.go index 84157304e98..7eb8a5657e8 100644 --- a/pkg/controller/disruption/disruption_test.go +++ b/pkg/controller/disruption/disruption_test.go @@ -25,9 +25,10 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/apis/policy" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + policy "k8s.io/kubernetes/pkg/apis/policy/v1beta1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller" @@ -95,7 +96,7 @@ func newFakeDisruptionController() (*DisruptionController, *pdbStates) { broadcaster: record.NewBroadcaster(), } - dc.recorder = dc.broadcaster.NewRecorder(api.EventSource{Component: "disruption_test"}) + dc.recorder = dc.broadcaster.NewRecorder(v1.EventSource{Component: "disruption_test"}) return dc, ps } @@ -115,11 +116,11 @@ func newSelFooBar() *unversioned.LabelSelector { func newPodDisruptionBudget(t *testing.T, minAvailable intstr.IntOrString) (*policy.PodDisruptionBudget, string) { pdb := &policy.PodDisruptionBudget{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + ObjectMeta: v1.ObjectMeta{ UID: uuid.NewUUID(), Name: "foobar", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, ResourceVersion: "18", }, Spec: policy.PodDisruptionBudgetSpec{ @@ -136,21 +137,21 @@ func newPodDisruptionBudget(t *testing.T, minAvailable intstr.IntOrString) (*pol return pdb, pdbName } -func newPod(t *testing.T, name string) (*api.Pod, string) { - pod := &api.Pod{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ +func newPod(t *testing.T, name string) (*v1.Pod, string) { + pod := &v1.Pod{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + ObjectMeta: v1.ObjectMeta{ UID: uuid.NewUUID(), Annotations: make(map[string]string), Name: name, - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, ResourceVersion: "18", Labels: fooBar(), }, - Spec: api.PodSpec{}, - Status: api.PodStatus{ - Conditions: []api.PodCondition{ - {Type: api.PodReady, Status: api.ConditionTrue}, + Spec: v1.PodSpec{}, + Status: v1.PodStatus{ + Conditions: []v1.PodCondition{ + {Type: v1.PodReady, Status: v1.ConditionTrue}, }, }, } @@ -163,18 +164,18 @@ func newPod(t *testing.T, name string) (*api.Pod, string) { return pod, podName } -func newReplicationController(t *testing.T, size int32) (*api.ReplicationController, string) { - rc := &api.ReplicationController{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ +func newReplicationController(t *testing.T, size int32) (*v1.ReplicationController, string) { + rc := &v1.ReplicationController{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + ObjectMeta: v1.ObjectMeta{ UID: uuid.NewUUID(), Name: "foobar", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, ResourceVersion: "18", Labels: fooBar(), }, - Spec: api.ReplicationControllerSpec{ - Replicas: size, + Spec: v1.ReplicationControllerSpec{ + Replicas: &size, Selector: fooBar(), }, } @@ -189,16 +190,16 @@ func newReplicationController(t *testing.T, size int32) (*api.ReplicationControl func newDeployment(t *testing.T, size int32) (*extensions.Deployment, string) { d := &extensions.Deployment{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + ObjectMeta: v1.ObjectMeta{ UID: uuid.NewUUID(), Name: "foobar", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, ResourceVersion: "18", Labels: fooBar(), }, Spec: extensions.DeploymentSpec{ - Replicas: size, + Replicas: &size, Selector: newSelFooBar(), }, } @@ -213,16 +214,16 @@ func newDeployment(t *testing.T, size int32) (*extensions.Deployment, string) { func newReplicaSet(t *testing.T, size int32) (*extensions.ReplicaSet, string) { rs := &extensions.ReplicaSet{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + ObjectMeta: v1.ObjectMeta{ UID: uuid.NewUUID(), Name: "foobar", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, ResourceVersion: "18", Labels: fooBar(), }, Spec: extensions.ReplicaSetSpec{ - Replicas: size, + Replicas: &size, Selector: newSelFooBar(), }, } @@ -274,7 +275,7 @@ func TestUnavailable(t *testing.T) { dc.sync(pdbName) // Add three pods, verifying that the counts go up at each step. - pods := []*api.Pod{} + pods := []*v1.Pod{} for i := int32(0); i < 4; i++ { ps.VerifyPdbStatus(t, pdbName, 0, i, 3, i, map[string]unversioned.Time{}) pod, _ := newPod(t, fmt.Sprintf("yo-yo-yo %d", i)) @@ -285,7 +286,7 @@ func TestUnavailable(t *testing.T) { ps.VerifyPdbStatus(t, pdbName, 1, 4, 3, 4, map[string]unversioned.Time{}) // Now set one pod as unavailable - pods[0].Status.Conditions = []api.PodCondition{} + pods[0].Status.Conditions = []v1.PodCondition{} update(t, dc.podLister.Indexer, pods[0]) dc.sync(pdbName) @@ -387,7 +388,7 @@ func TestReplicationController(t *testing.T) { // about the RC. This is a known bug. TODO(mml): file issue ps.VerifyPdbStatus(t, pdbName, 0, 0, 0, 0, map[string]unversioned.Time{}) - pods := []*api.Pod{} + pods := []*v1.Pod{} for i := int32(0); i < 3; i++ { pod, _ := newPod(t, fmt.Sprintf("foobar %d", i)) @@ -439,7 +440,7 @@ func TestTwoControllers(t *testing.T) { ps.VerifyPdbStatus(t, pdbName, 0, 0, 0, 0, map[string]unversioned.Time{}) - pods := []*api.Pod{} + pods := []*v1.Pod{} unavailablePods := collectionSize - minimumOne - 1 for i := int32(1); i <= collectionSize; i++ { @@ -447,7 +448,7 @@ func TestTwoControllers(t *testing.T) { pods = append(pods, pod) pod.Labels = rcLabels if i <= unavailablePods { - pod.Status.Conditions = []api.PodCondition{} + pod.Status.Conditions = []v1.PodCondition{} } add(t, dc.podLister.Indexer, pod) dc.sync(pdbName) @@ -480,7 +481,7 @@ func TestTwoControllers(t *testing.T) { pods = append(pods, pod) pod.Labels = dLabels if i <= unavailablePods { - pod.Status.Conditions = []api.PodCondition{} + pod.Status.Conditions = []v1.PodCondition{} } add(t, dc.podLister.Indexer, pod) dc.sync(pdbName) @@ -498,17 +499,17 @@ func TestTwoControllers(t *testing.T) { // but if we bring down two, it's not. Then we make the pod ready again and // verify that a disruption is permitted again. ps.VerifyPdbStatus(t, pdbName, 2, 2+minimumTwo, minimumTwo, 2*collectionSize, map[string]unversioned.Time{}) - pods[collectionSize-1].Status.Conditions = []api.PodCondition{} + pods[collectionSize-1].Status.Conditions = []v1.PodCondition{} update(t, dc.podLister.Indexer, pods[collectionSize-1]) dc.sync(pdbName) ps.VerifyPdbStatus(t, pdbName, 1, 1+minimumTwo, minimumTwo, 2*collectionSize, map[string]unversioned.Time{}) - pods[collectionSize-2].Status.Conditions = []api.PodCondition{} + pods[collectionSize-2].Status.Conditions = []v1.PodCondition{} update(t, dc.podLister.Indexer, pods[collectionSize-2]) dc.sync(pdbName) ps.VerifyPdbStatus(t, pdbName, 0, minimumTwo, minimumTwo, 2*collectionSize, map[string]unversioned.Time{}) - pods[collectionSize-1].Status.Conditions = []api.PodCondition{{Type: api.PodReady, Status: api.ConditionTrue}} + pods[collectionSize-1].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue}} update(t, dc.podLister.Indexer, pods[collectionSize-1]) dc.sync(pdbName) ps.VerifyPdbStatus(t, pdbName, 1, 1+minimumTwo, minimumTwo, 2*collectionSize, map[string]unversioned.Time{}) diff --git a/pkg/controller/endpoint/BUILD b/pkg/controller/endpoint/BUILD index 53bf530a02e..c9f91a1fceb 100644 --- a/pkg/controller/endpoint/BUILD +++ b/pkg/controller/endpoint/BUILD @@ -18,12 +18,12 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/api/endpoints:go_default_library", "//pkg/api/errors:go_default_library", - "//pkg/api/pod:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/endpoints:go_default_library", + "//pkg/api/v1/pod:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/controller:go_default_library", "//pkg/controller/informers:go_default_library", "//pkg/labels:go_default_library", @@ -44,13 +44,13 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/api/endpoints:go_default_library", "//pkg/api/testapi:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/endpoints:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/controller:go_default_library", "//pkg/runtime:go_default_library", diff --git a/pkg/controller/endpoint/endpoints_controller.go b/pkg/controller/endpoint/endpoints_controller.go index 91aad17b2b9..86c83060621 100644 --- a/pkg/controller/endpoint/endpoints_controller.go +++ b/pkg/controller/endpoint/endpoints_controller.go @@ -24,13 +24,13 @@ import ( "encoding/json" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/endpoints" "k8s.io/kubernetes/pkg/api/errors" - podutil "k8s.io/kubernetes/pkg/api/pod" - utilpod "k8s.io/kubernetes/pkg/api/pod" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/api/v1/endpoints" + podutil "k8s.io/kubernetes/pkg/api/v1/pod" + utilpod "k8s.io/kubernetes/pkg/api/v1/pod" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/informers" "k8s.io/kubernetes/pkg/labels" @@ -80,14 +80,14 @@ func NewEndpointController(podInformer cache.SharedIndexInformer, client clients e.serviceStore.Indexer, e.serviceController = cache.NewIndexerInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return e.client.Core().Services(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return e.client.Core().Services(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return e.client.Core().Services(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return e.client.Core().Services(v1.NamespaceAll).Watch(options) }, }, - &api.Service{}, + &v1.Service{}, // TODO: Can we have much longer period here? FullServiceResyncPeriod, cache.ResourceEventHandlerFuncs{ @@ -180,7 +180,7 @@ func (e *EndpointController) Run(workers int, stopCh <-chan struct{}) { <-stopCh } -func (e *EndpointController) getPodServiceMemberships(pod *api.Pod) (sets.String, error) { +func (e *EndpointController) getPodServiceMemberships(pod *v1.Pod) (sets.String, error) { set := sets.String{} services, err := e.serviceStore.GetPodServices(pod) if err != nil { @@ -199,9 +199,9 @@ func (e *EndpointController) getPodServiceMemberships(pod *api.Pod) (sets.String } // When a pod is added, figure out what services it will be a member of and -// enqueue them. obj must have *api.Pod type. +// enqueue them. obj must have *v1.Pod type. func (e *EndpointController) addPod(obj interface{}) { - pod := obj.(*api.Pod) + pod := obj.(*v1.Pod) services, err := e.getPodServiceMemberships(pod) if err != nil { utilruntime.HandleError(fmt.Errorf("Unable to get pod %v/%v's service memberships: %v", pod.Namespace, pod.Name, err)) @@ -214,10 +214,10 @@ func (e *EndpointController) addPod(obj interface{}) { // When a pod is updated, figure out what services it used to be a member of // and what services it will be a member of, and enqueue the union of these. -// old and cur must be *api.Pod types. +// old and cur must be *v1.Pod types. func (e *EndpointController) updatePod(old, cur interface{}) { - newPod := cur.(*api.Pod) - oldPod := old.(*api.Pod) + newPod := cur.(*v1.Pod) + oldPod := old.(*v1.Pod) if newPod.ResourceVersion == oldPod.ResourceVersion { // Periodic resync will send update events for all known pods. // Two different versions of the same pod will always have different RVs. @@ -244,12 +244,12 @@ func (e *EndpointController) updatePod(old, cur interface{}) { } } -func hostNameAndDomainAreEqual(pod1, pod2 *api.Pod) bool { +func hostNameAndDomainAreEqual(pod1, pod2 *v1.Pod) bool { return getHostname(pod1) == getHostname(pod2) && getSubdomain(pod1) == getSubdomain(pod2) } -func getHostname(pod *api.Pod) string { +func getHostname(pod *v1.Pod) string { if len(pod.Spec.Hostname) > 0 { return pod.Spec.Hostname } @@ -259,7 +259,7 @@ func getHostname(pod *api.Pod) string { return "" } -func getSubdomain(pod *api.Pod) string { +func getSubdomain(pod *v1.Pod) string { if len(pod.Spec.Subdomain) > 0 { return pod.Spec.Subdomain } @@ -270,9 +270,9 @@ func getSubdomain(pod *api.Pod) string { } // When a pod is deleted, enqueue the services the pod used to be a member of. -// obj could be an *api.Pod, or a DeletionFinalStateUnknown marker item. +// obj could be an *v1.Pod, or a DeletionFinalStateUnknown marker item. func (e *EndpointController) deletePod(obj interface{}) { - if _, ok := obj.(*api.Pod); ok { + if _, ok := obj.(*v1.Pod); ok { // Enqueue all the services that the pod used to be a member // of. This happens to be exactly the same thing we do when a // pod is added. @@ -289,7 +289,7 @@ func (e *EndpointController) deletePod(obj interface{}) { // TODO: keep a map of pods to services to handle this condition. } -// obj could be an *api.Service, or a DeletionFinalStateUnknown marker item. +// obj could be an *v1.Service, or a DeletionFinalStateUnknown marker item. func (e *EndpointController) enqueueService(obj interface{}) { key, err := keyFunc(obj) if err != nil { @@ -354,7 +354,7 @@ func (e *EndpointController) syncService(key string) error { return nil } - service := obj.(*api.Service) + service := obj.(*v1.Service) if service.Spec.Selector == nil { // services without a selector receive no endpoints from this controller; // these services will receive the endpoints that are created out-of-band via the REST API. @@ -369,7 +369,7 @@ func (e *EndpointController) syncService(key string) error { return err } - subsets := []api.EndpointSubset{} + subsets := []v1.EndpointSubset{} podHostNames := map[string]endpoints.HostRecord{} var tolerateUnreadyEndpoints bool @@ -407,11 +407,11 @@ func (e *EndpointController) syncService(key string) error { continue } - epp := api.EndpointPort{Name: portName, Port: int32(portNum), Protocol: portProto} - epa := api.EndpointAddress{ + epp := v1.EndpointPort{Name: portName, Port: int32(portNum), Protocol: portProto} + epa := v1.EndpointAddress{ IP: pod.Status.PodIP, NodeName: &pod.Spec.NodeName, - TargetRef: &api.ObjectReference{ + TargetRef: &v1.ObjectReference{ Kind: "Pod", Namespace: pod.ObjectMeta.Namespace, Name: pod.ObjectMeta.Name, @@ -431,17 +431,17 @@ func (e *EndpointController) syncService(key string) error { epa.Hostname = hostname } - if tolerateUnreadyEndpoints || api.IsPodReady(pod) { - subsets = append(subsets, api.EndpointSubset{ - Addresses: []api.EndpointAddress{epa}, - Ports: []api.EndpointPort{epp}, + if tolerateUnreadyEndpoints || v1.IsPodReady(pod) { + subsets = append(subsets, v1.EndpointSubset{ + Addresses: []v1.EndpointAddress{epa}, + Ports: []v1.EndpointPort{epp}, }) readyEps++ } else { glog.V(5).Infof("Pod is out of service: %v/%v", pod.Namespace, pod.Name) - subsets = append(subsets, api.EndpointSubset{ - NotReadyAddresses: []api.EndpointAddress{epa}, - Ports: []api.EndpointPort{epp}, + subsets = append(subsets, v1.EndpointSubset{ + NotReadyAddresses: []v1.EndpointAddress{epa}, + Ports: []v1.EndpointPort{epp}, }) notReadyEps++ } @@ -453,8 +453,8 @@ func (e *EndpointController) syncService(key string) error { currentEndpoints, err := e.client.Core().Endpoints(service.Namespace).Get(service.Name) if err != nil { if errors.IsNotFound(err) { - currentEndpoints = &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + currentEndpoints = &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: service.Name, Labels: service.Labels, }, @@ -521,7 +521,7 @@ func (e *EndpointController) syncService(key string) error { // some stragglers could have been left behind if the endpoint controller // reboots). func (e *EndpointController) checkLeftoverEndpoints() { - list, err := e.client.Core().Endpoints(api.NamespaceAll).List(api.ListOptions{}) + list, err := e.client.Core().Endpoints(v1.NamespaceAll).List(v1.ListOptions{}) if err != nil { utilruntime.HandleError(fmt.Errorf("Unable to list endpoints (%v); orphaned endpoints will not be cleaned up. (They're pretty harmless, but you can restart this component if you want another attempt made.)", err)) return diff --git a/pkg/controller/endpoint/endpoints_controller_test.go b/pkg/controller/endpoint/endpoints_controller_test.go index 90449be3d80..4489dd0da87 100644 --- a/pkg/controller/endpoint/endpoints_controller_test.go +++ b/pkg/controller/endpoint/endpoints_controller_test.go @@ -22,14 +22,14 @@ import ( "net/http/httptest" "testing" - "k8s.io/kubernetes/pkg/api" - endptspkg "k8s.io/kubernetes/pkg/api/endpoints" "k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + endptspkg "k8s.io/kubernetes/pkg/api/v1/endpoints" "k8s.io/kubernetes/pkg/apimachinery/registered" _ "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/runtime" @@ -42,32 +42,32 @@ var emptyNodeName string func addPods(store cache.Store, namespace string, nPods int, nPorts int, nNotReady int) { for i := 0; i < nPods+nNotReady; i++ { - p := &api.Pod{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ + p := &v1.Pod{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + ObjectMeta: v1.ObjectMeta{ Namespace: namespace, Name: fmt.Sprintf("pod%d", i), Labels: map[string]string{"foo": "bar"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{{Ports: []api.ContainerPort{}}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Ports: []v1.ContainerPort{}}}, }, - Status: api.PodStatus{ + Status: v1.PodStatus{ PodIP: fmt.Sprintf("1.2.3.%d", 4+i), - Conditions: []api.PodCondition{ + Conditions: []v1.PodCondition{ { - Type: api.PodReady, - Status: api.ConditionTrue, + Type: v1.PodReady, + Status: v1.ConditionTrue, }, }, }, } if i >= nPods { - p.Status.Conditions[0].Status = api.ConditionFalse + p.Status.Conditions[0].Status = v1.ConditionFalse } for j := 0; j < nPorts; j++ { p.Spec.Containers[0].Ports = append(p.Spec.Containers[0].Ports, - api.ContainerPort{Name: fmt.Sprintf("port%d", i), ContainerPort: int32(8080 + j)}) + v1.ContainerPort{Name: fmt.Sprintf("port%d", i), ContainerPort: int32(8080 + j)}) } store.Add(p) } @@ -94,54 +94,54 @@ func makeTestServer(t *testing.T, namespace string, endpointsResponse serverResp } func TestSyncEndpointsItemsPreserveNoSelector(t *testing.T) { - ns := api.NamespaceDefault + ns := v1.NamespaceDefault testServer, endpointsHandler := makeTestServer(t, ns, - serverResponse{http.StatusOK, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + serverResponse{http.StatusOK, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, - Ports: []api.EndpointPort{{Port: 1000}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, + Ports: []v1.EndpointPort{{Port: 1000}}, }}, }}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady - endpoints.serviceStore.Indexer.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: ns}, - Spec: api.ServiceSpec{Ports: []api.ServicePort{{Port: 80}}}, + endpoints.serviceStore.Indexer.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: ns}, + Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{Port: 80}}}, }) endpoints.syncService(ns + "/foo") endpointsHandler.ValidateRequestCount(t, 0) } func TestCheckLeftoverEndpoints(t *testing.T) { - ns := api.NamespaceDefault + ns := v1.NamespaceDefault // Note that this requests *all* endpoints, therefore the NamespaceAll // below. - testServer, _ := makeTestServer(t, api.NamespaceAll, - serverResponse{http.StatusOK, &api.EndpointsList{ + testServer, _ := makeTestServer(t, v1.NamespaceAll, + serverResponse{http.StatusOK, &v1.EndpointsList{ ListMeta: unversioned.ListMeta{ ResourceVersion: "1", }, - Items: []api.Endpoints{{ - ObjectMeta: api.ObjectMeta{ + Items: []v1.Endpoints{{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, - Ports: []api.EndpointPort{{Port: 1000}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, + Ports: []v1.EndpointPort{{Port: 1000}}, }}, }}, }}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady endpoints.checkLeftoverEndpoints() @@ -158,41 +158,41 @@ func TestCheckLeftoverEndpoints(t *testing.T) { func TestSyncEndpointsProtocolTCP(t *testing.T) { ns := "other" testServer, endpointsHandler := makeTestServer(t, ns, - serverResponse{http.StatusOK, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + serverResponse{http.StatusOK, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, - Ports: []api.EndpointPort{{Port: 1000, Protocol: "TCP"}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, + Ports: []v1.EndpointPort{{Port: 1000, Protocol: "TCP"}}, }}, }}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady addPods(endpoints.podStore.Indexer, ns, 1, 1, 0) - endpoints.serviceStore.Indexer.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: ns}, - Spec: api.ServiceSpec{ + endpoints.serviceStore.Indexer.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: ns}, + Spec: v1.ServiceSpec{ Selector: map[string]string{}, - Ports: []api.ServicePort{{Port: 80, TargetPort: intstr.FromInt(8080), Protocol: "TCP"}}, + Ports: []v1.ServicePort{{Port: 80, TargetPort: intstr.FromInt(8080), Protocol: "TCP"}}, }, }) endpoints.syncService(ns + "/foo") endpointsHandler.ValidateRequestCount(t, 2) - data := runtime.EncodeOrDie(testapi.Default.Codec(), &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + data := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, - Ports: []api.EndpointPort{{Port: 8080, Protocol: "TCP"}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, + Ports: []v1.EndpointPort{{Port: 8080, Protocol: "TCP"}}, }}, }) endpointsHandler.ValidateRequest(t, testapi.Default.ResourcePath("endpoints", ns, "foo"), "PUT", &data) @@ -201,40 +201,40 @@ func TestSyncEndpointsProtocolTCP(t *testing.T) { func TestSyncEndpointsProtocolUDP(t *testing.T) { ns := "other" testServer, endpointsHandler := makeTestServer(t, ns, - serverResponse{http.StatusOK, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + serverResponse{http.StatusOK, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, - Ports: []api.EndpointPort{{Port: 1000, Protocol: "UDP"}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, + Ports: []v1.EndpointPort{{Port: 1000, Protocol: "UDP"}}, }}, }}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady addPods(endpoints.podStore.Indexer, ns, 1, 1, 0) - endpoints.serviceStore.Indexer.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: ns}, - Spec: api.ServiceSpec{ + endpoints.serviceStore.Indexer.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: ns}, + Spec: v1.ServiceSpec{ Selector: map[string]string{}, - Ports: []api.ServicePort{{Port: 80, TargetPort: intstr.FromInt(8080), Protocol: "UDP"}}, + Ports: []v1.ServicePort{{Port: 80, TargetPort: intstr.FromInt(8080), Protocol: "UDP"}}, }, }) endpoints.syncService(ns + "/foo") endpointsHandler.ValidateRequestCount(t, 2) - data := runtime.EncodeOrDie(testapi.Default.Codec(), &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + data := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, - Ports: []api.EndpointPort{{Port: 8080, Protocol: "UDP"}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, + Ports: []v1.EndpointPort{{Port: 8080, Protocol: "UDP"}}, }}, }) endpointsHandler.ValidateRequest(t, testapi.Default.ResourcePath("endpoints", ns, "foo"), "PUT", &data) @@ -243,36 +243,36 @@ func TestSyncEndpointsProtocolUDP(t *testing.T) { func TestSyncEndpointsItemsEmptySelectorSelectsAll(t *testing.T) { ns := "other" testServer, endpointsHandler := makeTestServer(t, ns, - serverResponse{http.StatusOK, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + serverResponse{http.StatusOK, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{}, + Subsets: []v1.EndpointSubset{}, }}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady addPods(endpoints.podStore.Indexer, ns, 1, 1, 0) - endpoints.serviceStore.Indexer.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: ns}, - Spec: api.ServiceSpec{ + endpoints.serviceStore.Indexer.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: ns}, + Spec: v1.ServiceSpec{ Selector: map[string]string{}, - Ports: []api.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, + Ports: []v1.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, }, }) endpoints.syncService(ns + "/foo") - data := runtime.EncodeOrDie(testapi.Default.Codec(), &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + data := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, - Ports: []api.EndpointPort{{Port: 8080, Protocol: "TCP"}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, + Ports: []v1.EndpointPort{{Port: 8080, Protocol: "TCP"}}, }}, }) endpointsHandler.ValidateRequest(t, testapi.Default.ResourcePath("endpoints", ns, "foo"), "PUT", &data) @@ -281,36 +281,36 @@ func TestSyncEndpointsItemsEmptySelectorSelectsAll(t *testing.T) { func TestSyncEndpointsItemsEmptySelectorSelectsAllNotReady(t *testing.T) { ns := "other" testServer, endpointsHandler := makeTestServer(t, ns, - serverResponse{http.StatusOK, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + serverResponse{http.StatusOK, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{}, + Subsets: []v1.EndpointSubset{}, }}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady addPods(endpoints.podStore.Indexer, ns, 0, 1, 1) - endpoints.serviceStore.Indexer.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: ns}, - Spec: api.ServiceSpec{ + endpoints.serviceStore.Indexer.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: ns}, + Spec: v1.ServiceSpec{ Selector: map[string]string{}, - Ports: []api.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, + Ports: []v1.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, }, }) endpoints.syncService(ns + "/foo") - data := runtime.EncodeOrDie(testapi.Default.Codec(), &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + data := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{{ - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, - Ports: []api.EndpointPort{{Port: 8080, Protocol: "TCP"}}, + Subsets: []v1.EndpointSubset{{ + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, + Ports: []v1.EndpointPort{{Port: 8080, Protocol: "TCP"}}, }}, }) endpointsHandler.ValidateRequest(t, testapi.Default.ResourcePath("endpoints", ns, "foo"), "PUT", &data) @@ -319,37 +319,37 @@ func TestSyncEndpointsItemsEmptySelectorSelectsAllNotReady(t *testing.T) { func TestSyncEndpointsItemsEmptySelectorSelectsAllMixed(t *testing.T) { ns := "other" testServer, endpointsHandler := makeTestServer(t, ns, - serverResponse{http.StatusOK, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + serverResponse{http.StatusOK, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{}, + Subsets: []v1.EndpointSubset{}, }}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady addPods(endpoints.podStore.Indexer, ns, 1, 1, 1) - endpoints.serviceStore.Indexer.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: ns}, - Spec: api.ServiceSpec{ + endpoints.serviceStore.Indexer.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: ns}, + Spec: v1.ServiceSpec{ Selector: map[string]string{}, - Ports: []api.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, + Ports: []v1.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, }, }) endpoints.syncService(ns + "/foo") - data := runtime.EncodeOrDie(testapi.Default.Codec(), &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + data := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.5", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod1", Namespace: ns}}}, - Ports: []api.EndpointPort{{Port: 8080, Protocol: "TCP"}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, + NotReadyAddresses: []v1.EndpointAddress{{IP: "1.2.3.5", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod1", Namespace: ns}}}, + Ports: []v1.EndpointPort{{Port: 8080, Protocol: "TCP"}}, }}, }) endpointsHandler.ValidateRequest(t, testapi.Default.ResourcePath("endpoints", ns, "foo"), "PUT", &data) @@ -358,108 +358,108 @@ func TestSyncEndpointsItemsEmptySelectorSelectsAllMixed(t *testing.T) { func TestSyncEndpointsItemsPreexisting(t *testing.T) { ns := "bar" testServer, endpointsHandler := makeTestServer(t, ns, - serverResponse{http.StatusOK, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + serverResponse{http.StatusOK, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, - Ports: []api.EndpointPort{{Port: 1000}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, + Ports: []v1.EndpointPort{{Port: 1000}}, }}, }}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady addPods(endpoints.podStore.Indexer, ns, 1, 1, 0) - endpoints.serviceStore.Indexer.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: ns}, - Spec: api.ServiceSpec{ + endpoints.serviceStore.Indexer.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: ns}, + Spec: v1.ServiceSpec{ Selector: map[string]string{"foo": "bar"}, - Ports: []api.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, + Ports: []v1.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, }, }) endpoints.syncService(ns + "/foo") - data := runtime.EncodeOrDie(testapi.Default.Codec(), &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + data := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, - Ports: []api.EndpointPort{{Port: 8080, Protocol: "TCP"}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, + Ports: []v1.EndpointPort{{Port: 8080, Protocol: "TCP"}}, }}, }) endpointsHandler.ValidateRequest(t, testapi.Default.ResourcePath("endpoints", ns, "foo"), "PUT", &data) } func TestSyncEndpointsItemsPreexistingIdentical(t *testing.T) { - ns := api.NamespaceDefault - testServer, endpointsHandler := makeTestServer(t, api.NamespaceDefault, - serverResponse{http.StatusOK, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + ns := v1.NamespaceDefault + testServer, endpointsHandler := makeTestServer(t, v1.NamespaceDefault, + serverResponse{http.StatusOK, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ ResourceVersion: "1", Name: "foo", Namespace: ns, }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, - Ports: []api.EndpointPort{{Port: 8080, Protocol: "TCP"}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, + Ports: []v1.EndpointPort{{Port: 8080, Protocol: "TCP"}}, }}, }}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady - addPods(endpoints.podStore.Indexer, api.NamespaceDefault, 1, 1, 0) - endpoints.serviceStore.Indexer.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: api.NamespaceDefault}, - Spec: api.ServiceSpec{ + addPods(endpoints.podStore.Indexer, v1.NamespaceDefault, 1, 1, 0) + endpoints.serviceStore.Indexer.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: v1.NamespaceDefault}, + Spec: v1.ServiceSpec{ Selector: map[string]string{"foo": "bar"}, - Ports: []api.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, + Ports: []v1.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, }, }) endpoints.syncService(ns + "/foo") - endpointsHandler.ValidateRequest(t, testapi.Default.ResourcePath("endpoints", api.NamespaceDefault, "foo"), "GET", nil) + endpointsHandler.ValidateRequest(t, testapi.Default.ResourcePath("endpoints", v1.NamespaceDefault, "foo"), "GET", nil) } func TestSyncEndpointsItems(t *testing.T) { ns := "other" testServer, endpointsHandler := makeTestServer(t, ns, - serverResponse{http.StatusOK, &api.Endpoints{}}) + serverResponse{http.StatusOK, &v1.Endpoints{}}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady addPods(endpoints.podStore.Indexer, ns, 3, 2, 0) addPods(endpoints.podStore.Indexer, "blah", 5, 2, 0) // make sure these aren't found! - endpoints.serviceStore.Indexer.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: ns}, - Spec: api.ServiceSpec{ + endpoints.serviceStore.Indexer.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: ns}, + Spec: v1.ServiceSpec{ Selector: map[string]string{"foo": "bar"}, - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ {Name: "port0", Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, {Name: "port1", Port: 88, Protocol: "TCP", TargetPort: intstr.FromInt(8088)}, }, }, }) endpoints.syncService("other/foo") - expectedSubsets := []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}, - {IP: "1.2.3.5", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod1", Namespace: ns}}, - {IP: "1.2.3.6", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod2", Namespace: ns}}, + expectedSubsets := []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{ + {IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}, + {IP: "1.2.3.5", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod1", Namespace: ns}}, + {IP: "1.2.3.6", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod2", Namespace: ns}}, }, - Ports: []api.EndpointPort{ + Ports: []v1.EndpointPort{ {Name: "port0", Port: 8080, Protocol: "TCP"}, {Name: "port1", Port: 8088, Protocol: "TCP"}, }, }} - data := runtime.EncodeOrDie(testapi.Default.Codec(), &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + data := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ ResourceVersion: "", }, Subsets: endptspkg.SortSubsets(expectedSubsets), @@ -472,41 +472,41 @@ func TestSyncEndpointsItems(t *testing.T) { func TestSyncEndpointsItemsWithLabels(t *testing.T) { ns := "other" testServer, endpointsHandler := makeTestServer(t, ns, - serverResponse{http.StatusOK, &api.Endpoints{}}) + serverResponse{http.StatusOK, &v1.Endpoints{}}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady addPods(endpoints.podStore.Indexer, ns, 3, 2, 0) serviceLabels := map[string]string{"foo": "bar"} - endpoints.serviceStore.Indexer.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{ + endpoints.serviceStore.Indexer.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, Labels: serviceLabels, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: map[string]string{"foo": "bar"}, - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ {Name: "port0", Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, {Name: "port1", Port: 88, Protocol: "TCP", TargetPort: intstr.FromInt(8088)}, }, }, }) endpoints.syncService(ns + "/foo") - expectedSubsets := []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}, - {IP: "1.2.3.5", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod1", Namespace: ns}}, - {IP: "1.2.3.6", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod2", Namespace: ns}}, + expectedSubsets := []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{ + {IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}, + {IP: "1.2.3.5", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod1", Namespace: ns}}, + {IP: "1.2.3.6", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod2", Namespace: ns}}, }, - Ports: []api.EndpointPort{ + Ports: []v1.EndpointPort{ {Name: "port0", Port: 8080, Protocol: "TCP"}, {Name: "port1", Port: 8088, Protocol: "TCP"}, }, }} - data := runtime.EncodeOrDie(testapi.Default.Codec(), &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + data := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ ResourceVersion: "", Labels: serviceLabels, }, @@ -520,8 +520,8 @@ func TestSyncEndpointsItemsWithLabels(t *testing.T) { func TestSyncEndpointsItemsPreexistingLabelsChange(t *testing.T) { ns := "bar" testServer, endpointsHandler := makeTestServer(t, ns, - serverResponse{http.StatusOK, &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + serverResponse{http.StatusOK, &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", @@ -529,39 +529,39 @@ func TestSyncEndpointsItemsPreexistingLabelsChange(t *testing.T) { "foo": "bar", }, }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, - Ports: []api.EndpointPort{{Port: 1000}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "6.7.8.9", NodeName: &emptyNodeName}}, + Ports: []v1.EndpointPort{{Port: 1000}}, }}, }}) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) endpoints := NewEndpointControllerFromClient(client, controller.NoResyncPeriodFunc) endpoints.podStoreSynced = alwaysReady addPods(endpoints.podStore.Indexer, ns, 1, 1, 0) serviceLabels := map[string]string{"baz": "blah"} - endpoints.serviceStore.Indexer.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{ + endpoints.serviceStore.Indexer.Add(&v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, Labels: serviceLabels, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: map[string]string{"foo": "bar"}, - Ports: []api.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, + Ports: []v1.ServicePort{{Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}}, }, }) endpoints.syncService(ns + "/foo") - data := runtime.EncodeOrDie(testapi.Default.Codec(), &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + data := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, ResourceVersion: "1", Labels: serviceLabels, }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &api.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, - Ports: []api.EndpointPort{{Port: 8080, Protocol: "TCP"}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4", NodeName: &emptyNodeName, TargetRef: &v1.ObjectReference{Kind: "Pod", Name: "pod0", Namespace: ns}}}, + Ports: []v1.EndpointPort{{Port: 8080, Protocol: "TCP"}}, }}, }) endpointsHandler.ValidateRequest(t, testapi.Default.ResourcePath("endpoints", ns, "foo"), "PUT", &data) diff --git a/pkg/controller/garbagecollector/BUILD b/pkg/controller/garbagecollector/BUILD index 2e847b0d24c..6d19a6d3fca 100644 --- a/pkg/controller/garbagecollector/BUILD +++ b/pkg/controller/garbagecollector/BUILD @@ -51,7 +51,6 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/install:go_default_library", "//pkg/api/meta/metatypes:go_default_library", "//pkg/api/unversioned:go_default_library", diff --git a/pkg/controller/garbagecollector/garbagecollector.go b/pkg/controller/garbagecollector/garbagecollector.go index e3beadff917..1708cfb5c8e 100644 --- a/pkg/controller/garbagecollector/garbagecollector.go +++ b/pkg/controller/garbagecollector/garbagecollector.go @@ -232,7 +232,7 @@ func shouldOrphanDependents(e *event, accessor meta.Object) bool { } finalizers := accessor.GetFinalizers() for _, finalizer := range finalizers { - if finalizer == api.FinalizerOrphan { + if finalizer == v1.FinalizerOrphan { return true } } @@ -277,7 +277,7 @@ func (gc *GarbageCollector) removeOrphanFinalizer(owner *node) error { var newFinalizers []string found := false for _, f := range finalizers { - if f == api.FinalizerOrphan { + if f == v1.FinalizerOrphan { found = true break } else { @@ -450,24 +450,24 @@ type GarbageCollector struct { func gcListWatcher(client *dynamic.Client, resource unversioned.GroupVersionResource) *cache.ListWatch { return &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { // APIResource.Kind is not used by the dynamic client, so // leave it empty. We want to list this resource in all // namespaces if it's namespace scoped, so leave // APIResource.Namespaced as false is all right. apiResource := unversioned.APIResource{Name: resource.Resource} return client.ParameterCodec(dynamic.VersionedParameterEncoderWithV1Fallback). - Resource(&apiResource, api.NamespaceAll). + Resource(&apiResource, v1.NamespaceAll). List(&options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { // APIResource.Kind is not used by the dynamic client, so // leave it empty. We want to list this resource in all // namespaces if it's namespace scoped, so leave // APIResource.Namespaced as false is all right. apiResource := unversioned.APIResource{Name: resource.Resource} return client.ParameterCodec(dynamic.VersionedParameterEncoderWithV1Fallback). - Resource(&apiResource, api.NamespaceAll). + Resource(&apiResource, v1.NamespaceAll). Watch(&options) }, } diff --git a/pkg/controller/garbagecollector/garbagecollector_test.go b/pkg/controller/garbagecollector/garbagecollector_test.go index 54174a78ec3..2a3211d2add 100644 --- a/pkg/controller/garbagecollector/garbagecollector_test.go +++ b/pkg/controller/garbagecollector/garbagecollector_test.go @@ -27,7 +27,6 @@ import ( _ "k8s.io/kubernetes/pkg/api/install" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/meta/metatypes" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" @@ -231,14 +230,14 @@ func verifyGraphInvariants(scenario string, uidToNode map[types.UID]*node, t *te } func createEvent(eventType eventType, selfUID string, owners []string) event { - var ownerReferences []api.OwnerReference + var ownerReferences []v1.OwnerReference for i := 0; i < len(owners); i++ { - ownerReferences = append(ownerReferences, api.OwnerReference{UID: types.UID(owners[i])}) + ownerReferences = append(ownerReferences, v1.OwnerReference{UID: types.UID(owners[i])}) } return event{ eventType: eventType, - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + obj: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: types.UID(selfUID), OwnerReferences: ownerReferences, }, @@ -350,8 +349,8 @@ func TestGCListWatcher(t *testing.T) { t.Fatal(err) } lw := gcListWatcher(client, podResource) - lw.Watch(api.ListOptions{ResourceVersion: "1"}) - lw.List(api.ListOptions{ResourceVersion: "1"}) + lw.Watch(v1.ListOptions{ResourceVersion: "1"}) + lw.List(v1.ListOptions{ResourceVersion: "1"}) if e, a := 2, len(testHandler.actions); e != a { t.Errorf("expect %d requests, got %d", e, a) } diff --git a/pkg/controller/informers/BUILD b/pkg/controller/informers/BUILD index 2b48aea4204..72ea099a2aa 100644 --- a/pkg/controller/informers/BUILD +++ b/pkg/controller/informers/BUILD @@ -25,13 +25,17 @@ go_library( deps = [ "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/batch:go_default_library", + "//pkg/apis/batch/v1:go_default_library", "//pkg/apis/extensions:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/apis/rbac:go_default_library", - "//pkg/apis/storage:go_default_library", + "//pkg/apis/storage/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/listers/batch/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/listers/batch/v1:go_default_library", "//pkg/client/listers/core/internalversion:go_default_library", "//pkg/runtime:go_default_library", "//pkg/watch:go_default_library", diff --git a/pkg/controller/informers/batch.go b/pkg/controller/informers/batch.go index 3143d555e70..ababccdc4ad 100644 --- a/pkg/controller/informers/batch.go +++ b/pkg/controller/informers/batch.go @@ -20,11 +20,11 @@ import ( "reflect" "time" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/batch" + "k8s.io/kubernetes/pkg/api/v1" + batch "k8s.io/kubernetes/pkg/apis/batch/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - batchinternallisters "k8s.io/kubernetes/pkg/client/listers/batch/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + batchv1listers "k8s.io/kubernetes/pkg/client/listers/batch/v1" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/watch" ) @@ -33,7 +33,7 @@ import ( // Interface provides constructor for informer and lister for jobs type JobInformer interface { Informer() cache.SharedIndexInformer - Lister() batchinternallisters.JobLister + Lister() batchv1listers.JobLister } type jobInformer struct { @@ -61,11 +61,11 @@ func (f *jobInformer) Informer() cache.SharedIndexInformer { func NewJobInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { sharedIndexInformer := cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return client.Batch().Jobs(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return client.Batch().Jobs(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return client.Batch().Jobs(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return client.Batch().Jobs(v1.NamespaceAll).Watch(options) }, }, &batch.Job{}, @@ -77,7 +77,7 @@ func NewJobInformer(client clientset.Interface, resyncPeriod time.Duration) cach } // Lister returns lister for jobInformer -func (f *jobInformer) Lister() batchinternallisters.JobLister { +func (f *jobInformer) Lister() batchv1listers.JobLister { informer := f.Informer() - return batchinternallisters.NewJobLister(informer.GetIndexer()) + return batchv1listers.NewJobLister(informer.GetIndexer()) } diff --git a/pkg/controller/informers/core.go b/pkg/controller/informers/core.go index c035cfacdd4..0619ab27bad 100644 --- a/pkg/controller/informers/core.go +++ b/pkg/controller/informers/core.go @@ -21,8 +21,10 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" coreinternallisters "k8s.io/kubernetes/pkg/client/listers/core/internalversion" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/watch" @@ -45,7 +47,7 @@ func (f *podInformer) Informer() cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() - informerType := reflect.TypeOf(&api.Pod{}) + informerType := reflect.TypeOf(&v1.Pod{}) informer, exists := f.informers[informerType] if exists { return informer @@ -81,7 +83,7 @@ func (f *namespaceInformer) Informer() cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() - informerType := reflect.TypeOf(&api.Namespace{}) + informerType := reflect.TypeOf(&v1.Namespace{}) informer, exists := f.informers[informerType] if exists { return informer @@ -100,6 +102,42 @@ func (f *namespaceInformer) Lister() *cache.IndexerToNamespaceLister { //***************************************************************************** +// InternalNamespaceInformer is type of SharedIndexInformer which watches and lists all namespaces. +// Interface provides constructor for informer and lister for namsespaces +type InternalNamespaceInformer interface { + Informer() cache.SharedIndexInformer + Lister() coreinternallisters.NamespaceLister +} + +type internalNamespaceInformer struct { + *sharedInformerFactory +} + +// Informer checks whether internalNamespaceInformer exists in sharedInformerFactory and if not, it creates new informer of type +// internalNamespaceInformer and connects it to sharedInformerFactory +func (f *internalNamespaceInformer) Informer() cache.SharedIndexInformer { + f.lock.Lock() + defer f.lock.Unlock() + + informerType := reflect.TypeOf(&api.Namespace{}) + informer, exists := f.informers[informerType] + if exists { + return informer + } + informer = NewInternalNamespaceInformer(f.internalclient, f.defaultResync) + f.informers[informerType] = informer + + return informer +} + +// Lister returns lister for internalNamespaceInformer +func (f *internalNamespaceInformer) Lister() coreinternallisters.NamespaceLister { + informer := f.Informer() + return coreinternallisters.NewNamespaceLister(informer.GetIndexer()) +} + +//***************************************************************************** + // NodeInformer is type of SharedIndexInformer which watches and lists all nodes. // Interface provides constructor for informer and lister for nodes type NodeInformer interface { @@ -117,7 +155,7 @@ func (f *nodeInformer) Informer() cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() - informerType := reflect.TypeOf(&api.Node{}) + informerType := reflect.TypeOf(&v1.Node{}) informer, exists := f.informers[informerType] if exists { return informer @@ -153,7 +191,7 @@ func (f *pvcInformer) Informer() cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() - informerType := reflect.TypeOf(&api.PersistentVolumeClaim{}) + informerType := reflect.TypeOf(&v1.PersistentVolumeClaim{}) informer, exists := f.informers[informerType] if exists { return informer @@ -189,7 +227,7 @@ func (f *pvInformer) Informer() cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() - informerType := reflect.TypeOf(&api.PersistentVolume{}) + informerType := reflect.TypeOf(&v1.PersistentVolume{}) informer, exists := f.informers[informerType] if exists { return informer @@ -212,7 +250,7 @@ func (f *pvInformer) Lister() *cache.StoreToPVFetcher { // Interface provides constructor for informer and lister for limit ranges. type LimitRangeInformer interface { Informer() cache.SharedIndexInformer - Lister() coreinternallisters.LimitRangeLister + Lister() *cache.StoreToLimitRangeLister } type limitRangeInformer struct { @@ -225,7 +263,7 @@ func (f *limitRangeInformer) Informer() cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() - informerType := reflect.TypeOf(&api.LimitRange{}) + informerType := reflect.TypeOf(&v1.LimitRange{}) informer, exists := f.informers[informerType] if exists { return informer @@ -237,23 +275,61 @@ func (f *limitRangeInformer) Informer() cache.SharedIndexInformer { } // Lister returns lister for limitRangeInformer -func (f *limitRangeInformer) Lister() coreinternallisters.LimitRangeLister { +func (f *limitRangeInformer) Lister() *cache.StoreToLimitRangeLister { + informer := f.Informer() + return &cache.StoreToLimitRangeLister{Indexer: informer.GetIndexer()} +} + +//***************************************************************************** + +// InternalLimitRangeInformer is type of SharedIndexInformer which watches and lists all limit ranges. +// Interface provides constructor for informer and lister for limit ranges. +type InternalLimitRangeInformer interface { + Informer() cache.SharedIndexInformer + Lister() coreinternallisters.LimitRangeLister +} + +type internalLimitRangeInformer struct { + *sharedInformerFactory +} + +// Informer checks whether pvcInformer exists in sharedInformerFactory and if not, it creates new informer of type +// internalLimitRangeInformer and connects it to sharedInformerFactory +func (f *internalLimitRangeInformer) Informer() cache.SharedIndexInformer { + f.lock.Lock() + defer f.lock.Unlock() + + informerType := reflect.TypeOf(&api.LimitRange{}) + informer, exists := f.informers[informerType] + if exists { + return informer + } + informer = NewInternalLimitRangeInformer(f.internalclient, f.defaultResync) + f.informers[informerType] = informer + + return informer +} + +// Lister returns lister for internalLimitRangeInformer +func (f *internalLimitRangeInformer) Lister() coreinternallisters.LimitRangeLister { informer := f.Informer() return coreinternallisters.NewLimitRangeLister(informer.GetIndexer()) } +//***************************************************************************** + // NewPodInformer returns a SharedIndexInformer that lists and watches all pods func NewPodInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { sharedIndexInformer := cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return client.Core().Pods(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return client.Core().Pods(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return client.Core().Pods(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return client.Core().Pods(v1.NamespaceAll).Watch(options) }, }, - &api.Pod{}, + &v1.Pod{}, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, ) @@ -265,14 +341,14 @@ func NewPodInformer(client clientset.Interface, resyncPeriod time.Duration) cach func NewNodeInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { sharedIndexInformer := cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return client.Core().Nodes().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return client.Core().Nodes().Watch(options) }, }, - &api.Node{}, + &v1.Node{}, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}) @@ -283,14 +359,14 @@ func NewNodeInformer(client clientset.Interface, resyncPeriod time.Duration) cac func NewPVCInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { sharedIndexInformer := cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return client.Core().PersistentVolumeClaims(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return client.Core().PersistentVolumeClaims(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return client.Core().PersistentVolumeClaims(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return client.Core().PersistentVolumeClaims(v1.NamespaceAll).Watch(options) }, }, - &api.PersistentVolumeClaim{}, + &v1.PersistentVolumeClaim{}, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, ) @@ -302,14 +378,14 @@ func NewPVCInformer(client clientset.Interface, resyncPeriod time.Duration) cach func NewPVInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { sharedIndexInformer := cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return client.Core().PersistentVolumes().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return client.Core().PersistentVolumes().Watch(options) }, }, - &api.PersistentVolume{}, + &v1.PersistentVolume{}, resyncPeriod, cache.Indexers{}) @@ -320,13 +396,35 @@ func NewPVInformer(client clientset.Interface, resyncPeriod time.Duration) cache func NewNamespaceInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { sharedIndexInformer := cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return client.Core().Namespaces().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return client.Core().Namespaces().Watch(options) }, }, + &v1.Namespace{}, + resyncPeriod, + cache.Indexers{}) + + return sharedIndexInformer +} + +// NewInternalNamespaceInformer returns a SharedIndexInformer that lists and watches namespaces +func NewInternalNamespaceInformer(client internalclientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + sharedIndexInformer := cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return client.Core().Namespaces().List(internalOptions) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return client.Core().Namespaces().Watch(internalOptions) + }, + }, &api.Namespace{}, resyncPeriod, cache.Indexers{}) @@ -338,11 +436,33 @@ func NewNamespaceInformer(client clientset.Interface, resyncPeriod time.Duration func NewLimitRangeInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { sharedIndexInformer := cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return client.Core().LimitRanges(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return client.Core().LimitRanges(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return client.Core().LimitRanges(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return client.Core().LimitRanges(v1.NamespaceAll).Watch(options) + }, + }, + &v1.LimitRange{}, + resyncPeriod, + cache.Indexers{}) + + return sharedIndexInformer +} + +// NewInternalLimitRangeInformer returns a SharedIndexInformer that lists and watches all LimitRanges +func NewInternalLimitRangeInformer(internalclient internalclientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + sharedIndexInformer := cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return internalclient.Core().LimitRanges(v1.NamespaceAll).List(internalOptions) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return internalclient.Core().LimitRanges(v1.NamespaceAll).Watch(internalOptions) }, }, &api.LimitRange{}, @@ -371,7 +491,7 @@ func (f *serviceAccountInformer) Informer() cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() - informerType := reflect.TypeOf(&api.ServiceAccount{}) + informerType := reflect.TypeOf(&v1.ServiceAccount{}) informer, exists := f.informers[informerType] if exists { return informer @@ -392,14 +512,14 @@ func (f *serviceAccountInformer) Lister() *cache.StoreToServiceAccountLister { func NewServiceAccountInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { sharedIndexInformer := cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return client.Core().ServiceAccounts(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return client.Core().ServiceAccounts(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return client.Core().ServiceAccounts(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return client.Core().ServiceAccounts(v1.NamespaceAll).Watch(options) }, }, - &api.ServiceAccount{}, + &v1.ServiceAccount{}, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}) diff --git a/pkg/controller/informers/extensions.go b/pkg/controller/informers/extensions.go index 95e9e8d67fa..a5650cb5275 100644 --- a/pkg/controller/informers/extensions.go +++ b/pkg/controller/informers/extensions.go @@ -20,8 +20,8 @@ import ( "reflect" "time" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/watch" @@ -49,11 +49,11 @@ func (f *daemonSetInformer) Informer() cache.SharedIndexInformer { } informer = cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return f.client.Extensions().DaemonSets(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return f.client.Extensions().DaemonSets(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return f.client.Extensions().DaemonSets(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return f.client.Extensions().DaemonSets(v1.NamespaceAll).Watch(options) }, }, &extensions.DaemonSet{}, @@ -91,11 +91,11 @@ func (f *deploymentInformer) Informer() cache.SharedIndexInformer { } informer = cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return f.client.Extensions().Deployments(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return f.client.Extensions().Deployments(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return f.client.Extensions().Deployments(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return f.client.Extensions().Deployments(v1.NamespaceAll).Watch(options) }, }, &extensions.Deployment{}, @@ -135,11 +135,11 @@ func (f *replicaSetInformer) Informer() cache.SharedIndexInformer { } informer = cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return f.client.Extensions().ReplicaSets(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return f.client.Extensions().ReplicaSets(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return f.client.Extensions().ReplicaSets(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return f.client.Extensions().ReplicaSets(v1.NamespaceAll).Watch(options) }, }, &extensions.ReplicaSet{}, diff --git a/pkg/controller/informers/factory.go b/pkg/controller/informers/factory.go index 084e2e21b6a..7eb3c9dfee6 100644 --- a/pkg/controller/informers/factory.go +++ b/pkg/controller/informers/factory.go @@ -23,7 +23,8 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" ) // SharedInformerFactory provides interface which holds unique informers for pods, nodes, namespaces, persistent volume @@ -38,7 +39,9 @@ type SharedInformerFactory interface { Pods() PodInformer LimitRanges() LimitRangeInformer + InternalLimitRanges() InternalLimitRangeInformer Namespaces() NamespaceInformer + InternalNamespaces() InternalNamespaceInformer Nodes() NodeInformer PersistentVolumeClaims() PVCInformer PersistentVolumes() PVInformer @@ -59,9 +62,11 @@ type SharedInformerFactory interface { } type sharedInformerFactory struct { - client clientset.Interface - lock sync.Mutex - defaultResync time.Duration + client clientset.Interface + // for admission plugins etc. + internalclient internalclientset.Interface + lock sync.Mutex + defaultResync time.Duration informers map[reflect.Type]cache.SharedIndexInformer // startedInformers is used for tracking which informers have been started @@ -70,9 +75,10 @@ type sharedInformerFactory struct { } // NewSharedInformerFactory constructs a new instance of sharedInformerFactory -func NewSharedInformerFactory(client clientset.Interface, defaultResync time.Duration) SharedInformerFactory { +func NewSharedInformerFactory(client clientset.Interface, internalclient internalclientset.Interface, defaultResync time.Duration) SharedInformerFactory { return &sharedInformerFactory{ client: client, + internalclient: internalclient, defaultResync: defaultResync, informers: make(map[reflect.Type]cache.SharedIndexInformer), startedInformers: make(map[reflect.Type]bool), @@ -107,6 +113,11 @@ func (f *sharedInformerFactory) Namespaces() NamespaceInformer { return &namespaceInformer{sharedInformerFactory: f} } +// InternalNamespaces returns a SharedIndexInformer that lists and watches all namespaces +func (f *sharedInformerFactory) InternalNamespaces() InternalNamespaceInformer { + return &internalNamespaceInformer{sharedInformerFactory: f} +} + // PersistentVolumeClaims returns a SharedIndexInformer that lists and watches all persistent volume claims func (f *sharedInformerFactory) PersistentVolumeClaims() PVCInformer { return &pvcInformer{sharedInformerFactory: f} @@ -156,6 +167,11 @@ func (f *sharedInformerFactory) LimitRanges() LimitRangeInformer { return &limitRangeInformer{sharedInformerFactory: f} } +// InternalLimitRanges returns a SharedIndexInformer that lists and watches all limit ranges. +func (f *sharedInformerFactory) InternalLimitRanges() InternalLimitRangeInformer { + return &internalLimitRangeInformer{sharedInformerFactory: f} +} + // StorageClasses returns a SharedIndexInformer that lists and watches all storage classes func (f *sharedInformerFactory) StorageClasses() StorageClassInformer { return &storageClassInformer{sharedInformerFactory: f} diff --git a/pkg/controller/informers/generic.go b/pkg/controller/informers/generic.go index fc6a6e0052b..e3c63dd5c9a 100644 --- a/pkg/controller/informers/generic.go +++ b/pkg/controller/informers/generic.go @@ -22,8 +22,8 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/batch" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/apis/rbac" + extensionsinternal "k8s.io/kubernetes/pkg/apis/extensions" + rbacinternal "k8s.io/kubernetes/pkg/apis/rbac" "k8s.io/kubernetes/pkg/client/cache" ) @@ -53,20 +53,20 @@ func (f *sharedInformerFactory) ForResource(resource unversioned.GroupResource) case api.Resource("serviceaccounts"): return &genericInformer{resource: resource, informer: f.ServiceAccounts().Informer()}, nil - case extensions.Resource("daemonsets"): + case extensionsinternal.Resource("daemonsets"): return &genericInformer{resource: resource, informer: f.DaemonSets().Informer()}, nil - case extensions.Resource("deployments"): + case extensionsinternal.Resource("deployments"): return &genericInformer{resource: resource, informer: f.Deployments().Informer()}, nil - case extensions.Resource("replicasets"): + case extensionsinternal.Resource("replicasets"): return &genericInformer{resource: resource, informer: f.ReplicaSets().Informer()}, nil - case rbac.Resource("clusterrolebindings"): + case rbacinternal.Resource("clusterrolebindings"): return &genericInformer{resource: resource, informer: f.ClusterRoleBindings().Informer()}, nil - case rbac.Resource("clusterroles"): + case rbacinternal.Resource("clusterroles"): return &genericInformer{resource: resource, informer: f.ClusterRoles().Informer()}, nil - case rbac.Resource("rolebindings"): + case rbacinternal.Resource("rolebindings"): return &genericInformer{resource: resource, informer: f.RoleBindings().Informer()}, nil - case rbac.Resource("roles"): + case rbacinternal.Resource("roles"): return &genericInformer{resource: resource, informer: f.Roles().Informer()}, nil case batch.Resource("jobs"): diff --git a/pkg/controller/informers/rbac.go b/pkg/controller/informers/rbac.go index aa5681f3db4..057a64b4e95 100644 --- a/pkg/controller/informers/rbac.go +++ b/pkg/controller/informers/rbac.go @@ -19,8 +19,8 @@ package informers import ( "reflect" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/rbac" + "k8s.io/kubernetes/pkg/api/v1" + rbac "k8s.io/kubernetes/pkg/apis/rbac" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/watch" @@ -46,10 +46,10 @@ func (f *clusterRoleInformer) Informer() cache.SharedIndexInformer { } informer = cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return f.client.Rbac().ClusterRoles().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return f.client.Rbac().ClusterRoles().Watch(options) }, }, @@ -86,10 +86,10 @@ func (f *clusterRoleBindingInformer) Informer() cache.SharedIndexInformer { } informer = cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return f.client.Rbac().ClusterRoleBindings().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return f.client.Rbac().ClusterRoleBindings().Watch(options) }, }, @@ -126,11 +126,11 @@ func (f *roleInformer) Informer() cache.SharedIndexInformer { } informer = cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return f.client.Rbac().Roles(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return f.client.Rbac().Roles(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return f.client.Rbac().Roles(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return f.client.Rbac().Roles(v1.NamespaceAll).Watch(options) }, }, &rbac.Role{}, @@ -166,11 +166,11 @@ func (f *roleBindingInformer) Informer() cache.SharedIndexInformer { } informer = cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return f.client.Rbac().RoleBindings(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return f.client.Rbac().RoleBindings(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return f.client.Rbac().RoleBindings(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return f.client.Rbac().RoleBindings(v1.NamespaceAll).Watch(options) }, }, &rbac.RoleBinding{}, diff --git a/pkg/controller/informers/storage.go b/pkg/controller/informers/storage.go index 32f6ef8938b..cfff5f41879 100644 --- a/pkg/controller/informers/storage.go +++ b/pkg/controller/informers/storage.go @@ -19,8 +19,8 @@ package informers import ( "reflect" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/storage" + "k8s.io/kubernetes/pkg/api/v1" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/watch" @@ -48,10 +48,10 @@ func (f *storageClassInformer) Informer() cache.SharedIndexInformer { } informer = cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return f.client.Storage().StorageClasses().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return f.client.Storage().StorageClasses().Watch(options) }, }, diff --git a/pkg/controller/job/BUILD b/pkg/controller/job/BUILD index 20782b81d2e..ef41567a3c7 100644 --- a/pkg/controller/job/BUILD +++ b/pkg/controller/job/BUILD @@ -19,14 +19,14 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/batch:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/batch/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", - "//pkg/client/listers/batch/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", + "//pkg/client/listers/batch/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/controller:go_default_library", "//pkg/controller/informers:go_default_library", @@ -49,11 +49,12 @@ go_test( deps = [ "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/apis/batch:go_default_library", + "//pkg/apis/batch/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/controller:go_default_library", diff --git a/pkg/controller/job/jobcontroller.go b/pkg/controller/job/jobcontroller.go index 049b0969733..928456db97a 100644 --- a/pkg/controller/job/jobcontroller.go +++ b/pkg/controller/job/jobcontroller.go @@ -23,14 +23,14 @@ import ( "sync" "time" - "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/api/v1" + batch "k8s.io/kubernetes/pkg/apis/batch/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" - batchinternallisters "k8s.io/kubernetes/pkg/client/listers/batch/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" + batchv1listers "k8s.io/kubernetes/pkg/client/listers/batch/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/informers" @@ -60,7 +60,7 @@ type JobController struct { expectations controller.ControllerExpectationsInterface // A store of jobs - jobLister batchinternallisters.JobLister + jobLister batchv1listers.JobLister // A store of pods, populated by the podController podStore cache.StoreToPodLister @@ -75,7 +75,7 @@ func NewJobController(podInformer cache.SharedIndexInformer, jobInformer informe eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(glog.Infof) // TODO: remove the wrapper when every clients have moved to use the clientset. - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.Core().Events("")}) if kubeClient != nil && kubeClient.Core().RESTClient().GetRateLimiter() != nil { metrics.RegisterMetricAndTrackRateLimiterUsage("job_controller", kubeClient.Core().RESTClient().GetRateLimiter()) @@ -85,11 +85,11 @@ func NewJobController(podInformer cache.SharedIndexInformer, jobInformer informe kubeClient: kubeClient, podControl: controller.RealPodControl{ KubeClient: kubeClient, - Recorder: eventBroadcaster.NewRecorder(api.EventSource{Component: "job-controller"}), + Recorder: eventBroadcaster.NewRecorder(v1.EventSource{Component: "job-controller"}), }, expectations: controller.NewControllerExpectations(), queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "job"), - recorder: eventBroadcaster.NewRecorder(api.EventSource{Component: "job-controller"}), + recorder: eventBroadcaster.NewRecorder(v1.EventSource{Component: "job-controller"}), } jobInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ @@ -135,7 +135,7 @@ func (jm *JobController) Run(workers int, stopCh <-chan struct{}) { } // getPodJob returns the job managing the given pod. -func (jm *JobController) getPodJob(pod *api.Pod) *batch.Job { +func (jm *JobController) getPodJob(pod *v1.Pod) *batch.Job { jobs, err := jm.jobLister.GetPodJobs(pod) if err != nil { glog.V(4).Infof("No jobs found for pod %v, job controller will avoid syncing", pod.Name) @@ -150,7 +150,7 @@ func (jm *JobController) getPodJob(pod *api.Pod) *batch.Job { // When a pod is created, enqueue the controller that manages it and update it's expectations. func (jm *JobController) addPod(obj interface{}) { - pod := obj.(*api.Pod) + pod := obj.(*v1.Pod) if pod.DeletionTimestamp != nil { // on a restart of the controller controller, it's possible a new pod shows up in a state that // is already pending deletion. Prevent the pod from being a creation observation. @@ -170,10 +170,10 @@ func (jm *JobController) addPod(obj interface{}) { // When a pod is updated, figure out what job/s manage it and wake them up. // If the labels of the pod have changed we need to awaken both the old -// and new job. old and cur must be *api.Pod types. +// and new job. old and cur must be *v1.Pod types. func (jm *JobController) updatePod(old, cur interface{}) { - curPod := cur.(*api.Pod) - oldPod := old.(*api.Pod) + curPod := cur.(*v1.Pod) + oldPod := old.(*v1.Pod) if curPod.ResourceVersion == oldPod.ResourceVersion { // Periodic resync will send update events for all known pods. // Two different versions of the same pod will always have different RVs. @@ -201,9 +201,9 @@ func (jm *JobController) updatePod(old, cur interface{}) { } // When a pod is deleted, enqueue the job that manages the pod and update its expectations. -// obj could be an *api.Pod, or a DeletionFinalStateUnknown marker item. +// obj could be an *v1.Pod, or a DeletionFinalStateUnknown marker item. func (jm *JobController) deletePod(obj interface{}) { - pod, ok := obj.(*api.Pod) + pod, ok := obj.(*v1.Pod) // When a delete is dropped, the relist will notice a pod in the store not // in the list, leading to the insertion of a tombstone object which contains @@ -215,7 +215,7 @@ func (jm *JobController) deletePod(obj interface{}) { utilruntime.HandleError(fmt.Errorf("Couldn't get object from tombstone %+v", obj)) return } - pod, ok = tombstone.Obj.(*api.Pod) + pod, ok = tombstone.Obj.(*v1.Pod) if !ok { utilruntime.HandleError(fmt.Errorf("Tombstone contained object that is not a pod %+v", obj)) return @@ -346,7 +346,7 @@ func (jm *JobController) syncJob(key string) error { failed += active active = 0 job.Status.Conditions = append(job.Status.Conditions, newCondition(batch.JobFailed, "DeadlineExceeded", "Job was active longer than specified deadline")) - jm.recorder.Event(&job, api.EventTypeNormal, "DeadlineExceeded", "Job was active longer than specified deadline") + jm.recorder.Event(&job, v1.EventTypeNormal, "DeadlineExceeded", "Job was active longer than specified deadline") } else { if jobNeedsSync && job.DeletionTimestamp == nil { active = jm.manageJob(activePods, succeeded, &job) @@ -371,10 +371,10 @@ func (jm *JobController) syncJob(key string) error { if completions >= *job.Spec.Completions { complete = true if active > 0 { - jm.recorder.Event(&job, api.EventTypeWarning, "TooManyActivePods", "Too many active pods running after completion count reached") + jm.recorder.Event(&job, v1.EventTypeWarning, "TooManyActivePods", "Too many active pods running after completion count reached") } if completions > *job.Spec.Completions { - jm.recorder.Event(&job, api.EventTypeWarning, "TooManySucceededPods", "Too many succeeded pods running after completion count reached") + jm.recorder.Event(&job, v1.EventTypeWarning, "TooManySucceededPods", "Too many succeeded pods running after completion count reached") } } } @@ -413,7 +413,7 @@ func pastActiveDeadline(job *batch.Job) bool { func newCondition(conditionType batch.JobConditionType, reason, message string) batch.JobCondition { return batch.JobCondition{ Type: conditionType, - Status: api.ConditionTrue, + Status: v1.ConditionTrue, LastProbeTime: unversioned.Now(), LastTransitionTime: unversioned.Now(), Reason: reason, @@ -422,16 +422,16 @@ func newCondition(conditionType batch.JobConditionType, reason, message string) } // getStatus returns no of succeeded and failed pods running a job -func getStatus(pods []*api.Pod) (succeeded, failed int32) { - succeeded = int32(filterPods(pods, api.PodSucceeded)) - failed = int32(filterPods(pods, api.PodFailed)) +func getStatus(pods []*v1.Pod) (succeeded, failed int32) { + succeeded = int32(filterPods(pods, v1.PodSucceeded)) + failed = int32(filterPods(pods, v1.PodFailed)) return } // manageJob is the core method responsible for managing the number of running // pods according to what is specified in the job.Spec. // Does NOT modify . -func (jm *JobController) manageJob(activePods []*api.Pod, succeeded int32, job *batch.Job) int32 { +func (jm *JobController) manageJob(activePods []*v1.Pod, succeeded int32, job *batch.Job) int32 { var activeLock sync.Mutex active := int32(len(activePods)) parallelism := *job.Spec.Parallelism @@ -523,7 +523,7 @@ func (jm *JobController) updateJobStatus(job *batch.Job) error { } // filterPods returns pods based on their phase. -func filterPods(pods []*api.Pod, phase api.PodPhase) int { +func filterPods(pods []*v1.Pod, phase v1.PodPhase) int { result := 0 for i := range pods { if phase == pods[i].Status.Phase { diff --git a/pkg/controller/job/jobcontroller_test.go b/pkg/controller/job/jobcontroller_test.go index 2dcd6687275..5216ab5081f 100644 --- a/pkg/controller/job/jobcontroller_test.go +++ b/pkg/controller/job/jobcontroller_test.go @@ -23,11 +23,12 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/batch" + batch "k8s.io/kubernetes/pkg/apis/batch/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/controller" @@ -41,22 +42,22 @@ var alwaysReady = func() bool { return true } func newJob(parallelism, completions int32) *batch.Job { j := &batch.Job{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "foobar", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, Spec: batch.JobSpec{ Selector: &unversioned.LabelSelector{ MatchLabels: map[string]string{"foo": "bar"}, }, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{ "foo": "bar", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Image: "foo/bar"}, }, }, @@ -88,23 +89,23 @@ func getKey(job *batch.Job, t *testing.T) string { } func newJobControllerFromClient(kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc) (*JobController, informers.SharedInformerFactory) { - sharedInformers := informers.NewSharedInformerFactory(kubeClient, resyncPeriod()) + sharedInformers := informers.NewSharedInformerFactory(kubeClient, nil, resyncPeriod()) jm := NewJobController(sharedInformers.Pods().Informer(), sharedInformers.Jobs(), kubeClient) return jm, sharedInformers } // create count pods with the given phase for the given job -func newPodList(count int32, status api.PodPhase, job *batch.Job) []api.Pod { - pods := []api.Pod{} +func newPodList(count int32, status v1.PodPhase, job *batch.Job) []v1.Pod { + pods := []v1.Pod{} for i := int32(0); i < count; i++ { - newPod := api.Pod{ - ObjectMeta: api.ObjectMeta{ + newPod := v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: fmt.Sprintf("pod-%v", rand.String(10)), Labels: job.Spec.Selector.MatchLabels, Namespace: job.Namespace, }, - Status: api.PodStatus{Phase: status}, + Status: v1.PodStatus{Phase: status}, } pods = append(pods, newPod) } @@ -227,7 +228,7 @@ func TestControllerSyncJob(t *testing.T) { for name, tc := range testCases { // job manager setup - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager, sharedInformerFactory := newJobControllerFromClient(clientset, controller.NoResyncPeriodFunc) fakePodControl := controller.FakePodControl{Err: tc.podControllerError} manager.podControl = &fakePodControl @@ -247,16 +248,16 @@ func TestControllerSyncJob(t *testing.T) { } sharedInformerFactory.Jobs().Informer().GetIndexer().Add(job) podIndexer := sharedInformerFactory.Pods().Informer().GetIndexer() - for _, pod := range newPodList(tc.pendingPods, api.PodPending, job) { + for _, pod := range newPodList(tc.pendingPods, v1.PodPending, job) { podIndexer.Add(&pod) } - for _, pod := range newPodList(tc.activePods, api.PodRunning, job) { + for _, pod := range newPodList(tc.activePods, v1.PodRunning, job) { podIndexer.Add(&pod) } - for _, pod := range newPodList(tc.succeededPods, api.PodSucceeded, job) { + for _, pod := range newPodList(tc.succeededPods, v1.PodSucceeded, job) { podIndexer.Add(&pod) } - for _, pod := range newPodList(tc.failedPods, api.PodFailed, job) { + for _, pod := range newPodList(tc.failedPods, v1.PodFailed, job) { podIndexer.Add(&pod) } @@ -331,7 +332,7 @@ func TestSyncJobPastDeadline(t *testing.T) { for name, tc := range testCases { // job manager setup - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager, sharedInformerFactory := newJobControllerFromClient(clientset, controller.NoResyncPeriodFunc) fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl @@ -350,13 +351,13 @@ func TestSyncJobPastDeadline(t *testing.T) { job.Status.StartTime = &start sharedInformerFactory.Jobs().Informer().GetIndexer().Add(job) podIndexer := sharedInformerFactory.Pods().Informer().GetIndexer() - for _, pod := range newPodList(tc.activePods, api.PodRunning, job) { + for _, pod := range newPodList(tc.activePods, v1.PodRunning, job) { podIndexer.Add(&pod) } - for _, pod := range newPodList(tc.succeededPods, api.PodSucceeded, job) { + for _, pod := range newPodList(tc.succeededPods, v1.PodSucceeded, job) { podIndexer.Add(&pod) } - for _, pod := range newPodList(tc.failedPods, api.PodFailed, job) { + for _, pod := range newPodList(tc.failedPods, v1.PodFailed, job) { podIndexer.Add(&pod) } @@ -395,7 +396,7 @@ func TestSyncJobPastDeadline(t *testing.T) { func getCondition(job *batch.Job, condition batch.JobConditionType) bool { for _, v := range job.Status.Conditions { - if v.Type == condition && v.Status == api.ConditionTrue { + if v.Type == condition && v.Status == v1.ConditionTrue { return true } } @@ -403,7 +404,7 @@ func getCondition(job *batch.Job, condition batch.JobConditionType) bool { } func TestSyncPastDeadlineJobFinished(t *testing.T) { - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager, sharedInformerFactory := newJobControllerFromClient(clientset, controller.NoResyncPeriodFunc) fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl @@ -438,7 +439,7 @@ func TestSyncPastDeadlineJobFinished(t *testing.T) { } func TestSyncJobComplete(t *testing.T) { - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager, sharedInformerFactory := newJobControllerFromClient(clientset, controller.NoResyncPeriodFunc) fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl @@ -463,7 +464,7 @@ func TestSyncJobComplete(t *testing.T) { } func TestSyncJobDeleted(t *testing.T) { - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager, _ := newJobControllerFromClient(clientset, controller.NoResyncPeriodFunc) fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl @@ -484,7 +485,7 @@ func TestSyncJobDeleted(t *testing.T) { } func TestSyncJobUpdateRequeue(t *testing.T) { - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager, sharedInformerFactory := newJobControllerFromClient(clientset, controller.NoResyncPeriodFunc) fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl @@ -510,38 +511,38 @@ func TestSyncJobUpdateRequeue(t *testing.T) { } func TestJobPodLookup(t *testing.T) { - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager, sharedInformerFactory := newJobControllerFromClient(clientset, controller.NoResyncPeriodFunc) manager.podStoreSynced = alwaysReady manager.jobStoreSynced = alwaysReady testCases := []struct { job *batch.Job - pod *api.Pod + pod *v1.Pod expectedName string }{ // pods without labels don't match any job { job: &batch.Job{ - ObjectMeta: api.ObjectMeta{Name: "basic"}, + ObjectMeta: v1.ObjectMeta{Name: "basic"}, }, - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo1", Namespace: api.NamespaceAll}, + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "foo1", Namespace: v1.NamespaceAll}, }, expectedName: "", }, // matching labels, different namespace { job: &batch.Job{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, + ObjectMeta: v1.ObjectMeta{Name: "foo"}, Spec: batch.JobSpec{ Selector: &unversioned.LabelSelector{ MatchLabels: map[string]string{"foo": "bar"}, }, }, }, - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "foo2", Namespace: "ns", Labels: map[string]string{"foo": "bar"}, @@ -552,7 +553,7 @@ func TestJobPodLookup(t *testing.T) { // matching ns and labels returns { job: &batch.Job{ - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "ns"}, + ObjectMeta: v1.ObjectMeta{Name: "bar", Namespace: "ns"}, Spec: batch.JobSpec{ Selector: &unversioned.LabelSelector{ MatchExpressions: []unversioned.LabelSelectorRequirement{ @@ -565,8 +566,8 @@ func TestJobPodLookup(t *testing.T) { }, }, }, - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "foo3", Namespace: "ns", Labels: map[string]string{"foo": "bar"}, @@ -601,7 +602,7 @@ func (fe FakeJobExpectations) SatisfiedExpectations(controllerKey string) bool { // TestSyncJobExpectations tests that a pod cannot sneak in between counting active pods // and checking expectations. func TestSyncJobExpectations(t *testing.T) { - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager, sharedInformerFactory := newJobControllerFromClient(clientset, controller.NoResyncPeriodFunc) fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl @@ -611,7 +612,7 @@ func TestSyncJobExpectations(t *testing.T) { job := newJob(2, 2) sharedInformerFactory.Jobs().Informer().GetIndexer().Add(job) - pods := newPodList(2, api.PodPending, job) + pods := newPodList(2, v1.PodPending, job) podIndexer := sharedInformerFactory.Pods().Informer().GetIndexer() podIndexer.Add(&pods[0]) @@ -714,9 +715,9 @@ func TestWatchPods(t *testing.T) { go sharedInformerFactory.Pods().Informer().Run(stopCh) go wait.Until(manager.worker, 10*time.Millisecond, stopCh) - pods := newPodList(1, api.PodRunning, testJob) + pods := newPodList(1, v1.PodRunning, testJob) testPod := pods[0] - testPod.Status.Phase = api.PodFailed + testPod.Status.Phase = v1.PodFailed fakeWatch.Add(&testPod) t.Log("Waiting for pod to reach syncHandler") diff --git a/pkg/controller/job/utils.go b/pkg/controller/job/utils.go index 64d1f4268a8..5d14f054c60 100644 --- a/pkg/controller/job/utils.go +++ b/pkg/controller/job/utils.go @@ -17,13 +17,13 @@ limitations under the License. package job import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/batch" + "k8s.io/kubernetes/pkg/api/v1" + batch "k8s.io/kubernetes/pkg/apis/batch/v1" ) func IsJobFinished(j *batch.Job) bool { for _, c := range j.Status.Conditions { - if (c.Type == batch.JobComplete || c.Type == batch.JobFailed) && c.Status == api.ConditionTrue { + if (c.Type == batch.JobComplete || c.Type == batch.JobFailed) && c.Status == v1.ConditionTrue { return true } } diff --git a/pkg/controller/job/utils_test.go b/pkg/controller/job/utils_test.go index 59f2b63f19f..cdf715a01d2 100644 --- a/pkg/controller/job/utils_test.go +++ b/pkg/controller/job/utils_test.go @@ -19,8 +19,8 @@ package job import ( "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/batch" + "k8s.io/kubernetes/pkg/api/v1" + batch "k8s.io/kubernetes/pkg/apis/batch/v1" ) func TestIsJobFinished(t *testing.T) { @@ -28,7 +28,7 @@ func TestIsJobFinished(t *testing.T) { Status: batch.JobStatus{ Conditions: []batch.JobCondition{{ Type: batch.JobComplete, - Status: api.ConditionTrue, + Status: v1.ConditionTrue, }}, }, } @@ -37,12 +37,12 @@ func TestIsJobFinished(t *testing.T) { t.Error("Job was expected to be finished") } - job.Status.Conditions[0].Status = api.ConditionFalse + job.Status.Conditions[0].Status = v1.ConditionFalse if IsJobFinished(job) { t.Error("Job was not expected to be finished") } - job.Status.Conditions[0].Status = api.ConditionUnknown + job.Status.Conditions[0].Status = v1.ConditionUnknown if IsJobFinished(job) { t.Error("Job was not expected to be finished") } diff --git a/pkg/controller/namespace/BUILD b/pkg/controller/namespace/BUILD index 4b3e393f199..cda37896f86 100644 --- a/pkg/controller/namespace/BUILD +++ b/pkg/controller/namespace/BUILD @@ -19,12 +19,11 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/typed/dynamic:go_default_library", "//pkg/controller:go_default_library", "//pkg/runtime:go_default_library", @@ -47,9 +46,10 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/client/typed/dynamic:go_default_library", diff --git a/pkg/controller/namespace/namespace_controller.go b/pkg/controller/namespace/namespace_controller.go index 69065aa7ca0..3bb1b1dd986 100644 --- a/pkg/controller/namespace/namespace_controller.go +++ b/pkg/controller/namespace/namespace_controller.go @@ -19,10 +19,10 @@ package namespace import ( "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/typed/dynamic" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/runtime" @@ -52,7 +52,7 @@ type NamespaceController struct { // opCache is a cache to remember if a particular operation is not supported to aid dynamic client. opCache *operationNotSupportedCache // finalizerToken is the finalizer token managed by this controller - finalizerToken api.FinalizerName + finalizerToken v1.FinalizerName } // NewNamespaceController creates a new NamespaceController @@ -61,7 +61,7 @@ func NewNamespaceController( clientPool dynamic.ClientPool, groupVersionResourcesFn func() ([]unversioned.GroupVersionResource, error), resyncPeriod time.Duration, - finalizerToken api.FinalizerName) *NamespaceController { + finalizerToken v1.FinalizerName) *NamespaceController { // the namespace deletion code looks at the discovery document to enumerate the set of resources on the server. // it then finds all namespaced resources, and in response to namespace deletion, will call delete on all of them. @@ -98,22 +98,22 @@ func NewNamespaceController( // configure the backing store/controller store, controller := cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return kubeClient.Core().Namespaces().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return kubeClient.Core().Namespaces().Watch(options) }, }, - &api.Namespace{}, + &v1.Namespace{}, resyncPeriod, cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { - namespace := obj.(*api.Namespace) + namespace := obj.(*v1.Namespace) namespaceController.enqueueNamespace(namespace) }, UpdateFunc: func(oldObj, newObj interface{}) { - namespace := newObj.(*api.Namespace) + namespace := newObj.(*v1.Namespace) namespaceController.enqueueNamespace(namespace) }, }, @@ -125,7 +125,7 @@ func NewNamespaceController( } // enqueueNamespace adds an object to the controller work queue -// obj could be an *api.Namespace, or a DeletionFinalStateUnknown item. +// obj could be an *v1.Namespace, or a DeletionFinalStateUnknown item. func (nm *NamespaceController) enqueueNamespace(obj interface{}) { key, err := controller.KeyFunc(obj) if err != nil { @@ -190,7 +190,7 @@ func (nm *NamespaceController) syncNamespaceFromKey(key string) (err error) { nm.queue.Add(key) return err } - namespace := obj.(*api.Namespace) + namespace := obj.(*v1.Namespace) return syncNamespace(nm.kubeClient, nm.clientPool, nm.opCache, nm.groupVersionResourcesFn, namespace, nm.finalizerToken) } diff --git a/pkg/controller/namespace/namespace_controller_test.go b/pkg/controller/namespace/namespace_controller_test.go index f4d4cb67e1c..8930b1b3a45 100644 --- a/pkg/controller/namespace/namespace_controller_test.go +++ b/pkg/controller/namespace/namespace_controller_test.go @@ -28,9 +28,10 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/client/typed/dynamic" @@ -39,15 +40,15 @@ import ( ) func TestFinalized(t *testing.T) { - testNamespace := &api.Namespace{ - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{"a", "b"}, + testNamespace := &v1.Namespace{ + Spec: v1.NamespaceSpec{ + Finalizers: []v1.FinalizerName{"a", "b"}, }, } if finalized(testNamespace) { t.Errorf("Unexpected result, namespace is not finalized") } - testNamespace.Spec.Finalizers = []api.FinalizerName{} + testNamespace.Spec.Finalizers = []v1.FinalizerName{} if !finalized(testNamespace) { t.Errorf("Expected object to be finalized") } @@ -55,16 +56,16 @@ func TestFinalized(t *testing.T) { func TestFinalizeNamespaceFunc(t *testing.T) { mockClient := &fake.Clientset{} - testNamespace := &api.Namespace{ - ObjectMeta: api.ObjectMeta{ + testNamespace := &v1.Namespace{ + ObjectMeta: v1.ObjectMeta{ Name: "test", ResourceVersion: "1", }, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{"kubernetes", "other"}, + Spec: v1.NamespaceSpec{ + Finalizers: []v1.FinalizerName{"kubernetes", "other"}, }, } - finalizeNamespace(mockClient, testNamespace, api.FinalizerKubernetes) + finalizeNamespace(mockClient, testNamespace, v1.FinalizerKubernetes) actions := mockClient.Actions() if len(actions) != 1 { t.Errorf("Expected 1 mock client action, but got %v", len(actions)) @@ -72,7 +73,7 @@ func TestFinalizeNamespaceFunc(t *testing.T) { if !actions[0].Matches("create", "namespaces") || actions[0].GetSubresource() != "finalize" { t.Errorf("Expected finalize-namespace action %v", actions[0]) } - finalizers := actions[0].(core.CreateAction).GetObject().(*api.Namespace).Spec.Finalizers + finalizers := actions[0].(core.CreateAction).GetObject().(*v1.Namespace).Spec.Finalizers if len(finalizers) != 1 { t.Errorf("There should be a single finalizer remaining") } @@ -84,28 +85,28 @@ func TestFinalizeNamespaceFunc(t *testing.T) { func testSyncNamespaceThatIsTerminating(t *testing.T, versions *unversioned.APIVersions) { now := unversioned.Now() namespaceName := "test" - testNamespacePendingFinalize := &api.Namespace{ - ObjectMeta: api.ObjectMeta{ + testNamespacePendingFinalize := &v1.Namespace{ + ObjectMeta: v1.ObjectMeta{ Name: namespaceName, ResourceVersion: "1", DeletionTimestamp: &now, }, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{"kubernetes"}, + Spec: v1.NamespaceSpec{ + Finalizers: []v1.FinalizerName{"kubernetes"}, }, - Status: api.NamespaceStatus{ - Phase: api.NamespaceTerminating, + Status: v1.NamespaceStatus{ + Phase: v1.NamespaceTerminating, }, } - testNamespaceFinalizeComplete := &api.Namespace{ - ObjectMeta: api.ObjectMeta{ + testNamespaceFinalizeComplete := &v1.Namespace{ + ObjectMeta: v1.ObjectMeta{ Name: namespaceName, ResourceVersion: "1", DeletionTimestamp: &now, }, - Spec: api.NamespaceSpec{}, - Status: api.NamespaceStatus{ - Phase: api.NamespaceTerminating, + Spec: v1.NamespaceSpec{}, + Status: v1.NamespaceStatus{ + Phase: v1.NamespaceTerminating, }, } @@ -126,7 +127,7 @@ func testSyncNamespaceThatIsTerminating(t *testing.T, versions *unversioned.APIV } scenarios := map[string]struct { - testNamespace *api.Namespace + testNamespace *v1.Namespace kubeClientActionSet sets.String dynamicClientActionSet sets.String gvrError error @@ -172,7 +173,7 @@ func testSyncNamespaceThatIsTerminating(t *testing.T, versions *unversioned.APIV return groupVersionResources, nil } - err := syncNamespace(mockClient, clientPool, &operationNotSupportedCache{m: make(map[operationKey]bool)}, fn, testInput.testNamespace, api.FinalizerKubernetes) + err := syncNamespace(mockClient, clientPool, &operationNotSupportedCache{m: make(map[operationKey]bool)}, fn, testInput.testNamespace, v1.FinalizerKubernetes) if err != nil { t.Errorf("scenario %s - Unexpected error when synching namespace %v", scenario, err) } @@ -202,14 +203,14 @@ func testSyncNamespaceThatIsTerminating(t *testing.T, versions *unversioned.APIV func TestRetryOnConflictError(t *testing.T) { mockClient := &fake.Clientset{} numTries := 0 - retryOnce := func(kubeClient clientset.Interface, namespace *api.Namespace) (*api.Namespace, error) { + retryOnce := func(kubeClient clientset.Interface, namespace *v1.Namespace) (*v1.Namespace, error) { numTries++ if numTries <= 1 { return namespace, errors.NewConflict(api.Resource("namespaces"), namespace.Name, fmt.Errorf("ERROR!")) } return namespace, nil } - namespace := &api.Namespace{} + namespace := &v1.Namespace{} _, err := retryOnConflictError(mockClient, namespace, retryOnce) if err != nil { t.Errorf("Unexpected error %v", err) @@ -229,22 +230,22 @@ func TestSyncNamespaceThatIsTerminatingV1Beta1(t *testing.T) { func TestSyncNamespaceThatIsActive(t *testing.T) { mockClient := &fake.Clientset{} - testNamespace := &api.Namespace{ - ObjectMeta: api.ObjectMeta{ + testNamespace := &v1.Namespace{ + ObjectMeta: v1.ObjectMeta{ Name: "test", ResourceVersion: "1", }, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{"kubernetes"}, + Spec: v1.NamespaceSpec{ + Finalizers: []v1.FinalizerName{"kubernetes"}, }, - Status: api.NamespaceStatus{ - Phase: api.NamespaceActive, + Status: v1.NamespaceStatus{ + Phase: v1.NamespaceActive, }, } fn := func() ([]unversioned.GroupVersionResource, error) { return testGroupVersionResources(), nil } - err := syncNamespace(mockClient, nil, &operationNotSupportedCache{m: make(map[operationKey]bool)}, fn, testNamespace, api.FinalizerKubernetes) + err := syncNamespace(mockClient, nil, &operationNotSupportedCache{m: make(map[operationKey]bool)}, fn, testNamespace, v1.FinalizerKubernetes) if err != nil { t.Errorf("Unexpected error when synching namespace %v", err) } diff --git a/pkg/controller/namespace/namespace_controller_utils.go b/pkg/controller/namespace/namespace_controller_utils.go index 04db7841eb9..5ab57323ac0 100644 --- a/pkg/controller/namespace/namespace_controller_utils.go +++ b/pkg/controller/namespace/namespace_controller_utils.go @@ -22,11 +22,10 @@ import ( "sync" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/typed/dynamic" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/sets" @@ -80,12 +79,12 @@ func (o *operationNotSupportedCache) setNotSupported(key operationKey) { } // updateNamespaceFunc is a function that makes an update to a namespace -type updateNamespaceFunc func(kubeClient clientset.Interface, namespace *api.Namespace) (*api.Namespace, error) +type updateNamespaceFunc func(kubeClient clientset.Interface, namespace *v1.Namespace) (*v1.Namespace, error) // retryOnConflictError retries the specified fn if there was a conflict error // it will return an error if the UID for an object changes across retry operations. // TODO RetryOnConflict should be a generic concept in client code -func retryOnConflictError(kubeClient clientset.Interface, namespace *api.Namespace, fn updateNamespaceFunc) (result *api.Namespace, err error) { +func retryOnConflictError(kubeClient clientset.Interface, namespace *v1.Namespace, fn updateNamespaceFunc) (result *v1.Namespace, err error) { latestNamespace := namespace for { result, err = fn(kubeClient, latestNamespace) @@ -107,32 +106,32 @@ func retryOnConflictError(kubeClient clientset.Interface, namespace *api.Namespa } // updateNamespaceStatusFunc will verify that the status of the namespace is correct -func updateNamespaceStatusFunc(kubeClient clientset.Interface, namespace *api.Namespace) (*api.Namespace, error) { - if namespace.DeletionTimestamp.IsZero() || namespace.Status.Phase == api.NamespaceTerminating { +func updateNamespaceStatusFunc(kubeClient clientset.Interface, namespace *v1.Namespace) (*v1.Namespace, error) { + if namespace.DeletionTimestamp.IsZero() || namespace.Status.Phase == v1.NamespaceTerminating { return namespace, nil } - newNamespace := api.Namespace{} + newNamespace := v1.Namespace{} newNamespace.ObjectMeta = namespace.ObjectMeta newNamespace.Status = namespace.Status - newNamespace.Status.Phase = api.NamespaceTerminating + newNamespace.Status.Phase = v1.NamespaceTerminating return kubeClient.Core().Namespaces().UpdateStatus(&newNamespace) } // finalized returns true if the namespace.Spec.Finalizers is an empty list -func finalized(namespace *api.Namespace) bool { +func finalized(namespace *v1.Namespace) bool { return len(namespace.Spec.Finalizers) == 0 } // finalizeNamespaceFunc returns a function that knows how to finalize a namespace for specified token. -func finalizeNamespaceFunc(finalizerToken api.FinalizerName) updateNamespaceFunc { - return func(kubeClient clientset.Interface, namespace *api.Namespace) (*api.Namespace, error) { +func finalizeNamespaceFunc(finalizerToken v1.FinalizerName) updateNamespaceFunc { + return func(kubeClient clientset.Interface, namespace *v1.Namespace) (*v1.Namespace, error) { return finalizeNamespace(kubeClient, namespace, finalizerToken) } } // finalizeNamespace removes the specified finalizerToken and finalizes the namespace -func finalizeNamespace(kubeClient clientset.Interface, namespace *api.Namespace, finalizerToken api.FinalizerName) (*api.Namespace, error) { - namespaceFinalize := api.Namespace{} +func finalizeNamespace(kubeClient clientset.Interface, namespace *v1.Namespace, finalizerToken v1.FinalizerName) (*v1.Namespace, error) { + namespaceFinalize := v1.Namespace{} namespaceFinalize.ObjectMeta = namespace.ObjectMeta namespaceFinalize.Spec = namespace.Spec finalizerSet := sets.NewString() @@ -141,9 +140,9 @@ func finalizeNamespace(kubeClient clientset.Interface, namespace *api.Namespace, finalizerSet.Insert(string(namespace.Spec.Finalizers[i])) } } - namespaceFinalize.Spec.Finalizers = make([]api.FinalizerName, 0, len(finalizerSet)) + namespaceFinalize.Spec.Finalizers = make([]v1.FinalizerName, 0, len(finalizerSet)) for _, value := range finalizerSet.List() { - namespaceFinalize.Spec.Finalizers = append(namespaceFinalize.Spec.Finalizers, api.FinalizerName(value)) + namespaceFinalize.Spec.Finalizers = append(namespaceFinalize.Spec.Finalizers, v1.FinalizerName(value)) } namespace, err := kubeClient.Core().Namespaces().Finalize(&namespaceFinalize) if err != nil { @@ -372,8 +371,8 @@ func syncNamespace( clientPool dynamic.ClientPool, opCache *operationNotSupportedCache, groupVersionResourcesFn func() ([]unversioned.GroupVersionResource, error), - namespace *api.Namespace, - finalizerToken api.FinalizerName, + namespace *v1.Namespace, + finalizerToken v1.FinalizerName, ) error { if namespace.DeletionTimestamp == nil { return nil @@ -409,10 +408,10 @@ func syncNamespace( // if the namespace is already finalized, delete it if finalized(namespace) { - var opts *api.DeleteOptions + var opts *v1.DeleteOptions uid := namespace.UID if len(uid) > 0 { - opts = &api.DeleteOptions{Preconditions: &api.Preconditions{UID: &uid}} + opts = &v1.DeleteOptions{Preconditions: &v1.Preconditions{UID: &uid}} } err = kubeClient.Core().Namespaces().Delete(namespace.Name, opts) if err != nil && !errors.IsNotFound(err) { @@ -483,14 +482,14 @@ func estimateGracefulTermination(kubeClient clientset.Interface, groupVersionRes func estimateGracefulTerminationForPods(kubeClient clientset.Interface, ns string) (int64, error) { glog.V(5).Infof("namespace controller - estimateGracefulTerminationForPods - namespace %s", ns) estimate := int64(0) - items, err := kubeClient.Core().Pods(ns).List(api.ListOptions{}) + items, err := kubeClient.Core().Pods(ns).List(v1.ListOptions{}) if err != nil { return estimate, err } for i := range items.Items { // filter out terminal pods phase := items.Items[i].Status.Phase - if api.PodSucceeded == phase || api.PodFailed == phase { + if v1.PodSucceeded == phase || v1.PodFailed == phase { continue } if items.Items[i].Spec.TerminationGracePeriodSeconds != nil { diff --git a/pkg/controller/node/BUILD b/pkg/controller/node/BUILD index 82eaed80f89..9ef42302861 100644 --- a/pkg/controller/node/BUILD +++ b/pkg/controller/node/BUILD @@ -28,10 +28,11 @@ go_library( "//pkg/api/errors:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/controller/informers:go_default_library", @@ -70,10 +71,11 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/cloudprovider/providers/fake:go_default_library", diff --git a/pkg/controller/node/cidr_allocator.go b/pkg/controller/node/cidr_allocator.go index 2bf1ac08cdc..81b8de1441e 100644 --- a/pkg/controller/node/cidr_allocator.go +++ b/pkg/controller/node/cidr_allocator.go @@ -22,9 +22,9 @@ import ( "net" "sync" - "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" @@ -50,8 +50,8 @@ type nodeAndCIDR struct { // CIDRAllocator is an interface implemented by things that know how to allocate/occupy/recycle CIDR for nodes. type CIDRAllocator interface { - AllocateOrOccupyCIDR(node *api.Node) error - ReleaseCIDR(node *api.Node) error + AllocateOrOccupyCIDR(node *v1.Node) error + ReleaseCIDR(node *v1.Node) error } type rangeAllocator struct { @@ -72,9 +72,9 @@ type rangeAllocator struct { // Caller must ensure subNetMaskSize is not less than cluster CIDR mask size. // Caller must always pass in a list of existing nodes so the new allocator // can initialize its CIDR map. NodeList is only nil in testing. -func NewCIDRRangeAllocator(client clientset.Interface, clusterCIDR *net.IPNet, serviceCIDR *net.IPNet, subNetMaskSize int, nodeList *api.NodeList) (CIDRAllocator, error) { +func NewCIDRRangeAllocator(client clientset.Interface, clusterCIDR *net.IPNet, serviceCIDR *net.IPNet, subNetMaskSize int, nodeList *v1.NodeList) (CIDRAllocator, error) { eventBroadcaster := record.NewBroadcaster() - recorder := eventBroadcaster.NewRecorder(api.EventSource{Component: "cidrAllocator"}) + recorder := eventBroadcaster.NewRecorder(v1.EventSource{Component: "cidrAllocator"}) eventBroadcaster.StartLogging(glog.Infof) ra := &rangeAllocator{ @@ -145,7 +145,7 @@ func (r *rangeAllocator) removeNodeFromProcessing(nodeName string) { r.nodesInProcessing.Delete(nodeName) } -func (r *rangeAllocator) occupyCIDR(node *api.Node) error { +func (r *rangeAllocator) occupyCIDR(node *v1.Node) error { defer r.removeNodeFromProcessing(node.Name) if node.Spec.PodCIDR == "" { return nil @@ -164,7 +164,7 @@ func (r *rangeAllocator) occupyCIDR(node *api.Node) error { // if it doesn't currently have one or mark the CIDR as used if the node already have one. // WARNING: If you're adding any return calls or defer any more work from this function // you have to handle correctly nodesInProcessing. -func (r *rangeAllocator) AllocateOrOccupyCIDR(node *api.Node) error { +func (r *rangeAllocator) AllocateOrOccupyCIDR(node *v1.Node) error { if node == nil { return nil } @@ -191,7 +191,7 @@ func (r *rangeAllocator) AllocateOrOccupyCIDR(node *api.Node) error { } // ReleaseCIDR releases the CIDR of the removed node -func (r *rangeAllocator) ReleaseCIDR(node *api.Node) error { +func (r *rangeAllocator) ReleaseCIDR(node *v1.Node) error { if node == nil || node.Spec.PodCIDR == "" { return nil } @@ -225,7 +225,7 @@ func (r *rangeAllocator) filterOutServiceRange(serviceCIDR *net.IPNet) { // Assigns CIDR to Node and sends an update to the API server. func (r *rangeAllocator) updateCIDRAllocation(data nodeAndCIDR) error { var err error - var node *api.Node + var node *v1.Node defer r.removeNodeFromProcessing(data.nodeName) for rep := 0; rep < podCIDRUpdateRetry; rep++ { // TODO: change it to using PATCH instead of full Node updates. diff --git a/pkg/controller/node/cidr_allocator_test.go b/pkg/controller/node/cidr_allocator_test.go index 169448d9c77..85e51c7d5f3 100644 --- a/pkg/controller/node/cidr_allocator_test.go +++ b/pkg/controller/node/cidr_allocator_test.go @@ -21,8 +21,8 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/util/wait" ) @@ -52,9 +52,9 @@ func TestAllocateOrOccupyCIDRSuccess(t *testing.T) { { description: "When there's no ServiceCIDR return first CIDR in range", fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", }, }, @@ -72,9 +72,9 @@ func TestAllocateOrOccupyCIDRSuccess(t *testing.T) { { description: "Correctly filter out ServiceCIDR", fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", }, }, @@ -96,9 +96,9 @@ func TestAllocateOrOccupyCIDRSuccess(t *testing.T) { { description: "Correctly ignore already allocated CIDRs", fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", }, }, @@ -182,9 +182,9 @@ func TestAllocateOrOccupyCIDRFailure(t *testing.T) { { description: "When there's no ServiceCIDR return first CIDR in range", fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", }, }, @@ -265,9 +265,9 @@ func TestReleaseCIDRSuccess(t *testing.T) { { description: "Correctly release preallocated CIDR", fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", }, }, @@ -288,9 +288,9 @@ func TestReleaseCIDRSuccess(t *testing.T) { { description: "Correctly recycle CIDR", fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", }, }, @@ -357,8 +357,8 @@ func TestReleaseCIDRSuccess(t *testing.T) { } for _, cidrToRelease := range tc.cidrsToRelease { - nodeToRelease := api.Node{ - ObjectMeta: api.ObjectMeta{ + nodeToRelease := v1.Node{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", }, } diff --git a/pkg/controller/node/controller_utils.go b/pkg/controller/node/controller_utils.go index fa10c2e8b88..f69e2ddc91b 100644 --- a/pkg/controller/node/controller_utils.go +++ b/pkg/controller/node/controller_utils.go @@ -22,8 +22,9 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/fields" @@ -46,9 +47,9 @@ const ( // if any pods were deleted, or were found pending deletion. func deletePods(kubeClient clientset.Interface, recorder record.EventRecorder, nodeName, nodeUID string, daemonStore cache.StoreToDaemonSetLister) (bool, error) { remaining := false - selector := fields.OneTermEqualSelector(api.PodHostField, nodeName) - options := api.ListOptions{FieldSelector: selector} - pods, err := kubeClient.Core().Pods(api.NamespaceAll).List(options) + selector := fields.OneTermEqualSelector(api.PodHostField, nodeName).String() + options := v1.ListOptions{FieldSelector: selector} + pods, err := kubeClient.Core().Pods(v1.NamespaceAll).List(options) var updateErrList []error if err != nil { @@ -56,7 +57,7 @@ func deletePods(kubeClient clientset.Interface, recorder record.EventRecorder, n } if len(pods.Items) > 0 { - recordNodeEvent(recorder, nodeName, nodeUID, api.EventTypeNormal, "DeletingAllPods", fmt.Sprintf("Deleting all Pods from Node %v.", nodeName)) + recordNodeEvent(recorder, nodeName, nodeUID, v1.EventTypeNormal, "DeletingAllPods", fmt.Sprintf("Deleting all Pods from Node %v.", nodeName)) } for _, pod := range pods.Items { @@ -85,7 +86,7 @@ func deletePods(kubeClient clientset.Interface, recorder record.EventRecorder, n } glog.V(2).Infof("Starting deletion of pod %v", pod.Name) - recorder.Eventf(&pod, api.EventTypeNormal, "NodeControllerEviction", "Marking for deletion Pod %s from Node %s", pod.Name, nodeName) + recorder.Eventf(&pod, v1.EventTypeNormal, "NodeControllerEviction", "Marking for deletion Pod %s from Node %s", pod.Name, nodeName) if err := kubeClient.Core().Pods(pod.Namespace).Delete(pod.Name, nil); err != nil { return false, err } @@ -100,7 +101,7 @@ func deletePods(kubeClient clientset.Interface, recorder record.EventRecorder, n // setPodTerminationReason attempts to set a reason and message in the pod status, updates it in the apiserver, // and returns an error if it encounters one. -func setPodTerminationReason(kubeClient clientset.Interface, pod *api.Pod, nodeName string) (*api.Pod, error) { +func setPodTerminationReason(kubeClient clientset.Interface, pod *v1.Pod, nodeName string) (*v1.Pod, error) { if pod.Status.Reason == node.NodeUnreachablePodReason { return pod, nil } @@ -108,7 +109,7 @@ func setPodTerminationReason(kubeClient clientset.Interface, pod *api.Pod, nodeN pod.Status.Reason = node.NodeUnreachablePodReason pod.Status.Message = fmt.Sprintf(node.NodeUnreachablePodMessage, nodeName, pod.Name) - var updatedPod *api.Pod + var updatedPod *v1.Pod var err error if updatedPod, err = kubeClient.Core().Pods(pod.Namespace).UpdateStatus(pod); err != nil { return nil, err @@ -116,10 +117,10 @@ func setPodTerminationReason(kubeClient clientset.Interface, pod *api.Pod, nodeN return updatedPod, nil } -func forcefullyDeletePod(c clientset.Interface, pod *api.Pod) error { +func forcefullyDeletePod(c clientset.Interface, pod *v1.Pod) error { var zero int64 glog.Infof("NodeController is force deleting Pod: %v:%v", pod.Namespace, pod.Name) - err := c.Core().Pods(pod.Namespace).Delete(pod.Name, &api.DeleteOptions{GracePeriodSeconds: &zero}) + err := c.Core().Pods(pod.Namespace).Delete(pod.Name, &v1.DeleteOptions{GracePeriodSeconds: &zero}) if err == nil { glog.V(4).Infof("forceful deletion of %s succeeded", pod.Name) } @@ -138,14 +139,14 @@ func forcefullyDeleteNode(kubeClient clientset.Interface, nodeName string) error // maybeDeleteTerminatingPod non-gracefully deletes pods that are terminating // that should not be gracefully terminated. func (nc *NodeController) maybeDeleteTerminatingPod(obj interface{}) { - pod, ok := obj.(*api.Pod) + pod, ok := obj.(*v1.Pod) if !ok { tombstone, ok := obj.(cache.DeletedFinalStateUnknown) if !ok { glog.Errorf("Couldn't get object from tombstone %#v", obj) return } - pod, ok = tombstone.Obj.(*api.Pod) + pod, ok = tombstone.Obj.(*v1.Pod) if !ok { glog.Errorf("Tombstone contained object that is not a Pod %#v", obj) return @@ -176,7 +177,7 @@ func (nc *NodeController) maybeDeleteTerminatingPod(obj interface{}) { // TODO(mikedanese): this can be removed when we no longer // guarantee backwards compatibility of master API to kubelets with // versions less than 1.1.0 - node := nodeObj.(*api.Node) + node := nodeObj.(*v1.Node) v, err := version.Parse(node.Status.NodeInfo.KubeletVersion) if err != nil { glog.V(0).Infof("couldn't parse verions %q of minion: %v", node.Status.NodeInfo.KubeletVersion, err) @@ -191,7 +192,7 @@ func (nc *NodeController) maybeDeleteTerminatingPod(obj interface{}) { // update ready status of all pods running on given node from master // return true if success -func markAllPodsNotReady(kubeClient clientset.Interface, node *api.Node) error { +func markAllPodsNotReady(kubeClient clientset.Interface, node *v1.Node) error { // Don't set pods to NotReady if the kubelet is running a version that // doesn't understand how to correct readiness. // TODO: Remove this check when we no longer guarantee backward compatibility @@ -201,8 +202,8 @@ func markAllPodsNotReady(kubeClient clientset.Interface, node *api.Node) error { } nodeName := node.Name glog.V(2).Infof("Update ready status of pods on node [%v]", nodeName) - opts := api.ListOptions{FieldSelector: fields.OneTermEqualSelector(api.PodHostField, nodeName)} - pods, err := kubeClient.Core().Pods(api.NamespaceAll).List(opts) + opts := v1.ListOptions{FieldSelector: fields.OneTermEqualSelector(api.PodHostField, nodeName).String()} + pods, err := kubeClient.Core().Pods(v1.NamespaceAll).List(opts) if err != nil { return err } @@ -215,8 +216,8 @@ func markAllPodsNotReady(kubeClient clientset.Interface, node *api.Node) error { } for i, cond := range pod.Status.Conditions { - if cond.Type == api.PodReady { - pod.Status.Conditions[i].Status = api.ConditionFalse + if cond.Type == v1.PodReady { + pod.Status.Conditions[i].Status = v1.ConditionFalse glog.V(2).Infof("Updating ready status of pod %v to false", pod.Name) _, err := kubeClient.Core().Pods(pod.Namespace).UpdateStatus(&pod) if err != nil { @@ -237,7 +238,7 @@ func markAllPodsNotReady(kubeClient clientset.Interface, node *api.Node) error { // in the nodeInfo of the given node is "outdated", meaning < 1.2.0. // Older versions were inflexible and modifying pod.Status directly through // the apiserver would result in unexpected outcomes. -func nodeRunningOutdatedKubelet(node *api.Node) bool { +func nodeRunningOutdatedKubelet(node *v1.Node) bool { v, err := version.Parse(node.Status.NodeInfo.KubeletVersion) if err != nil { glog.Errorf("couldn't parse version %q of node %v", node.Status.NodeInfo.KubeletVersion, err) @@ -265,7 +266,7 @@ func nodeExistsInCloudProvider(cloud cloudprovider.Interface, nodeName types.Nod } func recordNodeEvent(recorder record.EventRecorder, nodeName, nodeUID, eventtype, reason, event string) { - ref := &api.ObjectReference{ + ref := &v1.ObjectReference{ Kind: "Node", Name: nodeName, UID: types.UID(nodeUID), @@ -275,8 +276,8 @@ func recordNodeEvent(recorder record.EventRecorder, nodeName, nodeUID, eventtype recorder.Eventf(ref, eventtype, reason, "Node %s event: %s", nodeName, event) } -func recordNodeStatusChange(recorder record.EventRecorder, node *api.Node, new_status string) { - ref := &api.ObjectReference{ +func recordNodeStatusChange(recorder record.EventRecorder, node *v1.Node, new_status string) { + ref := &v1.ObjectReference{ Kind: "Node", Name: node.Name, UID: node.UID, @@ -285,5 +286,5 @@ func recordNodeStatusChange(recorder record.EventRecorder, node *api.Node, new_s glog.V(2).Infof("Recording status change %s event message for node %s", new_status, node.Name) // TODO: This requires a transaction, either both node status is updated // and event is recorded or neither should happen, see issue #6055. - recorder.Eventf(ref, api.EventTypeNormal, new_status, "Node %s status is now: %s", node.Name, new_status) + recorder.Eventf(ref, v1.EventTypeNormal, new_status, "Node %s status is now: %s", node.Name, new_status) } diff --git a/pkg/controller/node/nodecontroller.go b/pkg/controller/node/nodecontroller.go index 7d494f3f92b..6c539aec3a9 100644 --- a/pkg/controller/node/nodecontroller.go +++ b/pkg/controller/node/nodecontroller.go @@ -26,9 +26,10 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/controller/informers" @@ -83,7 +84,7 @@ const ( type nodeStatusData struct { probeTimestamp unversioned.Time readyTransitionTimestamp unversioned.Time - status api.NodeStatus + status v1.NodeStatus } type NodeController struct { @@ -91,7 +92,7 @@ type NodeController struct { cloud cloudprovider.Interface clusterCIDR *net.IPNet serviceCIDR *net.IPNet - knownNodeSet map[string]*api.Node + knownNodeSet map[string]*v1.Node kubeClient clientset.Interface // Method for easy mocking in unittest. lookupIP func(host string) ([]net.IP, error) @@ -140,9 +141,9 @@ type NodeController struct { // allocate/recycle CIDRs for node if allocateNodeCIDRs == true cidrAllocator CIDRAllocator - forcefullyDeletePod func(*api.Pod) error + forcefullyDeletePod func(*v1.Pod) error nodeExistsInCloudProvider func(types.NodeName) (bool, error) - computeZoneStateFunc func(nodeConditions []*api.NodeCondition) (int, zoneState) + computeZoneStateFunc func(nodeConditions []*v1.NodeCondition) (int, zoneState) enterPartialDisruptionFunc func(nodeNum int) float32 enterFullDisruptionFunc func(nodeNum int) float32 @@ -183,11 +184,11 @@ func NewNodeController( nodeCIDRMaskSize int, allocateNodeCIDRs bool) (*NodeController, error) { eventBroadcaster := record.NewBroadcaster() - recorder := eventBroadcaster.NewRecorder(api.EventSource{Component: "controllermanager"}) + recorder := eventBroadcaster.NewRecorder(v1.EventSource{Component: "controllermanager"}) eventBroadcaster.StartLogging(glog.Infof) if kubeClient != nil { glog.V(0).Infof("Sending events to api server.") - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.Core().Events("")}) } else { glog.V(0).Infof("No api server defined - no events will be sent to API server.") } @@ -208,7 +209,7 @@ func NewNodeController( nc := &NodeController{ cloud: cloud, - knownNodeSet: make(map[string]*api.Node), + knownNodeSet: make(map[string]*v1.Node), kubeClient: kubeClient, recorder: recorder, podEvictionTimeout: podEvictionTimeout, @@ -223,7 +224,7 @@ func NewNodeController( clusterCIDR: clusterCIDR, serviceCIDR: serviceCIDR, allocateNodeCIDRs: allocateNodeCIDRs, - forcefullyDeletePod: func(p *api.Pod) error { return forcefullyDeletePod(kubeClient, p) }, + forcefullyDeletePod: func(p *v1.Pod) error { return forcefullyDeletePod(kubeClient, p) }, nodeExistsInCloudProvider: func(nodeName types.NodeName) (bool, error) { return nodeExistsInCloudProvider(cloud, nodeName) }, evictionLimiterQPS: evictionLimiterQPS, secondaryEvictionLimiterQPS: secondaryEvictionLimiterQPS, @@ -246,14 +247,14 @@ func NewNodeController( nodeEventHandlerFuncs := cache.ResourceEventHandlerFuncs{} if nc.allocateNodeCIDRs { - var nodeList *api.NodeList + var nodeList *v1.NodeList var err error // We must poll because apiserver might not be up. This error causes // controller manager to restart. if pollErr := wait.Poll(10*time.Second, apiserverStartupGracePeriod, func() (bool, error) { - nodeList, err = kubeClient.Core().Nodes().List(api.ListOptions{ - FieldSelector: fields.Everything(), - LabelSelector: labels.Everything(), + nodeList, err = kubeClient.Core().Nodes().List(v1.ListOptions{ + FieldSelector: fields.Everything().String(), + LabelSelector: labels.Everything().String(), }) if err != nil { glog.Errorf("Failed to list all nodes: %v", err) @@ -275,14 +276,14 @@ func NewNodeController( utilruntime.HandleError(err) return } - node := obj.(*api.Node) + node := obj.(*v1.Node) if err := nc.cidrAllocator.AllocateOrOccupyCIDR(node); err != nil { utilruntime.HandleError(fmt.Errorf("Error allocating CIDR: %v", err)) } }, UpdateFunc: func(_, obj interface{}) { - node := obj.(*api.Node) + node := obj.(*v1.Node) // If the PodCIDR is not empty we either: // - already processed a Node that already had a CIDR after NC restarted // (cidr is marked as used), @@ -309,7 +310,7 @@ func NewNodeController( return } - if err := nc.cidrAllocator.AllocateOrOccupyCIDR(nodeCopy.(*api.Node)); err != nil { + if err := nc.cidrAllocator.AllocateOrOccupyCIDR(nodeCopy.(*v1.Node)); err != nil { utilruntime.HandleError(fmt.Errorf("Error allocating CIDR: %v", err)) } } @@ -321,15 +322,15 @@ func NewNodeController( return } - node, isNode := obj.(*api.Node) - // We can get DeletedFinalStateUnknown instead of *api.Node here and we need to handle that correctly. #34692 + node, isNode := obj.(*v1.Node) + // We can get DeletedFinalStateUnknown instead of *v1.Node here and we need to handle that correctly. #34692 if !isNode { deletedState, ok := obj.(cache.DeletedFinalStateUnknown) if !ok { glog.Errorf("Received unexpected object: %v", obj) return } - node, ok = deletedState.Obj.(*api.Node) + node, ok = deletedState.Obj.(*v1.Node) if !ok { glog.Errorf("DeletedFinalStateUnknown contained non-Node object: %v", deletedState.Obj) return @@ -381,7 +382,7 @@ func (nc *NodeController) Run() { } else if !exists { glog.Warningf("Node %v no longer present in nodeStore!", value.Value) } else { - node, _ := obj.(*api.Node) + node, _ := obj.(*v1.Node) zone := utilnode.GetZoneKey(node) EvictionsNumber.WithLabelValues(zone).Inc() } @@ -410,14 +411,14 @@ func (nc *NodeController) monitorNodeStatus() error { // It is enough to list Nodes from apiserver, since we can tolerate some small // delays comparing to state from etcd and there is eventual consistency anyway. // TODO: We should list them from local cache: nodeStore. - nodes, err := nc.kubeClient.Core().Nodes().List(api.ListOptions{ResourceVersion: "0"}) + nodes, err := nc.kubeClient.Core().Nodes().List(v1.ListOptions{ResourceVersion: "0"}) if err != nil { return err } added, deleted := nc.checkForNodeAddedDeleted(nodes) for i := range added { glog.V(1).Infof("NodeController observed a new Node: %#v", added[i].Name) - recordNodeEvent(nc.recorder, added[i].Name, string(added[i].UID), api.EventTypeNormal, "RegisteredNode", fmt.Sprintf("Registered Node %v in NodeController", added[i].Name)) + recordNodeEvent(nc.recorder, added[i].Name, string(added[i].UID), v1.EventTypeNormal, "RegisteredNode", fmt.Sprintf("Registered Node %v in NodeController", added[i].Name)) nc.knownNodeSet[added[i].Name] = added[i] // When adding new Nodes we need to check if new zone appeared, and if so add new evictor. zone := utilnode.GetZoneKey(added[i]) @@ -434,15 +435,15 @@ func (nc *NodeController) monitorNodeStatus() error { for i := range deleted { glog.V(1).Infof("NodeController observed a Node deletion: %v", deleted[i].Name) - recordNodeEvent(nc.recorder, deleted[i].Name, string(deleted[i].UID), api.EventTypeNormal, "RemovingNode", fmt.Sprintf("Removing Node %v from NodeController", deleted[i].Name)) + recordNodeEvent(nc.recorder, deleted[i].Name, string(deleted[i].UID), v1.EventTypeNormal, "RemovingNode", fmt.Sprintf("Removing Node %v from NodeController", deleted[i].Name)) delete(nc.knownNodeSet, deleted[i].Name) } - zoneToNodeConditions := map[string][]*api.NodeCondition{} + zoneToNodeConditions := map[string][]*v1.NodeCondition{} for i := range nodes.Items { var gracePeriod time.Duration - var observedReadyCondition api.NodeCondition - var currentReadyCondition *api.NodeCondition + var observedReadyCondition v1.NodeCondition + var currentReadyCondition *v1.NodeCondition node := &nodes.Items[i] for rep := 0; rep < nodeStatusUpdateRetry; rep++ { gracePeriod, observedReadyCondition, currentReadyCondition, err = nc.tryUpdateNodeStatus(node) @@ -463,33 +464,33 @@ func (nc *NodeController) monitorNodeStatus() error { continue } // We do not treat a master node as a part of the cluster for network disruption checking. - if !system.IsMasterNode(node) { + if !system.IsMasterNode(node.Name) { zoneToNodeConditions[utilnode.GetZoneKey(node)] = append(zoneToNodeConditions[utilnode.GetZoneKey(node)], currentReadyCondition) } decisionTimestamp := nc.now() if currentReadyCondition != nil { // Check eviction timeout against decisionTimestamp - if observedReadyCondition.Status == api.ConditionFalse && + if observedReadyCondition.Status == v1.ConditionFalse && decisionTimestamp.After(nc.nodeStatusMap[node.Name].readyTransitionTimestamp.Add(nc.podEvictionTimeout)) { if nc.evictPods(node) { glog.V(2).Infof("Evicting pods on node %s: %v is later than %v + %v", node.Name, decisionTimestamp, nc.nodeStatusMap[node.Name].readyTransitionTimestamp, nc.podEvictionTimeout) } } - if observedReadyCondition.Status == api.ConditionUnknown && + if observedReadyCondition.Status == v1.ConditionUnknown && decisionTimestamp.After(nc.nodeStatusMap[node.Name].probeTimestamp.Add(nc.podEvictionTimeout)) { if nc.evictPods(node) { glog.V(2).Infof("Evicting pods on node %s: %v is later than %v + %v", node.Name, decisionTimestamp, nc.nodeStatusMap[node.Name].readyTransitionTimestamp, nc.podEvictionTimeout-gracePeriod) } } - if observedReadyCondition.Status == api.ConditionTrue { + if observedReadyCondition.Status == v1.ConditionTrue { if nc.cancelPodEviction(node) { glog.V(2).Infof("Node %s is ready again, cancelled pod eviction", node.Name) } } // Report node event. - if currentReadyCondition.Status != api.ConditionTrue && observedReadyCondition.Status == api.ConditionTrue { + if currentReadyCondition.Status != v1.ConditionTrue && observedReadyCondition.Status == v1.ConditionTrue { recordNodeStatusChange(nc.recorder, node, "NodeNotReady") if err = markAllPodsNotReady(nc.kubeClient, node); err != nil { utilruntime.HandleError(fmt.Errorf("Unable to mark all pods NotReady on node %v: %v", node.Name, err)) @@ -498,7 +499,7 @@ func (nc *NodeController) monitorNodeStatus() error { // Check with the cloud provider to see if the node still exists. If it // doesn't, delete the node immediately. - if currentReadyCondition.Status != api.ConditionTrue && nc.cloud != nil { + if currentReadyCondition.Status != v1.ConditionTrue && nc.cloud != nil { exists, err := nc.nodeExistsInCloudProvider(types.NodeName(node.Name)) if err != nil { glog.Errorf("Error determining if node %v exists in cloud: %v", node.Name, err) @@ -506,7 +507,7 @@ func (nc *NodeController) monitorNodeStatus() error { } if !exists { glog.V(2).Infof("Deleting node (no longer present in cloud provider): %s", node.Name) - recordNodeEvent(nc.recorder, node.Name, string(node.UID), api.EventTypeNormal, "DeletingNode", fmt.Sprintf("Deleting Node %v because it's not present according to cloud provider", node.Name)) + recordNodeEvent(nc.recorder, node.Name, string(node.UID), v1.EventTypeNormal, "DeletingNode", fmt.Sprintf("Deleting Node %v because it's not present according to cloud provider", node.Name)) go func(nodeName string) { defer utilruntime.HandleCrash() // Kubelet is not reporting and Cloud Provider says node @@ -526,7 +527,7 @@ func (nc *NodeController) monitorNodeStatus() error { return nil } -func (nc *NodeController) handleDisruption(zoneToNodeConditions map[string][]*api.NodeCondition, nodes *api.NodeList) { +func (nc *NodeController) handleDisruption(zoneToNodeConditions map[string][]*v1.NodeCondition, nodes *v1.NodeList) { newZoneStates := map[string]zoneState{} allAreFullyDisrupted := true for k, v := range zoneToNodeConditions { @@ -627,18 +628,18 @@ func (nc *NodeController) setLimiterInZone(zone string, zoneSize int, state zone // For a given node checks its conditions and tries to update it. Returns grace period to which given node // is entitled, state of current and last observed Ready Condition, and an error if it occurred. -func (nc *NodeController) tryUpdateNodeStatus(node *api.Node) (time.Duration, api.NodeCondition, *api.NodeCondition, error) { +func (nc *NodeController) tryUpdateNodeStatus(node *v1.Node) (time.Duration, v1.NodeCondition, *v1.NodeCondition, error) { var err error var gracePeriod time.Duration - var observedReadyCondition api.NodeCondition - _, currentReadyCondition := api.GetNodeCondition(&node.Status, api.NodeReady) + var observedReadyCondition v1.NodeCondition + _, currentReadyCondition := v1.GetNodeCondition(&node.Status, v1.NodeReady) if currentReadyCondition == nil { // If ready condition is nil, then kubelet (or nodecontroller) never posted node status. // A fake ready condition is created, where LastProbeTime and LastTransitionTime is set // to node.CreationTimestamp to avoid handle the corner case. - observedReadyCondition = api.NodeCondition{ - Type: api.NodeReady, - Status: api.ConditionUnknown, + observedReadyCondition = v1.NodeCondition{ + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: node.CreationTimestamp, LastTransitionTime: node.CreationTimestamp, } @@ -669,11 +670,11 @@ func (nc *NodeController) tryUpdateNodeStatus(node *api.Node) (time.Duration, ap // - if 'LastProbeTime' have gone back in time its probably an error, currently we ignore it, // - currently only correct Ready State transition outside of Node Controller is marking it ready by Kubelet, we don't check // if that's the case, but it does not seem necessary. - var savedCondition *api.NodeCondition + var savedCondition *v1.NodeCondition if found { - _, savedCondition = api.GetNodeCondition(&savedNodeStatus.status, api.NodeReady) + _, savedCondition = v1.GetNodeCondition(&savedNodeStatus.status, v1.NodeReady) } - _, observedCondition := api.GetNodeCondition(&node.Status, api.NodeReady) + _, observedCondition := v1.GetNodeCondition(&node.Status, v1.NodeReady) if !found { glog.Warningf("Missing timestamp for Node %s. Assuming now as a timestamp.", node.Name) savedNodeStatus = nodeStatusData{ @@ -725,9 +726,9 @@ func (nc *NodeController) tryUpdateNodeStatus(node *api.Node) (time.Duration, ap // (regardless of its current value) in the master. if currentReadyCondition == nil { glog.V(2).Infof("node %v is never updated by kubelet", node.Name) - node.Status.Conditions = append(node.Status.Conditions, api.NodeCondition{ - Type: api.NodeReady, - Status: api.ConditionUnknown, + node.Status.Conditions = append(node.Status.Conditions, v1.NodeCondition{ + Type: v1.NodeReady, + Status: v1.ConditionUnknown, Reason: "NodeStatusNeverUpdated", Message: fmt.Sprintf("Kubelet never posted node status."), LastHeartbeatTime: node.CreationTimestamp, @@ -736,8 +737,8 @@ func (nc *NodeController) tryUpdateNodeStatus(node *api.Node) (time.Duration, ap } else { glog.V(4).Infof("node %v hasn't been updated for %+v. Last ready condition is: %+v", node.Name, nc.now().Time.Sub(savedNodeStatus.probeTimestamp.Time), observedReadyCondition) - if observedReadyCondition.Status != api.ConditionUnknown { - currentReadyCondition.Status = api.ConditionUnknown + if observedReadyCondition.Status != v1.ConditionUnknown { + currentReadyCondition.Status = v1.ConditionUnknown currentReadyCondition.Reason = "NodeStatusUnknown" currentReadyCondition.Message = fmt.Sprintf("Kubelet stopped posting node status.") // LastProbeTime is the last time we heard from kubelet. @@ -749,12 +750,12 @@ func (nc *NodeController) tryUpdateNodeStatus(node *api.Node) (time.Duration, ap // Like NodeReady condition, NodeOutOfDisk was last set longer ago than gracePeriod, so update // it to Unknown (regardless of its current value) in the master. // TODO(madhusudancs): Refactor this with readyCondition to remove duplicated code. - _, oodCondition := api.GetNodeCondition(&node.Status, api.NodeOutOfDisk) + _, oodCondition := v1.GetNodeCondition(&node.Status, v1.NodeOutOfDisk) if oodCondition == nil { glog.V(2).Infof("Out of disk condition of node %v is never updated by kubelet", node.Name) - node.Status.Conditions = append(node.Status.Conditions, api.NodeCondition{ - Type: api.NodeOutOfDisk, - Status: api.ConditionUnknown, + node.Status.Conditions = append(node.Status.Conditions, v1.NodeCondition{ + Type: v1.NodeOutOfDisk, + Status: v1.ConditionUnknown, Reason: "NodeStatusNeverUpdated", Message: fmt.Sprintf("Kubelet never posted node status."), LastHeartbeatTime: node.CreationTimestamp, @@ -763,15 +764,15 @@ func (nc *NodeController) tryUpdateNodeStatus(node *api.Node) (time.Duration, ap } else { glog.V(4).Infof("node %v hasn't been updated for %+v. Last out of disk condition is: %+v", node.Name, nc.now().Time.Sub(savedNodeStatus.probeTimestamp.Time), oodCondition) - if oodCondition.Status != api.ConditionUnknown { - oodCondition.Status = api.ConditionUnknown + if oodCondition.Status != v1.ConditionUnknown { + oodCondition.Status = v1.ConditionUnknown oodCondition.Reason = "NodeStatusUnknown" oodCondition.Message = fmt.Sprintf("Kubelet stopped posting node status.") oodCondition.LastTransitionTime = nc.now() } } - _, currentCondition := api.GetNodeCondition(&node.Status, api.NodeReady) + _, currentCondition := v1.GetNodeCondition(&node.Status, v1.NodeReady) if !api.Semantic.DeepEqual(currentCondition, &observedReadyCondition) { if _, err = nc.kubeClient.Core().Nodes().UpdateStatus(node); err != nil { glog.Errorf("Error updating node %s: %v", node.Name, err) @@ -790,7 +791,7 @@ func (nc *NodeController) tryUpdateNodeStatus(node *api.Node) (time.Duration, ap return gracePeriod, observedReadyCondition, currentReadyCondition, err } -func (nc *NodeController) checkForNodeAddedDeleted(nodes *api.NodeList) (added, deleted []*api.Node) { +func (nc *NodeController) checkForNodeAddedDeleted(nodes *v1.NodeList) (added, deleted []*v1.Node) { for i := range nodes.Items { if _, has := nc.knownNodeSet[nodes.Items[i].Name]; !has { added = append(added, &nodes.Items[i]) @@ -799,7 +800,7 @@ func (nc *NodeController) checkForNodeAddedDeleted(nodes *api.NodeList) (added, // If there's a difference between lengths of known Nodes and observed nodes // we must have removed some Node. if len(nc.knownNodeSet)+len(added) != len(nodes.Items) { - knowSetCopy := map[string]*api.Node{} + knowSetCopy := map[string]*v1.Node{} for k, v := range nc.knownNodeSet { knowSetCopy[k] = v } @@ -815,7 +816,7 @@ func (nc *NodeController) checkForNodeAddedDeleted(nodes *api.NodeList) (added, // cancelPodEviction removes any queued evictions, typically because the node is available again. It // returns true if an eviction was queued. -func (nc *NodeController) cancelPodEviction(node *api.Node) bool { +func (nc *NodeController) cancelPodEviction(node *v1.Node) bool { zone := utilnode.GetZoneKey(node) nc.evictorLock.Lock() defer nc.evictorLock.Unlock() @@ -829,7 +830,7 @@ func (nc *NodeController) cancelPodEviction(node *api.Node) bool { // evictPods queues an eviction for the provided node name, and returns false if the node is already // queued for eviction. -func (nc *NodeController) evictPods(node *api.Node) bool { +func (nc *NodeController) evictPods(node *v1.Node) bool { nc.evictorLock.Lock() defer nc.evictorLock.Unlock() return nc.zonePodEvictor[utilnode.GetZoneKey(node)].Add(node.Name, string(node.UID)) @@ -853,11 +854,11 @@ func (nc *NodeController) ReducedQPSFunc(nodeNum int) float32 { // - fullyDisrupted if there're no Ready Nodes, // - partiallyDisrupted if at least than nc.unhealthyZoneThreshold percent of Nodes are not Ready, // - normal otherwise -func (nc *NodeController) ComputeZoneState(nodeReadyConditions []*api.NodeCondition) (int, zoneState) { +func (nc *NodeController) ComputeZoneState(nodeReadyConditions []*v1.NodeCondition) (int, zoneState) { readyNodes := 0 notReadyNodes := 0 for i := range nodeReadyConditions { - if nodeReadyConditions[i] != nil && nodeReadyConditions[i].Status == api.ConditionTrue { + if nodeReadyConditions[i] != nil && nodeReadyConditions[i].Status == v1.ConditionTrue { readyNodes++ } else { notReadyNodes++ diff --git a/pkg/controller/node/nodecontroller_test.go b/pkg/controller/node/nodecontroller_test.go index 2b8b6a24a13..bd43c2c3f7e 100644 --- a/pkg/controller/node/nodecontroller_test.go +++ b/pkg/controller/node/nodecontroller_test.go @@ -25,10 +25,11 @@ import ( "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/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" testcore "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/cloudprovider" fakecloud "k8s.io/kubernetes/pkg/cloudprovider/providers/fake" @@ -65,7 +66,7 @@ func NewNodeControllerFromClient( nodeCIDRMaskSize int, allocateNodeCIDRs bool) (*NodeController, error) { - factory := informers.NewSharedInformerFactory(kubeClient, controller.NoResyncPeriodFunc()) + factory := informers.NewSharedInformerFactory(kubeClient, nil, controller.NoResyncPeriodFunc()) nc, err := NewNodeController(factory.Pods(), factory.Nodes(), factory.DaemonSets(), cloud, kubeClient, podEvictionTimeout, evictionLimiterQPS, secondaryEvictionLimiterQPS, largeClusterThreshold, unhealthyZoneThreshold, nodeMonitorGracePeriod, nodeStartupGracePeriod, nodeMonitorPeriod, clusterCIDR, @@ -84,11 +85,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { // Because of the logic that prevents NC from evicting anything when all Nodes are NotReady // we need second healthy node in tests. Because of how the tests are written we need to update // the status of this Node. - healthyNodeNewStatus := api.NodeStatus{ - Conditions: []api.NodeCondition{ + healthyNodeNewStatus := v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, // Node status has just been updated, and is NotReady for 10min. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 9, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), @@ -100,17 +101,17 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { fakeNodeHandler *FakeNodeHandler daemonSets []extensions.DaemonSet timeToPass time.Duration - newNodeStatus api.NodeStatus - secondNodeNewStatus api.NodeStatus + newNodeStatus v1.NodeStatus + secondNodeNewStatus v1.NodeStatus expectedEvictPods bool description string }{ // Node created recently, with no status (happens only at cluster startup). { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: fakeNow, Labels: map[string]string{ @@ -120,7 +121,7 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -128,11 +129,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -140,11 +141,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, daemonSets: nil, timeToPass: 0, - newNodeStatus: api.NodeStatus{}, + newNodeStatus: v1.NodeStatus{}, secondNodeNewStatus: healthyNodeNewStatus, expectedEvictPods: false, description: "Node created recently, with no status.", @@ -152,9 +153,9 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { // Node created long time ago, and kubelet posted NotReady for a short period of time. { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -162,11 +163,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionFalse, + Type: v1.NodeReady, + Status: v1.ConditionFalse, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -174,7 +175,7 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -182,11 +183,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -194,15 +195,15 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, daemonSets: nil, timeToPass: evictionTimeout, - newNodeStatus: api.NodeStatus{ - Conditions: []api.NodeCondition{ + newNodeStatus: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionFalse, + Type: v1.NodeReady, + Status: v1.ConditionFalse, // Node status has just been updated, and is NotReady for 10min. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 9, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), @@ -216,9 +217,9 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { // Pod is ds-managed, and kubelet posted NotReady for a long period of time. { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -226,11 +227,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionFalse, + Type: v1.NodeReady, + Status: v1.ConditionFalse, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -238,7 +239,7 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -246,11 +247,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -259,15 +260,15 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, Clientset: fake.NewSimpleClientset( - &api.PodList{ - Items: []api.Pod{ + &v1.PodList{ + Items: []v1.Pod{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "pod0", Namespace: "default", Labels: map[string]string{"daemon": "yes"}, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: "node0", }, }, @@ -277,7 +278,7 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, daemonSets: []extensions.DaemonSet{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "ds0", Namespace: "default", }, @@ -289,11 +290,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, timeToPass: time.Hour, - newNodeStatus: api.NodeStatus{ - Conditions: []api.NodeCondition{ + newNodeStatus: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionFalse, + Type: v1.NodeReady, + Status: v1.ConditionFalse, // Node status has just been updated, and is NotReady for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 59, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), @@ -307,9 +308,9 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { // Node created long time ago, and kubelet posted NotReady for a long period of time. { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -317,11 +318,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionFalse, + Type: v1.NodeReady, + Status: v1.ConditionFalse, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -329,7 +330,7 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -337,11 +338,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -349,15 +350,15 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, daemonSets: nil, timeToPass: time.Hour, - newNodeStatus: api.NodeStatus{ - Conditions: []api.NodeCondition{ + newNodeStatus: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionFalse, + Type: v1.NodeReady, + Status: v1.ConditionFalse, // Node status has just been updated, and is NotReady for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 59, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), @@ -371,9 +372,9 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { // Node created long time ago, node controller posted Unknown for a short period of time. { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -381,11 +382,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -393,7 +394,7 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -401,11 +402,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -413,15 +414,15 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, daemonSets: nil, timeToPass: evictionTimeout - testNodeMonitorGracePeriod, - newNodeStatus: api.NodeStatus{ - Conditions: []api.NodeCondition{ + newNodeStatus: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, // Node status was updated by nodecontroller 10min ago LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), @@ -435,9 +436,9 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { // Node created long time ago, node controller posted Unknown for a long period of time. { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -445,11 +446,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -457,7 +458,7 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -465,11 +466,11 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -477,15 +478,15 @@ func TestMonitorNodeStatusEvictPods(t *testing.T) { }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, daemonSets: nil, timeToPass: 60 * time.Minute, - newNodeStatus: api.NodeStatus{ - Conditions: []api.NodeCondition{ + newNodeStatus: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, // Node status was updated by nodecontroller 1hr ago LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), @@ -547,11 +548,11 @@ func TestPodStatusChange(t *testing.T) { // Because of the logic that prevents NC from evicting anything when all Nodes are NotReady // we need second healthy node in tests. Because of how the tests are written we need to update // the status of this Node. - healthyNodeNewStatus := api.NodeStatus{ - Conditions: []api.NodeCondition{ + healthyNodeNewStatus := v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, // Node status has just been updated, and is NotReady for 10min. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 9, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), @@ -564,17 +565,17 @@ func TestPodStatusChange(t *testing.T) { fakeNodeHandler *FakeNodeHandler daemonSets []extensions.DaemonSet timeToPass time.Duration - newNodeStatus api.NodeStatus - secondNodeNewStatus api.NodeStatus + newNodeStatus v1.NodeStatus + secondNodeNewStatus v1.NodeStatus expectedPodUpdate bool expectedReason string description string }{ { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -582,11 +583,11 @@ func TestPodStatusChange(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -594,7 +595,7 @@ func TestPodStatusChange(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -602,11 +603,11 @@ func TestPodStatusChange(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -614,14 +615,14 @@ func TestPodStatusChange(t *testing.T) { }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, timeToPass: 60 * time.Minute, - newNodeStatus: api.NodeStatus{ - Conditions: []api.NodeCondition{ + newNodeStatus: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, // Node status was updated by nodecontroller 1hr ago LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), @@ -664,7 +665,7 @@ func TestPodStatusChange(t *testing.T) { podReasonUpdate := false for _, action := range item.fakeNodeHandler.Actions() { if action.GetVerb() == "update" && action.GetResource().Resource == "pods" { - updateReason := action.(testcore.UpdateActionImpl).GetObject().(*api.Pod).Status.Reason + updateReason := action.(testcore.UpdateActionImpl).GetObject().(*v1.Pod).Status.Reason podReasonUpdate = true if updateReason != item.expectedReason { t.Errorf("expected pod status reason: %+v, got %+v for %+v", item.expectedReason, updateReason, item.description) @@ -687,21 +688,21 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { // Because of the logic that prevents NC from evicting anything when all Nodes are NotReady // we need second healthy node in tests. Because of how the tests are written we need to update // the status of this Node. - healthyNodeNewStatus := api.NodeStatus{ - Conditions: []api.NodeCondition{ + healthyNodeNewStatus := v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 13, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, }, } - unhealthyNodeNewStatus := api.NodeStatus{ - Conditions: []api.NodeCondition{ + unhealthyNodeNewStatus := v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, // Node status was updated by nodecontroller 1hr ago LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), @@ -710,9 +711,9 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { } table := []struct { - nodeList []*api.Node - podList []api.Pod - updatedNodeStatuses []api.NodeStatus + nodeList []*v1.Node + podList []v1.Pod + updatedNodeStatuses []v1.NodeStatus expectedInitialStates map[string]zoneState expectedFollowingStates map[string]zoneState expectedEvictPods bool @@ -721,9 +722,9 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { // NetworkDisruption: Node created long time ago, node controller posted Unknown for a long period of time on both Nodes. // Only zone is down - eviction shouldn't take place { - nodeList: []*api.Node{ + nodeList: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -731,11 +732,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -743,7 +744,7 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -751,11 +752,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -763,8 +764,8 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, }, - podList: []api.Pod{*newPod("pod0", "node0")}, - updatedNodeStatuses: []api.NodeStatus{ + podList: []v1.Pod{*newPod("pod0", "node0")}, + updatedNodeStatuses: []v1.NodeStatus{ unhealthyNodeNewStatus, unhealthyNodeNewStatus, }, @@ -776,9 +777,9 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { // NetworkDisruption: Node created long time ago, node controller posted Unknown for a long period of time on both Nodes. // Both zones down - eviction shouldn't take place { - nodeList: []*api.Node{ + nodeList: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -786,11 +787,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -798,7 +799,7 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -806,11 +807,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone2", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -819,8 +820,8 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, - podList: []api.Pod{*newPod("pod0", "node0")}, - updatedNodeStatuses: []api.NodeStatus{ + podList: []v1.Pod{*newPod("pod0", "node0")}, + updatedNodeStatuses: []v1.NodeStatus{ unhealthyNodeNewStatus, unhealthyNodeNewStatus, }, @@ -838,9 +839,9 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { // NetworkDisruption: Node created long time ago, node controller posted Unknown for a long period of time on both Nodes. // One zone is down - eviction should take place { - nodeList: []*api.Node{ + nodeList: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -848,11 +849,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -860,7 +861,7 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -868,11 +869,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone2", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -880,8 +881,8 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, }, - podList: []api.Pod{*newPod("pod0", "node0")}, - updatedNodeStatuses: []api.NodeStatus{ + podList: []v1.Pod{*newPod("pod0", "node0")}, + updatedNodeStatuses: []v1.NodeStatus{ unhealthyNodeNewStatus, healthyNodeNewStatus, }, @@ -899,9 +900,9 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { // NetworkDisruption: Node created long time ago, node controller posted Unknown for a long period // of on first Node, eviction should stop even though -master Node is healthy. { - nodeList: []*api.Node{ + nodeList: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -909,11 +910,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -921,7 +922,7 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node-master", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -929,11 +930,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -941,8 +942,8 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, }, - podList: []api.Pod{*newPod("pod0", "node0")}, - updatedNodeStatuses: []api.NodeStatus{ + podList: []v1.Pod{*newPod("pod0", "node0")}, + updatedNodeStatuses: []v1.NodeStatus{ unhealthyNodeNewStatus, healthyNodeNewStatus, }, @@ -958,9 +959,9 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { // NetworkDisruption: Node created long time ago, node controller posted Unknown for a long period of time on both Nodes. // Initially both zones down, one comes back - eviction should take place { - nodeList: []*api.Node{ + nodeList: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -968,11 +969,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -980,7 +981,7 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -988,11 +989,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone2", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -1001,8 +1002,8 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, - podList: []api.Pod{*newPod("pod0", "node0")}, - updatedNodeStatuses: []api.NodeStatus{ + podList: []v1.Pod{*newPod("pod0", "node0")}, + updatedNodeStatuses: []v1.NodeStatus{ unhealthyNodeNewStatus, healthyNodeNewStatus, }, @@ -1020,9 +1021,9 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { // NetworkDisruption: Node created long time ago, node controller posted Unknown for a long period of time on both Nodes. // Zone is partially disrupted - eviction should take place { - nodeList: []*api.Node{ + nodeList: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -1030,11 +1031,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -1042,7 +1043,7 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node1", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -1050,11 +1051,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -1062,7 +1063,7 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node2", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -1070,11 +1071,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -1082,7 +1083,7 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node3", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -1090,11 +1091,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -1102,7 +1103,7 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node4", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Labels: map[string]string{ @@ -1110,11 +1111,11 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { unversioned.LabelZoneFailureDomain: "zone1", }, }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -1123,8 +1124,8 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { }, }, - podList: []api.Pod{*newPod("pod0", "node0")}, - updatedNodeStatuses: []api.NodeStatus{ + podList: []v1.Pod{*newPod("pod0", "node0")}, + updatedNodeStatuses: []v1.NodeStatus{ unhealthyNodeNewStatus, unhealthyNodeNewStatus, unhealthyNodeNewStatus, @@ -1145,7 +1146,7 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { for _, item := range table { fakeNodeHandler := &FakeNodeHandler{ Existing: item.nodeList, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: item.podList}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: item.podList}), } nodeController, _ := NewNodeControllerFromClient(nil, fakeNodeHandler, evictionTimeout, testRateLimiterQPS, testRateLimiterQPS, testLargeClusterThreshold, testUnhealtyThreshold, testNodeMonitorGracePeriod, @@ -1211,17 +1212,17 @@ func TestMonitorNodeStatusEvictPodsWithDisruption(t *testing.T) { // the node is gone. func TestCloudProviderNoRateLimit(t *testing.T) { fnh := &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, @@ -1229,7 +1230,7 @@ func TestCloudProviderNoRateLimit(t *testing.T) { }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0"), *newPod("pod1", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0"), *newPod("pod1", "node0")}}), deleteWaitChan: make(chan struct{}), } nodeController, _ := NewNodeControllerFromClient(nil, fnh, 10*time.Minute, @@ -1263,45 +1264,45 @@ func TestMonitorNodeStatusUpdateStatus(t *testing.T) { table := []struct { fakeNodeHandler *FakeNodeHandler timeToPass time.Duration - newNodeStatus api.NodeStatus + newNodeStatus v1.NodeStatus expectedEvictPods bool expectedRequestCount int - expectedNodes []*api.Node + expectedNodes []*v1.Node }{ // Node created long time ago, without status: // Expect Unknown status posted from node controller. { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, expectedRequestCount: 2, // List+Update - expectedNodes: []*api.Node{ + expectedNodes: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, Reason: "NodeStatusNeverUpdated", Message: "Kubelet never posted node status.", LastHeartbeatTime: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), LastTransitionTime: fakeNow, }, { - Type: api.NodeOutOfDisk, - Status: api.ConditionUnknown, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionUnknown, Reason: "NodeStatusNeverUpdated", Message: "Kubelet never posted node status.", LastHeartbeatTime: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), @@ -1316,15 +1317,15 @@ func TestMonitorNodeStatusUpdateStatus(t *testing.T) { // Expect no action from node controller (within startup grace period). { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: fakeNow, }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, expectedRequestCount: 1, // List expectedNodes: nil, @@ -1333,96 +1334,96 @@ func TestMonitorNodeStatusUpdateStatus(t *testing.T) { // Expect Unknown status posted from node controller. { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, { - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionFalse, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, }, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, - Spec: api.NodeSpec{ + Spec: v1.NodeSpec{ ExternalID: "node0", }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, expectedRequestCount: 3, // (List+)List+Update timeToPass: time.Hour, - newNodeStatus: api.NodeStatus{ - Conditions: []api.NodeCondition{ + newNodeStatus: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, { - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionFalse, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, }, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, - expectedNodes: []*api.Node{ + expectedNodes: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, Reason: "NodeStatusUnknown", Message: "Kubelet stopped posting node status.", LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Time{Time: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC).Add(time.Hour)}, }, { - Type: api.NodeOutOfDisk, - Status: api.ConditionUnknown, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionUnknown, Reason: "NodeStatusUnknown", Message: "Kubelet stopped posting node status.", LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Time{Time: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC).Add(time.Hour)}, }, }, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, - Spec: api.NodeSpec{ + Spec: v1.NodeSpec{ ExternalID: "node0", }, }, @@ -1432,33 +1433,33 @@ func TestMonitorNodeStatusUpdateStatus(t *testing.T) { // Expect no action from node controller (within monitor grace period). { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, // Node status has just been updated. LastHeartbeatTime: fakeNow, LastTransitionTime: fakeNow, }, }, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, - Spec: api.NodeSpec{ + Spec: v1.NodeSpec{ ExternalID: "node0", }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, expectedRequestCount: 1, // List expectedNodes: nil, @@ -1497,22 +1498,22 @@ func TestMonitorNodeStatusMarkPodsNotReady(t *testing.T) { table := []struct { fakeNodeHandler *FakeNodeHandler timeToPass time.Duration - newNodeStatus api.NodeStatus + newNodeStatus v1.NodeStatus expectedPodStatusUpdate bool }{ // Node created recently, without status. // Expect no action from node controller (within startup grace period). { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: fakeNow, }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, expectedPodStatusUpdate: false, }, @@ -1520,33 +1521,33 @@ func TestMonitorNodeStatusMarkPodsNotReady(t *testing.T) { // Expect no action from node controller (within monitor grace period). { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, // Node status has just been updated. LastHeartbeatTime: fakeNow, LastTransitionTime: fakeNow, }, }, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, - Spec: api.NodeSpec{ + Spec: v1.NodeSpec{ ExternalID: "node0", }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, expectedPodStatusUpdate: false, }, @@ -1554,68 +1555,68 @@ func TestMonitorNodeStatusMarkPodsNotReady(t *testing.T) { // Expect pods status updated and Unknown node status posted from node controller { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, - Status: api.NodeStatus{ - NodeInfo: api.NodeSystemInfo{ + Status: v1.NodeStatus{ + NodeInfo: v1.NodeSystemInfo{ KubeletVersion: "v1.2.0", }, - Conditions: []api.NodeCondition{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, { - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionFalse, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, }, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, - Spec: api.NodeSpec{ + Spec: v1.NodeSpec{ ExternalID: "node0", }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, timeToPass: 1 * time.Minute, - newNodeStatus: api.NodeStatus{ - NodeInfo: api.NodeSystemInfo{ + newNodeStatus: v1.NodeStatus{ + NodeInfo: v1.NodeSystemInfo{ KubeletVersion: "v1.2.0", }, - Conditions: []api.NodeCondition{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, { - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionFalse, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, }, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, expectedPodStatusUpdate: true, @@ -1624,68 +1625,68 @@ func TestMonitorNodeStatusMarkPodsNotReady(t *testing.T) { // updated by kubelet exceeds grace period. Expect no action from node controller. { fakeNodeHandler: &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", CreationTimestamp: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, - Status: api.NodeStatus{ - NodeInfo: api.NodeSystemInfo{ + Status: v1.NodeStatus{ + NodeInfo: v1.NodeSystemInfo{ KubeletVersion: "v1.1.0", }, - Conditions: []api.NodeCondition{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, { - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionFalse, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, }, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, - Spec: api.NodeSpec{ + Spec: v1.NodeSpec{ ExternalID: "node0", }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), }, timeToPass: 1 * time.Minute, - newNodeStatus: api.NodeStatus{ - NodeInfo: api.NodeSystemInfo{ + newNodeStatus: v1.NodeStatus{ + NodeInfo: v1.NodeSystemInfo{ KubeletVersion: "v1.1.0", }, - Conditions: []api.NodeCondition{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, { - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionFalse, // Node status hasn't been updated for 1hr. LastHeartbeatTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), }, }, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, expectedPodStatusUpdate: false, @@ -1723,21 +1724,21 @@ func TestMonitorNodeStatusMarkPodsNotReady(t *testing.T) { func TestNodeEventGeneration(t *testing.T) { fakeNow := unversioned.Date(2016, 9, 10, 12, 0, 0, 0, time.UTC) fakeNodeHandler := &FakeNodeHandler{ - Existing: []*api.Node{ + Existing: []*v1.Node{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "node0", UID: "1234567890", CreationTimestamp: unversioned.Date(2015, 8, 10, 0, 0, 0, 0, time.UTC), }, - Spec: api.NodeSpec{ + Spec: v1.NodeSpec{ ExternalID: "node0", }, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionUnknown, + Type: v1.NodeReady, + Status: v1.ConditionUnknown, LastHeartbeatTime: unversioned.Date(2015, 8, 10, 0, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2015, 8, 10, 0, 0, 0, 0, time.UTC), }, @@ -1745,7 +1746,7 @@ func TestNodeEventGeneration(t *testing.T) { }, }, }, - Clientset: fake.NewSimpleClientset(&api.PodList{Items: []api.Pod{*newPod("pod0", "node0")}}), + Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*newPod("pod0", "node0")}}), } nodeController, _ := NewNodeControllerFromClient(nil, fakeNodeHandler, 5*time.Minute, @@ -1783,77 +1784,77 @@ func TestNodeEventGeneration(t *testing.T) { func TestCheckPod(t *testing.T) { tcs := []struct { - pod api.Pod + pod v1.Pod prune bool }{ { - pod: api.Pod{ - ObjectMeta: api.ObjectMeta{DeletionTimestamp: nil}, - Spec: api.PodSpec{NodeName: "new"}, + pod: v1.Pod{ + ObjectMeta: v1.ObjectMeta{DeletionTimestamp: nil}, + Spec: v1.PodSpec{NodeName: "new"}, }, prune: false, }, { - pod: api.Pod{ - ObjectMeta: api.ObjectMeta{DeletionTimestamp: nil}, - Spec: api.PodSpec{NodeName: "old"}, + pod: v1.Pod{ + ObjectMeta: v1.ObjectMeta{DeletionTimestamp: nil}, + Spec: v1.PodSpec{NodeName: "old"}, }, prune: false, }, { - pod: api.Pod{ - ObjectMeta: api.ObjectMeta{DeletionTimestamp: nil}, - Spec: api.PodSpec{NodeName: ""}, + pod: v1.Pod{ + ObjectMeta: v1.ObjectMeta{DeletionTimestamp: nil}, + Spec: v1.PodSpec{NodeName: ""}, }, prune: false, }, { - pod: api.Pod{ - ObjectMeta: api.ObjectMeta{DeletionTimestamp: nil}, - Spec: api.PodSpec{NodeName: "nonexistant"}, + pod: v1.Pod{ + ObjectMeta: v1.ObjectMeta{DeletionTimestamp: nil}, + Spec: v1.PodSpec{NodeName: "nonexistant"}, }, prune: false, }, { - pod: api.Pod{ - ObjectMeta: api.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, - Spec: api.PodSpec{NodeName: "new"}, + pod: v1.Pod{ + ObjectMeta: v1.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, + Spec: v1.PodSpec{NodeName: "new"}, }, prune: false, }, { - pod: api.Pod{ - ObjectMeta: api.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, - Spec: api.PodSpec{NodeName: "old"}, + pod: v1.Pod{ + ObjectMeta: v1.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, + Spec: v1.PodSpec{NodeName: "old"}, }, prune: true, }, { - pod: api.Pod{ - ObjectMeta: api.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, - Spec: api.PodSpec{NodeName: "older"}, + pod: v1.Pod{ + ObjectMeta: v1.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, + Spec: v1.PodSpec{NodeName: "older"}, }, prune: true, }, { - pod: api.Pod{ - ObjectMeta: api.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, - Spec: api.PodSpec{NodeName: "oldest"}, + pod: v1.Pod{ + ObjectMeta: v1.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, + Spec: v1.PodSpec{NodeName: "oldest"}, }, prune: true, }, { - pod: api.Pod{ - ObjectMeta: api.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, - Spec: api.PodSpec{NodeName: ""}, + pod: v1.Pod{ + ObjectMeta: v1.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, + Spec: v1.PodSpec{NodeName: ""}, }, prune: false, }, { - pod: api.Pod{ - ObjectMeta: api.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, - Spec: api.PodSpec{NodeName: "nonexistant"}, + pod: v1.Pod{ + ObjectMeta: v1.ObjectMeta{DeletionTimestamp: &unversioned.Time{}}, + Spec: v1.PodSpec{NodeName: "nonexistant"}, }, prune: false, }, @@ -1861,42 +1862,42 @@ func TestCheckPod(t *testing.T) { nc, _ := NewNodeControllerFromClient(nil, fake.NewSimpleClientset(), 0, 0, 0, 0, 0, 0, 0, 0, nil, nil, 0, false) nc.nodeStore.Store = cache.NewStore(cache.MetaNamespaceKeyFunc) - nc.nodeStore.Store.Add(&api.Node{ - ObjectMeta: api.ObjectMeta{ + nc.nodeStore.Store.Add(&v1.Node{ + ObjectMeta: v1.ObjectMeta{ Name: "new", }, - Status: api.NodeStatus{ - NodeInfo: api.NodeSystemInfo{ + Status: v1.NodeStatus{ + NodeInfo: v1.NodeSystemInfo{ KubeletVersion: "v1.1.0", }, }, }) - nc.nodeStore.Store.Add(&api.Node{ - ObjectMeta: api.ObjectMeta{ + nc.nodeStore.Store.Add(&v1.Node{ + ObjectMeta: v1.ObjectMeta{ Name: "old", }, - Status: api.NodeStatus{ - NodeInfo: api.NodeSystemInfo{ + Status: v1.NodeStatus{ + NodeInfo: v1.NodeSystemInfo{ KubeletVersion: "v1.0.0", }, }, }) - nc.nodeStore.Store.Add(&api.Node{ - ObjectMeta: api.ObjectMeta{ + nc.nodeStore.Store.Add(&v1.Node{ + ObjectMeta: v1.ObjectMeta{ Name: "older", }, - Status: api.NodeStatus{ - NodeInfo: api.NodeSystemInfo{ + Status: v1.NodeStatus{ + NodeInfo: v1.NodeSystemInfo{ KubeletVersion: "v0.21.4", }, }, }) - nc.nodeStore.Store.Add(&api.Node{ - ObjectMeta: api.ObjectMeta{ + nc.nodeStore.Store.Add(&v1.Node{ + ObjectMeta: v1.ObjectMeta{ Name: "oldest", }, - Status: api.NodeStatus{ - NodeInfo: api.NodeSystemInfo{ + Status: v1.NodeStatus{ + NodeInfo: v1.NodeSystemInfo{ KubeletVersion: "v0.19.3", }, }, @@ -1904,7 +1905,7 @@ func TestCheckPod(t *testing.T) { for i, tc := range tcs { var deleteCalls int - nc.forcefullyDeletePod = func(_ *api.Pod) error { + nc.forcefullyDeletePod = func(_ *v1.Pod) error { deleteCalls++ return nil } @@ -1964,9 +1965,9 @@ func TestCheckNodeKubeletVersionParsing(t *testing.T) { } for _, ov := range tests { - n := &api.Node{ - Status: api.NodeStatus{ - NodeInfo: api.NodeSystemInfo{ + n := &v1.Node{ + Status: v1.NodeStatus{ + NodeInfo: v1.NodeSystemInfo{ KubeletVersion: ov.version, }, }, diff --git a/pkg/controller/node/test_utils.go b/pkg/controller/node/test_utils.go index 72584e8ee37..e5bd2a5d1e5 100644 --- a/pkg/controller/node/test_utils.go +++ b/pkg/controller/node/test_utils.go @@ -26,8 +26,9 @@ import ( apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/clock" utilnode "k8s.io/kubernetes/pkg/util/node" @@ -43,14 +44,14 @@ type FakeNodeHandler struct { *fake.Clientset // Input: Hooks determine if request is valid or not - CreateHook func(*FakeNodeHandler, *api.Node) bool - Existing []*api.Node + CreateHook func(*FakeNodeHandler, *v1.Node) bool + Existing []*v1.Node // Output - CreatedNodes []*api.Node - DeletedNodes []*api.Node - UpdatedNodes []*api.Node - UpdatedNodeStatuses []*api.Node + CreatedNodes []*v1.Node + DeletedNodes []*v1.Node + UpdatedNodes []*v1.Node + UpdatedNodeStatuses []*v1.Node RequestCount int // Synchronization @@ -59,29 +60,29 @@ type FakeNodeHandler struct { } type FakeLegacyHandler struct { - unversionedcore.CoreInterface + v1core.CoreV1Interface n *FakeNodeHandler } -func (c *FakeNodeHandler) getUpdatedNodesCopy() []*api.Node { +func (c *FakeNodeHandler) getUpdatedNodesCopy() []*v1.Node { c.lock.Lock() defer c.lock.Unlock() - updatedNodesCopy := make([]*api.Node, len(c.UpdatedNodes), len(c.UpdatedNodes)) + updatedNodesCopy := make([]*v1.Node, len(c.UpdatedNodes), len(c.UpdatedNodes)) for i, ptr := range c.UpdatedNodes { updatedNodesCopy[i] = ptr } return updatedNodesCopy } -func (c *FakeNodeHandler) Core() unversionedcore.CoreInterface { +func (c *FakeNodeHandler) Core() v1core.CoreV1Interface { return &FakeLegacyHandler{c.Clientset.Core(), c} } -func (m *FakeLegacyHandler) Nodes() unversionedcore.NodeInterface { +func (m *FakeLegacyHandler) Nodes() v1core.NodeInterface { return m.n } -func (m *FakeNodeHandler) Create(node *api.Node) (*api.Node, error) { +func (m *FakeNodeHandler) Create(node *v1.Node) (*v1.Node, error) { m.lock.Lock() defer func() { m.RequestCount++ @@ -101,7 +102,7 @@ func (m *FakeNodeHandler) Create(node *api.Node) (*api.Node, error) { } } -func (m *FakeNodeHandler) Get(name string) (*api.Node, error) { +func (m *FakeNodeHandler) Get(name string) (*v1.Node, error) { m.lock.Lock() defer func() { m.RequestCount++ @@ -122,13 +123,13 @@ func (m *FakeNodeHandler) Get(name string) (*api.Node, error) { return nil, nil } -func (m *FakeNodeHandler) List(opts api.ListOptions) (*api.NodeList, error) { +func (m *FakeNodeHandler) List(opts v1.ListOptions) (*v1.NodeList, error) { m.lock.Lock() defer func() { m.RequestCount++ m.lock.Unlock() }() - var nodes []*api.Node + var nodes []*v1.Node for i := 0; i < len(m.UpdatedNodes); i++ { if !contains(m.UpdatedNodes[i], m.DeletedNodes) { nodes = append(nodes, m.UpdatedNodes[i]) @@ -144,14 +145,14 @@ func (m *FakeNodeHandler) List(opts api.ListOptions) (*api.NodeList, error) { nodes = append(nodes, m.CreatedNodes[i]) } } - nodeList := &api.NodeList{} + nodeList := &v1.NodeList{} for _, node := range nodes { nodeList.Items = append(nodeList.Items, *node) } return nodeList, nil } -func (m *FakeNodeHandler) Delete(id string, opt *api.DeleteOptions) error { +func (m *FakeNodeHandler) Delete(id string, opt *v1.DeleteOptions) error { m.lock.Lock() defer func() { m.RequestCount++ @@ -164,11 +165,11 @@ func (m *FakeNodeHandler) Delete(id string, opt *api.DeleteOptions) error { return nil } -func (m *FakeNodeHandler) DeleteCollection(opt *api.DeleteOptions, listOpts api.ListOptions) error { +func (m *FakeNodeHandler) DeleteCollection(opt *v1.DeleteOptions, listOpts v1.ListOptions) error { return nil } -func (m *FakeNodeHandler) Update(node *api.Node) (*api.Node, error) { +func (m *FakeNodeHandler) Update(node *v1.Node) (*v1.Node, error) { m.lock.Lock() defer func() { m.RequestCount++ @@ -185,7 +186,7 @@ func (m *FakeNodeHandler) Update(node *api.Node) (*api.Node, error) { return node, nil } -func (m *FakeNodeHandler) UpdateStatus(node *api.Node) (*api.Node, error) { +func (m *FakeNodeHandler) UpdateStatus(node *v1.Node) (*v1.Node, error) { m.lock.Lock() defer func() { m.RequestCount++ @@ -196,23 +197,23 @@ func (m *FakeNodeHandler) UpdateStatus(node *api.Node) (*api.Node, error) { return node, nil } -func (m *FakeNodeHandler) PatchStatus(nodeName string, data []byte) (*api.Node, error) { +func (m *FakeNodeHandler) PatchStatus(nodeName string, data []byte) (*v1.Node, error) { m.RequestCount++ - return &api.Node{}, nil + return &v1.Node{}, nil } -func (m *FakeNodeHandler) Watch(opts api.ListOptions) (watch.Interface, error) { +func (m *FakeNodeHandler) Watch(opts v1.ListOptions) (watch.Interface, error) { return watch.NewFake(), nil } -func (m *FakeNodeHandler) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (*api.Node, error) { +func (m *FakeNodeHandler) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (*v1.Node, error) { return nil, nil } // FakeRecorder is used as a fake during testing. type FakeRecorder struct { - source api.EventSource - events []*api.Event + source v1.EventSource + events []*v1.Event clock clock.Clock } @@ -228,7 +229,7 @@ func (f *FakeRecorder) PastEventf(obj runtime.Object, timestamp unversioned.Time } func (f *FakeRecorder) generateEvent(obj runtime.Object, timestamp unversioned.Time, eventtype, reason, message string) { - ref, err := api.GetReference(obj) + ref, err := v1.GetReference(obj) if err != nil { return } @@ -240,15 +241,15 @@ func (f *FakeRecorder) generateEvent(obj runtime.Object, timestamp unversioned.T } } -func (f *FakeRecorder) makeEvent(ref *api.ObjectReference, eventtype, reason, message string) *api.Event { +func (f *FakeRecorder) makeEvent(ref *v1.ObjectReference, eventtype, reason, message string) *v1.Event { fmt.Println("make event") t := unversioned.Time{Time: f.clock.Now()} namespace := ref.Namespace if namespace == "" { - namespace = api.NamespaceDefault + namespace = v1.NamespaceDefault } - return &api.Event{ - ObjectMeta: api.ObjectMeta{ + return &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: fmt.Sprintf("%v.%x", ref.Name, t.UnixNano()), Namespace: namespace, }, @@ -264,41 +265,41 @@ func (f *FakeRecorder) makeEvent(ref *api.ObjectReference, eventtype, reason, me func NewFakeRecorder() *FakeRecorder { return &FakeRecorder{ - source: api.EventSource{Component: "nodeControllerTest"}, - events: []*api.Event{}, + source: v1.EventSource{Component: "nodeControllerTest"}, + events: []*v1.Event{}, clock: clock.NewFakeClock(time.Now()), } } -func newNode(name string) *api.Node { - return &api.Node{ - ObjectMeta: api.ObjectMeta{Name: name}, - Spec: api.NodeSpec{ +func newNode(name string) *v1.Node { + return &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: name}, + Spec: v1.NodeSpec{ ExternalID: name, }, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Status: v1.NodeStatus{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, } } -func newPod(name, host string) *api.Pod { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func newPod(name, host string) *v1.Pod { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", Name: name, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: host, }, - Status: api.PodStatus{ - Conditions: []api.PodCondition{ + Status: v1.PodStatus{ + Conditions: []v1.PodCondition{ { - Type: api.PodReady, - Status: api.ConditionTrue, + Type: v1.PodReady, + Status: v1.ConditionTrue, }, }, }, @@ -307,7 +308,7 @@ func newPod(name, host string) *api.Pod { return pod } -func contains(node *api.Node, nodes []*api.Node) bool { +func contains(node *v1.Node, nodes []*v1.Node) bool { for i := 0; i < len(nodes); i++ { if node.Name == nodes[i].Name { return true @@ -318,7 +319,7 @@ func contains(node *api.Node, nodes []*api.Node) bool { // Returns list of zones for all Nodes stored in FakeNodeHandler func getZones(nodeHandler *FakeNodeHandler) []string { - nodes, _ := nodeHandler.List(api.ListOptions{}) + nodes, _ := nodeHandler.List(v1.ListOptions{}) zones := sets.NewString() for _, node := range nodes.Items { zones.Insert(utilnode.GetZoneKey(&node)) diff --git a/pkg/controller/petset/BUILD b/pkg/controller/petset/BUILD index a0dab13dcde..cd410f8c399 100644 --- a/pkg/controller/petset/BUILD +++ b/pkg/controller/petset/BUILD @@ -22,16 +22,16 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", - "//pkg/api/pod:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/apps:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/pod:go_default_library", + "//pkg/apis/apps/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/apps/internalversion:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/apps/v1beta1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/controller:go_default_library", "//pkg/runtime:go_default_library", @@ -58,16 +58,16 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/api/pod:go_default_library", "//pkg/api/testapi:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/pod:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/apis/apps:go_default_library", + "//pkg/apis/apps/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/apps/internalversion:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/apps/internalversion/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/apps/v1beta1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/apps/v1beta1/fake:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/controller:go_default_library", diff --git a/pkg/controller/petset/fakes.go b/pkg/controller/petset/fakes.go index bb403174e1e..bf84ee5f2f1 100644 --- a/pkg/controller/petset/fakes.go +++ b/pkg/controller/petset/fakes.go @@ -22,11 +22,11 @@ import ( inf "gopkg.in/inf.v0" - "k8s.io/kubernetes/pkg/api" - api_pod "k8s.io/kubernetes/pkg/api/pod" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/apps" + "k8s.io/kubernetes/pkg/api/v1" + api_pod "k8s.io/kubernetes/pkg/api/v1/pod" + apps "k8s.io/kubernetes/pkg/apis/apps/v1beta1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/sets" @@ -36,34 +36,34 @@ func dec(i int64, exponent int) *inf.Dec { return inf.NewDec(i, inf.Scale(-exponent)) } -func newPVC(name string) api.PersistentVolumeClaim { - return api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ +func newPVC(name string) v1.PersistentVolumeClaim { + return v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PersistentVolumeClaimSpec{ - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceStorage: *resource.NewQuantity(1, resource.BinarySI), + Spec: v1.PersistentVolumeClaimSpec{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceStorage: *resource.NewQuantity(1, resource.BinarySI), }, }, }, } } -func newStatefulSetWithVolumes(replicas int, name string, petMounts []api.VolumeMount, podMounts []api.VolumeMount) *apps.StatefulSet { +func newStatefulSetWithVolumes(replicas int, name string, petMounts []v1.VolumeMount, podMounts []v1.VolumeMount) *apps.StatefulSet { mounts := append(petMounts, podMounts...) - claims := []api.PersistentVolumeClaim{} + claims := []v1.PersistentVolumeClaim{} for _, m := range petMounts { claims = append(claims, newPVC(m.Name)) } - vols := []api.Volume{} + vols := []v1.Volume{} for _, m := range podMounts { - vols = append(vols, api.Volume{ + vols = append(vols, v1.Volume{ Name: m.Name, - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{ + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{ Path: fmt.Sprintf("/tmp/%v", m.Name), }, }, @@ -75,19 +75,19 @@ func newStatefulSetWithVolumes(replicas int, name string, petMounts []api.Volume Kind: "StatefulSet", APIVersion: "apps/v1beta1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: name, - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, UID: types.UID("test"), }, Spec: apps.StatefulSetSpec{ Selector: &unversioned.LabelSelector{ MatchLabels: map[string]string{"foo": "bar"}, }, - Replicas: int32(replicas), - Template: api.PodTemplateSpec{ - Spec: api.PodSpec{ - Containers: []api.Container{ + Replicas: func() *int32 { i := int32(replicas); return &i }(), + Template: v1.PodTemplateSpec{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "nginx", Image: "nginx", @@ -103,16 +103,16 @@ func newStatefulSetWithVolumes(replicas int, name string, petMounts []api.Volume } } -func runningPod(ns, name string) *api.Pod { - p := &api.Pod{Status: api.PodStatus{Phase: api.PodRunning}} +func runningPod(ns, name string) *v1.Pod { + p := &v1.Pod{Status: v1.PodStatus{Phase: v1.PodRunning}} p.Namespace = ns p.Name = name return p } -func newPodList(ps *apps.StatefulSet, num int) []*api.Pod { +func newPodList(ps *apps.StatefulSet, num int) []*v1.Pod { // knownPods are pods in the system - knownPods := []*api.Pod{} + knownPods := []*v1.Pod{} for i := 0; i < num; i++ { k, _ := newPCB(fmt.Sprintf("%v", i), ps) knownPods = append(knownPods, k.pod) @@ -121,16 +121,16 @@ func newPodList(ps *apps.StatefulSet, num int) []*api.Pod { } func newStatefulSet(replicas int) *apps.StatefulSet { - petMounts := []api.VolumeMount{ + petMounts := []v1.VolumeMount{ {Name: "datadir", MountPath: "/tmp/zookeeper"}, } - podMounts := []api.VolumeMount{ + podMounts := []v1.VolumeMount{ {Name: "home", MountPath: "/home"}, } return newStatefulSetWithVolumes(replicas, "foo", petMounts, podMounts) } -func checkPodForMount(pod *api.Pod, mountName string) error { +func checkPodForMount(pod *v1.Pod, mountName string) error { for _, c := range pod.Spec.Containers { for _, v := range c.VolumeMounts { if v.Name == mountName { @@ -144,7 +144,7 @@ func checkPodForMount(pod *api.Pod, mountName string) error { func newFakePetClient() *fakePetClient { return &fakePetClient{ pets: []*pcb{}, - claims: []api.PersistentVolumeClaim{}, + claims: []v1.PersistentVolumeClaim{}, recorder: &record.FakeRecorder{}, petHealthChecker: &defaultPetHealthChecker{}, } @@ -152,7 +152,7 @@ func newFakePetClient() *fakePetClient { type fakePetClient struct { pets []*pcb - claims []api.PersistentVolumeClaim + claims []v1.PersistentVolumeClaim petsCreated int petsDeleted int claimsCreated int @@ -168,7 +168,7 @@ func (f *fakePetClient) Delete(p *pcb) error { for i, pet := range f.pets { if p.pod.Name == pet.pod.Name { found = true - f.recorder.Eventf(pet.parent, api.EventTypeNormal, "SuccessfulDelete", "pod: %v", pet.pod.Name) + f.recorder.Eventf(pet.parent, v1.EventTypeNormal, "SuccessfulDelete", "pod: %v", pet.pod.Name) continue } pets = append(pets, f.pets[i]) @@ -199,7 +199,7 @@ func (f *fakePetClient) Create(p *pcb) error { return fmt.Errorf("Create failed: pod %v already exists", p.pod.Name) } } - f.recorder.Eventf(p.parent, api.EventTypeNormal, "SuccessfulCreate", "pod: %v", p.pod.Name) + f.recorder.Eventf(p.parent, v1.EventTypeNormal, "SuccessfulCreate", "pod: %v", p.pod.Name) f.pets = append(f.pets, p) f.petsCreated++ return nil @@ -226,8 +226,8 @@ func (f *fakePetClient) Update(expected, wanted *pcb) error { return nil } -func (f *fakePetClient) getPodList() []*api.Pod { - p := []*api.Pod{} +func (f *fakePetClient) getPodList() []*v1.Pod { + p := []*v1.Pod{} for i, pet := range f.pets { if pet.pod == nil { continue @@ -251,10 +251,10 @@ func (f *fakePetClient) setHealthy(index int) error { if len(f.pets) <= index { return fmt.Errorf("Index out of range, len %v index %v", len(f.pets), index) } - f.pets[index].pod.Status.Phase = api.PodRunning + f.pets[index].pod.Status.Phase = v1.PodRunning f.pets[index].pod.Annotations[StatefulSetInitAnnotation] = "true" - f.pets[index].pod.Status.Conditions = []api.PodCondition{ - {Type: api.PodReady, Status: api.ConditionTrue}, + f.pets[index].pod.Status.Conditions = []v1.PodCondition{ + {Type: v1.PodReady, Status: v1.ConditionTrue}, } return nil } @@ -262,7 +262,7 @@ func (f *fakePetClient) setHealthy(index int) error { // isHealthy is a convenience wrapper around the default health checker. // The first invocation returns not-healthy, but marks the pet healthy so // subsequent invocations see it as healthy. -func (f *fakePetClient) isHealthy(pod *api.Pod) bool { +func (f *fakePetClient) isHealthy(pod *v1.Pod) bool { if f.petHealthChecker.isHealthy(pod) { return true } @@ -280,11 +280,11 @@ func (f *fakePetClient) setDeletionTimestamp(index int) error { // SyncPVCs fakes pvc syncing. func (f *fakePetClient) SyncPVCs(pet *pcb) error { v := pet.pvcs - updateClaims := map[string]api.PersistentVolumeClaim{} + updateClaims := map[string]v1.PersistentVolumeClaim{} for i, update := range v { updateClaims[update.Name] = v[i] } - claimList := []api.PersistentVolumeClaim{} + claimList := []v1.PersistentVolumeClaim{} for i, existing := range f.claims { if update, ok := updateClaims[existing.Name]; ok { claimList = append(claimList, update) @@ -296,7 +296,7 @@ func (f *fakePetClient) SyncPVCs(pet *pcb) error { for _, remaining := range updateClaims { claimList = append(claimList, remaining) f.claimsCreated++ - f.recorder.Eventf(pet.parent, api.EventTypeNormal, "SuccessfulCreate", "pvc: %v", remaining.Name) + f.recorder.Eventf(pet.parent, v1.EventTypeNormal, "SuccessfulCreate", "pvc: %v", remaining.Name) } f.claims = claimList return nil @@ -309,12 +309,12 @@ func (f *fakePetClient) DeletePVCs(pet *pcb) error { for _, c := range claimsToDelete { deleteClaimNames.Insert(c.Name) } - pvcs := []api.PersistentVolumeClaim{} + pvcs := []v1.PersistentVolumeClaim{} for i, existing := range f.claims { if deleteClaimNames.Has(existing.Name) { deleteClaimNames.Delete(existing.Name) f.claimsDeleted++ - f.recorder.Eventf(pet.parent, api.EventTypeNormal, "SuccessfulDelete", "pvc: %v", existing.Name) + f.recorder.Eventf(pet.parent, v1.EventTypeNormal, "SuccessfulDelete", "pvc: %v", existing.Name) continue } pvcs = append(pvcs, f.claims[i]) diff --git a/pkg/controller/petset/identity_mappers.go b/pkg/controller/petset/identity_mappers.go index 5aedded48d0..860b9f70eb9 100644 --- a/pkg/controller/petset/identity_mappers.go +++ b/pkg/controller/petset/identity_mappers.go @@ -23,9 +23,9 @@ import ( "strings" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - podapi "k8s.io/kubernetes/pkg/api/pod" - "k8s.io/kubernetes/pkg/apis/apps" + "k8s.io/kubernetes/pkg/api/v1" + podapi "k8s.io/kubernetes/pkg/api/v1/pod" + apps "k8s.io/kubernetes/pkg/apis/apps/v1beta1" "k8s.io/kubernetes/pkg/util/sets" ) @@ -41,10 +41,10 @@ type identityMapper interface { // SetIdentity takes an id and assigns the given pet an identity based // on the stateful set spec. The is must be unique amongst members of the // stateful set. - SetIdentity(id string, pet *api.Pod) + SetIdentity(id string, pet *v1.Pod) // Identity returns the identity of the pet. - Identity(pod *api.Pod) string + Identity(pod *v1.Pod) string } func newIdentityMappers(ps *apps.StatefulSet) []identityMapper { @@ -61,19 +61,19 @@ type NetworkIdentityMapper struct { } // SetIdentity sets network identity on the pet. -func (n *NetworkIdentityMapper) SetIdentity(id string, pet *api.Pod) { +func (n *NetworkIdentityMapper) SetIdentity(id string, pet *v1.Pod) { pet.Annotations[podapi.PodHostnameAnnotation] = fmt.Sprintf("%v-%v", n.ps.Name, id) pet.Annotations[podapi.PodSubdomainAnnotation] = n.ps.Spec.ServiceName return } // Identity returns the network identity of the pet. -func (n *NetworkIdentityMapper) Identity(pet *api.Pod) string { +func (n *NetworkIdentityMapper) Identity(pet *v1.Pod) string { return n.String(pet) } // String is a string function for the network identity of the pet. -func (n *NetworkIdentityMapper) String(pet *api.Pod) string { +func (n *NetworkIdentityMapper) String(pet *v1.Pod) string { hostname := pet.Annotations[podapi.PodHostnameAnnotation] subdomain := pet.Annotations[podapi.PodSubdomainAnnotation] return strings.Join([]string{hostname, subdomain, n.ps.Namespace}, ".") @@ -85,13 +85,13 @@ type VolumeIdentityMapper struct { } // SetIdentity sets storge identity on the pet. -func (v *VolumeIdentityMapper) SetIdentity(id string, pet *api.Pod) { - petVolumes := []api.Volume{} +func (v *VolumeIdentityMapper) SetIdentity(id string, pet *v1.Pod) { + petVolumes := []v1.Volume{} petClaims := v.GetClaims(id) // These volumes will all go down with the pod. If a name matches one of // the claims in the stateful set, it gets clobbered. - podVolumes := map[string]api.Volume{} + podVolumes := map[string]v1.Volume{} for _, podVol := range pet.Spec.Volumes { podVolumes[podVol.Name] = podVol } @@ -105,10 +105,10 @@ func (v *VolumeIdentityMapper) SetIdentity(id string, pet *api.Pod) { // TODO: Validate and reject this. glog.V(4).Infof("Overwriting existing volume source %v", podVol.Name) } - newVol := api.Volume{ + newVol := v1.Volume{ Name: name, - VolumeSource: api.VolumeSource{ - PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ + VolumeSource: v1.VolumeSource{ + PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: claim.Name, // TODO: Use source definition to set this value when we have one. ReadOnly: false, @@ -129,13 +129,13 @@ func (v *VolumeIdentityMapper) SetIdentity(id string, pet *api.Pod) { } // Identity returns the storage identity of the pet. -func (v *VolumeIdentityMapper) Identity(pet *api.Pod) string { +func (v *VolumeIdentityMapper) Identity(pet *v1.Pod) string { // TODO: Make this a hash? return v.String(pet) } // String is a string function for the network identity of the pet. -func (v *VolumeIdentityMapper) String(pet *api.Pod) string { +func (v *VolumeIdentityMapper) String(pet *v1.Pod) string { ids := []string{} petVols := sets.NewString() for _, petVol := range v.ps.Spec.VolumeClaimTemplates { @@ -160,8 +160,8 @@ func (v *VolumeIdentityMapper) String(pet *api.Pod) string { // GetClaims returns the volume claims associated with the given id. // The claims belong to the statefulset. The id should be unique within a statefulset. -func (v *VolumeIdentityMapper) GetClaims(id string) map[string]api.PersistentVolumeClaim { - petClaims := map[string]api.PersistentVolumeClaim{} +func (v *VolumeIdentityMapper) GetClaims(id string) map[string]v1.PersistentVolumeClaim { + petClaims := map[string]v1.PersistentVolumeClaim{} for _, pvc := range v.ps.Spec.VolumeClaimTemplates { claim := pvc // TODO: Name length checking in validation. @@ -177,12 +177,12 @@ func (v *VolumeIdentityMapper) GetClaims(id string) map[string]api.PersistentVol } // GetClaimsForPet returns the pvcs for the given pet. -func (v *VolumeIdentityMapper) GetClaimsForPet(pet *api.Pod) []api.PersistentVolumeClaim { +func (v *VolumeIdentityMapper) GetClaimsForPet(pet *v1.Pod) []v1.PersistentVolumeClaim { // Strip out the "-(index)" from the pet name and use it to generate // claim names. id := strings.Split(pet.Name, "-") petID := id[len(id)-1] - pvcs := []api.PersistentVolumeClaim{} + pvcs := []v1.PersistentVolumeClaim{} for _, pvc := range v.GetClaims(petID) { pvcs = append(pvcs, pvc) } @@ -196,25 +196,25 @@ type NameIdentityMapper struct { } // SetIdentity sets the pet namespace and name. -func (n *NameIdentityMapper) SetIdentity(id string, pet *api.Pod) { +func (n *NameIdentityMapper) SetIdentity(id string, pet *v1.Pod) { pet.Name = fmt.Sprintf("%v-%v", n.ps.Name, id) pet.Namespace = n.ps.Namespace return } // Identity returns the name identity of the pet. -func (n *NameIdentityMapper) Identity(pet *api.Pod) string { +func (n *NameIdentityMapper) Identity(pet *v1.Pod) string { return n.String(pet) } // String is a string function for the name identity of the pet. -func (n *NameIdentityMapper) String(pet *api.Pod) string { +func (n *NameIdentityMapper) String(pet *v1.Pod) string { return fmt.Sprintf("%v/%v", pet.Namespace, pet.Name) } // identityHash computes a hash of the pet by running all the above identity // mappers. -func identityHash(ps *apps.StatefulSet, pet *api.Pod) string { +func identityHash(ps *apps.StatefulSet, pet *v1.Pod) string { id := "" for _, idMapper := range newIdentityMappers(ps) { id += idMapper.Identity(pet) @@ -226,7 +226,7 @@ func identityHash(ps *apps.StatefulSet, pet *api.Pod) string { // Note that this is *not* a literal copy, but a copy of the fields that // contribute to the pet's identity. The returned boolean 'needsUpdate' will // be false if the realPet already has the same identity as the expectedPet. -func copyPetID(realPet, expectedPet *pcb) (pod api.Pod, needsUpdate bool, err error) { +func copyPetID(realPet, expectedPet *pcb) (pod v1.Pod, needsUpdate bool, err error) { if realPet.pod == nil || expectedPet.pod == nil { return pod, false, fmt.Errorf("Need a valid to and from pet for copy") } diff --git a/pkg/controller/petset/identity_mappers_test.go b/pkg/controller/petset/identity_mappers_test.go index 1ee97df8c3b..e19d41e5b12 100644 --- a/pkg/controller/petset/identity_mappers_test.go +++ b/pkg/controller/petset/identity_mappers_test.go @@ -23,8 +23,8 @@ import ( "testing" - "k8s.io/kubernetes/pkg/api" - api_pod "k8s.io/kubernetes/pkg/api/pod" + "k8s.io/kubernetes/pkg/api/v1" + api_pod "k8s.io/kubernetes/pkg/api/v1/pod" ) func TestPetIDName(t *testing.T) { @@ -150,10 +150,10 @@ func TestPetIDReset(t *testing.T) { if identityHash(ps, firstPCB.pod) == identityHash(ps, secondPCB.pod) { t.Fatalf("Failed to generate uniquey identities:\n%+v\n%+v", firstPCB.pod.Spec, secondPCB.pod.Spec) } - userAdded := api.Volume{ + userAdded := v1.Volume{ Name: "test", - VolumeSource: api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{Medium: api.StorageMediumMemory}, + VolumeSource: v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{Medium: v1.StorageMediumMemory}, }, } firstPCB.pod.Spec.Volumes = append(firstPCB.pod.Spec.Volumes, userAdded) diff --git a/pkg/controller/petset/iterator.go b/pkg/controller/petset/iterator.go index 77c37a05c0d..1acecf0b0ea 100644 --- a/pkg/controller/petset/iterator.go +++ b/pkg/controller/petset/iterator.go @@ -21,8 +21,8 @@ import ( "sort" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/apps" + "k8s.io/kubernetes/pkg/api/v1" + apps "k8s.io/kubernetes/pkg/apis/apps/v1beta1" "k8s.io/kubernetes/pkg/controller" ) @@ -35,7 +35,7 @@ func newPCB(id string, ps *apps.StatefulSet) (*pcb, error) { for _, im := range newIdentityMappers(ps) { im.SetIdentity(id, petPod) } - petPVCs := []api.PersistentVolumeClaim{} + petPVCs := []v1.PersistentVolumeClaim{} vMapper := &VolumeIdentityMapper{ps} for _, c := range vMapper.GetClaims(id) { petPVCs = append(petPVCs, c) @@ -87,7 +87,7 @@ func (pt *petQueue) empty() bool { } // NewPetQueue returns a queue for tracking pets -func NewPetQueue(ps *apps.StatefulSet, podList []*api.Pod) *petQueue { +func NewPetQueue(ps *apps.StatefulSet, podList []*v1.Pod) *petQueue { pt := petQueue{pets: []*pcb{}, idMapper: &NameIdentityMapper{ps}} // Seed the queue with existing pets. Assume all pets are scheduled for // deletion, enqueuing a pet will "undelete" it. We always want to delete @@ -118,7 +118,7 @@ type statefulSetIterator struct { func (pi *statefulSetIterator) Next() bool { var pet *pcb var err error - if pi.petCount < pi.ps.Spec.Replicas { + if pi.petCount < *(pi.ps.Spec.Replicas) { pet, err = newPCB(fmt.Sprintf("%d", pi.petCount), pi.ps) if err != nil { pi.errs = append(pi.errs, err) @@ -139,7 +139,7 @@ func (pi *statefulSetIterator) Value() *pcb { // NewStatefulSetIterator returns a new iterator. All pods in the given podList // are used to seed the queue of the iterator. -func NewStatefulSetIterator(ps *apps.StatefulSet, podList []*api.Pod) *statefulSetIterator { +func NewStatefulSetIterator(ps *apps.StatefulSet, podList []*v1.Pod) *statefulSetIterator { pi := &statefulSetIterator{ ps: ps, queue: NewPetQueue(ps, podList), @@ -150,7 +150,7 @@ func NewStatefulSetIterator(ps *apps.StatefulSet, podList []*api.Pod) *statefulS } // PodsByCreationTimestamp sorts a list of Pods by creation timestamp, using their names as a tie breaker. -type PodsByCreationTimestamp []*api.Pod +type PodsByCreationTimestamp []*v1.Pod func (o PodsByCreationTimestamp) Len() int { return len(o) } func (o PodsByCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] } diff --git a/pkg/controller/petset/iterator_test.go b/pkg/controller/petset/iterator_test.go index adbc52f0749..9b803040a96 100644 --- a/pkg/controller/petset/iterator_test.go +++ b/pkg/controller/petset/iterator_test.go @@ -21,14 +21,14 @@ import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/sets" ) func TestPetQueueCreates(t *testing.T) { replicas := 3 ps := newStatefulSet(replicas) - q := NewPetQueue(ps, []*api.Pod{}) + q := NewPetQueue(ps, []*v1.Pod{}) for i := 0; i < replicas; i++ { pet, _ := newPCB(fmt.Sprintf("%v", i), ps) q.enqueue(pet) @@ -107,7 +107,7 @@ func TestStatefulSetIteratorRelist(t *testing.T) { knownPods := newPodList(ps, 5) for i := range knownPods { knownPods[i].Spec.NodeName = fmt.Sprintf("foo-node-%v", i) - knownPods[i].Status.Phase = api.PodRunning + knownPods[i].Status.Phase = v1.PodRunning } pi := NewStatefulSetIterator(ps, knownPods) @@ -128,7 +128,7 @@ func TestStatefulSetIteratorRelist(t *testing.T) { } // Scale to 0 should delete all pods in system - ps.Spec.Replicas = 0 + *(ps.Spec.Replicas) = 0 pi = NewStatefulSetIterator(ps, knownPods) i = 0 for pi.Next() { @@ -143,7 +143,7 @@ func TestStatefulSetIteratorRelist(t *testing.T) { } // Relist with 0 replicas should no-op - pi = NewStatefulSetIterator(ps, []*api.Pod{}) + pi = NewStatefulSetIterator(ps, []*v1.Pod{}) if pi.Next() != false { t.Errorf("Unexpected iteration without any replicas or pods in system") } diff --git a/pkg/controller/petset/pet.go b/pkg/controller/petset/pet.go index f830fcd59aa..8e5fbe31998 100644 --- a/pkg/controller/petset/pet.go +++ b/pkg/controller/petset/pet.go @@ -20,10 +20,10 @@ import ( "fmt" "strconv" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/apis/apps" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + apps "k8s.io/kubernetes/pkg/apis/apps/v1beta1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/runtime" @@ -52,9 +52,9 @@ const ( // and parent fields to pass it around safely. type pcb struct { // pod is the desired pet pod. - pod *api.Pod + pod *v1.Pod // pvcs is a list of desired persistent volume claims for the pet pod. - pvcs []api.PersistentVolumeClaim + pvcs []v1.PersistentVolumeClaim // event is the lifecycle event associated with this update. event petLifeCycleEvent // id is the identity index of this pet. @@ -106,7 +106,7 @@ func (p *petSyncer) Sync(pet *pcb) error { return err } // if pet failed - we need to remove old one because of consistent naming - if exists && realPet.pod.Status.Phase == api.PodFailed { + if exists && realPet.pod.Status.Phase == v1.PodFailed { glog.V(2).Infof("Deleting evicted pod %v/%v", realPet.pod.Namespace, realPet.pod.Name) if err := p.petClient.Delete(realPet); err != nil { return err @@ -175,7 +175,7 @@ type petClient interface { // apiServerPetClient is a statefulset aware Kubernetes client. type apiServerPetClient struct { - c internalclientset.Interface + c clientset.Interface recorder record.EventRecorder petHealthChecker } @@ -242,12 +242,12 @@ func (p *apiServerPetClient) DeletePVCs(pet *pcb) error { return nil } -func (p *apiServerPetClient) getPVC(pvcName, pvcNamespace string) (*api.PersistentVolumeClaim, error) { +func (p *apiServerPetClient) getPVC(pvcName, pvcNamespace string) (*v1.PersistentVolumeClaim, error) { pvc, err := p.c.Core().PersistentVolumeClaims(pvcNamespace).Get(pvcName) return pvc, err } -func (p *apiServerPetClient) createPVC(pvc *api.PersistentVolumeClaim) error { +func (p *apiServerPetClient) createPVC(pvc *v1.PersistentVolumeClaim) error { _, err := p.c.Core().PersistentVolumeClaims(pvc.Namespace).Create(pvc) return err } @@ -280,17 +280,17 @@ func (p *apiServerPetClient) SyncPVCs(pet *pcb) error { // event formats an event for the given runtime object. func (p *apiServerPetClient) event(obj runtime.Object, reason, msg string, err error) { if err != nil { - p.recorder.Eventf(obj, api.EventTypeWarning, fmt.Sprintf("Failed%v", reason), fmt.Sprintf("%v, error: %v", msg, err)) + p.recorder.Eventf(obj, v1.EventTypeWarning, fmt.Sprintf("Failed%v", reason), fmt.Sprintf("%v, error: %v", msg, err)) } else { - p.recorder.Eventf(obj, api.EventTypeNormal, fmt.Sprintf("Successful%v", reason), msg) + p.recorder.Eventf(obj, v1.EventTypeNormal, fmt.Sprintf("Successful%v", reason), msg) } } // petHealthChecker is an interface to check pet health. It makes a boolean // decision based on the given pod. type petHealthChecker interface { - isHealthy(*api.Pod) bool - isDying(*api.Pod) bool + isHealthy(*v1.Pod) bool + isDying(*v1.Pod) bool } // defaultPetHealthChecks does basic health checking. @@ -299,11 +299,11 @@ type defaultPetHealthChecker struct{} // isHealthy returns true if the pod is ready & running. If the pod has the // "pod.alpha.kubernetes.io/initialized" annotation set to "false", pod state is ignored. -func (d *defaultPetHealthChecker) isHealthy(pod *api.Pod) bool { - if pod == nil || pod.Status.Phase != api.PodRunning { +func (d *defaultPetHealthChecker) isHealthy(pod *v1.Pod) bool { + if pod == nil || pod.Status.Phase != v1.PodRunning { return false } - podReady := api.IsPodReady(pod) + podReady := v1.IsPodReady(pod) // User may have specified a pod readiness override through a debug annotation. initialized, ok := pod.Annotations[StatefulSetInitAnnotation] @@ -321,6 +321,6 @@ func (d *defaultPetHealthChecker) isHealthy(pod *api.Pod) bool { // isDying returns true if the pod has a non-nil deletion timestamp. Since the // timestamp can only decrease, once this method returns true for a given pet, it // will never return false. -func (d *defaultPetHealthChecker) isDying(pod *api.Pod) bool { +func (d *defaultPetHealthChecker) isDying(pod *v1.Pod) bool { return pod != nil && pod.DeletionTimestamp != nil } diff --git a/pkg/controller/petset/pet_set.go b/pkg/controller/petset/pet_set.go index 141a3b541bc..b93d8ed8c41 100644 --- a/pkg/controller/petset/pet_set.go +++ b/pkg/controller/petset/pet_set.go @@ -22,12 +22,12 @@ import ( "sort" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/apps" + "k8s.io/kubernetes/pkg/api/v1" + apps "k8s.io/kubernetes/pkg/apis/apps/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller" @@ -52,7 +52,7 @@ const ( // StatefulSetController controls statefulsets. type StatefulSetController struct { - kubeClient internalclientset.Interface + kubeClient clientset.Interface // newSyncer returns an interface capable of syncing a single pet. // Abstracted out for testing. @@ -83,11 +83,11 @@ type StatefulSetController struct { } // NewStatefulSetController creates a new statefulset controller. -func NewStatefulSetController(podInformer cache.SharedIndexInformer, kubeClient internalclientset.Interface, resyncPeriod time.Duration) *StatefulSetController { +func NewStatefulSetController(podInformer cache.SharedIndexInformer, kubeClient clientset.Interface, resyncPeriod time.Duration) *StatefulSetController { eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(glog.Infof) - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) - recorder := eventBroadcaster.NewRecorder(api.EventSource{Component: "statefulset"}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.Core().Events("")}) + recorder := eventBroadcaster.NewRecorder(v1.EventSource{Component: "statefulset"}) pc := &apiServerPetClient{kubeClient, recorder, &defaultPetHealthChecker{}} psc := &StatefulSetController{ @@ -112,11 +112,11 @@ func NewStatefulSetController(podInformer cache.SharedIndexInformer, kubeClient psc.psStore.Store, psc.psController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return psc.kubeClient.Apps().StatefulSets(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return psc.kubeClient.Apps().StatefulSets(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return psc.kubeClient.Apps().StatefulSets(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return psc.kubeClient.Apps().StatefulSets(v1.NamespaceAll).Watch(options) }, }, &apps.StatefulSet{}, @@ -156,7 +156,7 @@ func (psc *StatefulSetController) Run(workers int, stopCh <-chan struct{}) { // addPod adds the statefulset for the pod to the sync queue func (psc *StatefulSetController) addPod(obj interface{}) { - pod := obj.(*api.Pod) + pod := obj.(*v1.Pod) glog.V(4).Infof("Pod %s created, labels: %+v", pod.Name, pod.Labels) ps := psc.getStatefulSetForPod(pod) if ps == nil { @@ -168,8 +168,8 @@ func (psc *StatefulSetController) addPod(obj interface{}) { // updatePod adds the statefulset for the current and old pods to the sync queue. // If the labels of the pod didn't change, this method enqueues a single statefulset. func (psc *StatefulSetController) updatePod(old, cur interface{}) { - curPod := cur.(*api.Pod) - oldPod := old.(*api.Pod) + curPod := cur.(*v1.Pod) + oldPod := old.(*v1.Pod) if curPod.ResourceVersion == oldPod.ResourceVersion { // Periodic resync will send update events for all known pods. // Two different versions of the same pod will always have different RVs. @@ -189,7 +189,7 @@ func (psc *StatefulSetController) updatePod(old, cur interface{}) { // deletePod enqueues the statefulset for the pod accounting for deletion tombstones. func (psc *StatefulSetController) deletePod(obj interface{}) { - pod, ok := obj.(*api.Pod) + pod, ok := obj.(*v1.Pod) // When a delete is dropped, the relist will notice a pod in the store not // in the list, leading to the insertion of a tombstone object which contains @@ -201,7 +201,7 @@ func (psc *StatefulSetController) deletePod(obj interface{}) { glog.Errorf("couldn't get object from tombstone %+v", obj) return } - pod, ok = tombstone.Obj.(*api.Pod) + pod, ok = tombstone.Obj.(*v1.Pod) if !ok { glog.Errorf("tombstone contained object that is not a pod %+v", obj) return @@ -214,18 +214,18 @@ func (psc *StatefulSetController) deletePod(obj interface{}) { } // getPodsForStatefulSets returns the pods that match the selectors of the given statefulset. -func (psc *StatefulSetController) getPodsForStatefulSet(ps *apps.StatefulSet) ([]*api.Pod, error) { +func (psc *StatefulSetController) getPodsForStatefulSet(ps *apps.StatefulSet) ([]*v1.Pod, error) { // TODO: Do we want the statefulset to fight with RCs? check parent statefulset annoation, or name prefix? sel, err := unversioned.LabelSelectorAsSelector(ps.Spec.Selector) if err != nil { - return []*api.Pod{}, err + return []*v1.Pod{}, err } pods, err := psc.podStore.Pods(ps.Namespace).List(sel) if err != nil { - return []*api.Pod{}, err + return []*v1.Pod{}, err } // TODO: Do we need to copy? - result := make([]*api.Pod, 0, len(pods)) + result := make([]*v1.Pod, 0, len(pods)) for i := range pods { result = append(result, &(*pods[i])) } @@ -233,7 +233,7 @@ func (psc *StatefulSetController) getPodsForStatefulSet(ps *apps.StatefulSet) ([ } // getStatefulSetForPod returns the pet set managing the given pod. -func (psc *StatefulSetController) getStatefulSetForPod(pod *api.Pod) *apps.StatefulSet { +func (psc *StatefulSetController) getStatefulSetForPod(pod *v1.Pod) *apps.StatefulSet { ps, err := psc.psStore.GetPodStatefulSets(pod) if err != nil { glog.V(4).Infof("No StatefulSets found for pod %v, StatefulSet controller will avoid syncing", pod.Name) @@ -320,7 +320,7 @@ func (psc *StatefulSetController) Sync(key string) error { } // syncStatefulSet syncs a tuple of (statefulset, pets). -func (psc *StatefulSetController) syncStatefulSet(ps *apps.StatefulSet, pets []*api.Pod) (int, error) { +func (psc *StatefulSetController) syncStatefulSet(ps *apps.StatefulSet, pets []*v1.Pod) (int, error) { glog.V(2).Infof("Syncing StatefulSet %v/%v with %d pods", ps.Namespace, ps.Name, len(pets)) it := NewStatefulSetIterator(ps, pets) diff --git a/pkg/controller/petset/pet_set_test.go b/pkg/controller/petset/pet_set_test.go index da98e6e955a..db19c46f588 100644 --- a/pkg/controller/petset/pet_set_test.go +++ b/pkg/controller/petset/pet_set_test.go @@ -22,12 +22,12 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/apps" + "k8s.io/kubernetes/pkg/api/v1" + apps "k8s.io/kubernetes/pkg/apis/apps/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - fake_internal "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/apps/internalversion" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/apps/internalversion/fake" + fake_internal "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/apps/v1beta1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/apps/v1beta1/fake" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/util/errors" ) @@ -50,7 +50,7 @@ func checkPets(ps *apps.StatefulSet, creates, deletes int, fc *fakePetClient, t if fc.petsCreated != creates || fc.petsDeleted != deletes { t.Errorf("Found (creates: %d, deletes: %d), expected (creates: %d, deletes: %d)", fc.petsCreated, fc.petsDeleted, creates, deletes) } - gotClaims := map[string]api.PersistentVolumeClaim{} + gotClaims := map[string]v1.PersistentVolumeClaim{} for _, pvc := range fc.claims { gotClaims[pvc.Name] = pvc } @@ -88,7 +88,7 @@ func scaleStatefulSet(t *testing.T, ps *apps.StatefulSet, psc *StatefulSetContro } func saturateStatefulSet(t *testing.T, ps *apps.StatefulSet, psc *StatefulSetController, fc *fakePetClient) { - err := scaleStatefulSet(t, ps, psc, fc, int(ps.Spec.Replicas)) + err := scaleStatefulSet(t, ps, psc, fc, int(*(ps.Spec.Replicas))) if err != nil { t.Errorf("Error scaleStatefulSet: %v", err) } @@ -119,7 +119,7 @@ func TestStatefulSetControllerDeletes(t *testing.T) { // Drain errs := []error{} - ps.Spec.Replicas = 0 + *(ps.Spec.Replicas) = 0 knownPods := fc.getPodList() for i := replicas - 1; i >= 0; i-- { if len(fc.pets) != i+1 { @@ -143,7 +143,7 @@ func TestStatefulSetControllerRespectsTermination(t *testing.T) { saturateStatefulSet(t, ps, psc, fc) fc.setDeletionTimestamp(replicas - 1) - ps.Spec.Replicas = 2 + *(ps.Spec.Replicas) = 2 _, err := psc.syncStatefulSet(ps, fc.getPodList()) if err != nil { t.Errorf("Error syncing StatefulSet: %v", err) @@ -169,7 +169,7 @@ func TestStatefulSetControllerRespectsOrder(t *testing.T) { saturateStatefulSet(t, ps, psc, fc) errs := []error{} - ps.Spec.Replicas = 0 + *(ps.Spec.Replicas) = 0 // Shuffle known list and check that pets are deleted in reverse knownPods := fc.getPodList() for i := range knownPods { @@ -285,16 +285,16 @@ type fakeClient struct { statefulsetClient *fakeStatefulSetClient } -func (c *fakeClient) Apps() internalversion.AppsInterface { - return &fakeApps{c, &fake.FakeApps{}} +func (c *fakeClient) Apps() v1beta1.AppsV1beta1Interface { + return &fakeApps{c, &fake.FakeAppsV1beta1{}} } type fakeApps struct { *fakeClient - *fake.FakeApps + *fake.FakeAppsV1beta1 } -func (c *fakeApps) StatefulSets(namespace string) internalversion.StatefulSetInterface { +func (c *fakeApps) StatefulSets(namespace string) v1beta1.StatefulSetInterface { c.statefulsetClient.Namespace = namespace return c.statefulsetClient } diff --git a/pkg/controller/petset/pet_set_utils.go b/pkg/controller/petset/pet_set_utils.go index 7775115148c..343f294404a 100644 --- a/pkg/controller/petset/pet_set_utils.go +++ b/pkg/controller/petset/pet_set_utils.go @@ -20,10 +20,10 @@ import ( "fmt" "sync" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/apps" + "k8s.io/kubernetes/pkg/api/v1" + apps "k8s.io/kubernetes/pkg/apis/apps/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - appsclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/apps/internalversion" + appsclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/apps/v1beta1" "k8s.io/kubernetes/pkg/controller" "github.com/golang/glog" @@ -51,7 +51,7 @@ func updatePetCount(psClient appsclientset.StatefulSetsGetter, ps apps.StatefulS var getErr error for i, ps := 0, &ps; ; i++ { glog.V(4).Infof(fmt.Sprintf("Updating replica count for StatefulSet: %s/%s, ", ps.Namespace, ps.Name) + - fmt.Sprintf("replicas %d->%d (need %d), ", ps.Status.Replicas, numPets, ps.Spec.Replicas)) + fmt.Sprintf("replicas %d->%d (need %d), ", ps.Status.Replicas, numPets, *(ps.Spec.Replicas))) ps.Status = apps.StatefulSetStatus{Replicas: int32(numPets)} _, updateErr = psClient.StatefulSets(ps.Namespace).UpdateStatus(ps) @@ -72,7 +72,7 @@ type unhealthyPetTracker struct { } // Get returns a previously recorded blocking pet for the given statefulset. -func (u *unhealthyPetTracker) Get(ps *apps.StatefulSet, knownPets []*api.Pod) (*pcb, error) { +func (u *unhealthyPetTracker) Get(ps *apps.StatefulSet, knownPets []*v1.Pod) (*pcb, error) { u.storeLock.Lock() defer u.storeLock.Unlock() diff --git a/pkg/controller/petset/pet_test.go b/pkg/controller/petset/pet_test.go index 5064ce1902d..dcdb5e5bc31 100644 --- a/pkg/controller/petset/pet_test.go +++ b/pkg/controller/petset/pet_test.go @@ -21,11 +21,11 @@ import ( "net/http/httptest" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/testapi" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/runtime" @@ -39,10 +39,10 @@ func newPetClient(client *clientset.Clientset) *apiServerPetClient { } func makeTwoDifferntPCB() (pcb1, pcb2 *pcb) { - userAdded := api.Volume{ + userAdded := v1.Volume{ Name: "test", - VolumeSource: api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{Medium: api.StorageMediumMemory}, + VolumeSource: v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{Medium: v1.StorageMediumMemory}, }, } ps := newStatefulSet(2) @@ -88,14 +88,14 @@ func TestUpdatePetWithoutRetry(t *testing.T) { } for k, tc := range testCases { - body := runtime.EncodeOrDie(testapi.Default.Codec(), &api.Pod{ObjectMeta: api.ObjectMeta{Name: "empty_pod"}}) + body := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "empty_pod"}}) fakeHandler := utiltesting.FakeHandler{ StatusCode: 200, ResponseBody: string(body), } testServer := httptest.NewServer(&fakeHandler) - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) petClient := newPetClient(client) err := petClient.Update(tc.realPet, tc.expectedPet) @@ -115,7 +115,7 @@ func TestUpdatePetWithFailure(t *testing.T) { testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) petClient := newPetClient(client) pcb1, pcb2 := makeTwoDifferntPCB() diff --git a/pkg/controller/podautoscaler/BUILD b/pkg/controller/podautoscaler/BUILD index f14b2566863..e9e260b0162 100644 --- a/pkg/controller/podautoscaler/BUILD +++ b/pkg/controller/podautoscaler/BUILD @@ -19,15 +19,15 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/autoscaling:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/autoscaling/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/autoscaling/internalversion:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/autoscaling/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/controller/podautoscaler/metrics:go_default_library", "//pkg/labels:go_default_library", @@ -48,15 +48,14 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/apis/autoscaling:go_default_library", - "//pkg/apis/extensions:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/apis/autoscaling/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/testing/core:go_default_library", diff --git a/pkg/controller/podautoscaler/horizontal.go b/pkg/controller/podautoscaler/horizontal.go index b5e7ab38764..55796952672 100644 --- a/pkg/controller/podautoscaler/horizontal.go +++ b/pkg/controller/podautoscaler/horizontal.go @@ -23,15 +23,15 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/autoscaling" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + autoscaling "k8s.io/kubernetes/pkg/apis/autoscaling/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - unversionedautoscaling "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/internalversion" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" - unversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion" + unversionedautoscaling "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/autoscaling/v1" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" + unversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/runtime" utilruntime "k8s.io/kubernetes/pkg/util/runtime" @@ -75,11 +75,11 @@ var upscaleForbiddenWindow = 3 * time.Minute func newInformer(controller *HorizontalController, resyncPeriod time.Duration) (cache.Store, *cache.Controller) { return cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return controller.hpaNamespacer.HorizontalPodAutoscalers(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return controller.hpaNamespacer.HorizontalPodAutoscalers(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return controller.hpaNamespacer.HorizontalPodAutoscalers(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return controller.hpaNamespacer.HorizontalPodAutoscalers(v1.NamespaceAll).Watch(options) }, }, &autoscaling.HorizontalPodAutoscaler{}, @@ -90,7 +90,7 @@ func newInformer(controller *HorizontalController, resyncPeriod time.Duration) ( hasCPUPolicy := hpa.Spec.TargetCPUUtilizationPercentage != nil _, hasCustomMetricsPolicy := hpa.Annotations[HpaCustomMetricsTargetAnnotationName] if !hasCPUPolicy && !hasCustomMetricsPolicy { - controller.eventRecorder.Event(hpa, api.EventTypeNormal, "DefaultPolicy", "No scaling policy specified - will use default one. See documentation for details") + controller.eventRecorder.Event(hpa, v1.EventTypeNormal, "DefaultPolicy", "No scaling policy specified - will use default one. See documentation for details") } err := controller.reconcileAutoscaler(hpa) if err != nil { @@ -109,10 +109,10 @@ func newInformer(controller *HorizontalController, resyncPeriod time.Duration) ( ) } -func NewHorizontalController(evtNamespacer unversionedcore.EventsGetter, scaleNamespacer unversionedextensions.ScalesGetter, hpaNamespacer unversionedautoscaling.HorizontalPodAutoscalersGetter, replicaCalc *ReplicaCalculator, resyncPeriod time.Duration) *HorizontalController { +func NewHorizontalController(evtNamespacer v1core.EventsGetter, scaleNamespacer unversionedextensions.ScalesGetter, hpaNamespacer unversionedautoscaling.HorizontalPodAutoscalersGetter, replicaCalc *ReplicaCalculator, resyncPeriod time.Duration) *HorizontalController { broadcaster := record.NewBroadcaster() - broadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: evtNamespacer.Events("")}) - recorder := broadcaster.NewRecorder(api.EventSource{Component: "horizontal-pod-autoscaler"}) + broadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: evtNamespacer.Events("")}) + recorder := broadcaster.NewRecorder(v1.EventSource{Component: "horizontal-pod-autoscaler"}) controller := &HorizontalController{ replicaCalc: replicaCalc, @@ -153,31 +153,31 @@ func (a *HorizontalController) computeReplicasForCPUUtilization(hpa *autoscaling if scale.Status.Selector == nil { errMsg := "selector is required" - a.eventRecorder.Event(hpa, api.EventTypeWarning, "SelectorRequired", errMsg) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "SelectorRequired", errMsg) return 0, nil, time.Time{}, fmt.Errorf(errMsg) } - selector, err := unversioned.LabelSelectorAsSelector(scale.Status.Selector) + selector, err := unversioned.LabelSelectorAsSelector(&unversioned.LabelSelector{MatchLabels: scale.Status.Selector}) if err != nil { errMsg := fmt.Sprintf("couldn't convert selector string to a corresponding selector object: %v", err) - a.eventRecorder.Event(hpa, api.EventTypeWarning, "InvalidSelector", errMsg) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "InvalidSelector", errMsg) return 0, nil, time.Time{}, fmt.Errorf(errMsg) } - desiredReplicas, utilization, timestamp, err := a.replicaCalc.GetResourceReplicas(currentReplicas, targetUtilization, api.ResourceCPU, hpa.Namespace, selector) + desiredReplicas, utilization, timestamp, err := a.replicaCalc.GetResourceReplicas(currentReplicas, targetUtilization, v1.ResourceCPU, hpa.Namespace, selector) if err != nil { lastScaleTime := getLastScaleTime(hpa) if time.Now().After(lastScaleTime.Add(upscaleForbiddenWindow)) { - a.eventRecorder.Event(hpa, api.EventTypeWarning, "FailedGetMetrics", err.Error()) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetMetrics", err.Error()) } else { - a.eventRecorder.Event(hpa, api.EventTypeNormal, "MetricsNotAvailableYet", err.Error()) + a.eventRecorder.Event(hpa, v1.EventTypeNormal, "MetricsNotAvailableYet", err.Error()) } return 0, nil, time.Time{}, fmt.Errorf("failed to get CPU utilization: %v", err) } if desiredReplicas != currentReplicas { - a.eventRecorder.Eventf(hpa, api.EventTypeNormal, "DesiredReplicasComputed", + a.eventRecorder.Eventf(hpa, v1.EventTypeNormal, "DesiredReplicasComputed", "Computed the desired num of replicas: %d (avgCPUutil: %d, current replicas: %d)", desiredReplicas, utilization, scale.Status.Replicas) } @@ -201,11 +201,11 @@ func (a *HorizontalController) computeReplicasForCustomMetrics(hpa *autoscaling. var targetList extensions.CustomMetricTargetList if err := json.Unmarshal([]byte(cmAnnotation), &targetList); err != nil { - a.eventRecorder.Event(hpa, api.EventTypeWarning, "FailedParseCustomMetricsAnnotation", err.Error()) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedParseCustomMetricsAnnotation", err.Error()) return 0, "", "", time.Time{}, fmt.Errorf("failed to parse custom metrics annotation: %v", err) } if len(targetList.Items) == 0 { - a.eventRecorder.Event(hpa, api.EventTypeWarning, "NoCustomMetricsInAnnotation", err.Error()) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "NoCustomMetricsInAnnotation", err.Error()) return 0, "", "", time.Time{}, fmt.Errorf("no custom metrics in annotation") } @@ -216,14 +216,14 @@ func (a *HorizontalController) computeReplicasForCustomMetrics(hpa *autoscaling. for _, customMetricTarget := range targetList.Items { if scale.Status.Selector == nil { errMsg := "selector is required" - a.eventRecorder.Event(hpa, api.EventTypeWarning, "SelectorRequired", errMsg) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "SelectorRequired", errMsg) return 0, "", "", time.Time{}, fmt.Errorf("selector is required") } - selector, err := unversioned.LabelSelectorAsSelector(scale.Status.Selector) + selector, err := unversioned.LabelSelectorAsSelector(&unversioned.LabelSelector{MatchLabels: scale.Status.Selector}) if err != nil { errMsg := fmt.Sprintf("couldn't convert selector string to a corresponding selector object: %v", err) - a.eventRecorder.Event(hpa, api.EventTypeWarning, "InvalidSelector", errMsg) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "InvalidSelector", errMsg) return 0, "", "", time.Time{}, fmt.Errorf("couldn't convert selector string to a corresponding selector object: %v", err) } floatTarget := float64(customMetricTarget.TargetValue.MilliValue()) / 1000.0 @@ -231,9 +231,9 @@ func (a *HorizontalController) computeReplicasForCustomMetrics(hpa *autoscaling. if err != nil { lastScaleTime := getLastScaleTime(hpa) if time.Now().After(lastScaleTime.Add(upscaleForbiddenWindow)) { - a.eventRecorder.Event(hpa, api.EventTypeWarning, "FailedGetCustomMetrics", err.Error()) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetCustomMetrics", err.Error()) } else { - a.eventRecorder.Event(hpa, api.EventTypeNormal, "CustomMetricsNotAvailableYet", err.Error()) + a.eventRecorder.Event(hpa, v1.EventTypeNormal, "CustomMetricsNotAvailableYet", err.Error()) } return 0, "", "", time.Time{}, fmt.Errorf("failed to get custom metric value: %v", err) @@ -246,7 +246,7 @@ func (a *HorizontalController) computeReplicasForCustomMetrics(hpa *autoscaling. } quantity, err := resource.ParseQuantity(fmt.Sprintf("%.3f", utilizationProposal)) if err != nil { - a.eventRecorder.Event(hpa, api.EventTypeWarning, "FailedSetCustomMetrics", err.Error()) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedSetCustomMetrics", err.Error()) return 0, "", "", time.Time{}, fmt.Errorf("failed to set custom metric value: %v", err) } statusList.Items = append(statusList.Items, extensions.CustomMetricCurrentStatus{ @@ -256,14 +256,14 @@ func (a *HorizontalController) computeReplicasForCustomMetrics(hpa *autoscaling. } byteStatusList, err := json.Marshal(statusList) if err != nil { - a.eventRecorder.Event(hpa, api.EventTypeWarning, "FailedSerializeCustomMetrics", err.Error()) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedSerializeCustomMetrics", err.Error()) return 0, "", "", time.Time{}, fmt.Errorf("failed to serialize custom metric status: %v", err) } if replicas != currentReplicas { - a.eventRecorder.Eventf(hpa, api.EventTypeNormal, "DesiredReplicasComputedCustomMetric", + a.eventRecorder.Eventf(hpa, v1.EventTypeNormal, "DesiredReplicasComputedCustomMetric", "Computed the desired num of replicas: %d, metric: %s, current replicas: %d", - int32(replicas), metric, scale.Status.Replicas) + func() *int32 { i := int32(replicas); return &i }(), metric, scale.Status.Replicas) } return replicas, metric, string(byteStatusList), timestamp, nil @@ -274,7 +274,7 @@ func (a *HorizontalController) reconcileAutoscaler(hpa *autoscaling.HorizontalPo scale, err := a.scaleNamespacer.Scales(hpa.Namespace).Get(hpa.Spec.ScaleTargetRef.Kind, hpa.Spec.ScaleTargetRef.Name) if err != nil { - a.eventRecorder.Event(hpa, api.EventTypeWarning, "FailedGetScale", err.Error()) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetScale", err.Error()) return fmt.Errorf("failed to query scale subresource for %s: %v", reference, err) } currentReplicas := scale.Status.Replicas @@ -367,10 +367,10 @@ func (a *HorizontalController) reconcileAutoscaler(hpa *autoscaling.HorizontalPo scale.Spec.Replicas = desiredReplicas _, err = a.scaleNamespacer.Scales(hpa.Namespace).Update(hpa.Spec.ScaleTargetRef.Kind, scale) if err != nil { - a.eventRecorder.Eventf(hpa, api.EventTypeWarning, "FailedRescale", "New size: %d; reason: %s; error: %v", desiredReplicas, rescaleReason, err.Error()) + a.eventRecorder.Eventf(hpa, v1.EventTypeWarning, "FailedRescale", "New size: %d; reason: %s; error: %v", desiredReplicas, rescaleReason, err.Error()) return fmt.Errorf("failed to rescale %s: %v", reference, err) } - a.eventRecorder.Eventf(hpa, api.EventTypeNormal, "SuccessfulRescale", "New size: %d; reason: %s", desiredReplicas, rescaleReason) + a.eventRecorder.Eventf(hpa, v1.EventTypeNormal, "SuccessfulRescale", "New size: %d; reason: %s", desiredReplicas, rescaleReason) glog.Infof("Successfull rescale of %s, old size: %d, new size: %d, reason: %s", hpa.Name, currentReplicas, desiredReplicas, rescaleReason) } else { @@ -428,7 +428,7 @@ func (a *HorizontalController) updateStatus(hpa *autoscaling.HorizontalPodAutosc _, err := a.hpaNamespacer.HorizontalPodAutoscalers(hpa.Namespace).UpdateStatus(hpa) if err != nil { - a.eventRecorder.Event(hpa, api.EventTypeWarning, "FailedUpdateStatus", err.Error()) + a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedUpdateStatus", err.Error()) return fmt.Errorf("failed to update status for %s: %v", hpa.Name, err) } glog.V(2).Infof("Successfully updated status for %s", hpa.Name) diff --git a/pkg/controller/podautoscaler/horizontal_test.go b/pkg/controller/podautoscaler/horizontal_test.go index 0652a4d8ba0..53ecbcdf9d3 100644 --- a/pkg/controller/podautoscaler/horizontal_test.go +++ b/pkg/controller/podautoscaler/horizontal_test.go @@ -27,15 +27,14 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" _ "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/autoscaling" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + autoscaling "k8s.io/kubernetes/pkg/apis/autoscaling/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/testing/core" @@ -84,7 +83,7 @@ type testCase struct { verifyCPUCurrent bool reportedLevels []uint64 reportedCPURequests []resource.Quantity - reportedPodReadiness []api.ConditionStatus + reportedPodReadiness []v1.ConditionStatus cmTarget *extensions.CustomMetricTargetList scaleUpdated bool statusUpdated bool @@ -151,7 +150,7 @@ func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset { obj := &autoscaling.HorizontalPodAutoscalerList{ Items: []autoscaling.HorizontalPodAutoscaler{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: hpaName, Namespace: namespace, SelfLink: "experimental/v1/namespaces/" + namespace + "/horizontalpodautoscalers/" + hpaName, @@ -192,7 +191,7 @@ func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset { defer tc.Unlock() obj := &extensions.Scale{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: tc.resource.name, Namespace: namespace, }, @@ -201,7 +200,7 @@ func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset { }, Status: extensions.ScaleStatus{ Replicas: tc.initialReplicas, - Selector: selector, + Selector: selector.MatchLabels, }, } return true, obj, nil @@ -212,7 +211,7 @@ func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset { defer tc.Unlock() obj := &extensions.Scale{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: tc.resource.name, Namespace: namespace, }, @@ -221,7 +220,7 @@ func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset { }, Status: extensions.ScaleStatus{ Replicas: tc.initialReplicas, - Selector: selector, + Selector: selector.MatchLabels, }, } return true, obj, nil @@ -232,7 +231,7 @@ func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset { defer tc.Unlock() obj := &extensions.Scale{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: tc.resource.name, Namespace: namespace, }, @@ -241,7 +240,7 @@ func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset { }, Status: extensions.ScaleStatus{ Replicas: tc.initialReplicas, - Selector: selector, + Selector: selector.MatchLabels, }, } return true, obj, nil @@ -251,36 +250,36 @@ func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset { tc.Lock() defer tc.Unlock() - obj := &api.PodList{} + obj := &v1.PodList{} for i := 0; i < len(tc.reportedCPURequests); i++ { - podReadiness := api.ConditionTrue + podReadiness := v1.ConditionTrue if tc.reportedPodReadiness != nil { podReadiness = tc.reportedPodReadiness[i] } podName := fmt.Sprintf("%s-%d", podNamePrefix, i) - pod := api.Pod{ - Status: api.PodStatus{ - Phase: api.PodRunning, - Conditions: []api.PodCondition{ + pod := v1.Pod{ + Status: v1.PodStatus{ + Phase: v1.PodRunning, + Conditions: []v1.PodCondition{ { - Type: api.PodReady, + Type: v1.PodReady, Status: podReadiness, }, }, }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Namespace: namespace, Labels: map[string]string{ "name": podNamePrefix, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceCPU: tc.reportedCPURequests[i], + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceCPU: tc.reportedCPURequests[i], }, }, }, @@ -420,7 +419,7 @@ func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset { tc.Lock() defer tc.Unlock() - obj := action.(core.CreateAction).GetObject().(*api.Event) + obj := action.(core.CreateAction).GetObject().(*v1.Event) if tc.verifyEvents { switch obj.Reason { case "SuccessfulRescale": @@ -460,8 +459,8 @@ func (tc *testCase) runTest(t *testing.T) { metricsClient := metrics.NewHeapsterMetricsClient(testClient, metrics.DefaultHeapsterNamespace, metrics.DefaultHeapsterScheme, metrics.DefaultHeapsterService, metrics.DefaultHeapsterPort) broadcaster := record.NewBroadcasterForTests(0) - broadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: testClient.Core().Events("")}) - recorder := broadcaster.NewRecorder(api.EventSource{Component: "horizontal-pod-autoscaler"}) + broadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: testClient.Core().Events("")}) + recorder := broadcaster.NewRecorder(v1.EventSource{Component: "horizontal-pod-autoscaler"}) replicaCalc := &ReplicaCalculator{ metricsClient: metricsClient, @@ -574,7 +573,7 @@ func TestScaleUpUnreadyLessScale(t *testing.T) { verifyCPUCurrent: true, reportedLevels: []uint64{300, 500, 700}, reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, - reportedPodReadiness: []api.ConditionStatus{api.ConditionFalse, api.ConditionTrue, api.ConditionTrue}, + reportedPodReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue}, useMetricsApi: true, } tc.runTest(t) @@ -591,7 +590,7 @@ func TestScaleUpUnreadyNoScale(t *testing.T) { verifyCPUCurrent: true, reportedLevels: []uint64{400, 500, 700}, reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, - reportedPodReadiness: []api.ConditionStatus{api.ConditionTrue, api.ConditionFalse, api.ConditionFalse}, + reportedPodReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse}, useMetricsApi: true, } tc.runTest(t) @@ -670,7 +669,7 @@ func TestScaleUpCMUnreadyLessScale(t *testing.T) { }}, }, reportedLevels: []uint64{50, 10, 30}, - reportedPodReadiness: []api.ConditionStatus{api.ConditionTrue, api.ConditionTrue, api.ConditionFalse}, + reportedPodReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse}, reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, } tc.runTest(t) @@ -690,7 +689,7 @@ func TestScaleUpCMUnreadyNoScaleWouldScaleDown(t *testing.T) { }}, }, reportedLevels: []uint64{50, 15, 30}, - reportedPodReadiness: []api.ConditionStatus{api.ConditionFalse, api.ConditionTrue, api.ConditionFalse}, + reportedPodReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionFalse}, reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, } tc.runTest(t) @@ -755,7 +754,7 @@ func TestScaleDownIgnoresUnreadyPods(t *testing.T) { reportedLevels: []uint64{100, 300, 500, 250, 250}, reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, useMetricsApi: true, - reportedPodReadiness: []api.ConditionStatus{api.ConditionTrue, api.ConditionTrue, api.ConditionTrue, api.ConditionFalse, api.ConditionFalse}, + reportedPodReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse}, } tc.runTest(t) } diff --git a/pkg/controller/podautoscaler/metrics/BUILD b/pkg/controller/podautoscaler/metrics/BUILD index 71421ab3172..6d663f224ed 100644 --- a/pkg/controller/podautoscaler/metrics/BUILD +++ b/pkg/controller/podautoscaler/metrics/BUILD @@ -18,10 +18,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/v1:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/labels:go_default_library", "//vendor:github.com/golang/glog", "//vendor:k8s.io/heapster/metrics/api/v1/types", @@ -35,12 +34,11 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/labels:go_default_library", diff --git a/pkg/controller/podautoscaler/metrics/metrics_client.go b/pkg/controller/podautoscaler/metrics/metrics_client.go index 623a8fce2cb..807df5d3ee9 100644 --- a/pkg/controller/podautoscaler/metrics/metrics_client.go +++ b/pkg/controller/podautoscaler/metrics/metrics_client.go @@ -23,10 +23,9 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/v1" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/labels" heapster "k8s.io/heapster/metrics/api/v1/types" @@ -46,7 +45,7 @@ type PodMetricsInfo map[string]float64 type MetricsClient interface { // GetResourceMetric gets the given resource metric (and an associated oldest timestamp) // for all pods matching the specified selector in the given namespace - GetResourceMetric(resource api.ResourceName, namespace string, selector labels.Selector) (PodResourceInfo, time.Time, error) + GetResourceMetric(resource v1.ResourceName, namespace string, selector labels.Selector) (PodResourceInfo, time.Time, error) // GetRawMetric gets the given metric (and an associated oldest timestamp) // for all pods matching the specified selector in the given namespace @@ -63,8 +62,8 @@ const ( var heapsterQueryStart = -5 * time.Minute type HeapsterMetricsClient struct { - services unversionedcore.ServiceInterface - podsGetter unversionedcore.PodsGetter + services v1core.ServiceInterface + podsGetter v1core.PodsGetter heapsterScheme string heapsterService string heapsterPort string @@ -80,7 +79,7 @@ func NewHeapsterMetricsClient(client clientset.Interface, namespace, scheme, ser } } -func (h *HeapsterMetricsClient) GetResourceMetric(resource api.ResourceName, namespace string, selector labels.Selector) (PodResourceInfo, time.Time, error) { +func (h *HeapsterMetricsClient) GetResourceMetric(resource v1.ResourceName, namespace string, selector labels.Selector) (PodResourceInfo, time.Time, error) { metricPath := fmt.Sprintf("/apis/metrics/v1alpha1/namespaces/%s/pods", namespace) params := map[string]string{"labelSelector": selector.String()} @@ -132,7 +131,7 @@ func (h *HeapsterMetricsClient) GetResourceMetric(resource api.ResourceName, nam } func (h *HeapsterMetricsClient) GetRawMetric(metricName string, namespace string, selector labels.Selector) (PodMetricsInfo, time.Time, error) { - podList, err := h.podsGetter.Pods(namespace).List(api.ListOptions{LabelSelector: selector}) + podList, err := h.podsGetter.Pods(namespace).List(v1.ListOptions{LabelSelector: selector.String()}) if err != nil { return nil, time.Time{}, fmt.Errorf("failed to get pod list while fetching metrics: %v", err) } diff --git a/pkg/controller/podautoscaler/metrics/metrics_client_test.go b/pkg/controller/podautoscaler/metrics/metrics_client_test.go index 5e3e95a97f9..acabd94acce 100644 --- a/pkg/controller/podautoscaler/metrics/metrics_client_test.go +++ b/pkg/controller/podautoscaler/metrics/metrics_client_test.go @@ -23,12 +23,11 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" _ "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/labels" @@ -76,7 +75,7 @@ type testCase struct { namespace string selector labels.Selector - resourceName api.ResourceName + resourceName v1.ResourceName metricName string } @@ -93,10 +92,10 @@ func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset { fakeClient := &fake.Clientset{} fakeClient.AddReactor("list", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) { - obj := &api.PodList{} + obj := &v1.PodList{} for i := 0; i < tc.replicas; i++ { podName := fmt.Sprintf("%s-%d", podNamePrefix, i) - pod := buildPod(namespace, podName, podLabels, api.PodRunning, "1024") + pod := buildPod(namespace, podName, podLabels, v1.PodRunning, "1024") obj.Items = append(obj.Items, pod) } return true, obj, nil @@ -161,30 +160,30 @@ func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset { return fakeClient } -func buildPod(namespace, podName string, podLabels map[string]string, phase api.PodPhase, request string) api.Pod { - return api.Pod{ - ObjectMeta: api.ObjectMeta{ +func buildPod(namespace, podName string, podLabels map[string]string, phase v1.PodPhase, request string) v1.Pod { + return v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Namespace: namespace, Labels: podLabels, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceCPU: resource.MustParse(request), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse(request), }, }, }, }, }, - Status: api.PodStatus{ + Status: v1.PodStatus{ Phase: phase, - Conditions: []api.PodCondition{ + Conditions: []v1.PodCondition{ { - Type: api.PodReady, - Status: api.ConditionTrue, + Type: v1.PodReady, + Status: v1.ConditionTrue, }, }, }, @@ -231,7 +230,7 @@ func TestCPU(t *testing.T) { desiredResourceValues: PodResourceInfo{ "test-pod-0": 5000, "test-pod-1": 5000, "test-pod-2": 5000, }, - resourceName: api.ResourceCPU, + resourceName: v1.ResourceCPU, targetTimestamp: 1, reportedPodMetrics: [][]int64{{5000}, {5000}, {5000}}, } @@ -271,7 +270,7 @@ func TestCPUMoreMetrics(t *testing.T) { "test-pod-0": 5000, "test-pod-1": 5000, "test-pod-2": 5000, "test-pod-3": 5000, "test-pod-4": 5000, }, - resourceName: api.ResourceCPU, + resourceName: v1.ResourceCPU, targetTimestamp: 10, reportedPodMetrics: [][]int64{{1000, 2000, 2000}, {5000}, {1000, 1000, 1000, 2000}, {4000, 1000}, {5000}}, } @@ -284,7 +283,7 @@ func TestCPUMissingMetrics(t *testing.T) { desiredResourceValues: PodResourceInfo{ "test-pod-0": 4000, }, - resourceName: api.ResourceCPU, + resourceName: v1.ResourceCPU, reportedPodMetrics: [][]int64{{4000}}, } tc.runTest(t) @@ -314,7 +313,7 @@ func TestQpsSuperfluousMetrics(t *testing.T) { func TestCPUEmptyMetrics(t *testing.T) { tc := testCase{ replicas: 3, - resourceName: api.ResourceCPU, + resourceName: v1.ResourceCPU, desiredError: fmt.Errorf("no metrics returned from heapster"), reportedMetricsPoints: [][]metricPoint{}, reportedPodMetrics: [][]int64{}, @@ -338,7 +337,7 @@ func TestQpsEmptyEntries(t *testing.T) { func TestCPUZeroReplicas(t *testing.T) { tc := testCase{ replicas: 0, - resourceName: api.ResourceCPU, + resourceName: v1.ResourceCPU, desiredError: fmt.Errorf("no metrics returned from heapster"), reportedPodMetrics: [][]int64{}, } @@ -348,7 +347,7 @@ func TestCPUZeroReplicas(t *testing.T) { func TestCPUEmptyMetricsForOnePod(t *testing.T) { tc := testCase{ replicas: 3, - resourceName: api.ResourceCPU, + resourceName: v1.ResourceCPU, desiredResourceValues: PodResourceInfo{ "test-pod-0": 100, "test-pod-1": 700, }, diff --git a/pkg/controller/podautoscaler/replica_calculator.go b/pkg/controller/podautoscaler/replica_calculator.go index 1618cbda88f..205d8b1382f 100644 --- a/pkg/controller/podautoscaler/replica_calculator.go +++ b/pkg/controller/podautoscaler/replica_calculator.go @@ -21,8 +21,8 @@ import ( "math" "time" - "k8s.io/kubernetes/pkg/api" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + "k8s.io/kubernetes/pkg/api/v1" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" metricsclient "k8s.io/kubernetes/pkg/controller/podautoscaler/metrics" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/sets" @@ -30,10 +30,10 @@ import ( type ReplicaCalculator struct { metricsClient metricsclient.MetricsClient - podsGetter unversionedcore.PodsGetter + podsGetter v1core.PodsGetter } -func NewReplicaCalculator(metricsClient metricsclient.MetricsClient, podsGetter unversionedcore.PodsGetter) *ReplicaCalculator { +func NewReplicaCalculator(metricsClient metricsclient.MetricsClient, podsGetter v1core.PodsGetter) *ReplicaCalculator { return &ReplicaCalculator{ metricsClient: metricsClient, podsGetter: podsGetter, @@ -42,13 +42,13 @@ func NewReplicaCalculator(metricsClient metricsclient.MetricsClient, podsGetter // GetResourceReplicas calculates the desired replica count based on a target resource utilization percentage // of the given resource for pods matching the given selector in the given namespace, and the current replica count -func (c *ReplicaCalculator) GetResourceReplicas(currentReplicas int32, targetUtilization int32, resource api.ResourceName, namespace string, selector labels.Selector) (replicaCount int32, utilization int32, timestamp time.Time, err error) { +func (c *ReplicaCalculator) GetResourceReplicas(currentReplicas int32, targetUtilization int32, resource v1.ResourceName, namespace string, selector labels.Selector) (replicaCount int32, utilization int32, timestamp time.Time, err error) { metrics, timestamp, err := c.metricsClient.GetResourceMetric(resource, namespace, selector) if err != nil { return 0, 0, time.Time{}, fmt.Errorf("unable to get metrics for resource %s: %v", resource, err) } - podList, err := c.podsGetter.Pods(namespace).List(api.ListOptions{LabelSelector: selector}) + podList, err := c.podsGetter.Pods(namespace).List(v1.ListOptions{LabelSelector: selector.String()}) if err != nil { return 0, 0, time.Time{}, fmt.Errorf("unable to get pods while calculating replica count: %v", err) } @@ -74,7 +74,7 @@ func (c *ReplicaCalculator) GetResourceReplicas(currentReplicas int32, targetUti requests[pod.Name] = podSum - if pod.Status.Phase != api.PodRunning || !api.IsPodReady(&pod) { + if pod.Status.Phase != v1.PodRunning || !v1.IsPodReady(&pod) { // save this pod name for later, but pretend it doesn't exist for now unreadyPods.Insert(pod.Name) delete(metrics, pod.Name) @@ -156,7 +156,7 @@ func (c *ReplicaCalculator) GetMetricReplicas(currentReplicas int32, targetUtili return 0, 0, time.Time{}, fmt.Errorf("unable to get metric %s: %v", metricName, err) } - podList, err := c.podsGetter.Pods(namespace).List(api.ListOptions{LabelSelector: selector}) + podList, err := c.podsGetter.Pods(namespace).List(v1.ListOptions{LabelSelector: selector.String()}) if err != nil { return 0, 0, time.Time{}, fmt.Errorf("unable to get pods while calculating replica count: %v", err) } @@ -170,7 +170,7 @@ func (c *ReplicaCalculator) GetMetricReplicas(currentReplicas int32, targetUtili missingPods := sets.NewString() for _, pod := range podList.Items { - if pod.Status.Phase != api.PodRunning || !api.IsPodReady(&pod) { + if pod.Status.Phase != v1.PodRunning || !v1.IsPodReady(&pod) { // save this pod name for later, but pretend it doesn't exist for now unreadyPods.Insert(pod.Name) delete(metrics, pod.Name) diff --git a/pkg/controller/podautoscaler/replica_calculator_test.go b/pkg/controller/podautoscaler/replica_calculator_test.go index 3defba8fee1..9ccadf983da 100644 --- a/pkg/controller/podautoscaler/replica_calculator_test.go +++ b/pkg/controller/podautoscaler/replica_calculator_test.go @@ -25,12 +25,11 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" _ "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/controller/podautoscaler/metrics" @@ -44,7 +43,7 @@ import ( ) type resourceInfo struct { - name api.ResourceName + name v1.ResourceName requests []resource.Quantity levels []int64 @@ -70,7 +69,7 @@ type replicaCalcTestCase struct { resource *resourceInfo metric *metricInfo - podReadiness []api.ConditionStatus + podReadiness []v1.ConditionStatus } const ( @@ -82,43 +81,43 @@ func (tc *replicaCalcTestCase) prepareTestClient(t *testing.T) *fake.Clientset { fakeClient := &fake.Clientset{} fakeClient.AddReactor("list", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) { - obj := &api.PodList{} + obj := &v1.PodList{} for i := 0; i < int(tc.currentReplicas); i++ { - podReadiness := api.ConditionTrue + podReadiness := v1.ConditionTrue if tc.podReadiness != nil { podReadiness = tc.podReadiness[i] } podName := fmt.Sprintf("%s-%d", podNamePrefix, i) - pod := api.Pod{ - Status: api.PodStatus{ - Phase: api.PodRunning, - Conditions: []api.PodCondition{ + pod := v1.Pod{ + Status: v1.PodStatus{ + Phase: v1.PodRunning, + Conditions: []v1.PodCondition{ { - Type: api.PodReady, + Type: v1.PodReady, Status: podReadiness, }, }, }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Namespace: testNamespace, Labels: map[string]string{ "name": podNamePrefix, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{{}, {}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{}, {}}, }, } if tc.resource != nil && i < len(tc.resource.requests) { - pod.Spec.Containers[0].Resources = api.ResourceRequirements{ - Requests: api.ResourceList{ + pod.Spec.Containers[0].Resources = v1.ResourceRequirements{ + Requests: v1.ResourceList{ tc.resource.name: tc.resource.requests[i], }, } - pod.Spec.Containers[1].Resources = api.ResourceRequirements{ - Requests: api.ResourceList{ + pod.Spec.Containers[1].Resources = v1.ResourceRequirements{ + Requests: v1.ResourceList{ tc.resource.name: tc.resource.requests[i], }, } @@ -255,7 +254,7 @@ func TestReplicaCalcScaleUp(t *testing.T) { currentReplicas: 3, expectedReplicas: 5, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{300, 500, 700}, @@ -270,9 +269,9 @@ func TestReplicaCalcScaleUpUnreadyLessScale(t *testing.T) { tc := replicaCalcTestCase{ currentReplicas: 3, expectedReplicas: 4, - podReadiness: []api.ConditionStatus{api.ConditionFalse, api.ConditionTrue, api.ConditionTrue}, + podReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue}, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{300, 500, 700}, @@ -287,9 +286,9 @@ func TestReplicaCalcScaleUpUnreadyNoScale(t *testing.T) { tc := replicaCalcTestCase{ currentReplicas: 3, expectedReplicas: 3, - podReadiness: []api.ConditionStatus{api.ConditionTrue, api.ConditionFalse, api.ConditionFalse}, + podReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse}, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{400, 500, 700}, @@ -318,7 +317,7 @@ func TestReplicaCalcScaleUpCMUnreadyLessScale(t *testing.T) { tc := replicaCalcTestCase{ currentReplicas: 3, expectedReplicas: 4, - podReadiness: []api.ConditionStatus{api.ConditionTrue, api.ConditionTrue, api.ConditionFalse}, + podReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse}, metric: &metricInfo{ name: "qps", levels: []float64{50.0, 10.0, 30.0}, @@ -333,7 +332,7 @@ func TestReplicaCalcScaleUpCMUnreadyNoScaleWouldScaleDown(t *testing.T) { tc := replicaCalcTestCase{ currentReplicas: 3, expectedReplicas: 3, - podReadiness: []api.ConditionStatus{api.ConditionFalse, api.ConditionTrue, api.ConditionFalse}, + podReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionFalse}, metric: &metricInfo{ name: "qps", levels: []float64{50.0, 15.0, 30.0}, @@ -349,7 +348,7 @@ func TestReplicaCalcScaleDown(t *testing.T) { currentReplicas: 5, expectedReplicas: 3, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{100, 300, 500, 250, 250}, @@ -378,9 +377,9 @@ func TestReplicaCalcScaleDownIgnoresUnreadyPods(t *testing.T) { tc := replicaCalcTestCase{ currentReplicas: 5, expectedReplicas: 2, - podReadiness: []api.ConditionStatus{api.ConditionTrue, api.ConditionTrue, api.ConditionTrue, api.ConditionFalse, api.ConditionFalse}, + podReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse}, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{100, 300, 500, 250, 250}, @@ -396,7 +395,7 @@ func TestReplicaCalcTolerance(t *testing.T) { currentReplicas: 3, expectedReplicas: 3, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("0.9"), resource.MustParse("1.0"), resource.MustParse("1.1")}, levels: []int64{1010, 1030, 1020}, @@ -426,7 +425,7 @@ func TestReplicaCalcSuperfluousMetrics(t *testing.T) { currentReplicas: 4, expectedReplicas: 24, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{4000, 9500, 3000, 7000, 3200, 2000}, targetUtilization: 100, @@ -441,7 +440,7 @@ func TestReplicaCalcMissingMetrics(t *testing.T) { currentReplicas: 4, expectedReplicas: 3, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{400, 95}, @@ -457,7 +456,7 @@ func TestReplicaCalcEmptyMetrics(t *testing.T) { currentReplicas: 4, expectedError: fmt.Errorf("unable to get metrics for resource cpu: no metrics returned from heapster"), resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{}, @@ -472,7 +471,7 @@ func TestReplicaCalcEmptyCPURequest(t *testing.T) { currentReplicas: 1, expectedError: fmt.Errorf("missing request for"), resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{}, levels: []int64{200}, @@ -487,7 +486,7 @@ func TestReplicaCalcMissingMetricsNoChangeEq(t *testing.T) { currentReplicas: 2, expectedReplicas: 2, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{1000}, @@ -503,7 +502,7 @@ func TestReplicaCalcMissingMetricsNoChangeGt(t *testing.T) { currentReplicas: 2, expectedReplicas: 2, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{1900}, @@ -519,7 +518,7 @@ func TestReplicaCalcMissingMetricsNoChangeLt(t *testing.T) { currentReplicas: 2, expectedReplicas: 2, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{600}, @@ -534,9 +533,9 @@ func TestReplicaCalcMissingMetricsUnreadyNoChange(t *testing.T) { tc := replicaCalcTestCase{ currentReplicas: 3, expectedReplicas: 3, - podReadiness: []api.ConditionStatus{api.ConditionFalse, api.ConditionTrue, api.ConditionTrue}, + podReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue}, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{100, 450}, @@ -551,9 +550,9 @@ func TestReplicaCalcMissingMetricsUnreadyScaleUp(t *testing.T) { tc := replicaCalcTestCase{ currentReplicas: 3, expectedReplicas: 4, - podReadiness: []api.ConditionStatus{api.ConditionFalse, api.ConditionTrue, api.ConditionTrue}, + podReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue}, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{100, 2000}, @@ -568,9 +567,9 @@ func TestReplicaCalcMissingMetricsUnreadyScaleDown(t *testing.T) { tc := replicaCalcTestCase{ currentReplicas: 4, expectedReplicas: 3, - podReadiness: []api.ConditionStatus{api.ConditionFalse, api.ConditionTrue, api.ConditionTrue, api.ConditionTrue}, + podReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue}, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")}, levels: []int64{100, 100, 100}, @@ -609,7 +608,7 @@ func TestReplicaCalcComputedToleranceAlgImplementation(t *testing.T) { currentReplicas: startPods, expectedReplicas: finalPods, resource: &resourceInfo{ - name: api.ResourceCPU, + name: v1.ResourceCPU, levels: []int64{ totalUsedCPUOfAllPods / 10, totalUsedCPUOfAllPods / 10, diff --git a/pkg/controller/podgc/BUILD b/pkg/controller/podgc/BUILD index e3e7af3a552..2338a99d3ab 100644 --- a/pkg/controller/podgc/BUILD +++ b/pkg/controller/podgc/BUILD @@ -18,9 +18,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/controller:go_default_library", "//pkg/controller/informers:go_default_library", "//pkg/labels:go_default_library", @@ -39,10 +39,10 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/labels:go_default_library", "//pkg/util/sets:go_default_library", ], diff --git a/pkg/controller/podgc/gc_controller.go b/pkg/controller/podgc/gc_controller.go index 800b942e5c5..e9fb4270ff2 100644 --- a/pkg/controller/podgc/gc_controller.go +++ b/pkg/controller/podgc/gc_controller.go @@ -21,9 +21,9 @@ import ( "sync" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/informers" "k8s.io/kubernetes/pkg/labels" @@ -69,7 +69,7 @@ func NewPodGC(kubeClient clientset.Interface, podInformer cache.SharedIndexInfor terminatedPodThreshold: terminatedPodThreshold, deletePod: func(namespace, name string) error { glog.Infof("PodGC is force deleting Pod: %v:%v", namespace, name) - return kubeClient.Core().Pods(namespace).Delete(name, api.NewDeleteOptions(0)) + return kubeClient.Core().Pods(namespace).Delete(name, v1.NewDeleteOptions(0)) }, } @@ -78,14 +78,14 @@ func NewPodGC(kubeClient clientset.Interface, podInformer cache.SharedIndexInfor gcc.nodeStore.Store, gcc.nodeController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return gcc.kubeClient.Core().Nodes().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return gcc.kubeClient.Core().Nodes().Watch(options) }, }, - &api.Node{}, + &v1.Node{}, controller.NoResyncPeriodFunc(), cache.ResourceEventHandlerFuncs{}, ) @@ -129,15 +129,15 @@ func (gcc *PodGCController) gc() { gcc.gcUnscheduledTerminating(pods) } -func isPodTerminated(pod *api.Pod) bool { - if phase := pod.Status.Phase; phase != api.PodPending && phase != api.PodRunning && phase != api.PodUnknown { +func isPodTerminated(pod *v1.Pod) bool { + if phase := pod.Status.Phase; phase != v1.PodPending && phase != v1.PodRunning && phase != v1.PodUnknown { return true } return false } -func (gcc *PodGCController) gcTerminated(pods []*api.Pod) { - terminatedPods := []*api.Pod{} +func (gcc *PodGCController) gcTerminated(pods []*v1.Pod) { + terminatedPods := []*v1.Pod{} for _, pod := range pods { if isPodTerminated(pod) { terminatedPods = append(terminatedPods, pod) @@ -171,7 +171,7 @@ func (gcc *PodGCController) gcTerminated(pods []*api.Pod) { } // gcOrphaned deletes pods that are bound to nodes that don't exist. -func (gcc *PodGCController) gcOrphaned(pods []*api.Pod) { +func (gcc *PodGCController) gcOrphaned(pods []*v1.Pod) { glog.V(4).Infof("GC'ing orphaned") for _, pod := range pods { @@ -191,7 +191,7 @@ func (gcc *PodGCController) gcOrphaned(pods []*api.Pod) { } // gcUnscheduledTerminating deletes pods that are terminating and haven't been scheduled to a particular node. -func (gcc *PodGCController) gcUnscheduledTerminating(pods []*api.Pod) { +func (gcc *PodGCController) gcUnscheduledTerminating(pods []*v1.Pod) { glog.V(4).Infof("GC'ing unscheduled pods which are terminating.") for _, pod := range pods { @@ -209,7 +209,7 @@ func (gcc *PodGCController) gcUnscheduledTerminating(pods []*api.Pod) { } // byCreationTimestamp sorts a list by creation timestamp, using their names as a tie breaker. -type byCreationTimestamp []*api.Pod +type byCreationTimestamp []*v1.Pod func (o byCreationTimestamp) Len() int { return len(o) } func (o byCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] } diff --git a/pkg/controller/podgc/gc_controller_test.go b/pkg/controller/podgc/gc_controller_test.go index 02558a80eb0..8a98d7f7b47 100644 --- a/pkg/controller/podgc/gc_controller_test.go +++ b/pkg/controller/podgc/gc_controller_test.go @@ -21,10 +21,10 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/sets" ) @@ -40,7 +40,7 @@ func (*FakeController) HasSynced() bool { func TestGCTerminated(t *testing.T) { type nameToPhase struct { name string - phase api.PodPhase + phase v1.PodPhase } testCases := []struct { @@ -50,8 +50,8 @@ func TestGCTerminated(t *testing.T) { }{ { pods: []nameToPhase{ - {name: "a", phase: api.PodFailed}, - {name: "b", phase: api.PodSucceeded}, + {name: "a", phase: v1.PodFailed}, + {name: "b", phase: v1.PodSucceeded}, }, threshold: 0, // threshold = 0 disables terminated pod deletion @@ -59,34 +59,34 @@ func TestGCTerminated(t *testing.T) { }, { pods: []nameToPhase{ - {name: "a", phase: api.PodFailed}, - {name: "b", phase: api.PodSucceeded}, - {name: "c", phase: api.PodFailed}, + {name: "a", phase: v1.PodFailed}, + {name: "b", phase: v1.PodSucceeded}, + {name: "c", phase: v1.PodFailed}, }, threshold: 1, deletedPodNames: sets.NewString("a", "b"), }, { pods: []nameToPhase{ - {name: "a", phase: api.PodRunning}, - {name: "b", phase: api.PodSucceeded}, - {name: "c", phase: api.PodFailed}, + {name: "a", phase: v1.PodRunning}, + {name: "b", phase: v1.PodSucceeded}, + {name: "c", phase: v1.PodFailed}, }, threshold: 1, deletedPodNames: sets.NewString("b"), }, { pods: []nameToPhase{ - {name: "a", phase: api.PodFailed}, - {name: "b", phase: api.PodSucceeded}, + {name: "a", phase: v1.PodFailed}, + {name: "b", phase: v1.PodSucceeded}, }, threshold: 1, deletedPodNames: sets.NewString("a"), }, { pods: []nameToPhase{ - {name: "a", phase: api.PodFailed}, - {name: "b", phase: api.PodSucceeded}, + {name: "a", phase: v1.PodFailed}, + {name: "b", phase: v1.PodSucceeded}, }, threshold: 5, deletedPodNames: sets.NewString(), @@ -108,16 +108,16 @@ func TestGCTerminated(t *testing.T) { creationTime := time.Unix(0, 0) for _, pod := range test.pods { creationTime = creationTime.Add(1 * time.Hour) - gcc.podStore.Indexer.Add(&api.Pod{ - ObjectMeta: api.ObjectMeta{Name: pod.name, CreationTimestamp: unversioned.Time{Time: creationTime}}, - Status: api.PodStatus{Phase: pod.phase}, - Spec: api.PodSpec{NodeName: "node"}, + gcc.podStore.Indexer.Add(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: pod.name, CreationTimestamp: unversioned.Time{Time: creationTime}}, + Status: v1.PodStatus{Phase: pod.phase}, + Spec: v1.PodSpec{NodeName: "node"}, }) } store := cache.NewStore(cache.MetaNamespaceKeyFunc) - store.Add(&api.Node{ - ObjectMeta: api.ObjectMeta{Name: "node"}, + store.Add(&v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: "node"}, }) gcc.nodeStore = cache.StoreToNodeLister{Store: store} gcc.podController = &FakeController{} @@ -143,7 +143,7 @@ func TestGCTerminated(t *testing.T) { func TestGCOrphaned(t *testing.T) { type nameToPhase struct { name string - phase api.PodPhase + phase v1.PodPhase } testCases := []struct { @@ -153,15 +153,15 @@ func TestGCOrphaned(t *testing.T) { }{ { pods: []nameToPhase{ - {name: "a", phase: api.PodFailed}, - {name: "b", phase: api.PodSucceeded}, + {name: "a", phase: v1.PodFailed}, + {name: "b", phase: v1.PodSucceeded}, }, threshold: 0, deletedPodNames: sets.NewString("a", "b"), }, { pods: []nameToPhase{ - {name: "a", phase: api.PodRunning}, + {name: "a", phase: v1.PodRunning}, }, threshold: 1, deletedPodNames: sets.NewString("a"), @@ -183,10 +183,10 @@ func TestGCOrphaned(t *testing.T) { creationTime := time.Unix(0, 0) for _, pod := range test.pods { creationTime = creationTime.Add(1 * time.Hour) - gcc.podStore.Indexer.Add(&api.Pod{ - ObjectMeta: api.ObjectMeta{Name: pod.name, CreationTimestamp: unversioned.Time{Time: creationTime}}, - Status: api.PodStatus{Phase: pod.phase}, - Spec: api.PodSpec{NodeName: "node"}, + gcc.podStore.Indexer.Add(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: pod.name, CreationTimestamp: unversioned.Time{Time: creationTime}}, + Status: v1.PodStatus{Phase: pod.phase}, + Spec: v1.PodSpec{NodeName: "node"}, }) } @@ -220,7 +220,7 @@ func TestGCOrphaned(t *testing.T) { func TestGCUnscheduledTerminating(t *testing.T) { type nameToPhase struct { name string - phase api.PodPhase + phase v1.PodPhase deletionTimeStamp *unversioned.Time nodeName string } @@ -233,18 +233,18 @@ func TestGCUnscheduledTerminating(t *testing.T) { { name: "Unscheduled pod in any phase must be deleted", pods: []nameToPhase{ - {name: "a", phase: api.PodFailed, deletionTimeStamp: &unversioned.Time{}, nodeName: ""}, - {name: "b", phase: api.PodSucceeded, deletionTimeStamp: &unversioned.Time{}, nodeName: ""}, - {name: "c", phase: api.PodRunning, deletionTimeStamp: &unversioned.Time{}, nodeName: ""}, + {name: "a", phase: v1.PodFailed, deletionTimeStamp: &unversioned.Time{}, nodeName: ""}, + {name: "b", phase: v1.PodSucceeded, deletionTimeStamp: &unversioned.Time{}, nodeName: ""}, + {name: "c", phase: v1.PodRunning, deletionTimeStamp: &unversioned.Time{}, nodeName: ""}, }, deletedPodNames: sets.NewString("a", "b", "c"), }, { name: "Scheduled pod in any phase must not be deleted", pods: []nameToPhase{ - {name: "a", phase: api.PodFailed, deletionTimeStamp: nil, nodeName: ""}, - {name: "b", phase: api.PodSucceeded, deletionTimeStamp: nil, nodeName: "node"}, - {name: "c", phase: api.PodRunning, deletionTimeStamp: &unversioned.Time{}, nodeName: "node"}, + {name: "a", phase: v1.PodFailed, deletionTimeStamp: nil, nodeName: ""}, + {name: "b", phase: v1.PodSucceeded, deletionTimeStamp: nil, nodeName: "node"}, + {name: "c", phase: v1.PodRunning, deletionTimeStamp: &unversioned.Time{}, nodeName: "node"}, }, deletedPodNames: sets.NewString(), }, @@ -265,11 +265,11 @@ func TestGCUnscheduledTerminating(t *testing.T) { creationTime := time.Unix(0, 0) for _, pod := range test.pods { creationTime = creationTime.Add(1 * time.Hour) - gcc.podStore.Indexer.Add(&api.Pod{ - ObjectMeta: api.ObjectMeta{Name: pod.name, CreationTimestamp: unversioned.Time{Time: creationTime}, + gcc.podStore.Indexer.Add(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: pod.name, CreationTimestamp: unversioned.Time{Time: creationTime}, DeletionTimestamp: pod.deletionTimeStamp}, - Status: api.PodStatus{Phase: pod.phase}, - Spec: api.PodSpec{NodeName: pod.nodeName}, + Status: v1.PodStatus{Phase: pod.phase}, + Spec: v1.PodSpec{NodeName: pod.nodeName}, }) } diff --git a/pkg/controller/replicaset/BUILD b/pkg/controller/replicaset/BUILD index 7a0a154bd1b..ab09f9dc279 100644 --- a/pkg/controller/replicaset/BUILD +++ b/pkg/controller/replicaset/BUILD @@ -22,12 +22,12 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/controller:go_default_library", "//pkg/controller/informers:go_default_library", @@ -50,11 +50,12 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/testapi:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/controller:go_default_library", diff --git a/pkg/controller/replicaset/replica_set.go b/pkg/controller/replicaset/replica_set.go index d7b36463afa..1e967de100e 100644 --- a/pkg/controller/replicaset/replica_set.go +++ b/pkg/controller/replicaset/replica_set.go @@ -26,14 +26,14 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/informers" @@ -107,13 +107,13 @@ func NewReplicaSetController(rsInformer informers.ReplicaSetInformer, podInforme } eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(glog.Infof) - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.Core().Events("")}) rsc := &ReplicaSetController{ kubeClient: kubeClient, podControl: controller.RealPodControl{ KubeClient: kubeClient, - Recorder: eventBroadcaster.NewRecorder(api.EventSource{Component: "replicaset-controller"}), + Recorder: eventBroadcaster.NewRecorder(v1.EventSource{Component: "replicaset-controller"}), }, burstReplicas: burstReplicas, expectations: controller.NewUIDTrackingControllerExpectations(controller.NewControllerExpectations()), @@ -176,7 +176,7 @@ func (rsc *ReplicaSetController) Run(workers int, stopCh <-chan struct{}) { // getPodReplicaSet returns the replica set managing the given pod. // TODO: Surface that we are ignoring multiple replica sets for a single pod. // TODO: use ownerReference.Controller to determine if the rs controls the pod. -func (rsc *ReplicaSetController) getPodReplicaSet(pod *api.Pod) *extensions.ReplicaSet { +func (rsc *ReplicaSetController) getPodReplicaSet(pod *v1.Pod) *extensions.ReplicaSet { // look up in the cache, if cached and the cache is valid, just return cached value if obj, cached := rsc.lookupCache.GetMatchingObject(pod); cached { rs, ok := obj.(*extensions.ReplicaSet) @@ -254,7 +254,7 @@ func (rsc *ReplicaSetController) updateRS(old, cur interface{}) { } // isCacheValid check if the cache is valid -func (rsc *ReplicaSetController) isCacheValid(pod *api.Pod, cachedRS *extensions.ReplicaSet) bool { +func (rsc *ReplicaSetController) isCacheValid(pod *v1.Pod, cachedRS *extensions.ReplicaSet) bool { _, err := rsc.rsLister.ReplicaSets(cachedRS.Namespace).Get(cachedRS.Name) // rs has been deleted or updated, cache is invalid if err != nil || !isReplicaSetMatch(pod, cachedRS) { @@ -265,7 +265,7 @@ func (rsc *ReplicaSetController) isCacheValid(pod *api.Pod, cachedRS *extensions // isReplicaSetMatch take a Pod and ReplicaSet, return whether the Pod and ReplicaSet are matching // TODO(mqliang): This logic is a copy from GetPodReplicaSets(), remove the duplication -func isReplicaSetMatch(pod *api.Pod, rs *extensions.ReplicaSet) bool { +func isReplicaSetMatch(pod *v1.Pod, rs *extensions.ReplicaSet) bool { if rs.Namespace != pod.Namespace { return false } @@ -284,7 +284,7 @@ func isReplicaSetMatch(pod *api.Pod, rs *extensions.ReplicaSet) bool { // When a pod is created, enqueue the replica set that manages it and update it's expectations. func (rsc *ReplicaSetController) addPod(obj interface{}) { - pod := obj.(*api.Pod) + pod := obj.(*v1.Pod) glog.V(4).Infof("Pod %s created: %#v.", pod.Name, pod) rs := rsc.getPodReplicaSet(pod) @@ -308,10 +308,10 @@ func (rsc *ReplicaSetController) addPod(obj interface{}) { // When a pod is updated, figure out what replica set/s manage it and wake them // up. If the labels of the pod have changed we need to awaken both the old -// and new replica set. old and cur must be *api.Pod types. +// and new replica set. old and cur must be *v1.Pod types. func (rsc *ReplicaSetController) updatePod(old, cur interface{}) { - curPod := cur.(*api.Pod) - oldPod := old.(*api.Pod) + curPod := cur.(*v1.Pod) + oldPod := old.(*v1.Pod) if curPod.ResourceVersion == oldPod.ResourceVersion { // Periodic resync will send update events for all known pods. // Two different versions of the same pod will always have different RVs. @@ -348,9 +348,9 @@ func (rsc *ReplicaSetController) updatePod(old, cur interface{}) { } // When a pod is deleted, enqueue the replica set that manages the pod and update its expectations. -// obj could be an *api.Pod, or a DeletionFinalStateUnknown marker item. +// obj could be an *v1.Pod, or a DeletionFinalStateUnknown marker item. func (rsc *ReplicaSetController) deletePod(obj interface{}) { - pod, ok := obj.(*api.Pod) + pod, ok := obj.(*v1.Pod) // When a delete is dropped, the relist will notice a pod in the store not // in the list, leading to the insertion of a tombstone object which contains @@ -362,7 +362,7 @@ func (rsc *ReplicaSetController) deletePod(obj interface{}) { utilruntime.HandleError(fmt.Errorf("Couldn't get object from tombstone %+v", obj)) return } - pod, ok = tombstone.Obj.(*api.Pod) + pod, ok = tombstone.Obj.(*v1.Pod) if !ok { utilruntime.HandleError(fmt.Errorf("Tombstone contained object that is not a pod %#v", obj)) return @@ -426,8 +426,8 @@ func (rsc *ReplicaSetController) processNextWorkItem() bool { // manageReplicas checks and updates replicas for the given ReplicaSet. // Does NOT modify . // It will requeue the replica set in case of an error while creating/deleting pods. -func (rsc *ReplicaSetController) manageReplicas(filteredPods []*api.Pod, rs *extensions.ReplicaSet) error { - diff := len(filteredPods) - int(rs.Spec.Replicas) +func (rsc *ReplicaSetController) manageReplicas(filteredPods []*v1.Pod, rs *extensions.ReplicaSet) error { + diff := len(filteredPods) - int(*(rs.Spec.Replicas)) rsKey, err := controller.KeyFunc(rs) if err != nil { utilruntime.HandleError(fmt.Errorf("Couldn't get key for ReplicaSet %#v: %v", rs, err)) @@ -448,7 +448,7 @@ func (rsc *ReplicaSetController) manageReplicas(filteredPods []*api.Pod, rs *ext rsc.expectations.ExpectCreations(rsKey, diff) var wg sync.WaitGroup wg.Add(diff) - glog.V(2).Infof("Too few %q/%q replicas, need %d, creating %d", rs.Namespace, rs.Name, rs.Spec.Replicas, diff) + glog.V(2).Infof("Too few %q/%q replicas, need %d, creating %d", rs.Namespace, rs.Name, *(rs.Spec.Replicas), diff) for i := 0; i < diff; i++ { go func() { defer wg.Done() @@ -456,7 +456,7 @@ func (rsc *ReplicaSetController) manageReplicas(filteredPods []*api.Pod, rs *ext if rsc.garbageCollectorEnabled { var trueVar = true - controllerRef := &api.OwnerReference{ + controllerRef := &v1.OwnerReference{ APIVersion: getRSKind().GroupVersion().String(), Kind: getRSKind().Kind, Name: rs.Name, @@ -481,9 +481,9 @@ func (rsc *ReplicaSetController) manageReplicas(filteredPods []*api.Pod, rs *ext diff = rsc.burstReplicas } errCh = make(chan error, diff) - glog.V(2).Infof("Too many %q/%q replicas, need %d, deleting %d", rs.Namespace, rs.Name, rs.Spec.Replicas, diff) + glog.V(2).Infof("Too many %q/%q replicas, need %d, deleting %d", rs.Namespace, rs.Name, *(rs.Spec.Replicas), diff) // No need to sort pods if we are about to delete all of them - if rs.Spec.Replicas != 0 { + if *(rs.Spec.Replicas) != 0 { // Sort the pods in the order such that not-ready < ready, unscheduled // < scheduled, and pending < running. This ensures that we delete pods // in the earlier stages whenever possible. @@ -567,7 +567,7 @@ func (rsc *ReplicaSetController) syncReplicaSet(key string) error { // NOTE: filteredPods are pointing to objects from cache - if you need to // modify them, you need to copy it first. // TODO: Do the List and Filter in a single pass, or use an index. - var filteredPods []*api.Pod + var filteredPods []*v1.Pod if rsc.garbageCollectorEnabled { // list all pods to include the pods that don't match the rs`s selector // anymore but has the stale controller ref. diff --git a/pkg/controller/replicaset/replica_set_test.go b/pkg/controller/replicaset/replica_set_test.go index 4b12b165b67..2b077f790e6 100644 --- a/pkg/controller/replicaset/replica_set_test.go +++ b/pkg/controller/replicaset/replica_set_test.go @@ -31,12 +31,13 @@ import ( "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/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" - fakeclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" + fakeclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/controller" @@ -51,7 +52,7 @@ import ( ) func testNewReplicaSetControllerFromClient(client clientset.Interface, stopCh chan struct{}, burstReplicas int, lookupCacheSize int) *ReplicaSetController { - informers := informers.NewSharedInformerFactory(client, controller.NoResyncPeriodFunc()) + informers := informers.NewSharedInformerFactory(client, nil, controller.NoResyncPeriodFunc()) ret := NewReplicaSetController(informers.ReplicaSets(), informers.Pods(), client, burstReplicas, lookupCacheSize, false) ret.podLister = &cache.StoreToPodLister{Indexer: cache.NewIndexer(cache.DeletionHandlingMetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})} ret.rsLister = &cache.StoreToReplicaSetLister{Indexer: cache.NewIndexer(cache.DeletionHandlingMetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})} @@ -98,34 +99,34 @@ func getKey(rs *extensions.ReplicaSet, t *testing.T) string { func newReplicaSet(replicas int, selectorMap map[string]string) *extensions.ReplicaSet { rs := &extensions.ReplicaSet{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + ObjectMeta: v1.ObjectMeta{ UID: uuid.NewUUID(), Name: "foobar", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, ResourceVersion: "18", }, Spec: extensions.ReplicaSetSpec{ - Replicas: int32(replicas), + Replicas: func() *int32 { i := int32(replicas); return &i }(), Selector: &unversioned.LabelSelector{MatchLabels: selectorMap}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{ "name": "foo", "type": "production", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Image: "foo/bar", - TerminationMessagePath: api.TerminationMessagePathDefault, - ImagePullPolicy: api.PullIfNotPresent, + TerminationMessagePath: v1.TerminationMessagePathDefault, + ImagePullPolicy: v1.PullIfNotPresent, SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), }, }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSDefault, + RestartPolicy: v1.RestartPolicyAlways, + DNSPolicy: v1.DNSDefault, NodeSelector: map[string]string{ "baz": "blah", }, @@ -137,40 +138,40 @@ func newReplicaSet(replicas int, selectorMap map[string]string) *extensions.Repl } // create a pod with the given phase for the given rs (same selectors and namespace) -func newPod(name string, rs *extensions.ReplicaSet, status api.PodPhase, lastTransitionTime *unversioned.Time) *api.Pod { - var conditions []api.PodCondition - if status == api.PodRunning { - condition := api.PodCondition{Type: api.PodReady, Status: api.ConditionTrue} +func newPod(name string, rs *extensions.ReplicaSet, status v1.PodPhase, lastTransitionTime *unversioned.Time) *v1.Pod { + var conditions []v1.PodCondition + if status == v1.PodRunning { + condition := v1.PodCondition{Type: v1.PodReady, Status: v1.ConditionTrue} if lastTransitionTime != nil { condition.LastTransitionTime = *lastTransitionTime } conditions = append(conditions, condition) } - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Namespace: rs.Namespace, Labels: rs.Spec.Selector.MatchLabels, }, - Status: api.PodStatus{Phase: status, Conditions: conditions}, + Status: v1.PodStatus{Phase: status, Conditions: conditions}, } } // create count pods with the given phase for the given ReplicaSet (same selectors and namespace), and add them to the store. -func newPodList(store cache.Store, count int, status api.PodPhase, labelMap map[string]string, rs *extensions.ReplicaSet, name string) *api.PodList { - pods := []api.Pod{} +func newPodList(store cache.Store, count int, status v1.PodPhase, labelMap map[string]string, rs *extensions.ReplicaSet, name string) *v1.PodList { + pods := []v1.Pod{} var trueVar = true - controllerReference := api.OwnerReference{UID: rs.UID, APIVersion: "v1beta1", Kind: "ReplicaSet", Name: rs.Name, Controller: &trueVar} + controllerReference := v1.OwnerReference{UID: rs.UID, APIVersion: "v1beta1", Kind: "ReplicaSet", Name: rs.Name, Controller: &trueVar} for i := 0; i < count; i++ { pod := newPod(fmt.Sprintf("%s%d", name, i), rs, status, nil) pod.ObjectMeta.Labels = labelMap - pod.OwnerReferences = []api.OwnerReference{controllerReference} + pod.OwnerReferences = []v1.OwnerReference{controllerReference} if store != nil { store.Add(pod) } pods = append(pods, *pod) } - return &api.PodList{ + return &v1.PodList{ Items: pods, } } @@ -197,7 +198,7 @@ type serverResponse struct { } func TestSyncReplicaSetDoesNothing(t *testing.T) { - client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} stopCh := make(chan struct{}) defer close(stopCh) @@ -208,7 +209,7 @@ func TestSyncReplicaSetDoesNothing(t *testing.T) { labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(2, labelMap) manager.rsLister.Indexer.Add(rsSpec) - newPodList(manager.podLister.Indexer, 2, api.PodRunning, labelMap, rsSpec, "pod") + newPodList(manager.podLister.Indexer, 2, v1.PodRunning, labelMap, rsSpec, "pod") manager.podControl = &fakePodControl manager.syncReplicaSet(getKey(rsSpec, t)) @@ -216,7 +217,7 @@ func TestSyncReplicaSetDoesNothing(t *testing.T) { } func TestSyncReplicaSetDeletes(t *testing.T) { - client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} stopCh := make(chan struct{}) defer close(stopCh) @@ -228,14 +229,14 @@ func TestSyncReplicaSetDeletes(t *testing.T) { labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(1, labelMap) manager.rsLister.Indexer.Add(rsSpec) - newPodList(manager.podLister.Indexer, 2, api.PodRunning, labelMap, rsSpec, "pod") + newPodList(manager.podLister.Indexer, 2, v1.PodRunning, labelMap, rsSpec, "pod") manager.syncReplicaSet(getKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 0, 1, 0) } func TestDeleteFinalStateUnknown(t *testing.T) { - client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} stopCh := make(chan struct{}) defer close(stopCh) @@ -254,7 +255,7 @@ func TestDeleteFinalStateUnknown(t *testing.T) { labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(1, labelMap) manager.rsLister.Indexer.Add(rsSpec) - pods := newPodList(nil, 1, api.PodRunning, labelMap, rsSpec, "pod") + pods := newPodList(nil, 1, v1.PodRunning, labelMap, rsSpec, "pod") manager.deletePod(cache.DeletedFinalStateUnknown{Key: "foo", Obj: &pods.Items[0]}) go manager.worker() @@ -271,7 +272,7 @@ func TestDeleteFinalStateUnknown(t *testing.T) { } func TestSyncReplicaSetCreates(t *testing.T) { - client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) stopCh := make(chan struct{}) defer close(stopCh) manager := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas, 0) @@ -297,7 +298,7 @@ func TestStatusUpdatesWithoutReplicasChange(t *testing.T) { } testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) stopCh := make(chan struct{}) defer close(stopCh) manager := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas, 0) @@ -309,7 +310,7 @@ func TestStatusUpdatesWithoutReplicasChange(t *testing.T) { rs := newReplicaSet(activePods, labelMap) manager.rsLister.Indexer.Add(rs) rs.Status = extensions.ReplicaSetStatus{Replicas: int32(activePods), ReadyReplicas: int32(activePods), AvailableReplicas: int32(activePods)} - newPodList(manager.podLister.Indexer, activePods, api.PodRunning, labelMap, rs, "pod") + newPodList(manager.podLister.Indexer, activePods, v1.PodRunning, labelMap, rs, "pod") fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl @@ -343,7 +344,7 @@ func TestControllerUpdateReplicas(t *testing.T) { testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) stopCh := make(chan struct{}) defer close(stopCh) manager := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas, 0) @@ -358,8 +359,8 @@ func TestControllerUpdateReplicas(t *testing.T) { manager.rsLister.Indexer.Add(rs) rs.Status = extensions.ReplicaSetStatus{Replicas: 2, FullyLabeledReplicas: 6, ReadyReplicas: 2, AvailableReplicas: 2, ObservedGeneration: 0} rs.Generation = 1 - newPodList(manager.podLister.Indexer, 2, api.PodRunning, labelMap, rs, "pod") - newPodList(manager.podLister.Indexer, 2, api.PodRunning, extraLabelMap, rs, "podWithExtraLabel") + newPodList(manager.podLister.Indexer, 2, v1.PodRunning, labelMap, rs, "pod") + newPodList(manager.podLister.Indexer, 2, v1.PodRunning, extraLabelMap, rs, "podWithExtraLabel") // This response body is just so we don't err out decoding the http response response := runtime.EncodeOrDie(testapi.Extensions.Codec(), &extensions.ReplicaSet{}) @@ -391,7 +392,7 @@ func TestSyncReplicaSetDormancy(t *testing.T) { } testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} stopCh := make(chan struct{}) @@ -404,7 +405,7 @@ func TestSyncReplicaSetDormancy(t *testing.T) { labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(2, labelMap) manager.rsLister.Indexer.Add(rsSpec) - newPodList(manager.podLister.Indexer, 1, api.PodRunning, labelMap, rsSpec, "pod") + newPodList(manager.podLister.Indexer, 1, v1.PodRunning, labelMap, rsSpec, "pod") // Creates a replica and sets expectations rsSpec.Status.Replicas = 1 @@ -453,32 +454,32 @@ func TestSyncReplicaSetDormancy(t *testing.T) { func TestPodControllerLookup(t *testing.T) { stopCh := make(chan struct{}) defer close(stopCh) - manager := testNewReplicaSetControllerFromClient(clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}), stopCh, BurstReplicas, 0) + manager := testNewReplicaSetControllerFromClient(clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}), stopCh, BurstReplicas, 0) manager.podListerSynced = alwaysReady testCases := []struct { inRSs []*extensions.ReplicaSet - pod *api.Pod + pod *v1.Pod outRSName string }{ // pods without labels don't match any ReplicaSets { inRSs: []*extensions.ReplicaSet{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}}, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo1", Namespace: api.NamespaceAll}}, + {ObjectMeta: v1.ObjectMeta{Name: "basic"}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo1", Namespace: v1.NamespaceAll}}, outRSName: "", }, // Matching labels, not namespace { inRSs: []*extensions.ReplicaSet{ { - ObjectMeta: api.ObjectMeta{Name: "foo"}, + ObjectMeta: v1.ObjectMeta{Name: "foo"}, Spec: extensions.ReplicaSetSpec{ Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, }, }, }, - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "foo2", Namespace: "ns", Labels: map[string]string{"foo": "bar"}}}, outRSName: "", }, @@ -486,14 +487,14 @@ func TestPodControllerLookup(t *testing.T) { { inRSs: []*extensions.ReplicaSet{ { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "ns"}, + ObjectMeta: v1.ObjectMeta{Name: "bar", Namespace: "ns"}, Spec: extensions.ReplicaSetSpec{ Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, }, }, }, - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "foo3", Namespace: "ns", Labels: map[string]string{"foo": "bar"}}}, outRSName: "bar", }, @@ -523,7 +524,7 @@ func TestWatchControllers(t *testing.T) { client.AddWatchReactor("replicasets", core.DefaultWatchReactor(fakeWatch, nil)) stopCh := make(chan struct{}) defer close(stopCh) - informers := informers.NewSharedInformerFactory(client, controller.NoResyncPeriodFunc()) + informers := informers.NewSharedInformerFactory(client, nil, controller.NoResyncPeriodFunc()) manager := NewReplicaSetController(informers.ReplicaSets(), informers.Pods(), client, BurstReplicas, 0, false) informers.Start(stopCh) manager.podListerSynced = alwaysReady @@ -592,9 +593,9 @@ func TestWatchPods(t *testing.T) { // and make sure it hits the sync method for the right ReplicaSet. go wait.Until(manager.worker, 10*time.Millisecond, stopCh) - pods := newPodList(nil, 1, api.PodRunning, labelMap, testRSSpec, "pod") + pods := newPodList(nil, 1, v1.PodRunning, labelMap, testRSSpec, "pod") testPod := pods.Items[0] - testPod.Status.Phase = api.PodFailed + testPod.Status.Phase = v1.PodFailed fakeWatch.Add(&testPod) select { @@ -636,7 +637,7 @@ func TestUpdatePods(t *testing.T) { // case 1: We put in the podLister a pod with labels matching testRSSpec1, // then update its labels to match testRSSpec2. We expect to receive a sync // request for both replica sets. - pod1 := newPodList(manager.podLister.Indexer, 1, api.PodRunning, labelMap1, testRSSpec1, "pod").Items[0] + pod1 := newPodList(manager.podLister.Indexer, 1, v1.PodRunning, labelMap1, testRSSpec1, "pod").Items[0] pod1.ResourceVersion = "1" pod2 := pod1 pod2.Labels = labelMap2 @@ -687,7 +688,7 @@ func TestControllerUpdateRequeue(t *testing.T) { stopCh := make(chan struct{}) defer close(stopCh) - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas, 0) manager.podListerSynced = alwaysReady @@ -695,7 +696,7 @@ func TestControllerUpdateRequeue(t *testing.T) { rs := newReplicaSet(1, labelMap) manager.rsLister.Indexer.Add(rs) rs.Status = extensions.ReplicaSetStatus{Replicas: 2} - newPodList(manager.podLister.Indexer, 1, api.PodRunning, labelMap, rs, "pod") + newPodList(manager.podLister.Indexer, 1, v1.PodRunning, labelMap, rs, "pod") fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl @@ -756,7 +757,7 @@ func TestControllerUpdateStatusWithFailure(t *testing.T) { // TODO: This test is too hairy for a unittest. It should be moved to an E2E suite. func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) { - client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} stopCh := make(chan struct{}) defer close(stopCh) @@ -769,7 +770,7 @@ func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) manager.rsLister.Indexer.Add(rsSpec) expectedPods := int32(0) - pods := newPodList(nil, numReplicas, api.PodPending, labelMap, rsSpec, "pod") + pods := newPodList(nil, numReplicas, v1.PodPending, labelMap, rsSpec, "pod") rsKey, err := controller.KeyFunc(rsSpec) if err != nil { @@ -779,7 +780,7 @@ func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) // Size up the controller, then size it down, and confirm the expected create/delete pattern for _, replicas := range []int32{int32(numReplicas), 0} { - rsSpec.Spec.Replicas = replicas + *(rsSpec.Spec.Replicas) = replicas manager.rsLister.Indexer.Add(rsSpec) for i := 0; i < numReplicas; i += burstReplicas { @@ -823,11 +824,11 @@ func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) // To accurately simulate a watch we must delete the exact pods // the rs is waiting for. expectedDels := manager.expectations.GetUIDs(getKey(rsSpec, t)) - podsToDelete := []*api.Pod{} + podsToDelete := []*v1.Pod{} for _, key := range expectedDels.List() { nsName := strings.Split(key, "/") - podsToDelete = append(podsToDelete, &api.Pod{ - ObjectMeta: api.ObjectMeta{ + podsToDelete = append(podsToDelete, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: nsName[1], Namespace: nsName[0], Labels: rsSpec.Spec.Selector.MatchLabels, @@ -867,8 +868,8 @@ func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) t.Fatalf("Waiting on unexpected number of deletes.") } nsName := strings.Split(expectedDel.List()[0], "/") - lastPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + lastPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: nsName[1], Namespace: nsName[0], Labels: rsSpec.Spec.Selector.MatchLabels, @@ -882,11 +883,11 @@ func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) // Confirm that we've created the right number of replicas activePods := int32(len(manager.podLister.Indexer.List())) - if activePods != rsSpec.Spec.Replicas { - t.Fatalf("Unexpected number of active pods, expected %d, got %d", rsSpec.Spec.Replicas, activePods) + if activePods != *(rsSpec.Spec.Replicas) { + t.Fatalf("Unexpected number of active pods, expected %d, got %d", *(rsSpec.Spec.Replicas), activePods) } // Replenish the pod list, since we cut it down sizing up - pods = newPodList(nil, int(replicas), api.PodRunning, labelMap, rsSpec, "pod") + pods = newPodList(nil, int(replicas), v1.PodRunning, labelMap, rsSpec, "pod") } } @@ -910,7 +911,7 @@ func (fe FakeRSExpectations) SatisfiedExpectations(controllerKey string) bool { // TestRSSyncExpectations tests that a pod cannot sneak in between counting active pods // and checking expectations. func TestRSSyncExpectations(t *testing.T) { - client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} stopCh := make(chan struct{}) defer close(stopCh) @@ -921,7 +922,7 @@ func TestRSSyncExpectations(t *testing.T) { labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(2, labelMap) manager.rsLister.Indexer.Add(rsSpec) - pods := newPodList(nil, 2, api.PodPending, labelMap, rsSpec, "pod") + pods := newPodList(nil, 2, v1.PodPending, labelMap, rsSpec, "pod") manager.podLister.Indexer.Add(&pods.Items[0]) postExpectationsPod := pods.Items[1] @@ -938,7 +939,7 @@ func TestRSSyncExpectations(t *testing.T) { } func TestDeleteControllerAndExpectations(t *testing.T) { - client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) stopCh := make(chan struct{}) defer close(stopCh) manager := testNewReplicaSetControllerFromClient(client, stopCh, 10, 0) @@ -993,7 +994,7 @@ func shuffle(controllers []*extensions.ReplicaSet) []*extensions.ReplicaSet { } func TestOverlappingRSs(t *testing.T) { - client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) labelMap := map[string]string{"foo": "bar"} for i := 0; i < 5; i++ { @@ -1016,7 +1017,7 @@ func TestOverlappingRSs(t *testing.T) { manager.rsLister.Indexer.Add(shuffledControllers[j]) } // Add a pod and make sure only the oldest ReplicaSet is synced - pods := newPodList(nil, 1, api.PodPending, labelMap, controllers[0], "pod") + pods := newPodList(nil, 1, v1.PodPending, labelMap, controllers[0], "pod") rsKey := getKey(controllers[0], t) manager.addPod(&pods.Items[0]) @@ -1029,7 +1030,7 @@ func TestOverlappingRSs(t *testing.T) { } func TestDeletionTimestamp(t *testing.T) { - c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) labelMap := map[string]string{"foo": "bar"} stopCh := make(chan struct{}) defer close(stopCh) @@ -1042,7 +1043,7 @@ func TestDeletionTimestamp(t *testing.T) { if err != nil { t.Errorf("Couldn't get key for object %#v: %v", rs, err) } - pod := newPodList(nil, 1, api.PodPending, labelMap, rs, "pod").Items[0] + pod := newPodList(nil, 1, v1.PodPending, labelMap, rs, "pod").Items[0] pod.DeletionTimestamp = &unversioned.Time{Time: time.Now()} pod.ResourceVersion = "1" manager.expectations.ExpectDeletions(rsKey, []string{controller.PodKey(&pod)}) @@ -1063,7 +1064,7 @@ func TestDeletionTimestamp(t *testing.T) { // An update from no deletion timestamp to having one should be treated // as a deletion. - oldPod := newPodList(nil, 1, api.PodPending, labelMap, rs, "pod").Items[0] + oldPod := newPodList(nil, 1, v1.PodPending, labelMap, rs, "pod").Items[0] oldPod.ResourceVersion = "2" manager.expectations.ExpectDeletions(rsKey, []string{controller.PodKey(&pod)}) manager.updatePod(&oldPod, &pod) @@ -1081,8 +1082,8 @@ func TestDeletionTimestamp(t *testing.T) { // An update to the pod (including an update to the deletion timestamp) // should not be counted as a second delete. - secondPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + secondPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: pod.Namespace, Name: "secondPod", Labels: pod.Labels, @@ -1142,10 +1143,10 @@ func TestDoNotPatchPodWithOtherControlRef(t *testing.T) { manager, fakePodControl := setupManagerWithGCEnabled(stopCh, rs) manager.rsLister.Indexer.Add(rs) var trueVar = true - otherControllerReference := api.OwnerReference{UID: uuid.NewUUID(), APIVersion: "v1beta1", Kind: "ReplicaSet", Name: "AnotherRS", Controller: &trueVar} + otherControllerReference := v1.OwnerReference{UID: uuid.NewUUID(), APIVersion: "v1beta1", Kind: "ReplicaSet", Name: "AnotherRS", Controller: &trueVar} // add to podLister a matching Pod controlled by another controller. Expect no patch. - pod := newPod("pod", rs, api.PodRunning, nil) - pod.OwnerReferences = []api.OwnerReference{otherControllerReference} + pod := newPod("pod", rs, v1.PodRunning, nil) + pod.OwnerReferences = []v1.OwnerReference{otherControllerReference} manager.podLister.Indexer.Add(pod) err := manager.syncReplicaSet(getKey(rs, t)) if err != nil { @@ -1165,9 +1166,9 @@ func TestPatchPodWithOtherOwnerRef(t *testing.T) { // add to podLister one more matching pod that doesn't have a controller // ref, but has an owner ref pointing to other object. Expect a patch to // take control of it. - unrelatedOwnerReference := api.OwnerReference{UID: uuid.NewUUID(), APIVersion: "batch/v1", Kind: "Job", Name: "Job"} - pod := newPod("pod", rs, api.PodRunning, nil) - pod.OwnerReferences = []api.OwnerReference{unrelatedOwnerReference} + unrelatedOwnerReference := v1.OwnerReference{UID: uuid.NewUUID(), APIVersion: "batch/v1", Kind: "Job", Name: "Job"} + pod := newPod("pod", rs, v1.PodRunning, nil) + pod.OwnerReferences = []v1.OwnerReference{unrelatedOwnerReference} manager.podLister.Indexer.Add(pod) err := manager.syncReplicaSet(getKey(rs, t)) @@ -1187,9 +1188,9 @@ func TestPatchPodWithCorrectOwnerRef(t *testing.T) { manager.rsLister.Indexer.Add(rs) // add to podLister a matching pod that has an ownerRef pointing to the rs, // but ownerRef.Controller is false. Expect a patch to take control it. - rsOwnerReference := api.OwnerReference{UID: rs.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: rs.Name} - pod := newPod("pod", rs, api.PodRunning, nil) - pod.OwnerReferences = []api.OwnerReference{rsOwnerReference} + rsOwnerReference := v1.OwnerReference{UID: rs.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: rs.Name} + pod := newPod("pod", rs, v1.PodRunning, nil) + pod.OwnerReferences = []v1.OwnerReference{rsOwnerReference} manager.podLister.Indexer.Add(pod) err := manager.syncReplicaSet(getKey(rs, t)) @@ -1209,8 +1210,8 @@ func TestPatchPodFails(t *testing.T) { manager.rsLister.Indexer.Add(rs) // add to podLister two matching pods. Expect two patches to take control // them. - manager.podLister.Indexer.Add(newPod("pod1", rs, api.PodRunning, nil)) - manager.podLister.Indexer.Add(newPod("pod2", rs, api.PodRunning, nil)) + manager.podLister.Indexer.Add(newPod("pod1", rs, v1.PodRunning, nil)) + manager.podLister.Indexer.Add(newPod("pod2", rs, v1.PodRunning, nil)) // let both patches fail. The rs controller will assume it fails to take // control of the pods and create new ones. fakePodControl.Err = fmt.Errorf("Fake Error") @@ -1231,9 +1232,9 @@ func TestPatchExtraPodsThenDelete(t *testing.T) { manager.rsLister.Indexer.Add(rs) // add to podLister three matching pods. Expect three patches to take control // them, and later delete one of them. - manager.podLister.Indexer.Add(newPod("pod1", rs, api.PodRunning, nil)) - manager.podLister.Indexer.Add(newPod("pod2", rs, api.PodRunning, nil)) - manager.podLister.Indexer.Add(newPod("pod3", rs, api.PodRunning, nil)) + manager.podLister.Indexer.Add(newPod("pod1", rs, v1.PodRunning, nil)) + manager.podLister.Indexer.Add(newPod("pod2", rs, v1.PodRunning, nil)) + manager.podLister.Indexer.Add(newPod("pod3", rs, v1.PodRunning, nil)) err := manager.syncReplicaSet(getKey(rs, t)) if err != nil { t.Fatal(err) @@ -1250,11 +1251,11 @@ func TestUpdateLabelsRemoveControllerRef(t *testing.T) { manager, fakePodControl := setupManagerWithGCEnabled(stopCh, rs) manager.rsLister.Indexer.Add(rs) // put one pod in the podLister - pod := newPod("pod", rs, api.PodRunning, nil) + pod := newPod("pod", rs, v1.PodRunning, nil) pod.ResourceVersion = "1" var trueVar = true - rsOwnerReference := api.OwnerReference{UID: rs.UID, APIVersion: "v1beta1", Kind: "ReplicaSet", Name: rs.Name, Controller: &trueVar} - pod.OwnerReferences = []api.OwnerReference{rsOwnerReference} + rsOwnerReference := v1.OwnerReference{UID: rs.UID, APIVersion: "v1beta1", Kind: "ReplicaSet", Name: rs.Name, Controller: &trueVar} + pod.OwnerReferences = []v1.OwnerReference{rsOwnerReference} updatedPod := *pod // reset the labels updatedPod.Labels = make(map[string]string) @@ -1277,7 +1278,7 @@ func TestUpdateLabelsRemoveControllerRef(t *testing.T) { t.Fatal(err) } // expect 1 patch to be sent to remove the controllerRef for the pod. - // expect 2 creates because the rs.Spec.Replicas=2 and there exists no + // expect 2 creates because the *(rs.Spec.Replicas)=2 and there exists no // matching pod. validateSyncReplicaSet(t, fakePodControl, 2, 0, 1) fakePodControl.Clear() @@ -1290,7 +1291,7 @@ func TestUpdateSelectorControllerRef(t *testing.T) { defer close(stopCh) manager, fakePodControl := setupManagerWithGCEnabled(stopCh, rs) // put 2 pods in the podLister - newPodList(manager.podLister.Indexer, 2, api.PodRunning, labelMap, rs, "pod") + newPodList(manager.podLister.Indexer, 2, v1.PodRunning, labelMap, rs, "pod") // update the RS so that its selector no longer matches the pods updatedRS := *rs updatedRS.Spec.Selector.MatchLabels = map[string]string{"foo": "baz"} @@ -1311,7 +1312,7 @@ func TestUpdateSelectorControllerRef(t *testing.T) { t.Fatal(err) } // expect 2 patches to be sent to remove the controllerRef for the pods. - // expect 2 creates because the rc.Spec.Replicas=2 and there exists no + // expect 2 creates because the *(rc.Spec.Replicas)=2 and there exists no // matching pod. validateSyncReplicaSet(t, fakePodControl, 2, 0, 2) fakePodControl.Clear() @@ -1328,7 +1329,7 @@ func TestDoNotAdoptOrCreateIfBeingDeleted(t *testing.T) { now := unversioned.Now() rs.DeletionTimestamp = &now manager.rsLister.Indexer.Add(rs) - pod1 := newPod("pod1", rs, api.PodRunning, nil) + pod1 := newPod("pod1", rs, v1.PodRunning, nil) manager.podLister.Indexer.Add(pod1) // no patch, no create @@ -1349,7 +1350,7 @@ func TestReadyReplicas(t *testing.T) { testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) stopCh := make(chan struct{}) defer close(stopCh) manager := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas, 0) @@ -1362,8 +1363,8 @@ func TestReadyReplicas(t *testing.T) { rs.Generation = 1 manager.rsLister.Indexer.Add(rs) - newPodList(manager.podLister.Indexer, 2, api.PodPending, labelMap, rs, "pod") - newPodList(manager.podLister.Indexer, 2, api.PodRunning, labelMap, rs, "pod") + newPodList(manager.podLister.Indexer, 2, v1.PodPending, labelMap, rs, "pod") + newPodList(manager.podLister.Indexer, 2, v1.PodRunning, labelMap, rs, "pod") // This response body is just so we don't err out decoding the http response response := runtime.EncodeOrDie(testapi.Extensions.Codec(), &extensions.ReplicaSet{}) @@ -1392,7 +1393,7 @@ func TestAvailableReplicas(t *testing.T) { testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) stopCh := make(chan struct{}) defer close(stopCh) manager := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas, 0) @@ -1409,12 +1410,12 @@ func TestAvailableReplicas(t *testing.T) { // First pod becomes ready 20s ago moment := unversioned.Time{Time: time.Now().Add(-2e10)} - pod := newPod("pod", rs, api.PodRunning, &moment) + pod := newPod("pod", rs, v1.PodRunning, &moment) manager.podLister.Indexer.Add(pod) // Second pod becomes ready now otherMoment := unversioned.Now() - otherPod := newPod("otherPod", rs, api.PodRunning, &otherMoment) + otherPod := newPod("otherPod", rs, v1.PodRunning, &otherMoment) manager.podLister.Indexer.Add(otherPod) // This response body is just so we don't err out decoding the http response @@ -1440,7 +1441,7 @@ var ( condImagePullBackOff = func() extensions.ReplicaSetCondition { return extensions.ReplicaSetCondition{ Type: imagePullBackOff, - Status: api.ConditionTrue, + Status: v1.ConditionTrue, Reason: "NonExistentImage", } } @@ -1448,7 +1449,7 @@ var ( condReplicaFailure = func() extensions.ReplicaSetCondition { return extensions.ReplicaSetCondition{ Type: extensions.ReplicaSetReplicaFailure, - Status: api.ConditionTrue, + Status: v1.ConditionTrue, Reason: "OtherFailure", } } @@ -1456,7 +1457,7 @@ var ( condReplicaFailure2 = func() extensions.ReplicaSetCondition { return extensions.ReplicaSetCondition{ Type: extensions.ReplicaSetReplicaFailure, - Status: api.ConditionTrue, + Status: v1.ConditionTrue, Reason: "AnotherFailure", } } @@ -1476,7 +1477,7 @@ func TestGetCondition(t *testing.T) { status extensions.ReplicaSetStatus condType extensions.ReplicaSetConditionType - condStatus api.ConditionStatus + condStatus v1.ConditionStatus condReason string expected bool diff --git a/pkg/controller/replicaset/replica_set_utils.go b/pkg/controller/replicaset/replica_set_utils.go index 1c20456b38a..5c2a899b038 100644 --- a/pkg/controller/replicaset/replica_set_utils.go +++ b/pkg/controller/replicaset/replica_set_utils.go @@ -26,8 +26,9 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - unversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + unversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1" "k8s.io/kubernetes/pkg/labels" ) @@ -62,7 +63,7 @@ func updateReplicaSetStatus(c unversionedextensions.ReplicaSetInterface, rs exte var getErr error for i, rs := 0, &rs; ; i++ { glog.V(4).Infof(fmt.Sprintf("Updating replica count for ReplicaSet: %s/%s, ", rs.Namespace, rs.Name) + - fmt.Sprintf("replicas %d->%d (need %d), ", rs.Status.Replicas, newStatus.Replicas, rs.Spec.Replicas) + + fmt.Sprintf("replicas %d->%d (need %d), ", rs.Status.Replicas, newStatus.Replicas, *(rs.Spec.Replicas)) + fmt.Sprintf("fullyLabeledReplicas %d->%d, ", rs.Status.FullyLabeledReplicas, newStatus.FullyLabeledReplicas) + fmt.Sprintf("readyReplicas %d->%d, ", rs.Status.ReadyReplicas, newStatus.ReadyReplicas) + fmt.Sprintf("availableReplicas %d->%d, ", rs.Status.AvailableReplicas, newStatus.AvailableReplicas) + @@ -95,7 +96,7 @@ func (o overlappingReplicaSets) Less(i, j int) bool { return o[i].CreationTimestamp.Before(o[j].CreationTimestamp) } -func calculateStatus(rs extensions.ReplicaSet, filteredPods []*api.Pod, manageReplicasErr error) extensions.ReplicaSetStatus { +func calculateStatus(rs extensions.ReplicaSet, filteredPods []*v1.Pod, manageReplicasErr error) extensions.ReplicaSetStatus { newStatus := rs.Status // Count the number of pods that have labels matching the labels of the pod // template of the replica set, the matching pods may have more @@ -110,9 +111,9 @@ func calculateStatus(rs extensions.ReplicaSet, filteredPods []*api.Pod, manageRe if templateLabel.Matches(labels.Set(pod.Labels)) { fullyLabeledReplicasCount++ } - if api.IsPodReady(pod) { + if v1.IsPodReady(pod) { readyReplicasCount++ - if api.IsPodAvailable(pod, rs.Spec.MinReadySeconds, unversioned.Now()) { + if v1.IsPodAvailable(pod, rs.Spec.MinReadySeconds, unversioned.Now()) { availableReplicasCount++ } } @@ -121,12 +122,12 @@ func calculateStatus(rs extensions.ReplicaSet, filteredPods []*api.Pod, manageRe failureCond := GetCondition(rs.Status, extensions.ReplicaSetReplicaFailure) if manageReplicasErr != nil && failureCond == nil { var reason string - if diff := len(filteredPods) - int(rs.Spec.Replicas); diff < 0 { + if diff := len(filteredPods) - int(*(rs.Spec.Replicas)); diff < 0 { reason = "FailedCreate" } else if diff > 0 { reason = "FailedDelete" } - cond := NewReplicaSetCondition(extensions.ReplicaSetReplicaFailure, api.ConditionTrue, reason, manageReplicasErr.Error()) + cond := NewReplicaSetCondition(extensions.ReplicaSetReplicaFailure, v1.ConditionTrue, reason, manageReplicasErr.Error()) SetCondition(&newStatus, cond) } else if manageReplicasErr == nil && failureCond != nil { RemoveCondition(&newStatus, extensions.ReplicaSetReplicaFailure) @@ -140,7 +141,7 @@ func calculateStatus(rs extensions.ReplicaSet, filteredPods []*api.Pod, manageRe } // NewReplicaSetCondition creates a new replica set condition. -func NewReplicaSetCondition(condType extensions.ReplicaSetConditionType, status api.ConditionStatus, reason, msg string) extensions.ReplicaSetCondition { +func NewReplicaSetCondition(condType extensions.ReplicaSetConditionType, status v1.ConditionStatus, reason, msg string) extensions.ReplicaSetCondition { return extensions.ReplicaSetCondition{ Type: condType, Status: status, diff --git a/pkg/controller/replication/BUILD b/pkg/controller/replication/BUILD index 9a4b476266c..7f00ac0f19b 100644 --- a/pkg/controller/replication/BUILD +++ b/pkg/controller/replication/BUILD @@ -19,13 +19,12 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/controller:go_default_library", "//pkg/controller/informers:go_default_library", @@ -51,10 +50,11 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/testapi:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/controller:go_default_library", diff --git a/pkg/controller/replication/replication_controller.go b/pkg/controller/replication/replication_controller.go index 31bf816f227..e84b13f6a90 100644 --- a/pkg/controller/replication/replication_controller.go +++ b/pkg/controller/replication/replication_controller.go @@ -25,13 +25,12 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/informers" @@ -122,9 +121,9 @@ type ReplicationManager struct { func NewReplicationManager(podInformer cache.SharedIndexInformer, kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, burstReplicas int, lookupCacheSize int, garbageCollectorEnabled bool) *ReplicationManager { eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(glog.Infof) - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.Core().Events("")}) return newReplicationManager( - eventBroadcaster.NewRecorder(api.EventSource{Component: "replication-controller"}), + eventBroadcaster.NewRecorder(v1.EventSource{Component: "replication-controller"}), podInformer, kubeClient, resyncPeriod, burstReplicas, lookupCacheSize, garbageCollectorEnabled) } @@ -148,14 +147,14 @@ func newReplicationManager(eventRecorder record.EventRecorder, podInformer cache rm.rcStore.Indexer, rm.rcController = cache.NewIndexerInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return rm.kubeClient.Core().ReplicationControllers(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return rm.kubeClient.Core().ReplicationControllers(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return rm.kubeClient.Core().ReplicationControllers(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return rm.kubeClient.Core().ReplicationControllers(v1.NamespaceAll).Watch(options) }, }, - &api.ReplicationController{}, + &v1.ReplicationController{}, // TODO: Can we have much longer period here? FullControllerResyncPeriod, cache.ResourceEventHandlerFuncs{ @@ -235,10 +234,10 @@ func (rm *ReplicationManager) Run(workers int, stopCh <-chan struct{}) { // getPodController returns the controller managing the given pod. // TODO: Surface that we are ignoring multiple controllers for a single pod. // TODO: use ownerReference.Controller to determine if the rc controls the pod. -func (rm *ReplicationManager) getPodController(pod *api.Pod) *api.ReplicationController { +func (rm *ReplicationManager) getPodController(pod *v1.Pod) *v1.ReplicationController { // look up in the cache, if cached and the cache is valid, just return cached value if obj, cached := rm.lookupCache.GetMatchingObject(pod); cached { - controller, ok := obj.(*api.ReplicationController) + controller, ok := obj.(*v1.ReplicationController) if !ok { // This should not happen glog.Errorf("lookup cache does not return a ReplicationController object") @@ -275,7 +274,7 @@ func (rm *ReplicationManager) getPodController(pod *api.Pod) *api.ReplicationCon } // isCacheValid check if the cache is valid -func (rm *ReplicationManager) isCacheValid(pod *api.Pod, cachedRC *api.ReplicationController) bool { +func (rm *ReplicationManager) isCacheValid(pod *v1.Pod, cachedRC *v1.ReplicationController) bool { _, err := rm.rcStore.ReplicationControllers(cachedRC.Namespace).Get(cachedRC.Name) // rc has been deleted or updated, cache is invalid if err != nil || !isControllerMatch(pod, cachedRC) { @@ -286,7 +285,7 @@ func (rm *ReplicationManager) isCacheValid(pod *api.Pod, cachedRC *api.Replicati // isControllerMatch take a Pod and ReplicationController, return whether the Pod and ReplicationController are matching // TODO(mqliang): This logic is a copy from GetPodControllers(), remove the duplication -func isControllerMatch(pod *api.Pod, rc *api.ReplicationController) bool { +func isControllerMatch(pod *v1.Pod, rc *v1.ReplicationController) bool { if rc.Namespace != pod.Namespace { return false } @@ -301,8 +300,8 @@ func isControllerMatch(pod *api.Pod, rc *api.ReplicationController) bool { // callback when RC is updated func (rm *ReplicationManager) updateRC(old, cur interface{}) { - oldRC := old.(*api.ReplicationController) - curRC := cur.(*api.ReplicationController) + oldRC := old.(*v1.ReplicationController) + curRC := cur.(*v1.ReplicationController) // We should invalidate the whole lookup cache if a RC's selector has been updated. // @@ -319,7 +318,7 @@ func (rm *ReplicationManager) updateRC(old, cur interface{}) { rm.lookupCache.InvalidateAll() } // TODO: Remove when #31981 is resolved! - glog.Infof("Observed updated replication controller %v. Desired pod count change: %d->%d", curRC.Name, oldRC.Spec.Replicas, curRC.Spec.Replicas) + glog.Infof("Observed updated replication controller %v. Desired pod count change: %d->%d", curRC.Name, *(oldRC.Spec.Replicas), *(curRC.Spec.Replicas)) // You might imagine that we only really need to enqueue the // controller when Spec changes, but it is safer to sync any @@ -342,7 +341,7 @@ func (rm *ReplicationManager) updateRC(old, cur interface{}) { // When a pod is created, enqueue the controller that manages it and update it's expectations. func (rm *ReplicationManager) addPod(obj interface{}) { - pod := obj.(*api.Pod) + pod := obj.(*v1.Pod) rc := rm.getPodController(pod) if rc == nil { @@ -366,10 +365,10 @@ func (rm *ReplicationManager) addPod(obj interface{}) { // When a pod is updated, figure out what controller/s manage it and wake them // up. If the labels of the pod have changed we need to awaken both the old -// and new controller. old and cur must be *api.Pod types. +// and new controller. old and cur must be *v1.Pod types. func (rm *ReplicationManager) updatePod(old, cur interface{}) { - curPod := cur.(*api.Pod) - oldPod := old.(*api.Pod) + curPod := cur.(*v1.Pod) + oldPod := old.(*v1.Pod) if curPod.ResourceVersion == oldPod.ResourceVersion { // Periodic resync will send update events for all known pods. // Two different versions of the same pod will always have different RVs. @@ -407,9 +406,9 @@ func (rm *ReplicationManager) updatePod(old, cur interface{}) { } // When a pod is deleted, enqueue the controller that manages the pod and update its expectations. -// obj could be an *api.Pod, or a DeletionFinalStateUnknown marker item. +// obj could be an *v1.Pod, or a DeletionFinalStateUnknown marker item. func (rm *ReplicationManager) deletePod(obj interface{}) { - pod, ok := obj.(*api.Pod) + pod, ok := obj.(*v1.Pod) // When a delete is dropped, the relist will notice a pod in the store not // in the list, leading to the insertion of a tombstone object which contains @@ -421,7 +420,7 @@ func (rm *ReplicationManager) deletePod(obj interface{}) { glog.Errorf("Couldn't get object from tombstone %#v", obj) return } - pod, ok = tombstone.Obj.(*api.Pod) + pod, ok = tombstone.Obj.(*v1.Pod) if !ok { glog.Errorf("Tombstone contained object that is not a pod %#v", obj) return @@ -439,7 +438,7 @@ func (rm *ReplicationManager) deletePod(obj interface{}) { } } -// obj could be an *api.ReplicationController, or a DeletionFinalStateUnknown marker item. +// obj could be an *v1.ReplicationController, or a DeletionFinalStateUnknown marker item. func (rm *ReplicationManager) enqueueController(obj interface{}) { key, err := controller.KeyFunc(obj) if err != nil { @@ -486,8 +485,8 @@ func (rm *ReplicationManager) worker() { // manageReplicas checks and updates replicas for the given replication controller. // Does NOT modify . -func (rm *ReplicationManager) manageReplicas(filteredPods []*api.Pod, rc *api.ReplicationController) error { - diff := len(filteredPods) - int(rc.Spec.Replicas) +func (rm *ReplicationManager) manageReplicas(filteredPods []*v1.Pod, rc *v1.ReplicationController) error { + diff := len(filteredPods) - int(*(rc.Spec.Replicas)) rcKey, err := controller.KeyFunc(rc) if err != nil { return err @@ -510,14 +509,14 @@ func (rm *ReplicationManager) manageReplicas(filteredPods []*api.Pod, rc *api.Re rm.expectations.ExpectCreations(rcKey, diff) var wg sync.WaitGroup wg.Add(diff) - glog.V(2).Infof("Too few %q/%q replicas, need %d, creating %d", rc.Namespace, rc.Name, rc.Spec.Replicas, diff) + glog.V(2).Infof("Too few %q/%q replicas, need %d, creating %d", rc.Namespace, rc.Name, *(rc.Spec.Replicas), diff) for i := 0; i < diff; i++ { go func() { defer wg.Done() var err error if rm.garbageCollectorEnabled { var trueVar = true - controllerRef := &api.OwnerReference{ + controllerRef := &v1.OwnerReference{ APIVersion: getRCKind().GroupVersion().String(), Kind: getRCKind().Kind, Name: rc.Name, @@ -554,9 +553,9 @@ func (rm *ReplicationManager) manageReplicas(filteredPods []*api.Pod, rc *api.Re if diff > rm.burstReplicas { diff = rm.burstReplicas } - glog.V(2).Infof("Too many %q/%q replicas, need %d, deleting %d", rc.Namespace, rc.Name, rc.Spec.Replicas, diff) + glog.V(2).Infof("Too many %q/%q replicas, need %d, deleting %d", rc.Namespace, rc.Name, *(rc.Spec.Replicas), diff) // No need to sort pods if we are about to delete all of them - if rc.Spec.Replicas != 0 { + if *(rc.Spec.Replicas) != 0 { // Sort the pods in the order such that not-ready < ready, unscheduled // < scheduled, and pending < running. This ensures that we delete pods // in the earlier stages whenever possible. @@ -636,7 +635,7 @@ func (rm *ReplicationManager) syncReplicationController(key string) error { if err != nil { return err } - rc := *obj.(*api.ReplicationController) + rc := *obj.(*v1.ReplicationController) // Check the expectations of the rc before counting active pods, otherwise a new pod can sneak in // and update the expectations after we've retrieved active pods from the store. If a new pod enters @@ -653,7 +652,7 @@ func (rm *ReplicationManager) syncReplicationController(key string) error { // NOTE: filteredPods are pointing to objects from cache - if you need to // modify them, you need to copy it first. // TODO: Do the List and Filter in a single pass, or use an index. - var filteredPods []*api.Pod + var filteredPods []*v1.Pod if rm.garbageCollectorEnabled { // list all pods to include the pods that don't match the rc's selector // anymore but has the stale controller ref. diff --git a/pkg/controller/replication/replication_controller_test.go b/pkg/controller/replication/replication_controller_test.go index f1620a153d4..91d87452817 100644 --- a/pkg/controller/replication/replication_controller_test.go +++ b/pkg/controller/replication/replication_controller_test.go @@ -30,11 +30,12 @@ import ( "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/apimachinery/registered" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" - fakeclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" + fakeclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/controller" @@ -49,7 +50,7 @@ import ( var alwaysReady = func() bool { return true } -func getKey(rc *api.ReplicationController, t *testing.T) string { +func getKey(rc *v1.ReplicationController, t *testing.T) string { if key, err := controller.KeyFunc(rc); err != nil { t.Errorf("Unexpected error getting key for rc %v: %v", rc.Name, err) return "" @@ -58,36 +59,36 @@ func getKey(rc *api.ReplicationController, t *testing.T) string { } } -func newReplicationController(replicas int) *api.ReplicationController { - rc := &api.ReplicationController{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - ObjectMeta: api.ObjectMeta{ +func newReplicationController(replicas int) *v1.ReplicationController { + rc := &v1.ReplicationController{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + ObjectMeta: v1.ObjectMeta{ UID: uuid.NewUUID(), Name: "foobar", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, ResourceVersion: "18", }, - Spec: api.ReplicationControllerSpec{ - Replicas: int32(replicas), + Spec: v1.ReplicationControllerSpec{ + Replicas: func() *int32 { i := int32(replicas); return &i }(), Selector: map[string]string{"foo": "bar"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{ "name": "foo", "type": "production", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Image: "foo/bar", - TerminationMessagePath: api.TerminationMessagePathDefault, - ImagePullPolicy: api.PullIfNotPresent, + TerminationMessagePath: v1.TerminationMessagePathDefault, + ImagePullPolicy: v1.PullIfNotPresent, SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), }, }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSDefault, + RestartPolicy: v1.RestartPolicyAlways, + DNSPolicy: v1.DNSDefault, NodeSelector: map[string]string{ "baz": "blah", }, @@ -99,39 +100,39 @@ func newReplicationController(replicas int) *api.ReplicationController { } // create a pod with the given phase for the given rc (same selectors and namespace). -func newPod(name string, rc *api.ReplicationController, status api.PodPhase, lastTransitionTime *unversioned.Time) *api.Pod { - var conditions []api.PodCondition - if status == api.PodRunning { - condition := api.PodCondition{Type: api.PodReady, Status: api.ConditionTrue} +func newPod(name string, rc *v1.ReplicationController, status v1.PodPhase, lastTransitionTime *unversioned.Time) *v1.Pod { + var conditions []v1.PodCondition + if status == v1.PodRunning { + condition := v1.PodCondition{Type: v1.PodReady, Status: v1.ConditionTrue} if lastTransitionTime != nil { condition.LastTransitionTime = *lastTransitionTime } conditions = append(conditions, condition) } - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: rc.Spec.Selector, Namespace: rc.Namespace, }, - Status: api.PodStatus{Phase: status, Conditions: conditions}, + Status: v1.PodStatus{Phase: status, Conditions: conditions}, } } // create count pods with the given phase for the given rc (same selectors and namespace), and add them to the store. -func newPodList(store cache.Store, count int, status api.PodPhase, rc *api.ReplicationController, name string) *api.PodList { - pods := []api.Pod{} +func newPodList(store cache.Store, count int, status v1.PodPhase, rc *v1.ReplicationController, name string) *v1.PodList { + pods := []v1.Pod{} var trueVar = true - controllerReference := api.OwnerReference{UID: rc.UID, APIVersion: "v1", Kind: "ReplicationController", Name: rc.Name, Controller: &trueVar} + controllerReference := v1.OwnerReference{UID: rc.UID, APIVersion: "v1", Kind: "ReplicationController", Name: rc.Name, Controller: &trueVar} for i := 0; i < count; i++ { pod := newPod(fmt.Sprintf("%s%d", name, i), rc, status, nil) - pod.OwnerReferences = []api.OwnerReference{controllerReference} + pod.OwnerReferences = []v1.OwnerReference{controllerReference} if store != nil { store.Add(pod) } pods = append(pods, *pod) } - return &api.PodList{ + return &v1.PodList{ Items: pods, } } @@ -158,7 +159,7 @@ type serverResponse struct { } func TestSyncReplicationControllerDoesNothing(t *testing.T) { - c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady @@ -166,7 +167,7 @@ func TestSyncReplicationControllerDoesNothing(t *testing.T) { // 2 running pods, a controller with 2 replicas, sync is a no-op controllerSpec := newReplicationController(2) manager.rcStore.Indexer.Add(controllerSpec) - newPodList(manager.podStore.Indexer, 2, api.PodRunning, controllerSpec, "pod") + newPodList(manager.podStore.Indexer, 2, v1.PodRunning, controllerSpec, "pod") manager.podControl = &fakePodControl manager.syncReplicationController(getKey(controllerSpec, t)) @@ -174,7 +175,7 @@ func TestSyncReplicationControllerDoesNothing(t *testing.T) { } func TestSyncReplicationControllerDeletes(t *testing.T) { - c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady @@ -183,14 +184,14 @@ func TestSyncReplicationControllerDeletes(t *testing.T) { // 2 running pods and a controller with 1 replica, one pod delete expected controllerSpec := newReplicationController(1) manager.rcStore.Indexer.Add(controllerSpec) - newPodList(manager.podStore.Indexer, 2, api.PodRunning, controllerSpec, "pod") + newPodList(manager.podStore.Indexer, 2, v1.PodRunning, controllerSpec, "pod") manager.syncReplicationController(getKey(controllerSpec, t)) validateSyncReplication(t, &fakePodControl, 0, 1, 0) } func TestDeleteFinalStateUnknown(t *testing.T) { - c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady @@ -206,7 +207,7 @@ func TestDeleteFinalStateUnknown(t *testing.T) { // the controller matching the selectors of the deleted pod into the work queue. controllerSpec := newReplicationController(1) manager.rcStore.Indexer.Add(controllerSpec) - pods := newPodList(nil, 1, api.PodRunning, controllerSpec, "pod") + pods := newPodList(nil, 1, v1.PodRunning, controllerSpec, "pod") manager.deletePod(cache.DeletedFinalStateUnknown{Key: "foo", Obj: &pods.Items[0]}) go manager.worker() @@ -223,7 +224,7 @@ func TestDeleteFinalStateUnknown(t *testing.T) { } func TestSyncReplicationControllerCreates(t *testing.T) { - c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady @@ -245,7 +246,7 @@ func TestStatusUpdatesWithoutReplicasChange(t *testing.T) { } testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady @@ -253,8 +254,8 @@ func TestStatusUpdatesWithoutReplicasChange(t *testing.T) { activePods := 5 rc := newReplicationController(activePods) manager.rcStore.Indexer.Add(rc) - rc.Status = api.ReplicationControllerStatus{Replicas: int32(activePods), ReadyReplicas: int32(activePods), AvailableReplicas: int32(activePods)} - newPodList(manager.podStore.Indexer, activePods, api.PodRunning, rc, "pod") + rc.Status = v1.ReplicationControllerStatus{Replicas: int32(activePods), ReadyReplicas: int32(activePods), AvailableReplicas: int32(activePods)} + newPodList(manager.podStore.Indexer, activePods, v1.PodRunning, rc, "pod") fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl @@ -267,7 +268,7 @@ func TestStatusUpdatesWithoutReplicasChange(t *testing.T) { // This response body is just so we don't err out decoding the http response, all // we care about is the request body sent below. - response := runtime.EncodeOrDie(testapi.Default.Codec(), &api.ReplicationController{}) + response := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.ReplicationController{}) fakeHandler.ResponseBody = response rc.Generation = rc.Generation + 1 @@ -286,7 +287,7 @@ func TestControllerUpdateReplicas(t *testing.T) { } testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady @@ -294,16 +295,16 @@ func TestControllerUpdateReplicas(t *testing.T) { // Status.Replica should update to match number of pods in system, 1 new pod should be created. rc := newReplicationController(5) manager.rcStore.Indexer.Add(rc) - rc.Status = api.ReplicationControllerStatus{Replicas: 2, FullyLabeledReplicas: 6, ReadyReplicas: 2, AvailableReplicas: 2, ObservedGeneration: 0} + rc.Status = v1.ReplicationControllerStatus{Replicas: 2, FullyLabeledReplicas: 6, ReadyReplicas: 2, AvailableReplicas: 2, ObservedGeneration: 0} rc.Generation = 1 - newPodList(manager.podStore.Indexer, 2, api.PodRunning, rc, "pod") + newPodList(manager.podStore.Indexer, 2, v1.PodRunning, rc, "pod") rcCopy := *rc extraLabelMap := map[string]string{"foo": "bar", "extraKey": "extraValue"} rcCopy.Spec.Selector = extraLabelMap - newPodList(manager.podStore.Indexer, 2, api.PodRunning, &rcCopy, "podWithExtraLabel") + newPodList(manager.podStore.Indexer, 2, v1.PodRunning, &rcCopy, "podWithExtraLabel") // This response body is just so we don't err out decoding the http response - response := runtime.EncodeOrDie(testapi.Default.Codec(), &api.ReplicationController{}) + response := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.ReplicationController{}) fakeHandler.ResponseBody = response fakePodControl := controller.FakePodControl{} @@ -315,7 +316,7 @@ func TestControllerUpdateReplicas(t *testing.T) { // 2. Status.FullyLabeledReplicas should equal to the number of pods that // has the extra labels, i.e., 2. // 3. Every update to the status should include the Generation of the spec. - rc.Status = api.ReplicationControllerStatus{Replicas: 4, ReadyReplicas: 4, AvailableReplicas: 4, ObservedGeneration: 1} + rc.Status = v1.ReplicationControllerStatus{Replicas: 4, ReadyReplicas: 4, AvailableReplicas: 4, ObservedGeneration: 1} decRc := runtime.EncodeOrDie(testapi.Default.Codec(), rc) fakeHandler.ValidateRequest(t, testapi.Default.ResourcePath(replicationControllerResourceName(), rc.Namespace, rc.Name)+"/status", "PUT", &decRc) @@ -331,7 +332,7 @@ func TestSyncReplicationControllerDormancy(t *testing.T) { } testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady @@ -339,7 +340,7 @@ func TestSyncReplicationControllerDormancy(t *testing.T) { controllerSpec := newReplicationController(2) manager.rcStore.Indexer.Add(controllerSpec) - newPodList(manager.podStore.Indexer, 1, api.PodRunning, controllerSpec, "pod") + newPodList(manager.podStore.Indexer, 1, v1.PodRunning, controllerSpec, "pod") // Creates a replica and sets expectations controllerSpec.Status.Replicas = 1 @@ -386,47 +387,47 @@ func TestSyncReplicationControllerDormancy(t *testing.T) { } func TestPodControllerLookup(t *testing.T) { - manager := NewReplicationManagerFromClient(clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}), controller.NoResyncPeriodFunc, BurstReplicas, 0) + manager := NewReplicationManagerFromClient(clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}), controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady testCases := []struct { - inRCs []*api.ReplicationController - pod *api.Pod + inRCs []*v1.ReplicationController + pod *v1.Pod outRCName string }{ // pods without labels don't match any rcs { - inRCs: []*api.ReplicationController{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}}, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo1", Namespace: api.NamespaceAll}}, + inRCs: []*v1.ReplicationController{ + {ObjectMeta: v1.ObjectMeta{Name: "basic"}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo1", Namespace: v1.NamespaceAll}}, outRCName: "", }, // Matching labels, not namespace { - inRCs: []*api.ReplicationController{ + inRCs: []*v1.ReplicationController{ { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.ReplicationControllerSpec{ + ObjectMeta: v1.ObjectMeta{Name: "foo"}, + Spec: v1.ReplicationControllerSpec{ Selector: map[string]string{"foo": "bar"}, }, }, }, - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "foo2", Namespace: "ns", Labels: map[string]string{"foo": "bar"}}}, outRCName: "", }, // Matching ns and labels returns the key to the rc, not the rc name { - inRCs: []*api.ReplicationController{ + inRCs: []*v1.ReplicationController{ { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "ns"}, - Spec: api.ReplicationControllerSpec{ + ObjectMeta: v1.ObjectMeta{Name: "bar", Namespace: "ns"}, + Spec: v1.ReplicationControllerSpec{ Selector: map[string]string{"foo": "bar"}, }, }, }, - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "foo3", Namespace: "ns", Labels: map[string]string{"foo": "bar"}}}, outRCName: "bar", }, @@ -452,7 +453,7 @@ func TestWatchControllers(t *testing.T) { manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady - var testControllerSpec api.ReplicationController + var testControllerSpec v1.ReplicationController received := make(chan string) // The update sent through the fakeWatcher should make its way into the workqueue, @@ -464,7 +465,7 @@ func TestWatchControllers(t *testing.T) { if !exists || err != nil { t.Errorf("Expected to find controller under key %v", key) } - controllerSpec := *obj.(*api.ReplicationController) + controllerSpec := *obj.(*v1.ReplicationController) if !api.Semantic.DeepDerivative(controllerSpec, testControllerSpec) { t.Errorf("Expected %#v, but got %#v", testControllerSpec, controllerSpec) } @@ -507,7 +508,7 @@ func TestWatchPods(t *testing.T) { if !exists || err != nil { t.Errorf("Expected to find controller under key %v", key) } - controllerSpec := obj.(*api.ReplicationController) + controllerSpec := obj.(*v1.ReplicationController) if !api.Semantic.DeepDerivative(controllerSpec, testControllerSpec) { t.Errorf("\nExpected %#v,\nbut got %#v", testControllerSpec, controllerSpec) } @@ -522,9 +523,9 @@ func TestWatchPods(t *testing.T) { go manager.internalPodInformer.Run(stopCh) go wait.Until(manager.worker, 10*time.Millisecond, stopCh) - pods := newPodList(nil, 1, api.PodRunning, testControllerSpec, "pod") + pods := newPodList(nil, 1, v1.PodRunning, testControllerSpec, "pod") testPod := pods.Items[0] - testPod.Status.Phase = api.PodFailed + testPod.Status.Phase = v1.PodFailed fakeWatch.Add(&testPod) select { @@ -545,7 +546,7 @@ func TestUpdatePods(t *testing.T) { if !exists || err != nil { t.Errorf("Expected to find controller under key %v", key) } - received <- obj.(*api.ReplicationController).Name + received <- obj.(*v1.ReplicationController).Name return nil } @@ -564,7 +565,7 @@ func TestUpdatePods(t *testing.T) { // case 1: We put in the podStore a pod with labels matching // testControllerSpec1, then update its labels to match testControllerSpec2. // We expect to receive a sync request for both controllers. - pod1 := newPodList(manager.podStore.Indexer, 1, api.PodRunning, testControllerSpec1, "pod").Items[0] + pod1 := newPodList(manager.podStore.Indexer, 1, v1.PodRunning, testControllerSpec1, "pod").Items[0] pod1.ResourceVersion = "1" pod2 := pod1 pod2.Labels = testControllerSpec2.Spec.Selector @@ -612,14 +613,14 @@ func TestControllerUpdateRequeue(t *testing.T) { testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady rc := newReplicationController(1) manager.rcStore.Indexer.Add(rc) - rc.Status = api.ReplicationControllerStatus{Replicas: 2} - newPodList(manager.podStore.Indexer, 1, api.PodRunning, rc, "pod") + rc.Status = v1.ReplicationControllerStatus{Replicas: 2} + newPodList(manager.podStore.Indexer, 1, v1.PodRunning, rc, "pod") fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl @@ -640,11 +641,11 @@ func TestControllerUpdateStatusWithFailure(t *testing.T) { return true, rc, nil }) c.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) { - return true, &api.ReplicationController{}, fmt.Errorf("Fake error") + return true, &v1.ReplicationController{}, fmt.Errorf("Fake error") }) fakeRCClient := c.Core().ReplicationControllers("default") numReplicas := int32(10) - status := api.ReplicationControllerStatus{Replicas: numReplicas} + status := v1.ReplicationControllerStatus{Replicas: numReplicas} updateReplicationControllerStatus(fakeRCClient, *rc, status) updates, gets := 0, 0 for _, a := range c.Actions() { @@ -664,7 +665,7 @@ func TestControllerUpdateStatusWithFailure(t *testing.T) { updates++ // Confirm that the update has the right status.Replicas even though the Get // returned an rc with replicas=1. - if c, ok := action.GetObject().(*api.ReplicationController); !ok { + if c, ok := action.GetObject().(*v1.ReplicationController); !ok { t.Errorf("Expected an rc as the argument to update, got %T", c) } else if c.Status.Replicas != numReplicas { t.Errorf("Expected update for rc to contain replicas %v, got %v instead", @@ -682,7 +683,7 @@ func TestControllerUpdateStatusWithFailure(t *testing.T) { // TODO: This test is too hairy for a unittest. It should be moved to an E2E suite. func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) { - c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, burstReplicas, 0) manager.podStoreSynced = alwaysReady @@ -692,7 +693,7 @@ func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) manager.rcStore.Indexer.Add(controllerSpec) expectedPods := 0 - pods := newPodList(nil, numReplicas, api.PodPending, controllerSpec, "pod") + pods := newPodList(nil, numReplicas, v1.PodPending, controllerSpec, "pod") rcKey, err := controller.KeyFunc(controllerSpec) if err != nil { @@ -702,7 +703,7 @@ func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) // Size up the controller, then size it down, and confirm the expected create/delete pattern for _, replicas := range []int{numReplicas, 0} { - controllerSpec.Spec.Replicas = int32(replicas) + *(controllerSpec.Spec.Replicas) = int32(replicas) manager.rcStore.Indexer.Add(controllerSpec) for i := 0; i < numReplicas; i += burstReplicas { @@ -745,11 +746,11 @@ func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) // To accurately simulate a watch we must delete the exact pods // the rc is waiting for. expectedDels := manager.expectations.GetUIDs(getKey(controllerSpec, t)) - podsToDelete := []*api.Pod{} + podsToDelete := []*v1.Pod{} for _, key := range expectedDels.List() { nsName := strings.Split(key, "/") - podsToDelete = append(podsToDelete, &api.Pod{ - ObjectMeta: api.ObjectMeta{ + podsToDelete = append(podsToDelete, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: nsName[1], Namespace: nsName[0], Labels: controllerSpec.Spec.Selector, @@ -789,8 +790,8 @@ func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) t.Fatalf("Waiting on unexpected number of deletes.") } nsName := strings.Split(expectedDel.List()[0], "/") - lastPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + lastPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: nsName[1], Namespace: nsName[0], Labels: controllerSpec.Spec.Selector, @@ -804,11 +805,11 @@ func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) // Confirm that we've created the right number of replicas activePods := int32(len(manager.podStore.Indexer.List())) - if activePods != controllerSpec.Spec.Replicas { - t.Fatalf("Unexpected number of active pods, expected %d, got %d", controllerSpec.Spec.Replicas, activePods) + if activePods != *(controllerSpec.Spec.Replicas) { + t.Fatalf("Unexpected number of active pods, expected %d, got %d", *(controllerSpec.Spec.Replicas), activePods) } // Replenish the pod list, since we cut it down sizing up - pods = newPodList(nil, replicas, api.PodRunning, controllerSpec, "pod") + pods = newPodList(nil, replicas, v1.PodRunning, controllerSpec, "pod") } } @@ -832,7 +833,7 @@ func (fe FakeRCExpectations) SatisfiedExpectations(controllerKey string) bool { // TestRCSyncExpectations tests that a pod cannot sneak in between counting active pods // and checking expectations. func TestRCSyncExpectations(t *testing.T) { - c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, 2, 0) manager.podStoreSynced = alwaysReady @@ -840,7 +841,7 @@ func TestRCSyncExpectations(t *testing.T) { controllerSpec := newReplicationController(2) manager.rcStore.Indexer.Add(controllerSpec) - pods := newPodList(nil, 2, api.PodPending, controllerSpec, "pod") + pods := newPodList(nil, 2, v1.PodPending, controllerSpec, "pod") manager.podStore.Indexer.Add(&pods.Items[0]) postExpectationsPod := pods.Items[1] @@ -857,7 +858,7 @@ func TestRCSyncExpectations(t *testing.T) { } func TestDeleteControllerAndExpectations(t *testing.T) { - c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, 10, 0) manager.podStoreSynced = alwaysReady @@ -899,7 +900,7 @@ func TestDeleteControllerAndExpectations(t *testing.T) { } func TestRCManagerNotReady(t *testing.T) { - c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) fakePodControl := controller.FakePodControl{} manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, 2, 0) manager.podControl = &fakePodControl @@ -925,10 +926,10 @@ func TestRCManagerNotReady(t *testing.T) { } // shuffle returns a new shuffled list of container controllers. -func shuffle(controllers []*api.ReplicationController) []*api.ReplicationController { +func shuffle(controllers []*v1.ReplicationController) []*v1.ReplicationController { numControllers := len(controllers) randIndexes := rand.Perm(numControllers) - shuffled := make([]*api.ReplicationController, numControllers) + shuffled := make([]*v1.ReplicationController, numControllers) for i := 0; i < numControllers; i++ { shuffled[i] = controllers[randIndexes[i]] } @@ -936,14 +937,14 @@ func shuffle(controllers []*api.ReplicationController) []*api.ReplicationControl } func TestOverlappingRCs(t *testing.T) { - c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) for i := 0; i < 5; i++ { manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, 10, 0) manager.podStoreSynced = alwaysReady // Create 10 rcs, shuffled them randomly and insert them into the rc manager's store - var controllers []*api.ReplicationController + var controllers []*v1.ReplicationController for j := 1; j < 10; j++ { controllerSpec := newReplicationController(1) controllerSpec.CreationTimestamp = unversioned.Date(2014, time.December, j, 0, 0, 0, 0, time.Local) @@ -955,7 +956,7 @@ func TestOverlappingRCs(t *testing.T) { manager.rcStore.Indexer.Add(shuffledControllers[j]) } // Add a pod and make sure only the oldest rc is synced - pods := newPodList(nil, 1, api.PodPending, controllers[0], "pod") + pods := newPodList(nil, 1, v1.PodPending, controllers[0], "pod") rcKey := getKey(controllers[0], t) manager.addPod(&pods.Items[0]) @@ -967,7 +968,7 @@ func TestOverlappingRCs(t *testing.T) { } func TestDeletionTimestamp(t *testing.T) { - c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, 10, 0) manager.podStoreSynced = alwaysReady @@ -977,7 +978,7 @@ func TestDeletionTimestamp(t *testing.T) { if err != nil { t.Errorf("Couldn't get key for object %#v: %v", controllerSpec, err) } - pod := newPodList(nil, 1, api.PodPending, controllerSpec, "pod").Items[0] + pod := newPodList(nil, 1, v1.PodPending, controllerSpec, "pod").Items[0] pod.DeletionTimestamp = &unversioned.Time{Time: time.Now()} pod.ResourceVersion = "1" manager.expectations.ExpectDeletions(rcKey, []string{controller.PodKey(&pod)}) @@ -998,7 +999,7 @@ func TestDeletionTimestamp(t *testing.T) { // An update from no deletion timestamp to having one should be treated // as a deletion. - oldPod := newPodList(nil, 1, api.PodPending, controllerSpec, "pod").Items[0] + oldPod := newPodList(nil, 1, v1.PodPending, controllerSpec, "pod").Items[0] oldPod.ResourceVersion = "2" manager.expectations.ExpectDeletions(rcKey, []string{controller.PodKey(&pod)}) manager.updatePod(&oldPod, &pod) @@ -1016,8 +1017,8 @@ func TestDeletionTimestamp(t *testing.T) { // An update to the pod (including an update to the deletion timestamp) // should not be counted as a second delete. - secondPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + secondPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: pod.Namespace, Name: "secondPod", Labels: pod.Labels, @@ -1057,20 +1058,20 @@ func TestDeletionTimestamp(t *testing.T) { } func BenchmarkGetPodControllerMultiNS(b *testing.B) { - client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager := NewReplicationManagerFromClient(client, controller.NoResyncPeriodFunc, BurstReplicas, 0) const nsNum = 1000 - pods := []api.Pod{} + pods := []v1.Pod{} for i := 0; i < nsNum; i++ { ns := fmt.Sprintf("ns-%d", i) for j := 0; j < 10; j++ { rcName := fmt.Sprintf("rc-%d", j) for k := 0; k < 10; k++ { podName := fmt.Sprintf("pod-%d-%d", j, k) - pods = append(pods, api.Pod{ - ObjectMeta: api.ObjectMeta{ + pods = append(pods, v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Namespace: ns, Labels: map[string]string{"rcName": rcName}, @@ -1084,9 +1085,9 @@ func BenchmarkGetPodControllerMultiNS(b *testing.B) { ns := fmt.Sprintf("ns-%d", i) for j := 0; j < 10; j++ { rcName := fmt.Sprintf("rc-%d", j) - manager.rcStore.Indexer.Add(&api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: rcName, Namespace: ns}, - Spec: api.ReplicationControllerSpec{ + manager.rcStore.Indexer.Add(&v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{Name: rcName, Namespace: ns}, + Spec: v1.ReplicationControllerSpec{ Selector: map[string]string{"rcName": rcName}, }, }) @@ -1103,19 +1104,19 @@ func BenchmarkGetPodControllerMultiNS(b *testing.B) { } func BenchmarkGetPodControllerSingleNS(b *testing.B) { - client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager := NewReplicationManagerFromClient(client, controller.NoResyncPeriodFunc, BurstReplicas, 0) const rcNum = 1000 const replicaNum = 3 - pods := []api.Pod{} + pods := []v1.Pod{} for i := 0; i < rcNum; i++ { rcName := fmt.Sprintf("rc-%d", i) for j := 0; j < replicaNum; j++ { podName := fmt.Sprintf("pod-%d-%d", i, j) - pods = append(pods, api.Pod{ - ObjectMeta: api.ObjectMeta{ + pods = append(pods, v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Namespace: "foo", Labels: map[string]string{"rcName": rcName}, @@ -1126,9 +1127,9 @@ func BenchmarkGetPodControllerSingleNS(b *testing.B) { for i := 0; i < rcNum; i++ { rcName := fmt.Sprintf("rc-%d", i) - manager.rcStore.Indexer.Add(&api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: rcName, Namespace: "foo"}, - Spec: api.ReplicationControllerSpec{ + manager.rcStore.Indexer.Add(&v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{Name: rcName, Namespace: "foo"}, + Spec: v1.ReplicationControllerSpec{ Selector: map[string]string{"rcName": rcName}, }, }) @@ -1158,10 +1159,10 @@ func TestDoNotPatchPodWithOtherControlRef(t *testing.T) { rc := newReplicationController(2) manager.rcStore.Indexer.Add(rc) var trueVar = true - otherControllerReference := api.OwnerReference{UID: uuid.NewUUID(), APIVersion: "v1", Kind: "ReplicationController", Name: "AnotherRC", Controller: &trueVar} + otherControllerReference := v1.OwnerReference{UID: uuid.NewUUID(), APIVersion: "v1", Kind: "ReplicationController", Name: "AnotherRC", Controller: &trueVar} // add to podStore a matching Pod controlled by another controller. Expect no patch. - pod := newPod("pod", rc, api.PodRunning, nil) - pod.OwnerReferences = []api.OwnerReference{otherControllerReference} + pod := newPod("pod", rc, v1.PodRunning, nil) + pod.OwnerReferences = []v1.OwnerReference{otherControllerReference} manager.podStore.Indexer.Add(pod) err := manager.syncReplicationController(getKey(rc, t)) if err != nil { @@ -1178,9 +1179,9 @@ func TestPatchPodWithOtherOwnerRef(t *testing.T) { // add to podStore one more matching pod that doesn't have a controller // ref, but has an owner ref pointing to other object. Expect a patch to // take control of it. - unrelatedOwnerReference := api.OwnerReference{UID: uuid.NewUUID(), APIVersion: "batch/v1", Kind: "Job", Name: "Job"} - pod := newPod("pod", rc, api.PodRunning, nil) - pod.OwnerReferences = []api.OwnerReference{unrelatedOwnerReference} + unrelatedOwnerReference := v1.OwnerReference{UID: uuid.NewUUID(), APIVersion: "batch/v1", Kind: "Job", Name: "Job"} + pod := newPod("pod", rc, v1.PodRunning, nil) + pod.OwnerReferences = []v1.OwnerReference{unrelatedOwnerReference} manager.podStore.Indexer.Add(pod) err := manager.syncReplicationController(getKey(rc, t)) @@ -1197,9 +1198,9 @@ func TestPatchPodWithCorrectOwnerRef(t *testing.T) { manager.rcStore.Indexer.Add(rc) // add to podStore a matching pod that has an ownerRef pointing to the rc, // but ownerRef.Controller is false. Expect a patch to take control it. - rcOwnerReference := api.OwnerReference{UID: rc.UID, APIVersion: "v1", Kind: "ReplicationController", Name: rc.Name} - pod := newPod("pod", rc, api.PodRunning, nil) - pod.OwnerReferences = []api.OwnerReference{rcOwnerReference} + rcOwnerReference := v1.OwnerReference{UID: rc.UID, APIVersion: "v1", Kind: "ReplicationController", Name: rc.Name} + pod := newPod("pod", rc, v1.PodRunning, nil) + pod.OwnerReferences = []v1.OwnerReference{rcOwnerReference} manager.podStore.Indexer.Add(pod) err := manager.syncReplicationController(getKey(rc, t)) @@ -1216,8 +1217,8 @@ func TestPatchPodFails(t *testing.T) { manager.rcStore.Indexer.Add(rc) // add to podStore two matching pods. Expect two patches to take control // them. - manager.podStore.Indexer.Add(newPod("pod1", rc, api.PodRunning, nil)) - manager.podStore.Indexer.Add(newPod("pod2", rc, api.PodRunning, nil)) + manager.podStore.Indexer.Add(newPod("pod1", rc, v1.PodRunning, nil)) + manager.podStore.Indexer.Add(newPod("pod2", rc, v1.PodRunning, nil)) // let both patches fail. The rc manager will assume it fails to take // control of the pods and create new ones. fakePodControl.Err = fmt.Errorf("Fake Error") @@ -1235,9 +1236,9 @@ func TestPatchExtraPodsThenDelete(t *testing.T) { manager.rcStore.Indexer.Add(rc) // add to podStore three matching pods. Expect three patches to take control // them, and later delete one of them. - manager.podStore.Indexer.Add(newPod("pod1", rc, api.PodRunning, nil)) - manager.podStore.Indexer.Add(newPod("pod2", rc, api.PodRunning, nil)) - manager.podStore.Indexer.Add(newPod("pod3", rc, api.PodRunning, nil)) + manager.podStore.Indexer.Add(newPod("pod1", rc, v1.PodRunning, nil)) + manager.podStore.Indexer.Add(newPod("pod2", rc, v1.PodRunning, nil)) + manager.podStore.Indexer.Add(newPod("pod3", rc, v1.PodRunning, nil)) err := manager.syncReplicationController(getKey(rc, t)) if err != nil { t.Fatal(err) @@ -1251,11 +1252,11 @@ func TestUpdateLabelsRemoveControllerRef(t *testing.T) { rc := newReplicationController(2) manager.rcStore.Indexer.Add(rc) // put one pod in the podStore - pod := newPod("pod", rc, api.PodRunning, nil) + pod := newPod("pod", rc, v1.PodRunning, nil) pod.ResourceVersion = "1" var trueVar = true - rcOwnerReference := api.OwnerReference{UID: rc.UID, APIVersion: "v1", Kind: "ReplicationController", Name: rc.Name, Controller: &trueVar} - pod.OwnerReferences = []api.OwnerReference{rcOwnerReference} + rcOwnerReference := v1.OwnerReference{UID: rc.UID, APIVersion: "v1", Kind: "ReplicationController", Name: rc.Name, Controller: &trueVar} + pod.OwnerReferences = []v1.OwnerReference{rcOwnerReference} updatedPod := *pod // reset the labels updatedPod.Labels = make(map[string]string) @@ -1278,7 +1279,7 @@ func TestUpdateLabelsRemoveControllerRef(t *testing.T) { t.Fatal(err) } // expect 1 patch to be sent to remove the controllerRef for the pod. - // expect 2 creates because the rc.Spec.Replicas=2 and there exists no + // expect 2 creates because the *(rc.Spec.Replicas)=2 and there exists no // matching pod. validateSyncReplication(t, fakePodControl, 2, 0, 1) fakePodControl.Clear() @@ -1288,7 +1289,7 @@ func TestUpdateSelectorControllerRef(t *testing.T) { manager, fakePodControl := setupManagerWithGCEnabled() rc := newReplicationController(2) // put 2 pods in the podStore - newPodList(manager.podStore.Indexer, 2, api.PodRunning, rc, "pod") + newPodList(manager.podStore.Indexer, 2, v1.PodRunning, rc, "pod") // update the RC so that its selector no longer matches the pods updatedRC := *rc updatedRC.Spec.Selector = map[string]string{"foo": "baz"} @@ -1309,7 +1310,7 @@ func TestUpdateSelectorControllerRef(t *testing.T) { t.Fatal(err) } // expect 2 patches to be sent to remove the controllerRef for the pods. - // expect 2 creates because the rc.Spec.Replicas=2 and there exists no + // expect 2 creates because the *(rc.Spec.Replicas)=2 and there exists no // matching pod. validateSyncReplication(t, fakePodControl, 2, 0, 2) fakePodControl.Clear() @@ -1323,7 +1324,7 @@ func TestDoNotAdoptOrCreateIfBeingDeleted(t *testing.T) { now := unversioned.Now() rc.DeletionTimestamp = &now manager.rcStore.Indexer.Add(rc) - pod1 := newPod("pod1", rc, api.PodRunning, nil) + pod1 := newPod("pod1", rc, v1.PodRunning, nil) manager.podStore.Indexer.Add(pod1) // no patch, no create @@ -1343,21 +1344,21 @@ func TestReadyReplicas(t *testing.T) { testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady // Status.Replica should update to match number of pods in system, 1 new pod should be created. rc := newReplicationController(2) - rc.Status = api.ReplicationControllerStatus{Replicas: 2, ReadyReplicas: 0, AvailableReplicas: 0, ObservedGeneration: 1} + rc.Status = v1.ReplicationControllerStatus{Replicas: 2, ReadyReplicas: 0, AvailableReplicas: 0, ObservedGeneration: 1} rc.Generation = 1 manager.rcStore.Indexer.Add(rc) - newPodList(manager.podStore.Indexer, 2, api.PodPending, rc, "pod") - newPodList(manager.podStore.Indexer, 2, api.PodRunning, rc, "pod") + newPodList(manager.podStore.Indexer, 2, v1.PodPending, rc, "pod") + newPodList(manager.podStore.Indexer, 2, v1.PodRunning, rc, "pod") // This response body is just so we don't err out decoding the http response - response := runtime.EncodeOrDie(testapi.Default.Codec(), &api.ReplicationController{}) + response := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.ReplicationController{}) fakeHandler.ResponseBody = response fakePodControl := controller.FakePodControl{} @@ -1366,7 +1367,7 @@ func TestReadyReplicas(t *testing.T) { manager.syncReplicationController(getKey(rc, t)) // ReadyReplicas should go from 0 to 2. - rc.Status = api.ReplicationControllerStatus{Replicas: 2, ReadyReplicas: 2, AvailableReplicas: 2, ObservedGeneration: 1} + rc.Status = v1.ReplicationControllerStatus{Replicas: 2, ReadyReplicas: 2, AvailableReplicas: 2, ObservedGeneration: 1} decRc := runtime.EncodeOrDie(testapi.Default.Codec(), rc) fakeHandler.ValidateRequest(t, testapi.Default.ResourcePath(replicationControllerResourceName(), rc.Namespace, rc.Name)+"/status", "PUT", &decRc) @@ -1382,13 +1383,13 @@ func TestAvailableReplicas(t *testing.T) { testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() - c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) manager := NewReplicationManagerFromClient(c, controller.NoResyncPeriodFunc, BurstReplicas, 0) manager.podStoreSynced = alwaysReady // Status.Replica should update to match number of pods in system, 1 new pod should be created. rc := newReplicationController(2) - rc.Status = api.ReplicationControllerStatus{Replicas: 2, ReadyReplicas: 0, ObservedGeneration: 1} + rc.Status = v1.ReplicationControllerStatus{Replicas: 2, ReadyReplicas: 0, ObservedGeneration: 1} rc.Generation = 1 // minReadySeconds set to 15s rc.Spec.MinReadySeconds = 15 @@ -1396,16 +1397,16 @@ func TestAvailableReplicas(t *testing.T) { // First pod becomes ready 20s ago moment := unversioned.Time{Time: time.Now().Add(-2e10)} - pod := newPod("pod", rc, api.PodRunning, &moment) + pod := newPod("pod", rc, v1.PodRunning, &moment) manager.podStore.Indexer.Add(pod) // Second pod becomes ready now otherMoment := unversioned.Now() - otherPod := newPod("otherPod", rc, api.PodRunning, &otherMoment) + otherPod := newPod("otherPod", rc, v1.PodRunning, &otherMoment) manager.podStore.Indexer.Add(otherPod) // This response body is just so we don't err out decoding the http response - response := runtime.EncodeOrDie(testapi.Default.Codec(), &api.ReplicationController{}) + response := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.ReplicationController{}) fakeHandler.ResponseBody = response fakePodControl := controller.FakePodControl{} @@ -1414,7 +1415,7 @@ func TestAvailableReplicas(t *testing.T) { // The controller should see only one available pod. manager.syncReplicationController(getKey(rc, t)) - rc.Status = api.ReplicationControllerStatus{Replicas: 2, ReadyReplicas: 2, AvailableReplicas: 1, ObservedGeneration: 1} + rc.Status = v1.ReplicationControllerStatus{Replicas: 2, ReadyReplicas: 2, AvailableReplicas: 1, ObservedGeneration: 1} decRc := runtime.EncodeOrDie(testapi.Default.Codec(), rc) fakeHandler.ValidateRequest(t, testapi.Default.ResourcePath(replicationControllerResourceName(), rc.Namespace, rc.Name)+"/status", "PUT", &decRc) @@ -1422,35 +1423,35 @@ func TestAvailableReplicas(t *testing.T) { } var ( - imagePullBackOff api.ReplicationControllerConditionType = "ImagePullBackOff" + imagePullBackOff v1.ReplicationControllerConditionType = "ImagePullBackOff" - condImagePullBackOff = func() api.ReplicationControllerCondition { - return api.ReplicationControllerCondition{ + condImagePullBackOff = func() v1.ReplicationControllerCondition { + return v1.ReplicationControllerCondition{ Type: imagePullBackOff, - Status: api.ConditionTrue, + Status: v1.ConditionTrue, Reason: "NonExistentImage", } } - condReplicaFailure = func() api.ReplicationControllerCondition { - return api.ReplicationControllerCondition{ - Type: api.ReplicationControllerReplicaFailure, - Status: api.ConditionTrue, + condReplicaFailure = func() v1.ReplicationControllerCondition { + return v1.ReplicationControllerCondition{ + Type: v1.ReplicationControllerReplicaFailure, + Status: v1.ConditionTrue, Reason: "OtherFailure", } } - condReplicaFailure2 = func() api.ReplicationControllerCondition { - return api.ReplicationControllerCondition{ - Type: api.ReplicationControllerReplicaFailure, - Status: api.ConditionTrue, + condReplicaFailure2 = func() v1.ReplicationControllerCondition { + return v1.ReplicationControllerCondition{ + Type: v1.ReplicationControllerReplicaFailure, + Status: v1.ConditionTrue, Reason: "AnotherFailure", } } - status = func() *api.ReplicationControllerStatus { - return &api.ReplicationControllerStatus{ - Conditions: []api.ReplicationControllerCondition{condReplicaFailure()}, + status = func() *v1.ReplicationControllerStatus { + return &v1.ReplicationControllerStatus{ + Conditions: []v1.ReplicationControllerCondition{condReplicaFailure()}, } } ) @@ -1461,9 +1462,9 @@ func TestGetCondition(t *testing.T) { tests := []struct { name string - status api.ReplicationControllerStatus - condType api.ReplicationControllerConditionType - condStatus api.ConditionStatus + status v1.ReplicationControllerStatus + condType v1.ReplicationControllerConditionType + condStatus v1.ConditionStatus condReason string expected bool @@ -1472,7 +1473,7 @@ func TestGetCondition(t *testing.T) { name: "condition exists", status: *exampleStatus, - condType: api.ReplicationControllerReplicaFailure, + condType: v1.ReplicationControllerReplicaFailure, expected: true, }, @@ -1499,34 +1500,34 @@ func TestSetCondition(t *testing.T) { tests := []struct { name string - status *api.ReplicationControllerStatus - cond api.ReplicationControllerCondition + status *v1.ReplicationControllerStatus + cond v1.ReplicationControllerCondition - expectedStatus *api.ReplicationControllerStatus + expectedStatus *v1.ReplicationControllerStatus }{ { name: "set for the first time", - status: &api.ReplicationControllerStatus{}, + status: &v1.ReplicationControllerStatus{}, cond: condReplicaFailure(), - expectedStatus: &api.ReplicationControllerStatus{Conditions: []api.ReplicationControllerCondition{condReplicaFailure()}}, + expectedStatus: &v1.ReplicationControllerStatus{Conditions: []v1.ReplicationControllerCondition{condReplicaFailure()}}, }, { name: "simple set", - status: &api.ReplicationControllerStatus{Conditions: []api.ReplicationControllerCondition{condImagePullBackOff()}}, + status: &v1.ReplicationControllerStatus{Conditions: []v1.ReplicationControllerCondition{condImagePullBackOff()}}, cond: condReplicaFailure(), - expectedStatus: &api.ReplicationControllerStatus{Conditions: []api.ReplicationControllerCondition{condImagePullBackOff(), condReplicaFailure()}}, + expectedStatus: &v1.ReplicationControllerStatus{Conditions: []v1.ReplicationControllerCondition{condImagePullBackOff(), condReplicaFailure()}}, }, { name: "overwrite", - status: &api.ReplicationControllerStatus{Conditions: []api.ReplicationControllerCondition{condReplicaFailure()}}, + status: &v1.ReplicationControllerStatus{Conditions: []v1.ReplicationControllerCondition{condReplicaFailure()}}, cond: condReplicaFailure2(), - expectedStatus: &api.ReplicationControllerStatus{Conditions: []api.ReplicationControllerCondition{condReplicaFailure2()}}, + expectedStatus: &v1.ReplicationControllerStatus{Conditions: []v1.ReplicationControllerCondition{condReplicaFailure2()}}, }, } @@ -1542,26 +1543,26 @@ func TestRemoveCondition(t *testing.T) { tests := []struct { name string - status *api.ReplicationControllerStatus - condType api.ReplicationControllerConditionType + status *v1.ReplicationControllerStatus + condType v1.ReplicationControllerConditionType - expectedStatus *api.ReplicationControllerStatus + expectedStatus *v1.ReplicationControllerStatus }{ { name: "remove from empty status", - status: &api.ReplicationControllerStatus{}, - condType: api.ReplicationControllerReplicaFailure, + status: &v1.ReplicationControllerStatus{}, + condType: v1.ReplicationControllerReplicaFailure, - expectedStatus: &api.ReplicationControllerStatus{}, + expectedStatus: &v1.ReplicationControllerStatus{}, }, { name: "simple remove", - status: &api.ReplicationControllerStatus{Conditions: []api.ReplicationControllerCondition{condReplicaFailure()}}, - condType: api.ReplicationControllerReplicaFailure, + status: &v1.ReplicationControllerStatus{Conditions: []v1.ReplicationControllerCondition{condReplicaFailure()}}, + condType: v1.ReplicationControllerReplicaFailure, - expectedStatus: &api.ReplicationControllerStatus{}, + expectedStatus: &v1.ReplicationControllerStatus{}, }, { name: "doesn't remove anything", diff --git a/pkg/controller/replication/replication_controller_utils.go b/pkg/controller/replication/replication_controller_utils.go index 0fbd425288d..c7d0260ee36 100644 --- a/pkg/controller/replication/replication_controller_utils.go +++ b/pkg/controller/replication/replication_controller_utils.go @@ -23,14 +23,14 @@ import ( "reflect" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + "k8s.io/kubernetes/pkg/api/v1" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/labels" ) // updateReplicationControllerStatus attempts to update the Status.Replicas of the given controller, with a single GET/PUT retry. -func updateReplicationControllerStatus(c unversionedcore.ReplicationControllerInterface, rc api.ReplicationController, newStatus api.ReplicationControllerStatus) (updateErr error) { +func updateReplicationControllerStatus(c v1core.ReplicationControllerInterface, rc v1.ReplicationController, newStatus v1.ReplicationControllerStatus) (updateErr error) { // This is the steady state. It happens when the rc doesn't have any expectations, since // we do a periodic relist every 30s. If the generations differ but the replicas are // the same, a caller might've resized to the same replica count. @@ -51,7 +51,7 @@ func updateReplicationControllerStatus(c unversionedcore.ReplicationControllerIn var getErr error for i, rc := 0, &rc; ; i++ { glog.V(4).Infof(fmt.Sprintf("Updating replica count for rc: %s/%s, ", rc.Namespace, rc.Name) + - fmt.Sprintf("replicas %d->%d (need %d), ", rc.Status.Replicas, newStatus.Replicas, rc.Spec.Replicas) + + fmt.Sprintf("replicas %d->%d (need %d), ", rc.Status.Replicas, newStatus.Replicas, *(rc.Spec.Replicas)) + fmt.Sprintf("fullyLabeledReplicas %d->%d, ", rc.Status.FullyLabeledReplicas, newStatus.FullyLabeledReplicas) + fmt.Sprintf("readyReplicas %d->%d, ", rc.Status.ReadyReplicas, newStatus.ReadyReplicas) + fmt.Sprintf("availableReplicas %d->%d, ", rc.Status.AvailableReplicas, newStatus.AvailableReplicas) + @@ -72,7 +72,7 @@ func updateReplicationControllerStatus(c unversionedcore.ReplicationControllerIn } // OverlappingControllers sorts a list of controllers by creation timestamp, using their names as a tie breaker. -type OverlappingControllers []*api.ReplicationController +type OverlappingControllers []*v1.ReplicationController func (o OverlappingControllers) Len() int { return len(o) } func (o OverlappingControllers) Swap(i, j int) { o[i], o[j] = o[j], o[i] } @@ -84,7 +84,7 @@ func (o OverlappingControllers) Less(i, j int) bool { return o[i].CreationTimestamp.Before(o[j].CreationTimestamp) } -func calculateStatus(rc api.ReplicationController, filteredPods []*api.Pod, manageReplicasErr error) api.ReplicationControllerStatus { +func calculateStatus(rc v1.ReplicationController, filteredPods []*v1.Pod, manageReplicasErr error) v1.ReplicationControllerStatus { newStatus := rc.Status // Count the number of pods that have labels matching the labels of the pod // template of the replication controller, the matching pods may have more @@ -99,26 +99,26 @@ func calculateStatus(rc api.ReplicationController, filteredPods []*api.Pod, mana if templateLabel.Matches(labels.Set(pod.Labels)) { fullyLabeledReplicasCount++ } - if api.IsPodReady(pod) { + if v1.IsPodReady(pod) { readyReplicasCount++ - if api.IsPodAvailable(pod, rc.Spec.MinReadySeconds, unversioned.Now()) { + if v1.IsPodAvailable(pod, rc.Spec.MinReadySeconds, unversioned.Now()) { availableReplicasCount++ } } } - failureCond := GetCondition(rc.Status, api.ReplicationControllerReplicaFailure) + failureCond := GetCondition(rc.Status, v1.ReplicationControllerReplicaFailure) if manageReplicasErr != nil && failureCond == nil { var reason string - if diff := len(filteredPods) - int(rc.Spec.Replicas); diff < 0 { + if diff := len(filteredPods) - int(*(rc.Spec.Replicas)); diff < 0 { reason = "FailedCreate" } else if diff > 0 { reason = "FailedDelete" } - cond := NewReplicationControllerCondition(api.ReplicationControllerReplicaFailure, api.ConditionTrue, reason, manageReplicasErr.Error()) + cond := NewReplicationControllerCondition(v1.ReplicationControllerReplicaFailure, v1.ConditionTrue, reason, manageReplicasErr.Error()) SetCondition(&newStatus, cond) } else if manageReplicasErr == nil && failureCond != nil { - RemoveCondition(&newStatus, api.ReplicationControllerReplicaFailure) + RemoveCondition(&newStatus, v1.ReplicationControllerReplicaFailure) } newStatus.Replicas = int32(len(filteredPods)) @@ -129,8 +129,8 @@ func calculateStatus(rc api.ReplicationController, filteredPods []*api.Pod, mana } // NewReplicationControllerCondition creates a new replication controller condition. -func NewReplicationControllerCondition(condType api.ReplicationControllerConditionType, status api.ConditionStatus, reason, msg string) api.ReplicationControllerCondition { - return api.ReplicationControllerCondition{ +func NewReplicationControllerCondition(condType v1.ReplicationControllerConditionType, status v1.ConditionStatus, reason, msg string) v1.ReplicationControllerCondition { + return v1.ReplicationControllerCondition{ Type: condType, Status: status, LastTransitionTime: unversioned.Now(), @@ -140,7 +140,7 @@ func NewReplicationControllerCondition(condType api.ReplicationControllerConditi } // GetCondition returns a replication controller condition with the provided type if it exists. -func GetCondition(status api.ReplicationControllerStatus, condType api.ReplicationControllerConditionType) *api.ReplicationControllerCondition { +func GetCondition(status v1.ReplicationControllerStatus, condType v1.ReplicationControllerConditionType) *v1.ReplicationControllerCondition { for i := range status.Conditions { c := status.Conditions[i] if c.Type == condType { @@ -151,7 +151,7 @@ func GetCondition(status api.ReplicationControllerStatus, condType api.Replicati } // SetCondition adds/replaces the given condition in the replication controller status. -func SetCondition(status *api.ReplicationControllerStatus, condition api.ReplicationControllerCondition) { +func SetCondition(status *v1.ReplicationControllerStatus, condition v1.ReplicationControllerCondition) { currentCond := GetCondition(*status, condition.Type) if currentCond != nil && currentCond.Status == condition.Status && currentCond.Reason == condition.Reason { return @@ -161,13 +161,13 @@ func SetCondition(status *api.ReplicationControllerStatus, condition api.Replica } // RemoveCondition removes the condition with the provided type from the replication controller status. -func RemoveCondition(status *api.ReplicationControllerStatus, condType api.ReplicationControllerConditionType) { +func RemoveCondition(status *v1.ReplicationControllerStatus, condType v1.ReplicationControllerConditionType) { status.Conditions = filterOutCondition(status.Conditions, condType) } // filterOutCondition returns a new slice of replication controller conditions without conditions with the provided type. -func filterOutCondition(conditions []api.ReplicationControllerCondition, condType api.ReplicationControllerConditionType) []api.ReplicationControllerCondition { - var newConditions []api.ReplicationControllerCondition +func filterOutCondition(conditions []v1.ReplicationControllerCondition, condType v1.ReplicationControllerConditionType) []v1.ReplicationControllerCondition { + var newConditions []v1.ReplicationControllerCondition for _, c := range conditions { if c.Type == condType { continue diff --git a/pkg/controller/resourcequota/BUILD b/pkg/controller/resourcequota/BUILD index f6afc4aea2e..4a4c4a5e5d4 100644 --- a/pkg/controller/resourcequota/BUILD +++ b/pkg/controller/resourcequota/BUILD @@ -22,8 +22,9 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/meta:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/controller:go_default_library", "//pkg/controller/informers:go_default_library", "//pkg/quota:go_default_library", @@ -50,7 +51,8 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/controller:go_default_library", "//pkg/quota/generic:go_default_library", diff --git a/pkg/controller/resourcequota/replenishment_controller.go b/pkg/controller/resourcequota/replenishment_controller.go index 0839fc10ecb..af24c5f968e 100644 --- a/pkg/controller/resourcequota/replenishment_controller.go +++ b/pkg/controller/resourcequota/replenishment_controller.go @@ -24,8 +24,9 @@ import ( "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/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/informers" "k8s.io/kubernetes/pkg/quota/evaluator/core" @@ -55,9 +56,9 @@ type ReplenishmentControllerOptions struct { // PodReplenishmentUpdateFunc will replenish if the old pod was quota tracked but the new is not func PodReplenishmentUpdateFunc(options *ReplenishmentControllerOptions) func(oldObj, newObj interface{}) { return func(oldObj, newObj interface{}) { - oldPod := oldObj.(*api.Pod) - newPod := newObj.(*api.Pod) - if core.QuotaPod(oldPod) && !core.QuotaPod(newPod) { + oldPod := oldObj.(*v1.Pod) + newPod := newObj.(*v1.Pod) + if core.QuotaV1Pod(oldPod) && !core.QuotaV1Pod(newPod) { options.ReplenishmentFunc(options.GroupKind, newPod.Namespace, oldPod) } } @@ -146,14 +147,14 @@ func (r *replenishmentControllerFactory) NewController(options *ReplenishmentCon // TODO move to informer when defined _, result = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return r.kubeClient.Core().Services(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return r.kubeClient.Core().Services(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return r.kubeClient.Core().Services(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return r.kubeClient.Core().Services(v1.NamespaceAll).Watch(options) }, }, - &api.Service{}, + &v1.Service{}, options.ResyncPeriod(), cache.ResourceEventHandlerFuncs{ UpdateFunc: ServiceReplenishmentUpdateFunc(options), @@ -164,14 +165,14 @@ func (r *replenishmentControllerFactory) NewController(options *ReplenishmentCon // TODO move to informer when defined _, result = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return r.kubeClient.Core().ReplicationControllers(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return r.kubeClient.Core().ReplicationControllers(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return r.kubeClient.Core().ReplicationControllers(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return r.kubeClient.Core().ReplicationControllers(v1.NamespaceAll).Watch(options) }, }, - &api.ReplicationController{}, + &v1.ReplicationController{}, options.ResyncPeriod(), cache.ResourceEventHandlerFuncs{ DeleteFunc: ObjectReplenishmentDeleteFunc(options), @@ -187,14 +188,14 @@ func (r *replenishmentControllerFactory) NewController(options *ReplenishmentCon // TODO (derekwaynecarr) remove me when we can require a sharedInformerFactory in all code paths... _, result = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return r.kubeClient.Core().PersistentVolumeClaims(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return r.kubeClient.Core().PersistentVolumeClaims(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return r.kubeClient.Core().PersistentVolumeClaims(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return r.kubeClient.Core().PersistentVolumeClaims(v1.NamespaceAll).Watch(options) }, }, - &api.PersistentVolumeClaim{}, + &v1.PersistentVolumeClaim{}, options.ResyncPeriod(), cache.ResourceEventHandlerFuncs{ DeleteFunc: ObjectReplenishmentDeleteFunc(options), @@ -204,14 +205,14 @@ func (r *replenishmentControllerFactory) NewController(options *ReplenishmentCon // TODO move to informer when defined _, result = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return r.kubeClient.Core().Secrets(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return r.kubeClient.Core().Secrets(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return r.kubeClient.Core().Secrets(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return r.kubeClient.Core().Secrets(v1.NamespaceAll).Watch(options) }, }, - &api.Secret{}, + &v1.Secret{}, options.ResyncPeriod(), cache.ResourceEventHandlerFuncs{ DeleteFunc: ObjectReplenishmentDeleteFunc(options), @@ -221,14 +222,14 @@ func (r *replenishmentControllerFactory) NewController(options *ReplenishmentCon // TODO move to informer when defined _, result = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return r.kubeClient.Core().ConfigMaps(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return r.kubeClient.Core().ConfigMaps(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return r.kubeClient.Core().ConfigMaps(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return r.kubeClient.Core().ConfigMaps(v1.NamespaceAll).Watch(options) }, }, - &api.ConfigMap{}, + &v1.ConfigMap{}, options.ResyncPeriod(), cache.ResourceEventHandlerFuncs{ DeleteFunc: ObjectReplenishmentDeleteFunc(options), @@ -243,8 +244,8 @@ func (r *replenishmentControllerFactory) NewController(options *ReplenishmentCon // ServiceReplenishmentUpdateFunc will replenish if the service was quota tracked has changed service type func ServiceReplenishmentUpdateFunc(options *ReplenishmentControllerOptions) func(oldObj, newObj interface{}) { return func(oldObj, newObj interface{}) { - oldService := oldObj.(*api.Service) - newService := newObj.(*api.Service) + oldService := oldObj.(*v1.Service) + newService := newObj.(*v1.Service) if core.GetQuotaServiceType(oldService) != core.GetQuotaServiceType(newService) { options.ReplenishmentFunc(options.GroupKind, newService.Namespace, nil) } diff --git a/pkg/controller/resourcequota/replenishment_controller_test.go b/pkg/controller/resourcequota/replenishment_controller_test.go index 37b65002e13..43a3a48eefc 100644 --- a/pkg/controller/resourcequota/replenishment_controller_test.go +++ b/pkg/controller/resourcequota/replenishment_controller_test.go @@ -21,6 +21,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/intstr" @@ -45,13 +46,13 @@ func TestPodReplenishmentUpdateFunc(t *testing.T) { ReplenishmentFunc: mockReplenish.Replenish, ResyncPeriod: controller.NoResyncPeriodFunc, } - oldPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "pod"}, - Status: api.PodStatus{Phase: api.PodRunning}, + oldPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Namespace: "test", Name: "pod"}, + Status: v1.PodStatus{Phase: v1.PodRunning}, } - newPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "pod"}, - Status: api.PodStatus{Phase: api.PodFailed}, + newPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Namespace: "test", Name: "pod"}, + Status: v1.PodStatus{Phase: v1.PodFailed}, } updateFunc := PodReplenishmentUpdateFunc(&options) updateFunc(oldPod, newPod) @@ -70,9 +71,9 @@ func TestObjectReplenishmentDeleteFunc(t *testing.T) { ReplenishmentFunc: mockReplenish.Replenish, ResyncPeriod: controller.NoResyncPeriodFunc, } - oldPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "pod"}, - Status: api.PodStatus{Phase: api.PodRunning}, + oldPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Namespace: "test", Name: "pod"}, + Status: v1.PodStatus{Phase: v1.PodRunning}, } deleteFunc := ObjectReplenishmentDeleteFunc(&options) deleteFunc(oldPod) @@ -91,21 +92,21 @@ func TestServiceReplenishmentUpdateFunc(t *testing.T) { ReplenishmentFunc: mockReplenish.Replenish, ResyncPeriod: controller.NoResyncPeriodFunc, } - oldService := &api.Service{ - ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "mysvc"}, - Spec: api.ServiceSpec{ - Type: api.ServiceTypeNodePort, - Ports: []api.ServicePort{{ + oldService := &v1.Service{ + ObjectMeta: v1.ObjectMeta{Namespace: "test", Name: "mysvc"}, + Spec: v1.ServiceSpec{ + Type: v1.ServiceTypeNodePort, + Ports: []v1.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}, }, } - newService := &api.Service{ - ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "mysvc"}, - Spec: api.ServiceSpec{ - Type: api.ServiceTypeClusterIP, - Ports: []api.ServicePort{{ + newService := &v1.Service{ + ObjectMeta: v1.ObjectMeta{Namespace: "test", Name: "mysvc"}, + Spec: v1.ServiceSpec{ + Type: v1.ServiceTypeClusterIP, + Ports: []v1.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}}, @@ -125,21 +126,21 @@ func TestServiceReplenishmentUpdateFunc(t *testing.T) { ReplenishmentFunc: mockReplenish.Replenish, ResyncPeriod: controller.NoResyncPeriodFunc, } - oldService = &api.Service{ - ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "mysvc"}, - Spec: api.ServiceSpec{ - Type: api.ServiceTypeNodePort, - Ports: []api.ServicePort{{ + oldService = &v1.Service{ + ObjectMeta: v1.ObjectMeta{Namespace: "test", Name: "mysvc"}, + Spec: v1.ServiceSpec{ + Type: v1.ServiceTypeNodePort, + Ports: []v1.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}, }, } - newService = &api.Service{ - ObjectMeta: api.ObjectMeta{Namespace: "test", Name: "mysvc"}, - Spec: api.ServiceSpec{ - Type: api.ServiceTypeNodePort, - Ports: []api.ServicePort{{ + newService = &v1.Service{ + ObjectMeta: v1.ObjectMeta{Namespace: "test", Name: "mysvc"}, + Spec: v1.ServiceSpec{ + Type: v1.ServiceTypeNodePort, + Ports: []v1.ServicePort{{ Port: 81, TargetPort: intstr.FromInt(81), }}}, diff --git a/pkg/controller/resourcequota/resource_quota_controller.go b/pkg/controller/resourcequota/resource_quota_controller.go index d28857a811e..d5fa2b0e0d5 100644 --- a/pkg/controller/resourcequota/resource_quota_controller.go +++ b/pkg/controller/resourcequota/resource_quota_controller.go @@ -23,8 +23,9 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/runtime" @@ -93,14 +94,14 @@ func NewResourceQuotaController(options *ResourceQuotaControllerOptions) *Resour // build the controller that observes quota rq.rqIndexer, rq.rqController = cache.NewIndexerInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return rq.kubeClient.Core().ResourceQuotas(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return rq.kubeClient.Core().ResourceQuotas(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return rq.kubeClient.Core().ResourceQuotas(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return rq.kubeClient.Core().ResourceQuotas(v1.NamespaceAll).Watch(options) }, }, - &api.ResourceQuota{}, + &v1.ResourceQuota{}, rq.resyncPeriod(), cache.ResourceEventHandlerFuncs{ AddFunc: rq.addQuota, @@ -113,9 +114,9 @@ func NewResourceQuotaController(options *ResourceQuotaControllerOptions) *Resour // that cannot be backed by a cache and result in a full query of a namespace's content, we do not // want to pay the price on spurious status updates. As a result, we have a separate routine that is // responsible for enqueue of all resource quotas when doing a full resync (enqueueAll) - oldResourceQuota := old.(*api.ResourceQuota) - curResourceQuota := cur.(*api.ResourceQuota) - if quota.Equals(curResourceQuota.Spec.Hard, oldResourceQuota.Spec.Hard) { + oldResourceQuota := old.(*v1.ResourceQuota) + curResourceQuota := cur.(*v1.ResourceQuota) + if quota.V1Equals(oldResourceQuota.Spec.Hard, curResourceQuota.Spec.Hard) { return } rq.addQuota(curResourceQuota) @@ -152,7 +153,7 @@ func (rq *ResourceQuotaController) enqueueAll() { } } -// obj could be an *api.ResourceQuota, or a DeletionFinalStateUnknown marker item. +// obj could be an *v1.ResourceQuota, or a DeletionFinalStateUnknown marker item. func (rq *ResourceQuotaController) enqueueResourceQuota(obj interface{}) { key, err := controller.KeyFunc(obj) if err != nil { @@ -169,7 +170,7 @@ func (rq *ResourceQuotaController) addQuota(obj interface{}) { return } - resourceQuota := obj.(*api.ResourceQuota) + resourceQuota := obj.(*v1.ResourceQuota) // if we declared an intent that is not yet captured in status (prioritize it) if !api.Semantic.DeepEqual(resourceQuota.Spec.Hard, resourceQuota.Status.Hard) { @@ -180,7 +181,7 @@ func (rq *ResourceQuotaController) addQuota(obj interface{}) { // if we declared a constraint that has no usage (which this controller can calculate, prioritize it) for constraint := range resourceQuota.Status.Hard { if _, usageFound := resourceQuota.Status.Used[constraint]; !usageFound { - matchedResources := []api.ResourceName{constraint} + matchedResources := []api.ResourceName{api.ResourceName(constraint)} for _, evaluator := range rq.registry.Evaluators() { if intersection := quota.Intersection(evaluator.MatchesResources(), matchedResources); len(intersection) != 0 { @@ -260,14 +261,19 @@ func (rq *ResourceQuotaController) syncResourceQuotaFromKey(key string) (err err rq.queue.Add(key) return err } - quota := *obj.(*api.ResourceQuota) + quota := *obj.(*v1.ResourceQuota) return rq.syncResourceQuota(quota) } // syncResourceQuota runs a complete sync of resource quota status across all known kinds -func (rq *ResourceQuotaController) syncResourceQuota(resourceQuota api.ResourceQuota) (err error) { +func (rq *ResourceQuotaController) syncResourceQuota(v1ResourceQuota v1.ResourceQuota) (err error) { // quota is dirty if any part of spec hard limits differs from the status hard limits - dirty := !api.Semantic.DeepEqual(resourceQuota.Spec.Hard, resourceQuota.Status.Hard) + dirty := !api.Semantic.DeepEqual(v1ResourceQuota.Spec.Hard, v1ResourceQuota.Status.Hard) + + resourceQuota := api.ResourceQuota{} + if err := v1.Convert_v1_ResourceQuota_To_api_ResourceQuota(&v1ResourceQuota, &resourceQuota, nil); err != nil { + return err + } // dirty tracks if the usage status differs from the previous sync, // if so, we send a new usage with latest status @@ -311,7 +317,11 @@ func (rq *ResourceQuotaController) syncResourceQuota(resourceQuota api.ResourceQ // there was a change observed by this controller that requires we update quota if dirty { - _, err = rq.kubeClient.Core().ResourceQuotas(usage.Namespace).UpdateStatus(&usage) + v1Usage := &v1.ResourceQuota{} + if err := v1.Convert_api_ResourceQuota_To_v1_ResourceQuota(&usage, v1Usage, nil); err != nil { + return err + } + _, err = rq.kubeClient.Core().ResourceQuotas(usage.Namespace).UpdateStatus(v1Usage) return err } return nil @@ -327,7 +337,7 @@ func (rq *ResourceQuotaController) replenishQuota(groupKind unversioned.GroupKin } // check if this namespace even has a quota... - indexKey := &api.ResourceQuota{} + indexKey := &v1.ResourceQuota{} indexKey.Namespace = namespace resourceQuotas, err := rq.rqIndexer.Index("namespace", indexKey) if err != nil { @@ -340,8 +350,13 @@ func (rq *ResourceQuotaController) replenishQuota(groupKind unversioned.GroupKin // only queue those quotas that are tracking a resource associated with this kind. matchedResources := evaluator.MatchesResources() for i := range resourceQuotas { - resourceQuota := resourceQuotas[i].(*api.ResourceQuota) - resourceQuotaResources := quota.ResourceNames(resourceQuota.Status.Hard) + resourceQuota := resourceQuotas[i].(*v1.ResourceQuota) + internalResourceQuota := &api.ResourceQuota{} + if err := v1.Convert_v1_ResourceQuota_To_api_ResourceQuota(resourceQuota, internalResourceQuota, nil); err != nil { + glog.Error(err) + continue + } + resourceQuotaResources := quota.ResourceNames(internalResourceQuota.Status.Hard) if len(quota.Intersection(matchedResources, resourceQuotaResources)) > 0 { // TODO: make this support targeted replenishment to a specific kind, right now it does a full recalc on that quota. rq.enqueueResourceQuota(resourceQuota) diff --git a/pkg/controller/resourcequota/resource_quota_controller_test.go b/pkg/controller/resourcequota/resource_quota_controller_test.go index 0221448a22f..f7dfcf8c66b 100644 --- a/pkg/controller/resourcequota/resource_quota_controller_test.go +++ b/pkg/controller/resourcequota/resource_quota_controller_test.go @@ -23,7 +23,8 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/quota/generic" @@ -31,74 +32,74 @@ import ( "k8s.io/kubernetes/pkg/util/sets" ) -func getResourceList(cpu, memory string) api.ResourceList { - res := api.ResourceList{} +func getResourceList(cpu, memory string) v1.ResourceList { + res := v1.ResourceList{} if cpu != "" { - res[api.ResourceCPU] = resource.MustParse(cpu) + res[v1.ResourceCPU] = resource.MustParse(cpu) } if memory != "" { - res[api.ResourceMemory] = resource.MustParse(memory) + res[v1.ResourceMemory] = resource.MustParse(memory) } return res } -func getResourceRequirements(requests, limits api.ResourceList) api.ResourceRequirements { - res := api.ResourceRequirements{} +func getResourceRequirements(requests, limits v1.ResourceList) v1.ResourceRequirements { + res := v1.ResourceRequirements{} res.Requests = requests res.Limits = limits return res } func TestSyncResourceQuota(t *testing.T) { - podList := api.PodList{ - Items: []api.Pod{ + podList := v1.PodList{ + Items: []v1.Pod{ { - ObjectMeta: api.ObjectMeta{Name: "pod-running", Namespace: "testing"}, - Status: api.PodStatus{Phase: api.PodRunning}, - Spec: api.PodSpec{ - Volumes: []api.Volume{{Name: "vol"}}, - Containers: []api.Container{{Name: "ctr", Image: "image", Resources: getResourceRequirements(getResourceList("100m", "1Gi"), getResourceList("", ""))}}, + ObjectMeta: v1.ObjectMeta{Name: "pod-running", Namespace: "testing"}, + Status: v1.PodStatus{Phase: v1.PodRunning}, + Spec: v1.PodSpec{ + Volumes: []v1.Volume{{Name: "vol"}}, + Containers: []v1.Container{{Name: "ctr", Image: "image", Resources: getResourceRequirements(getResourceList("100m", "1Gi"), getResourceList("", ""))}}, }, }, { - ObjectMeta: api.ObjectMeta{Name: "pod-running-2", Namespace: "testing"}, - Status: api.PodStatus{Phase: api.PodRunning}, - Spec: api.PodSpec{ - Volumes: []api.Volume{{Name: "vol"}}, - Containers: []api.Container{{Name: "ctr", Image: "image", Resources: getResourceRequirements(getResourceList("100m", "1Gi"), getResourceList("", ""))}}, + ObjectMeta: v1.ObjectMeta{Name: "pod-running-2", Namespace: "testing"}, + Status: v1.PodStatus{Phase: v1.PodRunning}, + Spec: v1.PodSpec{ + Volumes: []v1.Volume{{Name: "vol"}}, + Containers: []v1.Container{{Name: "ctr", Image: "image", Resources: getResourceRequirements(getResourceList("100m", "1Gi"), getResourceList("", ""))}}, }, }, { - ObjectMeta: api.ObjectMeta{Name: "pod-failed", Namespace: "testing"}, - Status: api.PodStatus{Phase: api.PodFailed}, - Spec: api.PodSpec{ - Volumes: []api.Volume{{Name: "vol"}}, - Containers: []api.Container{{Name: "ctr", Image: "image", Resources: getResourceRequirements(getResourceList("100m", "1Gi"), getResourceList("", ""))}}, + ObjectMeta: v1.ObjectMeta{Name: "pod-failed", Namespace: "testing"}, + Status: v1.PodStatus{Phase: v1.PodFailed}, + Spec: v1.PodSpec{ + Volumes: []v1.Volume{{Name: "vol"}}, + Containers: []v1.Container{{Name: "ctr", Image: "image", Resources: getResourceRequirements(getResourceList("100m", "1Gi"), getResourceList("", ""))}}, }, }, }, } - resourceQuota := api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{Name: "quota", Namespace: "testing"}, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("3"), - api.ResourceMemory: resource.MustParse("100Gi"), - api.ResourcePods: resource.MustParse("5"), + resourceQuota := v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{Name: "quota", Namespace: "testing"}, + Spec: v1.ResourceQuotaSpec{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("3"), + v1.ResourceMemory: resource.MustParse("100Gi"), + v1.ResourcePods: resource.MustParse("5"), }, }, } - expectedUsage := api.ResourceQuota{ - Status: api.ResourceQuotaStatus{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("3"), - api.ResourceMemory: resource.MustParse("100Gi"), - api.ResourcePods: resource.MustParse("5"), + expectedUsage := v1.ResourceQuota{ + Status: v1.ResourceQuotaStatus{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("3"), + v1.ResourceMemory: resource.MustParse("100Gi"), + v1.ResourcePods: resource.MustParse("5"), }, - Used: api.ResourceList{ - api.ResourceCPU: resource.MustParse("200m"), - api.ResourceMemory: resource.MustParse("2Gi"), - api.ResourcePods: resource.MustParse("2"), + Used: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("200m"), + v1.ResourceMemory: resource.MustParse("2Gi"), + v1.ResourcePods: resource.MustParse("2"), }, }, } @@ -135,7 +136,7 @@ func TestSyncResourceQuota(t *testing.T) { } lastActionIndex := len(kubeClient.Actions()) - 1 - usage := kubeClient.Actions()[lastActionIndex].(core.UpdateAction).GetObject().(*api.ResourceQuota) + usage := kubeClient.Actions()[lastActionIndex].(core.UpdateAction).GetObject().(*v1.ResourceQuota) // ensure hard and used limits are what we expected for k, v := range expectedUsage.Status.Hard { @@ -157,33 +158,33 @@ func TestSyncResourceQuota(t *testing.T) { } func TestSyncResourceQuotaSpecChange(t *testing.T) { - resourceQuota := api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ + resourceQuota := v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", Name: "rq", }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + Spec: v1.ResourceQuotaSpec{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, }, - Status: api.ResourceQuotaStatus{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("3"), + Status: v1.ResourceQuotaStatus{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("3"), }, - Used: api.ResourceList{ - api.ResourceCPU: resource.MustParse("0"), + Used: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("0"), }, }, } - expectedUsage := api.ResourceQuota{ - Status: api.ResourceQuotaStatus{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + expectedUsage := v1.ResourceQuota{ + Status: v1.ResourceQuotaStatus{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, - Used: api.ResourceList{ - api.ResourceCPU: resource.MustParse("0"), + Used: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("0"), }, }, } @@ -221,7 +222,7 @@ func TestSyncResourceQuotaSpecChange(t *testing.T) { } lastActionIndex := len(kubeClient.Actions()) - 1 - usage := kubeClient.Actions()[lastActionIndex].(core.UpdateAction).GetObject().(*api.ResourceQuota) + usage := kubeClient.Actions()[lastActionIndex].(core.UpdateAction).GetObject().(*v1.ResourceQuota) // ensure hard and used limits are what we expected for k, v := range expectedUsage.Status.Hard { @@ -243,35 +244,35 @@ func TestSyncResourceQuotaSpecChange(t *testing.T) { } func TestSyncResourceQuotaSpecHardChange(t *testing.T) { - resourceQuota := api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ + resourceQuota := v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", Name: "rq", }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + Spec: v1.ResourceQuotaSpec{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, }, - Status: api.ResourceQuotaStatus{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("3"), - api.ResourceMemory: resource.MustParse("1Gi"), + Status: v1.ResourceQuotaStatus{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("3"), + v1.ResourceMemory: resource.MustParse("1Gi"), }, - Used: api.ResourceList{ - api.ResourceCPU: resource.MustParse("0"), - api.ResourceMemory: resource.MustParse("0"), + Used: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("0"), + v1.ResourceMemory: resource.MustParse("0"), }, }, } - expectedUsage := api.ResourceQuota{ - Status: api.ResourceQuotaStatus{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + expectedUsage := v1.ResourceQuota{ + Status: v1.ResourceQuotaStatus{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, - Used: api.ResourceList{ - api.ResourceCPU: resource.MustParse("0"), + Used: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("0"), }, }, } @@ -309,7 +310,7 @@ func TestSyncResourceQuotaSpecHardChange(t *testing.T) { } lastActionIndex := len(kubeClient.Actions()) - 1 - usage := kubeClient.Actions()[lastActionIndex].(core.UpdateAction).GetObject().(*api.ResourceQuota) + usage := kubeClient.Actions()[lastActionIndex].(core.UpdateAction).GetObject().(*v1.ResourceQuota) // ensure hard and used limits are what we expected for k, v := range expectedUsage.Status.Hard { @@ -331,40 +332,40 @@ func TestSyncResourceQuotaSpecHardChange(t *testing.T) { // ensure usage hard and used are are synced with spec hard, not have dirty resource for k, v := range usage.Status.Hard { - if k == api.ResourceMemory { + if k == v1.ResourceMemory { t.Errorf("Unexpected Usage Hard: Key: %v, Value: %v", k, v.String()) } } for k, v := range usage.Status.Used { - if k == api.ResourceMemory { + if k == v1.ResourceMemory { t.Errorf("Unexpected Usage Used: Key: %v, Value: %v", k, v.String()) } } } func TestSyncResourceQuotaNoChange(t *testing.T) { - resourceQuota := api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ + resourceQuota := v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", Name: "rq", }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + Spec: v1.ResourceQuotaSpec{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, }, - Status: api.ResourceQuotaStatus{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + Status: v1.ResourceQuotaStatus{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, - Used: api.ResourceList{ - api.ResourceCPU: resource.MustParse("0"), + Used: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("0"), }, }, } - kubeClient := fake.NewSimpleClientset(&api.PodList{}, &resourceQuota) + kubeClient := fake.NewSimpleClientset(&v1.PodList{}, &resourceQuota) resourceQuotaControllerOptions := &ResourceQuotaControllerOptions{ KubeClient: kubeClient, ResyncPeriod: controller.NoResyncPeriodFunc, @@ -416,20 +417,20 @@ func TestAddQuota(t *testing.T) { testCases := []struct { name string - quota *api.ResourceQuota + quota *v1.ResourceQuota expectedPriority bool }{ { name: "no status", expectedPriority: true, - quota: &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ + quota: &v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", Name: "rq", }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + Spec: v1.ResourceQuotaSpec{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, }, }, @@ -437,19 +438,19 @@ func TestAddQuota(t *testing.T) { { name: "status, no usage", expectedPriority: true, - quota: &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ + quota: &v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", Name: "rq", }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + Spec: v1.ResourceQuotaSpec{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, }, - Status: api.ResourceQuotaStatus{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + Status: v1.ResourceQuotaStatus{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, }, }, @@ -457,22 +458,22 @@ func TestAddQuota(t *testing.T) { { name: "status, mismatch", expectedPriority: true, - quota: &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ + quota: &v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", Name: "rq", }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + Spec: v1.ResourceQuotaSpec{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, }, - Status: api.ResourceQuotaStatus{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("6"), + Status: v1.ResourceQuotaStatus{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("6"), }, - Used: api.ResourceList{ - api.ResourceCPU: resource.MustParse("0"), + Used: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("0"), }, }, }, @@ -480,19 +481,19 @@ func TestAddQuota(t *testing.T) { { name: "status, missing usage, but don't care", expectedPriority: false, - quota: &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ + quota: &v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", Name: "rq", }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceServices: resource.MustParse("4"), + Spec: v1.ResourceQuotaSpec{ + Hard: v1.ResourceList{ + v1.ResourceServices: resource.MustParse("4"), }, }, - Status: api.ResourceQuotaStatus{ - Hard: api.ResourceList{ - api.ResourceServices: resource.MustParse("4"), + Status: v1.ResourceQuotaStatus{ + Hard: v1.ResourceList{ + v1.ResourceServices: resource.MustParse("4"), }, }, }, @@ -500,22 +501,22 @@ func TestAddQuota(t *testing.T) { { name: "ready", expectedPriority: false, - quota: &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ + quota: &v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", Name: "rq", }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + Spec: v1.ResourceQuotaSpec{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, }, - Status: api.ResourceQuotaStatus{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4"), + Status: v1.ResourceQuotaStatus{ + Hard: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("4"), }, - Used: api.ResourceList{ - api.ResourceCPU: resource.MustParse("0"), + Used: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("0"), }, }, }, diff --git a/pkg/controller/route/BUILD b/pkg/controller/route/BUILD index 74eb9169d1d..98e0e680bac 100644 --- a/pkg/controller/route/BUILD +++ b/pkg/controller/route/BUILD @@ -18,11 +18,11 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/controller:go_default_library", "//pkg/runtime:go_default_library", @@ -41,8 +41,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/cloudprovider/providers/fake:go_default_library", diff --git a/pkg/controller/route/routecontroller.go b/pkg/controller/route/routecontroller.go index db8074e7c59..c17f41fd906 100644 --- a/pkg/controller/route/routecontroller.go +++ b/pkg/controller/route/routecontroller.go @@ -23,11 +23,11 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/runtime" @@ -71,14 +71,14 @@ func New(routes cloudprovider.Routes, kubeClient clientset.Interface, clusterNam rc.nodeStore.Store, rc.nodeController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return rc.kubeClient.Core().Nodes().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return rc.kubeClient.Core().Nodes().Watch(options) }, }, - &api.Node{}, + &v1.Node{}, controller.NoResyncPeriodFunc(), cache.ResourceEventHandlerFuncs{}, ) @@ -116,7 +116,7 @@ func (rc *RouteController) reconcileNodeRoutes() error { return rc.reconcile(nodeList.Items, routeList) } -func (rc *RouteController) reconcile(nodes []api.Node, routes []*cloudprovider.Route) error { +func (rc *RouteController) reconcile(nodes []v1.Node, routes []*cloudprovider.Route) error { // nodeCIDRs maps nodeName->nodeCIDR nodeCIDRs := make(map[types.NodeName]string) // routeMap maps routeTargetNode->route @@ -166,8 +166,8 @@ func (rc *RouteController) reconcile(nodes []api.Node, routes []*cloudprovider.R }(nodeName, nameHint, route) } else { // Update condition only if it doesn't reflect the current state. - _, condition := api.GetNodeCondition(&node.Status, api.NodeNetworkUnavailable) - if condition == nil || condition.Status != api.ConditionFalse { + _, condition := v1.GetNodeCondition(&node.Status, v1.NodeNetworkUnavailable) + if condition == nil || condition.Status != v1.ConditionFalse { rc.updateNetworkingCondition(types.NodeName(node.Name), true) } } @@ -203,17 +203,17 @@ func (rc *RouteController) updateNetworkingCondition(nodeName types.NodeName, ro // patch in the retry loop. currentTime := unversioned.Now() if routeCreated { - err = nodeutil.SetNodeCondition(rc.kubeClient, nodeName, api.NodeCondition{ - Type: api.NodeNetworkUnavailable, - Status: api.ConditionFalse, + err = nodeutil.SetNodeCondition(rc.kubeClient, nodeName, v1.NodeCondition{ + Type: v1.NodeNetworkUnavailable, + Status: v1.ConditionFalse, Reason: "RouteCreated", Message: "RouteController created a route", LastTransitionTime: currentTime, }) } else { - err = nodeutil.SetNodeCondition(rc.kubeClient, nodeName, api.NodeCondition{ - Type: api.NodeNetworkUnavailable, - Status: api.ConditionTrue, + err = nodeutil.SetNodeCondition(rc.kubeClient, nodeName, v1.NodeCondition{ + Type: v1.NodeNetworkUnavailable, + Status: v1.ConditionTrue, Reason: "NoRouteCreated", Message: "RouteController failed to create a route", LastTransitionTime: currentTime, diff --git a/pkg/controller/route/routecontroller_test.go b/pkg/controller/route/routecontroller_test.go index 6f64c521a83..5ad40e7e152 100644 --- a/pkg/controller/route/routecontroller_test.go +++ b/pkg/controller/route/routecontroller_test.go @@ -21,8 +21,8 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/cloudprovider" fakecloud "k8s.io/kubernetes/pkg/cloudprovider/providers/fake" @@ -70,12 +70,12 @@ func TestIsResponsibleForRoute(t *testing.T) { func TestReconcile(t *testing.T) { cluster := "my-k8s" - node1 := api.Node{ObjectMeta: api.ObjectMeta{Name: "node-1", UID: "01"}, Spec: api.NodeSpec{PodCIDR: "10.120.0.0/24"}} - node2 := api.Node{ObjectMeta: api.ObjectMeta{Name: "node-2", UID: "02"}, Spec: api.NodeSpec{PodCIDR: "10.120.1.0/24"}} - nodeNoCidr := api.Node{ObjectMeta: api.ObjectMeta{Name: "node-2", UID: "02"}, Spec: api.NodeSpec{PodCIDR: ""}} + node1 := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "node-1", UID: "01"}, Spec: v1.NodeSpec{PodCIDR: "10.120.0.0/24"}} + node2 := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "node-2", UID: "02"}, Spec: v1.NodeSpec{PodCIDR: "10.120.1.0/24"}} + nodeNoCidr := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "node-2", UID: "02"}, Spec: v1.NodeSpec{PodCIDR: ""}} testCases := []struct { - nodes []api.Node + nodes []v1.Node initialRoutes []*cloudprovider.Route expectedRoutes []*cloudprovider.Route expectedNetworkUnavailable []bool @@ -83,7 +83,7 @@ func TestReconcile(t *testing.T) { }{ // 2 nodes, routes already there { - nodes: []api.Node{ + nodes: []v1.Node{ node1, node2, }, @@ -96,11 +96,11 @@ func TestReconcile(t *testing.T) { {cluster + "-02", "node-2", "10.120.1.0/24"}, }, expectedNetworkUnavailable: []bool{true, true}, - clientset: fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{node1, node2}}), + clientset: fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{node1, node2}}), }, // 2 nodes, one route already there { - nodes: []api.Node{ + nodes: []v1.Node{ node1, node2, }, @@ -112,11 +112,11 @@ func TestReconcile(t *testing.T) { {cluster + "-02", "node-2", "10.120.1.0/24"}, }, expectedNetworkUnavailable: []bool{true, true}, - clientset: fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{node1, node2}}), + clientset: fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{node1, node2}}), }, // 2 nodes, no routes yet { - nodes: []api.Node{ + nodes: []v1.Node{ node1, node2, }, @@ -126,11 +126,11 @@ func TestReconcile(t *testing.T) { {cluster + "-02", "node-2", "10.120.1.0/24"}, }, expectedNetworkUnavailable: []bool{true, true}, - clientset: fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{node1, node2}}), + clientset: fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{node1, node2}}), }, // 2 nodes, a few too many routes { - nodes: []api.Node{ + nodes: []v1.Node{ node1, node2, }, @@ -145,11 +145,11 @@ func TestReconcile(t *testing.T) { {cluster + "-02", "node-2", "10.120.1.0/24"}, }, expectedNetworkUnavailable: []bool{true, true}, - clientset: fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{node1, node2}}), + clientset: fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{node1, node2}}), }, // 2 nodes, 2 routes, but only 1 is right { - nodes: []api.Node{ + nodes: []v1.Node{ node1, node2, }, @@ -162,11 +162,11 @@ func TestReconcile(t *testing.T) { {cluster + "-02", "node-2", "10.120.1.0/24"}, }, expectedNetworkUnavailable: []bool{true, true}, - clientset: fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{node1, node2}}), + clientset: fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{node1, node2}}), }, // 2 nodes, one node without CIDR assigned. { - nodes: []api.Node{ + nodes: []v1.Node{ node1, nodeNoCidr, }, @@ -175,7 +175,7 @@ func TestReconcile(t *testing.T) { {cluster + "-01", "node-1", "10.120.0.0/24"}, }, expectedNetworkUnavailable: []bool{true, false}, - clientset: fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{node1, nodeNoCidr}}), + clientset: fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{node1, nodeNoCidr}}), }, } for i, testCase := range testCases { @@ -197,13 +197,13 @@ func TestReconcile(t *testing.T) { } for _, action := range testCase.clientset.Actions() { if action.GetVerb() == "update" && action.GetResource().Resource == "nodes" { - node := action.(core.UpdateAction).GetObject().(*api.Node) - _, condition := api.GetNodeCondition(&node.Status, api.NodeNetworkUnavailable) + node := action.(core.UpdateAction).GetObject().(*v1.Node) + _, condition := v1.GetNodeCondition(&node.Status, v1.NodeNetworkUnavailable) if condition == nil { t.Errorf("%d. Missing NodeNetworkUnavailable condition for Node %v", i, node.Name) } else { check := func(index int) bool { - return (condition.Status == api.ConditionFalse) == testCase.expectedNetworkUnavailable[index] + return (condition.Status == v1.ConditionFalse) == testCase.expectedNetworkUnavailable[index] } index := -1 for j := range testCase.nodes { @@ -217,7 +217,7 @@ func TestReconcile(t *testing.T) { } if !check(index) { t.Errorf("%d. Invalid NodeNetworkUnavailable condition for Node %v, expected %v, got %v", - i, node.Name, testCase.expectedNetworkUnavailable[index], (condition.Status == api.ConditionFalse)) + i, node.Name, testCase.expectedNetworkUnavailable[index], (condition.Status == v1.ConditionFalse)) } } } diff --git a/pkg/controller/service/BUILD b/pkg/controller/service/BUILD index 61dc1e5d4d5..3b185972d0c 100644 --- a/pkg/controller/service/BUILD +++ b/pkg/controller/service/BUILD @@ -18,11 +18,11 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/controller:go_default_library", @@ -43,9 +43,9 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/testapi:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/cloudprovider/providers/fake:go_default_library", "//pkg/types:go_default_library", ], diff --git a/pkg/controller/service/servicecontroller.go b/pkg/controller/service/servicecontroller.go index 441c481dde8..772aa0fad80 100644 --- a/pkg/controller/service/servicecontroller.go +++ b/pkg/controller/service/servicecontroller.go @@ -25,11 +25,11 @@ import ( "reflect" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversioned_core "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + unversioned_core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/controller" @@ -65,7 +65,7 @@ const ( type cachedService struct { // The cached state of the service - state *api.Service + state *v1.Service // Controls error back-off lastRetryDelay time.Duration } @@ -78,7 +78,7 @@ type serviceCache struct { type ServiceController struct { cloud cloudprovider.Interface knownHosts []string - servicesToUpdate []*api.Service + servicesToUpdate []*v1.Service kubeClient clientset.Interface clusterName string balancer cloudprovider.LoadBalancer @@ -100,7 +100,7 @@ type ServiceController struct { func New(cloud cloudprovider.Interface, kubeClient clientset.Interface, clusterName string) (*ServiceController, error) { broadcaster := record.NewBroadcaster() broadcaster.StartRecordingToSink(&unversioned_core.EventSinkImpl{Interface: kubeClient.Core().Events("")}) - recorder := broadcaster.NewRecorder(api.EventSource{Component: "service-controller"}) + recorder := broadcaster.NewRecorder(v1.EventSource{Component: "service-controller"}) if kubeClient != nil && kubeClient.Core().RESTClient().GetRateLimiter() != nil { metrics.RegisterMetricAndTrackRateLimiterUsage("service_controller", kubeClient.Core().RESTClient().GetRateLimiter()) @@ -121,20 +121,20 @@ func New(cloud cloudprovider.Interface, kubeClient clientset.Interface, clusterN } s.serviceStore.Indexer, s.serviceController = cache.NewIndexerInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (pkg_runtime.Object, error) { - return s.kubeClient.Core().Services(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (pkg_runtime.Object, error) { + return s.kubeClient.Core().Services(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return s.kubeClient.Core().Services(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return s.kubeClient.Core().Services(v1.NamespaceAll).Watch(options) }, }, - &api.Service{}, + &v1.Service{}, serviceSyncPeriod, cache.ResourceEventHandlerFuncs{ AddFunc: s.enqueueService, UpdateFunc: func(old, cur interface{}) { - oldSvc, ok1 := old.(*api.Service) - curSvc, ok2 := cur.(*api.Service) + oldSvc, ok1 := old.(*v1.Service) + curSvc, ok2 := cur.(*v1.Service) if ok1 && ok2 && s.needsUpdate(oldSvc, curSvc) { s.enqueueService(cur) } @@ -149,7 +149,7 @@ func New(cloud cloudprovider.Interface, kubeClient clientset.Interface, clusterN return s, nil } -// obj could be an *api.Service, or a DeletionFinalStateUnknown marker item. +// obj could be an *v1.Service, or a DeletionFinalStateUnknown marker item. func (s *ServiceController) enqueueService(obj interface{}) { key, err := controller.KeyFunc(obj) if err != nil { @@ -175,8 +175,8 @@ func (s *ServiceController) Run(workers int) { for i := 0; i < workers; i++ { go wait.Until(s.worker, time.Second, wait.NeverStop) } - nodeLW := cache.NewListWatchFromClient(s.kubeClient.Core().RESTClient(), "nodes", api.NamespaceAll, fields.Everything()) - cache.NewReflector(nodeLW, &api.Node{}, s.nodeLister.Store, 0).Run() + nodeLW := cache.NewListWatchFromClient(s.kubeClient.Core().RESTClient(), "nodes", v1.NamespaceAll, fields.Everything()) + cache.NewReflector(nodeLW, &v1.Node{}, s.nodeLister.Store, 0).Run() go wait.Until(s.nodeSyncLoop, nodeSyncPeriod, wait.NeverStop) } @@ -224,7 +224,7 @@ func (s *ServiceController) init() error { // Returns an error if processing the service update failed, along with a time.Duration // indicating whether processing should be retried; zero means no-retry; otherwise // we should retry in that Duration. -func (s *ServiceController) processServiceUpdate(cachedService *cachedService, service *api.Service, key string) (error, time.Duration) { +func (s *ServiceController) processServiceUpdate(cachedService *cachedService, service *v1.Service, key string) (error, time.Duration) { // cache the service, we need the info for service deletion cachedService.state = service @@ -237,7 +237,7 @@ func (s *ServiceController) processServiceUpdate(cachedService *cachedService, s message += " (will not retry): " } message += err.Error() - s.eventRecorder.Event(service, api.EventTypeWarning, "CreatingLoadBalancerFailed", message) + s.eventRecorder.Event(service, v1.EventTypeWarning, "CreatingLoadBalancerFailed", message) return err, cachedService.nextRetryDelay() } @@ -253,13 +253,13 @@ func (s *ServiceController) processServiceUpdate(cachedService *cachedService, s // Returns whatever error occurred along with a boolean indicator of whether it // should be retried. -func (s *ServiceController) createLoadBalancerIfNeeded(key string, service *api.Service) (error, bool) { +func (s *ServiceController) createLoadBalancerIfNeeded(key string, service *v1.Service) (error, bool) { // Note: It is safe to just call EnsureLoadBalancer. But, on some clouds that requires a delete & create, // which may involve service interruption. Also, we would like user-friendly events. // Save the state so we can avoid a write if it doesn't change - previousState := api.LoadBalancerStatusDeepCopy(&service.Status.LoadBalancer) + previousState := v1.LoadBalancerStatusDeepCopy(&service.Status.LoadBalancer) if !wantsLoadBalancer(service) { needDelete := true @@ -273,31 +273,31 @@ func (s *ServiceController) createLoadBalancerIfNeeded(key string, service *api. if needDelete { glog.Infof("Deleting existing load balancer for service %s that no longer needs a load balancer.", key) - s.eventRecorder.Event(service, api.EventTypeNormal, "DeletingLoadBalancer", "Deleting load balancer") + s.eventRecorder.Event(service, v1.EventTypeNormal, "DeletingLoadBalancer", "Deleting load balancer") if err := s.balancer.EnsureLoadBalancerDeleted(s.clusterName, service); err != nil { return err, retryable } - s.eventRecorder.Event(service, api.EventTypeNormal, "DeletedLoadBalancer", "Deleted load balancer") + s.eventRecorder.Event(service, v1.EventTypeNormal, "DeletedLoadBalancer", "Deleted load balancer") } - service.Status.LoadBalancer = api.LoadBalancerStatus{} + service.Status.LoadBalancer = v1.LoadBalancerStatus{} } else { glog.V(2).Infof("Ensuring LB for service %s", key) // TODO: We could do a dry-run here if wanted to avoid the spurious cloud-calls & events when we restart // The load balancer doesn't exist yet, so create it. - s.eventRecorder.Event(service, api.EventTypeNormal, "CreatingLoadBalancer", "Creating load balancer") + s.eventRecorder.Event(service, v1.EventTypeNormal, "CreatingLoadBalancer", "Creating load balancer") err := s.createLoadBalancer(service) if err != nil { return fmt.Errorf("Failed to create load balancer for service %s: %v", key, err), retryable } - s.eventRecorder.Event(service, api.EventTypeNormal, "CreatedLoadBalancer", "Created load balancer") + s.eventRecorder.Event(service, v1.EventTypeNormal, "CreatedLoadBalancer", "Created load balancer") } // Write the state if changed // TODO: Be careful here ... what if there were other changes to the service? - if !api.LoadBalancerStatusEqual(previousState, &service.Status.LoadBalancer) { + if !v1.LoadBalancerStatusEqual(previousState, &service.Status.LoadBalancer) { if err := s.persistUpdate(service); err != nil { return fmt.Errorf("Failed to persist updated status to apiserver, even after retries. Giving up: %v", err), notRetryable } @@ -308,7 +308,7 @@ func (s *ServiceController) createLoadBalancerIfNeeded(key string, service *api. return nil, notRetryable } -func (s *ServiceController) persistUpdate(service *api.Service) error { +func (s *ServiceController) persistUpdate(service *v1.Service) error { var err error for i := 0; i < clientRetryCount; i++ { _, err = s.kubeClient.Core().Services(service.Namespace).UpdateStatus(service) @@ -338,7 +338,7 @@ func (s *ServiceController) persistUpdate(service *api.Service) error { return err } -func (s *ServiceController) createLoadBalancer(service *api.Service) error { +func (s *ServiceController) createLoadBalancer(service *v1.Service) error { nodes, err := s.nodeLister.List() if err != nil { return err @@ -381,10 +381,10 @@ func (s *serviceCache) GetByKey(key string) (interface{}, bool, error) { // ListKeys implements the interface required by DeltaFIFO to list the keys we // already know about. -func (s *serviceCache) allServices() []*api.Service { +func (s *serviceCache) allServices() []*v1.Service { s.mu.Lock() defer s.mu.Unlock() - services := make([]*api.Service, 0, len(s.serviceMap)) + services := make([]*v1.Service, 0, len(s.serviceMap)) for _, v := range s.serviceMap { services = append(services, v.state) } @@ -421,12 +421,12 @@ func (s *serviceCache) delete(serviceName string) { delete(s.serviceMap, serviceName) } -func (s *ServiceController) needsUpdate(oldService *api.Service, newService *api.Service) bool { +func (s *ServiceController) needsUpdate(oldService *v1.Service, newService *v1.Service) bool { if !wantsLoadBalancer(oldService) && !wantsLoadBalancer(newService) { return false } if wantsLoadBalancer(oldService) != wantsLoadBalancer(newService) { - s.eventRecorder.Eventf(newService, api.EventTypeNormal, "Type", "%v -> %v", + s.eventRecorder.Eventf(newService, v1.EventTypeNormal, "Type", "%v -> %v", oldService.Spec.Type, newService.Spec.Type) return true } @@ -434,18 +434,18 @@ func (s *ServiceController) needsUpdate(oldService *api.Service, newService *api return true } if !loadBalancerIPsAreEqual(oldService, newService) { - s.eventRecorder.Eventf(newService, api.EventTypeNormal, "LoadbalancerIP", "%v -> %v", + s.eventRecorder.Eventf(newService, v1.EventTypeNormal, "LoadbalancerIP", "%v -> %v", oldService.Spec.LoadBalancerIP, newService.Spec.LoadBalancerIP) return true } if len(oldService.Spec.ExternalIPs) != len(newService.Spec.ExternalIPs) { - s.eventRecorder.Eventf(newService, api.EventTypeNormal, "ExternalIP", "Count: %v -> %v", + s.eventRecorder.Eventf(newService, v1.EventTypeNormal, "ExternalIP", "Count: %v -> %v", len(oldService.Spec.ExternalIPs), len(newService.Spec.ExternalIPs)) return true } for i := range oldService.Spec.ExternalIPs { if oldService.Spec.ExternalIPs[i] != newService.Spec.ExternalIPs[i] { - s.eventRecorder.Eventf(newService, api.EventTypeNormal, "ExternalIP", "Added: %v", + s.eventRecorder.Eventf(newService, v1.EventTypeNormal, "ExternalIP", "Added: %v", newService.Spec.ExternalIPs[i]) return true } @@ -454,7 +454,7 @@ func (s *ServiceController) needsUpdate(oldService *api.Service, newService *api return true } if oldService.UID != newService.UID { - s.eventRecorder.Eventf(newService, api.EventTypeNormal, "UID", "%v -> %v", + s.eventRecorder.Eventf(newService, v1.EventTypeNormal, "UID", "%v -> %v", oldService.UID, newService.UID) return true } @@ -462,14 +462,14 @@ func (s *ServiceController) needsUpdate(oldService *api.Service, newService *api return false } -func (s *ServiceController) loadBalancerName(service *api.Service) string { +func (s *ServiceController) loadBalancerName(service *v1.Service) string { return cloudprovider.GetLoadBalancerName(service) } -func getPortsForLB(service *api.Service) ([]*api.ServicePort, error) { - var protocol api.Protocol +func getPortsForLB(service *v1.Service) ([]*v1.ServicePort, error) { + var protocol v1.Protocol - ports := []*api.ServicePort{} + ports := []*v1.ServicePort{} for i := range service.Spec.Ports { sp := &service.Spec.Ports[i] // The check on protocol was removed here. The cloud provider itself is now responsible for all protocol validation @@ -484,7 +484,7 @@ func getPortsForLB(service *api.Service) ([]*api.ServicePort, error) { return ports, nil } -func portsEqualForLB(x, y *api.Service) bool { +func portsEqualForLB(x, y *v1.Service) bool { xPorts, err := getPortsForLB(x) if err != nil { return false @@ -496,7 +496,7 @@ func portsEqualForLB(x, y *api.Service) bool { return portSlicesEqualForLB(xPorts, yPorts) } -func portSlicesEqualForLB(x, y []*api.ServicePort) bool { +func portSlicesEqualForLB(x, y []*v1.ServicePort) bool { if len(x) != len(y) { return false } @@ -509,7 +509,7 @@ func portSlicesEqualForLB(x, y []*api.ServicePort) bool { return true } -func portEqualForLB(x, y *api.ServicePort) bool { +func portEqualForLB(x, y *v1.ServicePort) bool { // TODO: Should we check name? (In theory, an LB could expose it) if x.Name != y.Name { return false @@ -569,11 +569,11 @@ func stringSlicesEqual(x, y []string) bool { return true } -func includeNodeFromNodeList(node *api.Node) bool { +func includeNodeFromNodeList(node *v1.Node) bool { return !node.Spec.Unschedulable } -func hostsFromNodeList(list *api.NodeList) []string { +func hostsFromNodeList(list *v1.NodeList) []string { result := []string{} for ix := range list.Items { if includeNodeFromNodeList(&list.Items[ix]) { @@ -583,7 +583,7 @@ func hostsFromNodeList(list *api.NodeList) []string { return result } -func hostsFromNodeSlice(nodes []*api.Node) []string { +func hostsFromNodeSlice(nodes []*v1.Node) []string { result := []string{} for _, node := range nodes { if includeNodeFromNodeList(node) { @@ -594,7 +594,7 @@ func hostsFromNodeSlice(nodes []*api.Node) []string { } func getNodeConditionPredicate() cache.NodeConditionPredicate { - return func(node *api.Node) bool { + return func(node *v1.Node) bool { // We add the master to the node list, but its unschedulable. So we use this to filter // the master. // TODO: Use a node annotation to indicate the master @@ -608,7 +608,7 @@ func getNodeConditionPredicate() cache.NodeConditionPredicate { for _, cond := range node.Status.Conditions { // We consider the node for load balancing only when its NodeReady condition status // is ConditionTrue - if cond.Type == api.NodeReady && cond.Status != api.ConditionTrue { + if cond.Type == v1.NodeReady && cond.Status != v1.ConditionTrue { glog.V(4).Infof("Ignoring node %v with %v condition status %v", node.Name, cond.Type, cond.Status) return false } @@ -648,7 +648,7 @@ func (s *ServiceController) nodeSyncLoop() { // updateLoadBalancerHosts updates all existing load balancers so that // they will match the list of hosts provided. // Returns the list of services that couldn't be updated. -func (s *ServiceController) updateLoadBalancerHosts(services []*api.Service, hosts []string) (servicesToRetry []*api.Service) { +func (s *ServiceController) updateLoadBalancerHosts(services []*v1.Service, hosts []string) (servicesToRetry []*v1.Service) { for _, service := range services { func() { if service == nil { @@ -665,7 +665,7 @@ func (s *ServiceController) updateLoadBalancerHosts(services []*api.Service, hos // Updates the load balancer of a service, assuming we hold the mutex // associated with the service. -func (s *ServiceController) lockedUpdateLoadBalancerHosts(service *api.Service, hosts []string) error { +func (s *ServiceController) lockedUpdateLoadBalancerHosts(service *v1.Service, hosts []string) error { if !wantsLoadBalancer(service) { return nil } @@ -673,7 +673,7 @@ func (s *ServiceController) lockedUpdateLoadBalancerHosts(service *api.Service, // This operation doesn't normally take very long (and happens pretty often), so we only record the final event err := s.balancer.UpdateLoadBalancer(s.clusterName, service, hosts) if err == nil { - s.eventRecorder.Event(service, api.EventTypeNormal, "UpdatedLoadBalancer", "Updated load balancer with new hosts") + s.eventRecorder.Event(service, v1.EventTypeNormal, "UpdatedLoadBalancer", "Updated load balancer with new hosts") return nil } @@ -684,15 +684,15 @@ func (s *ServiceController) lockedUpdateLoadBalancerHosts(service *api.Service, return nil } - s.eventRecorder.Eventf(service, api.EventTypeWarning, "LoadBalancerUpdateFailed", "Error updating load balancer with new hosts %v: %v", hosts, err) + s.eventRecorder.Eventf(service, v1.EventTypeWarning, "LoadBalancerUpdateFailed", "Error updating load balancer with new hosts %v: %v", hosts, err) return err } -func wantsLoadBalancer(service *api.Service) bool { - return service.Spec.Type == api.ServiceTypeLoadBalancer +func wantsLoadBalancer(service *v1.Service) bool { + return service.Spec.Type == v1.ServiceTypeLoadBalancer } -func loadBalancerIPsAreEqual(oldService, newService *api.Service) bool { +func loadBalancerIPsAreEqual(oldService, newService *v1.Service) bool { return oldService.Spec.LoadBalancerIP == newService.Spec.LoadBalancerIP } @@ -736,7 +736,7 @@ func (s *ServiceController) syncService(key string) error { glog.Infof("Service has been deleted %v", key) err, retryDelay = s.processServiceDeletion(key) } else { - service, ok := obj.(*api.Service) + service, ok := obj.(*v1.Service) if ok { cachedService = s.cache.getOrCreate(key) err, retryDelay = s.processServiceUpdate(cachedService, service, key) @@ -778,14 +778,14 @@ func (s *ServiceController) processServiceDeletion(key string) (error, time.Dura if !wantsLoadBalancer(service) { return nil, doNotRetry } - s.eventRecorder.Event(service, api.EventTypeNormal, "DeletingLoadBalancer", "Deleting load balancer") + s.eventRecorder.Event(service, v1.EventTypeNormal, "DeletingLoadBalancer", "Deleting load balancer") err := s.balancer.EnsureLoadBalancerDeleted(s.clusterName, service) if err != nil { message := "Error deleting load balancer (will retry): " + err.Error() - s.eventRecorder.Event(service, api.EventTypeWarning, "DeletingLoadBalancerFailed", message) + s.eventRecorder.Event(service, v1.EventTypeWarning, "DeletingLoadBalancerFailed", message) return err, cachedService.nextRetryDelay() } - s.eventRecorder.Event(service, api.EventTypeNormal, "DeletedLoadBalancer", "Deleted load balancer") + s.eventRecorder.Event(service, v1.EventTypeNormal, "DeletedLoadBalancer", "Deleted load balancer") s.cache.delete(key) cachedService.resetRetryDelay() diff --git a/pkg/controller/service/servicecontroller_test.go b/pkg/controller/service/servicecontroller_test.go index 4e868822c69..7d8d3d674cc 100644 --- a/pkg/controller/service/servicecontroller_test.go +++ b/pkg/controller/service/servicecontroller_test.go @@ -20,69 +20,69 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" fakecloud "k8s.io/kubernetes/pkg/cloudprovider/providers/fake" "k8s.io/kubernetes/pkg/types" ) const region = "us-central" -func newService(name string, uid types.UID, serviceType api.ServiceType) *api.Service { - return &api.Service{ObjectMeta: api.ObjectMeta{Name: name, Namespace: "namespace", UID: uid, SelfLink: testapi.Default.SelfLink("services", name)}, Spec: api.ServiceSpec{Type: serviceType}} +func newService(name string, uid types.UID, serviceType v1.ServiceType) *v1.Service { + return &v1.Service{ObjectMeta: v1.ObjectMeta{Name: name, Namespace: "namespace", UID: uid, SelfLink: testapi.Default.SelfLink("services", name)}, Spec: v1.ServiceSpec{Type: serviceType}} } func TestCreateExternalLoadBalancer(t *testing.T) { table := []struct { - service *api.Service + service *v1.Service expectErr bool expectCreateAttempt bool }{ { - service: &api.Service{ - ObjectMeta: api.ObjectMeta{ + service: &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: "no-external-balancer", Namespace: "default", }, - Spec: api.ServiceSpec{ - Type: api.ServiceTypeClusterIP, + Spec: v1.ServiceSpec{ + Type: v1.ServiceTypeClusterIP, }, }, expectErr: false, expectCreateAttempt: false, }, { - service: &api.Service{ - ObjectMeta: api.ObjectMeta{ + service: &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: "udp-service", Namespace: "default", SelfLink: testapi.Default.SelfLink("services", "udp-service"), }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{{ + Spec: v1.ServiceSpec{ + Ports: []v1.ServicePort{{ Port: 80, - Protocol: api.ProtocolUDP, + Protocol: v1.ProtocolUDP, }}, - Type: api.ServiceTypeLoadBalancer, + Type: v1.ServiceTypeLoadBalancer, }, }, expectErr: false, expectCreateAttempt: true, }, { - service: &api.Service{ - ObjectMeta: api.ObjectMeta{ + service: &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: "basic-service1", Namespace: "default", SelfLink: testapi.Default.SelfLink("services", "basic-service1"), }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{{ + Spec: v1.ServiceSpec{ + Ports: []v1.ServicePort{{ Port: 80, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }}, - Type: api.ServiceTypeLoadBalancer, + Type: v1.ServiceTypeLoadBalancer, }, }, expectErr: false, @@ -147,65 +147,65 @@ func TestCreateExternalLoadBalancer(t *testing.T) { func TestUpdateNodesInExternalLoadBalancer(t *testing.T) { hosts := []string{"node0", "node1", "node73"} table := []struct { - services []*api.Service + services []*v1.Service expectedUpdateCalls []fakecloud.FakeUpdateBalancerCall }{ { // No services present: no calls should be made. - services: []*api.Service{}, + services: []*v1.Service{}, expectedUpdateCalls: nil, }, { // Services do not have external load balancers: no calls should be made. - services: []*api.Service{ - newService("s0", "111", api.ServiceTypeClusterIP), - newService("s1", "222", api.ServiceTypeNodePort), + services: []*v1.Service{ + newService("s0", "111", v1.ServiceTypeClusterIP), + newService("s1", "222", v1.ServiceTypeNodePort), }, expectedUpdateCalls: nil, }, { // Services does have an external load balancer: one call should be made. - services: []*api.Service{ - newService("s0", "333", api.ServiceTypeLoadBalancer), + services: []*v1.Service{ + newService("s0", "333", v1.ServiceTypeLoadBalancer), }, expectedUpdateCalls: []fakecloud.FakeUpdateBalancerCall{ - {newService("s0", "333", api.ServiceTypeLoadBalancer), hosts}, + {newService("s0", "333", v1.ServiceTypeLoadBalancer), hosts}, }, }, { // Three services have an external load balancer: three calls. - services: []*api.Service{ - newService("s0", "444", api.ServiceTypeLoadBalancer), - newService("s1", "555", api.ServiceTypeLoadBalancer), - newService("s2", "666", api.ServiceTypeLoadBalancer), + services: []*v1.Service{ + newService("s0", "444", v1.ServiceTypeLoadBalancer), + newService("s1", "555", v1.ServiceTypeLoadBalancer), + newService("s2", "666", v1.ServiceTypeLoadBalancer), }, expectedUpdateCalls: []fakecloud.FakeUpdateBalancerCall{ - {newService("s0", "444", api.ServiceTypeLoadBalancer), hosts}, - {newService("s1", "555", api.ServiceTypeLoadBalancer), hosts}, - {newService("s2", "666", api.ServiceTypeLoadBalancer), hosts}, + {newService("s0", "444", v1.ServiceTypeLoadBalancer), hosts}, + {newService("s1", "555", v1.ServiceTypeLoadBalancer), hosts}, + {newService("s2", "666", v1.ServiceTypeLoadBalancer), hosts}, }, }, { // Two services have an external load balancer and two don't: two calls. - services: []*api.Service{ - newService("s0", "777", api.ServiceTypeNodePort), - newService("s1", "888", api.ServiceTypeLoadBalancer), - newService("s3", "999", api.ServiceTypeLoadBalancer), - newService("s4", "123", api.ServiceTypeClusterIP), + services: []*v1.Service{ + newService("s0", "777", v1.ServiceTypeNodePort), + newService("s1", "888", v1.ServiceTypeLoadBalancer), + newService("s3", "999", v1.ServiceTypeLoadBalancer), + newService("s4", "123", v1.ServiceTypeClusterIP), }, expectedUpdateCalls: []fakecloud.FakeUpdateBalancerCall{ - {newService("s1", "888", api.ServiceTypeLoadBalancer), hosts}, - {newService("s3", "999", api.ServiceTypeLoadBalancer), hosts}, + {newService("s1", "888", v1.ServiceTypeLoadBalancer), hosts}, + {newService("s3", "999", v1.ServiceTypeLoadBalancer), hosts}, }, }, { // One service has an external load balancer and one is nil: one call. - services: []*api.Service{ - newService("s0", "234", api.ServiceTypeLoadBalancer), + services: []*v1.Service{ + newService("s0", "234", v1.ServiceTypeLoadBalancer), nil, }, expectedUpdateCalls: []fakecloud.FakeUpdateBalancerCall{ - {newService("s0", "234", api.ServiceTypeLoadBalancer), hosts}, + {newService("s0", "234", v1.ServiceTypeLoadBalancer), hosts}, }, }, } @@ -218,7 +218,7 @@ func TestUpdateNodesInExternalLoadBalancer(t *testing.T) { controller.init() cloud.Calls = nil // ignore any cloud calls made in init() - var services []*api.Service + var services []*v1.Service for _, service := range item.services { services = append(services, service) } @@ -233,43 +233,43 @@ func TestUpdateNodesInExternalLoadBalancer(t *testing.T) { func TestHostsFromNodeList(t *testing.T) { tests := []struct { - nodes *api.NodeList + nodes *v1.NodeList expectedHosts []string }{ { - nodes: &api.NodeList{}, + nodes: &v1.NodeList{}, expectedHosts: []string{}, }, { - nodes: &api.NodeList{ - Items: []api.Node{ + nodes: &v1.NodeList{ + Items: []v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Status: api.NodeStatus{Phase: api.NodeRunning}, + ObjectMeta: v1.ObjectMeta{Name: "foo"}, + Status: v1.NodeStatus{Phase: v1.NodeRunning}, }, { - ObjectMeta: api.ObjectMeta{Name: "bar"}, - Status: api.NodeStatus{Phase: api.NodeRunning}, + ObjectMeta: v1.ObjectMeta{Name: "bar"}, + Status: v1.NodeStatus{Phase: v1.NodeRunning}, }, }, }, expectedHosts: []string{"foo", "bar"}, }, { - nodes: &api.NodeList{ - Items: []api.Node{ + nodes: &v1.NodeList{ + Items: []v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Status: api.NodeStatus{Phase: api.NodeRunning}, + ObjectMeta: v1.ObjectMeta{Name: "foo"}, + Status: v1.NodeStatus{Phase: v1.NodeRunning}, }, { - ObjectMeta: api.ObjectMeta{Name: "bar"}, - Status: api.NodeStatus{Phase: api.NodeRunning}, + ObjectMeta: v1.ObjectMeta{Name: "bar"}, + Status: v1.NodeStatus{Phase: v1.NodeRunning}, }, { - ObjectMeta: api.ObjectMeta{Name: "unschedulable"}, - Spec: api.NodeSpec{Unschedulable: true}, - Status: api.NodeStatus{Phase: api.NodeRunning}, + ObjectMeta: v1.ObjectMeta{Name: "unschedulable"}, + Spec: v1.NodeSpec{Unschedulable: true}, + Status: v1.NodeStatus{Phase: v1.NodeRunning}, }, }, }, @@ -287,20 +287,20 @@ func TestHostsFromNodeList(t *testing.T) { func TestGetNodeConditionPredicate(t *testing.T) { tests := []struct { - node api.Node + node v1.Node expectAccept bool name string }{ { - node: api.Node{}, + node: v1.Node{}, expectAccept: false, name: "empty", }, { - node: api.Node{ - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ - {Type: api.NodeReady, Status: api.ConditionTrue}, + node: v1.Node{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ + {Type: v1.NodeReady, Status: v1.ConditionTrue}, }, }, }, @@ -308,11 +308,11 @@ func TestGetNodeConditionPredicate(t *testing.T) { name: "basic", }, { - node: api.Node{ - Spec: api.NodeSpec{Unschedulable: true}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ - {Type: api.NodeReady, Status: api.ConditionTrue}, + node: v1.Node{ + Spec: v1.NodeSpec{Unschedulable: true}, + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ + {Type: v1.NodeReady, Status: v1.ConditionTrue}, }, }, }, diff --git a/pkg/controller/serviceaccount/BUILD b/pkg/controller/serviceaccount/BUILD index fafb2f7fb17..20c480bceb6 100644 --- a/pkg/controller/serviceaccount/BUILD +++ b/pkg/controller/serviceaccount/BUILD @@ -23,8 +23,9 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/meta:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/retry:go_default_library", "//pkg/controller/informers:go_default_library", "//pkg/fields:go_default_library", @@ -60,8 +61,9 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/controller:go_default_library", "//pkg/controller/informers:go_default_library", diff --git a/pkg/controller/serviceaccount/serviceaccounts_controller.go b/pkg/controller/serviceaccount/serviceaccounts_controller.go index e94bf891e69..db7c60f2212 100644 --- a/pkg/controller/serviceaccount/serviceaccounts_controller.go +++ b/pkg/controller/serviceaccount/serviceaccounts_controller.go @@ -21,11 +21,11 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" apierrs "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/meta" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller/informers" utilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/metrics" @@ -46,7 +46,7 @@ func nameIndexFunc(obj interface{}) ([]string, error) { // ServiceAccountsControllerOptions contains options for running a ServiceAccountsController type ServiceAccountsControllerOptions struct { // ServiceAccounts is the list of service accounts to ensure exist in every namespace - ServiceAccounts []api.ServiceAccount + ServiceAccounts []v1.ServiceAccount // ServiceAccountResync is the interval between full resyncs of ServiceAccounts. // If non-zero, all service accounts will be re-listed this often. @@ -61,8 +61,8 @@ type ServiceAccountsControllerOptions struct { func DefaultServiceAccountsControllerOptions() ServiceAccountsControllerOptions { return ServiceAccountsControllerOptions{ - ServiceAccounts: []api.ServiceAccount{ - {ObjectMeta: api.ObjectMeta{Name: "default"}}, + ServiceAccounts: []v1.ServiceAccount{ + {ObjectMeta: v1.ObjectMeta{Name: "default"}}, }, } } @@ -99,7 +99,7 @@ func NewServiceAccountsController(saInformer informers.ServiceAccountInformer, n // ServiceAccountsController manages ServiceAccount objects inside Namespaces type ServiceAccountsController struct { client clientset.Interface - serviceAccountsToEnsure []api.ServiceAccount + serviceAccountsToEnsure []v1.ServiceAccount // To allow injection for testing. syncHandler func(key string) error @@ -133,14 +133,14 @@ func (c *ServiceAccountsController) Run(workers int, stopCh <-chan struct{}) { // serviceAccountDeleted reacts to a ServiceAccount deletion by recreating a default ServiceAccount in the namespace if needed func (c *ServiceAccountsController) serviceAccountDeleted(obj interface{}) { - sa, ok := obj.(*api.ServiceAccount) + sa, ok := obj.(*v1.ServiceAccount) if !ok { tombstone, ok := obj.(cache.DeletedFinalStateUnknown) if !ok { utilruntime.HandleError(fmt.Errorf("Couldn't get object from tombstone %#v", obj)) return } - sa, ok = tombstone.Obj.(*api.ServiceAccount) + sa, ok = tombstone.Obj.(*v1.ServiceAccount) if !ok { utilruntime.HandleError(fmt.Errorf("Tombstone contained object that is not a ServiceAccount %#v", obj)) return @@ -151,13 +151,13 @@ func (c *ServiceAccountsController) serviceAccountDeleted(obj interface{}) { // namespaceAdded reacts to a Namespace creation by creating a default ServiceAccount object func (c *ServiceAccountsController) namespaceAdded(obj interface{}) { - namespace := obj.(*api.Namespace) + namespace := obj.(*v1.Namespace) c.queue.Add(namespace.Name) } // namespaceUpdated reacts to a Namespace update (or re-list) by creating a default ServiceAccount in the namespace if needed func (c *ServiceAccountsController) namespaceUpdated(oldObj interface{}, newObj interface{}) { - newNamespace := newObj.(*api.Namespace) + newNamespace := newObj.(*v1.Namespace) c.queue.Add(newNamespace.Name) } @@ -198,7 +198,7 @@ func (c *ServiceAccountsController) syncNamespace(key string) error { if err != nil { return err } - if ns.Status.Phase != api.NamespaceActive { + if ns.Status.Phase != v1.NamespaceActive { // If namespace is not active, we shouldn't try to create anything return nil } diff --git a/pkg/controller/serviceaccount/serviceaccounts_controller_test.go b/pkg/controller/serviceaccount/serviceaccounts_controller_test.go index e6a31fd2b76..5c79da00cb5 100644 --- a/pkg/controller/serviceaccount/serviceaccounts_controller_test.go +++ b/pkg/controller/serviceaccount/serviceaccounts_controller_test.go @@ -20,9 +20,9 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/informers" @@ -35,39 +35,39 @@ type serverResponse struct { } func TestServiceAccountCreation(t *testing.T) { - ns := api.NamespaceDefault + ns := v1.NamespaceDefault defaultName := "default" managedName := "managed" - activeNS := &api.Namespace{ - ObjectMeta: api.ObjectMeta{Name: ns}, - Status: api.NamespaceStatus{ - Phase: api.NamespaceActive, + activeNS := &v1.Namespace{ + ObjectMeta: v1.ObjectMeta{Name: ns}, + Status: v1.NamespaceStatus{ + Phase: v1.NamespaceActive, }, } - terminatingNS := &api.Namespace{ - ObjectMeta: api.ObjectMeta{Name: ns}, - Status: api.NamespaceStatus{ - Phase: api.NamespaceTerminating, + terminatingNS := &v1.Namespace{ + ObjectMeta: v1.ObjectMeta{Name: ns}, + Status: v1.NamespaceStatus{ + Phase: v1.NamespaceTerminating, }, } - defaultServiceAccount := &api.ServiceAccount{ - ObjectMeta: api.ObjectMeta{ + defaultServiceAccount := &v1.ServiceAccount{ + ObjectMeta: v1.ObjectMeta{ Name: defaultName, Namespace: ns, ResourceVersion: "1", }, } - managedServiceAccount := &api.ServiceAccount{ - ObjectMeta: api.ObjectMeta{ + managedServiceAccount := &v1.ServiceAccount{ + ObjectMeta: v1.ObjectMeta{ Name: managedName, Namespace: ns, ResourceVersion: "1", }, } - unmanagedServiceAccount := &api.ServiceAccount{ - ObjectMeta: api.ObjectMeta{ + unmanagedServiceAccount := &v1.ServiceAccount{ + ObjectMeta: v1.ObjectMeta{ Name: "other-unmanaged", Namespace: ns, ResourceVersion: "1", @@ -75,54 +75,54 @@ func TestServiceAccountCreation(t *testing.T) { } testcases := map[string]struct { - ExistingNamespace *api.Namespace - ExistingServiceAccounts []*api.ServiceAccount + ExistingNamespace *v1.Namespace + ExistingServiceAccounts []*v1.ServiceAccount - AddedNamespace *api.Namespace - UpdatedNamespace *api.Namespace - DeletedServiceAccount *api.ServiceAccount + AddedNamespace *v1.Namespace + UpdatedNamespace *v1.Namespace + DeletedServiceAccount *v1.ServiceAccount ExpectCreatedServiceAccounts []string }{ "new active namespace missing serviceaccounts": { - ExistingServiceAccounts: []*api.ServiceAccount{}, + ExistingServiceAccounts: []*v1.ServiceAccount{}, AddedNamespace: activeNS, ExpectCreatedServiceAccounts: sets.NewString(defaultName, managedName).List(), }, "new active namespace missing serviceaccount": { - ExistingServiceAccounts: []*api.ServiceAccount{managedServiceAccount}, + ExistingServiceAccounts: []*v1.ServiceAccount{managedServiceAccount}, AddedNamespace: activeNS, ExpectCreatedServiceAccounts: []string{defaultName}, }, "new active namespace with serviceaccounts": { - ExistingServiceAccounts: []*api.ServiceAccount{defaultServiceAccount, managedServiceAccount}, + ExistingServiceAccounts: []*v1.ServiceAccount{defaultServiceAccount, managedServiceAccount}, AddedNamespace: activeNS, ExpectCreatedServiceAccounts: []string{}, }, "new terminating namespace": { - ExistingServiceAccounts: []*api.ServiceAccount{}, + ExistingServiceAccounts: []*v1.ServiceAccount{}, AddedNamespace: terminatingNS, ExpectCreatedServiceAccounts: []string{}, }, "updated active namespace missing serviceaccounts": { - ExistingServiceAccounts: []*api.ServiceAccount{}, + ExistingServiceAccounts: []*v1.ServiceAccount{}, UpdatedNamespace: activeNS, ExpectCreatedServiceAccounts: sets.NewString(defaultName, managedName).List(), }, "updated active namespace missing serviceaccount": { - ExistingServiceAccounts: []*api.ServiceAccount{defaultServiceAccount}, + ExistingServiceAccounts: []*v1.ServiceAccount{defaultServiceAccount}, UpdatedNamespace: activeNS, ExpectCreatedServiceAccounts: []string{managedName}, }, "updated active namespace with serviceaccounts": { - ExistingServiceAccounts: []*api.ServiceAccount{defaultServiceAccount, managedServiceAccount}, + ExistingServiceAccounts: []*v1.ServiceAccount{defaultServiceAccount, managedServiceAccount}, UpdatedNamespace: activeNS, ExpectCreatedServiceAccounts: []string{}, }, "updated terminating namespace": { - ExistingServiceAccounts: []*api.ServiceAccount{}, + ExistingServiceAccounts: []*v1.ServiceAccount{}, UpdatedNamespace: terminatingNS, ExpectCreatedServiceAccounts: []string{}, }, @@ -132,7 +132,7 @@ func TestServiceAccountCreation(t *testing.T) { ExpectCreatedServiceAccounts: []string{}, }, "deleted serviceaccount with active namespace": { - ExistingServiceAccounts: []*api.ServiceAccount{managedServiceAccount}, + ExistingServiceAccounts: []*v1.ServiceAccount{managedServiceAccount}, ExistingNamespace: activeNS, DeletedServiceAccount: defaultServiceAccount, ExpectCreatedServiceAccounts: []string{defaultName}, @@ -143,7 +143,7 @@ func TestServiceAccountCreation(t *testing.T) { ExpectCreatedServiceAccounts: []string{}, }, "deleted unmanaged serviceaccount with active namespace": { - ExistingServiceAccounts: []*api.ServiceAccount{defaultServiceAccount, managedServiceAccount}, + ExistingServiceAccounts: []*v1.ServiceAccount{defaultServiceAccount, managedServiceAccount}, ExistingNamespace: activeNS, DeletedServiceAccount: unmanagedServiceAccount, ExpectCreatedServiceAccounts: []string{}, @@ -157,11 +157,11 @@ func TestServiceAccountCreation(t *testing.T) { for k, tc := range testcases { client := fake.NewSimpleClientset(defaultServiceAccount, managedServiceAccount) - informers := informers.NewSharedInformerFactory(fake.NewSimpleClientset(), controller.NoResyncPeriodFunc()) + informers := informers.NewSharedInformerFactory(fake.NewSimpleClientset(), nil, controller.NoResyncPeriodFunc()) options := DefaultServiceAccountsControllerOptions() - options.ServiceAccounts = []api.ServiceAccount{ - {ObjectMeta: api.ObjectMeta{Name: defaultName}}, - {ObjectMeta: api.ObjectMeta{Name: managedName}}, + options.ServiceAccounts = []v1.ServiceAccount{ + {ObjectMeta: v1.ObjectMeta{Name: defaultName}}, + {ObjectMeta: v1.ObjectMeta{Name: managedName}}, } controller := NewServiceAccountsController(informers.ServiceAccounts(), informers.Namespaces(), client, options) controller.saLister = &cache.StoreToServiceAccountLister{Indexer: cache.NewIndexer(cache.DeletionHandlingMetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})} @@ -220,7 +220,7 @@ func TestServiceAccountCreation(t *testing.T) { t.Errorf("%s: Unexpected action %s", k, action) break } - createdAccount := action.(core.CreateAction).GetObject().(*api.ServiceAccount) + createdAccount := action.(core.CreateAction).GetObject().(*v1.ServiceAccount) if createdAccount.Name != expectedName { t.Errorf("%s: Expected %s to be created, got %s", k, expectedName, createdAccount.Name) } diff --git a/pkg/controller/serviceaccount/tokengetter.go b/pkg/controller/serviceaccount/tokengetter.go index 76db9bfa881..75804ae9885 100644 --- a/pkg/controller/serviceaccount/tokengetter.go +++ b/pkg/controller/serviceaccount/tokengetter.go @@ -18,7 +18,8 @@ package serviceaccount import ( "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/registry/core/secret" secretetcd "k8s.io/kubernetes/pkg/registry/core/secret/etcd" serviceaccountregistry "k8s.io/kubernetes/pkg/registry/core/serviceaccount" @@ -40,10 +41,10 @@ type clientGetter struct { func NewGetterFromClient(c clientset.Interface) serviceaccount.ServiceAccountTokenGetter { return clientGetter{c} } -func (c clientGetter) GetServiceAccount(namespace, name string) (*api.ServiceAccount, error) { +func (c clientGetter) GetServiceAccount(namespace, name string) (*v1.ServiceAccount, error) { return c.client.Core().ServiceAccounts(namespace).Get(name) } -func (c clientGetter) GetSecret(namespace, name string) (*api.Secret, error) { +func (c clientGetter) GetSecret(namespace, name string) (*v1.Secret, error) { return c.client.Core().Secrets(namespace).Get(name) } @@ -58,13 +59,27 @@ type registryGetter struct { func NewGetterFromRegistries(serviceAccounts serviceaccountregistry.Registry, secrets secret.Registry) serviceaccount.ServiceAccountTokenGetter { return ®istryGetter{serviceAccounts, secrets} } -func (r *registryGetter) GetServiceAccount(namespace, name string) (*api.ServiceAccount, error) { +func (r *registryGetter) GetServiceAccount(namespace, name string) (*v1.ServiceAccount, error) { ctx := api.WithNamespace(api.NewContext(), namespace) - return r.serviceAccounts.GetServiceAccount(ctx, name) + internalServiceAccount, err := r.serviceAccounts.GetServiceAccount(ctx, name) + if err != nil { + return nil, err + } + v1ServiceAccount := v1.ServiceAccount{} + err = v1.Convert_api_ServiceAccount_To_v1_ServiceAccount(internalServiceAccount, &v1ServiceAccount, nil) + return &v1ServiceAccount, err + } -func (r *registryGetter) GetSecret(namespace, name string) (*api.Secret, error) { +func (r *registryGetter) GetSecret(namespace, name string) (*v1.Secret, error) { ctx := api.WithNamespace(api.NewContext(), namespace) - return r.secrets.GetSecret(ctx, name) + internalSecret, err := r.secrets.GetSecret(ctx, name) + if err != nil { + return nil, err + } + v1Secret := v1.Secret{} + err = v1.Convert_api_Secret_To_v1_Secret(internalSecret, &v1Secret, nil) + return &v1Secret, err + } // NewGetterFromStorageInterface returns a ServiceAccountTokenGetter that diff --git a/pkg/controller/serviceaccount/tokens_controller.go b/pkg/controller/serviceaccount/tokens_controller.go index a7c783bc10a..189c98257f0 100644 --- a/pkg/controller/serviceaccount/tokens_controller.go +++ b/pkg/controller/serviceaccount/tokens_controller.go @@ -24,8 +24,9 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" clientretry "k8s.io/kubernetes/pkg/client/retry" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/registry/core/secret" @@ -91,14 +92,14 @@ func NewTokensController(cl clientset.Interface, options TokensControllerOptions e.serviceAccounts, e.serviceAccountController = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return e.client.Core().ServiceAccounts(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return e.client.Core().ServiceAccounts(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return e.client.Core().ServiceAccounts(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return e.client.Core().ServiceAccounts(v1.NamespaceAll).Watch(options) }, }, - &api.ServiceAccount{}, + &v1.ServiceAccount{}, options.ServiceAccountResync, cache.ResourceEventHandlerFuncs{ AddFunc: e.queueServiceAccountSync, @@ -107,19 +108,19 @@ func NewTokensController(cl clientset.Interface, options TokensControllerOptions }, ) - tokenSelector := fields.SelectorFromSet(map[string]string{api.SecretTypeField: string(api.SecretTypeServiceAccountToken)}) + tokenSelector := fields.SelectorFromSet(map[string]string{api.SecretTypeField: string(v1.SecretTypeServiceAccountToken)}) e.secrets, e.secretController = cache.NewIndexerInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - options.FieldSelector = tokenSelector - return e.client.Core().Secrets(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + options.FieldSelector = tokenSelector.String() + return e.client.Core().Secrets(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - options.FieldSelector = tokenSelector - return e.client.Core().Secrets(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + options.FieldSelector = tokenSelector.String() + return e.client.Core().Secrets(v1.NamespaceAll).Watch(options) }, }, - &api.Secret{}, + &v1.Secret{}, options.SecretResync, cache.ResourceEventHandlerFuncs{ AddFunc: e.queueSecretSync, @@ -190,13 +191,13 @@ func (e *TokensController) Run(workers int, stopCh <-chan struct{}) { } func (e *TokensController) queueServiceAccountSync(obj interface{}) { - if serviceAccount, ok := obj.(*api.ServiceAccount); ok { + if serviceAccount, ok := obj.(*v1.ServiceAccount); ok { e.syncServiceAccountQueue.Add(makeServiceAccountKey(serviceAccount)) } } func (e *TokensController) queueServiceAccountUpdateSync(oldObj interface{}, newObj interface{}) { - if serviceAccount, ok := newObj.(*api.ServiceAccount); ok { + if serviceAccount, ok := newObj.(*v1.ServiceAccount); ok { e.syncServiceAccountQueue.Add(makeServiceAccountKey(serviceAccount)) } } @@ -219,13 +220,13 @@ func (e *TokensController) retryOrForget(queue workqueue.RateLimitingInterface, } func (e *TokensController) queueSecretSync(obj interface{}) { - if secret, ok := obj.(*api.Secret); ok { + if secret, ok := obj.(*v1.Secret); ok { e.syncSecretQueue.Add(makeSecretQueueKey(secret)) } } func (e *TokensController) queueSecretUpdateSync(oldObj interface{}, newObj interface{}) { - if secret, ok := newObj.(*api.Secret); ok { + if secret, ok := newObj.(*v1.Secret); ok { e.syncSecretQueue.Add(makeSecretQueueKey(secret)) } } @@ -256,7 +257,7 @@ func (e *TokensController) syncServiceAccount() { case sa == nil: // service account no longer exists, so delete related tokens glog.V(4).Infof("syncServiceAccount(%s/%s), service account deleted, removing tokens", saInfo.namespace, saInfo.name) - sa = &api.ServiceAccount{ObjectMeta: api.ObjectMeta{Namespace: saInfo.namespace, Name: saInfo.name, UID: saInfo.uid}} + sa = &v1.ServiceAccount{ObjectMeta: v1.ObjectMeta{Namespace: saInfo.namespace, Name: saInfo.name, UID: saInfo.uid}} if retriable, err := e.deleteTokens(sa); err != nil { glog.Errorf("error deleting serviceaccount tokens for %s/%s: %v", saInfo.namespace, saInfo.name, err) retry = retriable @@ -328,7 +329,7 @@ func (e *TokensController) syncSecret() { } } -func (e *TokensController) deleteTokens(serviceAccount *api.ServiceAccount) ( /*retry*/ bool, error) { +func (e *TokensController) deleteTokens(serviceAccount *v1.ServiceAccount) ( /*retry*/ bool, error) { tokens, err := e.listTokenSecrets(serviceAccount) if err != nil { // don't retry on cache lookup errors @@ -349,9 +350,9 @@ func (e *TokensController) deleteTokens(serviceAccount *api.ServiceAccount) ( /* } func (e *TokensController) deleteToken(ns, name string, uid types.UID) ( /*retry*/ bool, error) { - var opts *api.DeleteOptions + var opts *v1.DeleteOptions if len(uid) > 0 { - opts = &api.DeleteOptions{Preconditions: &api.Preconditions{UID: &uid}} + opts = &v1.DeleteOptions{Preconditions: &v1.Preconditions{UID: &uid}} } err := e.client.Core().Secrets(ns).Delete(name, opts) // NotFound doesn't need a retry (it's already been deleted) @@ -364,7 +365,7 @@ func (e *TokensController) deleteToken(ns, name string, uid types.UID) ( /*retry } // ensureReferencedToken makes sure at least one ServiceAccountToken secret exists, and is included in the serviceAccount's Secrets list -func (e *TokensController) ensureReferencedToken(serviceAccount *api.ServiceAccount) ( /* retry */ bool, error) { +func (e *TokensController) ensureReferencedToken(serviceAccount *v1.ServiceAccount) ( /* retry */ bool, error) { if len(serviceAccount.Secrets) > 0 { allSecrets, err := e.listTokenSecrets(serviceAccount) if err != nil { @@ -396,16 +397,16 @@ func (e *TokensController) ensureReferencedToken(serviceAccount *api.ServiceAcco } // Build the secret - secret := &api.Secret{ - ObjectMeta: api.ObjectMeta{ + secret := &v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Name: secret.Strategy.GenerateName(fmt.Sprintf("%s-token-", serviceAccount.Name)), Namespace: serviceAccount.Namespace, Annotations: map[string]string{ - api.ServiceAccountNameKey: serviceAccount.Name, - api.ServiceAccountUIDKey: string(serviceAccount.UID), + v1.ServiceAccountNameKey: serviceAccount.Name, + v1.ServiceAccountUIDKey: string(serviceAccount.UID), }, }, - Type: api.SecretTypeServiceAccountToken, + Type: v1.SecretTypeServiceAccountToken, Data: map[string][]byte{}, } @@ -415,10 +416,10 @@ func (e *TokensController) ensureReferencedToken(serviceAccount *api.ServiceAcco // retriable error return true, err } - secret.Data[api.ServiceAccountTokenKey] = []byte(token) - secret.Data[api.ServiceAccountNamespaceKey] = []byte(serviceAccount.Namespace) + secret.Data[v1.ServiceAccountTokenKey] = []byte(token) + secret.Data[v1.ServiceAccountNamespaceKey] = []byte(serviceAccount.Namespace) if e.rootCA != nil && len(e.rootCA) > 0 { - secret.Data[api.ServiceAccountRootCAKey] = e.rootCA + secret.Data[v1.ServiceAccountRootCAKey] = e.rootCA } // Save the secret @@ -431,12 +432,12 @@ func (e *TokensController) ensureReferencedToken(serviceAccount *api.ServiceAcco // This prevents the service account update (below) triggering another token creation, if the referenced token couldn't be found in the store e.secrets.Add(createdToken) - liveServiceAccount.Secrets = append(liveServiceAccount.Secrets, api.ObjectReference{Name: secret.Name}) + liveServiceAccount.Secrets = append(liveServiceAccount.Secrets, v1.ObjectReference{Name: secret.Name}) if _, err = serviceAccounts.Update(liveServiceAccount); err != nil { // we weren't able to use the token, try to clean it up. glog.V(2).Infof("deleting secret %s/%s because reference couldn't be added (%v)", secret.Namespace, secret.Name, err) - deleteOpts := &api.DeleteOptions{Preconditions: &api.Preconditions{UID: &createdToken.UID}} + deleteOpts := &v1.DeleteOptions{Preconditions: &v1.Preconditions{UID: &createdToken.UID}} if deleteErr := e.client.Core().Secrets(createdToken.Namespace).Delete(createdToken.Name, deleteOpts); deleteErr != nil { glog.Error(deleteErr) // if we fail, just log it } @@ -454,20 +455,20 @@ func (e *TokensController) ensureReferencedToken(serviceAccount *api.ServiceAcco return false, nil } -func (e *TokensController) secretUpdateNeeded(secret *api.Secret) (bool, bool, bool) { - caData := secret.Data[api.ServiceAccountRootCAKey] +func (e *TokensController) secretUpdateNeeded(secret *v1.Secret) (bool, bool, bool) { + caData := secret.Data[v1.ServiceAccountRootCAKey] needsCA := len(e.rootCA) > 0 && bytes.Compare(caData, e.rootCA) != 0 - needsNamespace := len(secret.Data[api.ServiceAccountNamespaceKey]) == 0 + needsNamespace := len(secret.Data[v1.ServiceAccountNamespaceKey]) == 0 - tokenData := secret.Data[api.ServiceAccountTokenKey] + tokenData := secret.Data[v1.ServiceAccountTokenKey] needsToken := len(tokenData) == 0 return needsCA, needsNamespace, needsToken } // generateTokenIfNeeded populates the token data for the given Secret if not already set -func (e *TokensController) generateTokenIfNeeded(serviceAccount *api.ServiceAccount, cachedSecret *api.Secret) ( /* retry */ bool, error) { +func (e *TokensController) generateTokenIfNeeded(serviceAccount *v1.ServiceAccount, cachedSecret *v1.Secret) ( /* retry */ bool, error) { // Check the cached secret to see if changes are needed if needsCA, needsNamespace, needsToken := e.secretUpdateNeeded(cachedSecret); !needsCA && !needsToken && !needsNamespace { return false, nil @@ -502,11 +503,11 @@ func (e *TokensController) generateTokenIfNeeded(serviceAccount *api.ServiceAcco // Set the CA if needsCA { - liveSecret.Data[api.ServiceAccountRootCAKey] = e.rootCA + liveSecret.Data[v1.ServiceAccountRootCAKey] = e.rootCA } // Set the namespace if needsNamespace { - liveSecret.Data[api.ServiceAccountNamespaceKey] = []byte(liveSecret.Namespace) + liveSecret.Data[v1.ServiceAccountNamespaceKey] = []byte(liveSecret.Namespace) } // Generate the token @@ -515,12 +516,12 @@ func (e *TokensController) generateTokenIfNeeded(serviceAccount *api.ServiceAcco if err != nil { return false, err } - liveSecret.Data[api.ServiceAccountTokenKey] = []byte(token) + liveSecret.Data[v1.ServiceAccountTokenKey] = []byte(token) } // Set annotations - liveSecret.Annotations[api.ServiceAccountNameKey] = serviceAccount.Name - liveSecret.Annotations[api.ServiceAccountUIDKey] = string(serviceAccount.UID) + liveSecret.Annotations[v1.ServiceAccountNameKey] = serviceAccount.Name + liveSecret.Annotations[v1.ServiceAccountUIDKey] = string(serviceAccount.UID) // Save the secret _, err = secrets.Update(liveSecret) @@ -560,7 +561,7 @@ func (e *TokensController) removeSecretReference(saNamespace string, saName stri } // Remove the secret - secrets := []api.ObjectReference{} + secrets := []v1.ObjectReference{} for _, s := range serviceAccount.Secrets { if s.Name != secretName { secrets = append(secrets, s) @@ -575,16 +576,16 @@ func (e *TokensController) removeSecretReference(saNamespace string, saName stri return err } -func (e *TokensController) getServiceAccount(ns string, name string, uid types.UID, fetchOnCacheMiss bool) (*api.ServiceAccount, error) { +func (e *TokensController) getServiceAccount(ns string, name string, uid types.UID, fetchOnCacheMiss bool) (*v1.ServiceAccount, error) { // Look up in cache obj, exists, err := e.serviceAccounts.GetByKey(makeCacheKey(ns, name)) if err != nil { return nil, err } if exists { - sa, ok := obj.(*api.ServiceAccount) + sa, ok := obj.(*v1.ServiceAccount) if !ok { - return nil, fmt.Errorf("expected *api.ServiceAccount, got %#v", sa) + return nil, fmt.Errorf("expected *v1.ServiceAccount, got %#v", sa) } // Ensure UID matches if given if len(uid) == 0 || uid == sa.UID { @@ -611,16 +612,16 @@ func (e *TokensController) getServiceAccount(ns string, name string, uid types.U return nil, nil } -func (e *TokensController) getSecret(ns string, name string, uid types.UID, fetchOnCacheMiss bool) (*api.Secret, error) { +func (e *TokensController) getSecret(ns string, name string, uid types.UID, fetchOnCacheMiss bool) (*v1.Secret, error) { // Look up in cache obj, exists, err := e.secrets.GetByKey(makeCacheKey(ns, name)) if err != nil { return nil, err } if exists { - secret, ok := obj.(*api.Secret) + secret, ok := obj.(*v1.Secret) if !ok { - return nil, fmt.Errorf("expected *api.Secret, got %#v", secret) + return nil, fmt.Errorf("expected *v1.Secret, got %#v", secret) } // Ensure UID matches if given if len(uid) == 0 || uid == secret.UID { @@ -649,15 +650,15 @@ func (e *TokensController) getSecret(ns string, name string, uid types.UID, fetc // listTokenSecrets returns a list of all of the ServiceAccountToken secrets that // reference the given service account's name and uid -func (e *TokensController) listTokenSecrets(serviceAccount *api.ServiceAccount) ([]*api.Secret, error) { +func (e *TokensController) listTokenSecrets(serviceAccount *v1.ServiceAccount) ([]*v1.Secret, error) { namespaceSecrets, err := e.secrets.ByIndex("namespace", serviceAccount.Namespace) if err != nil { return nil, err } - items := []*api.Secret{} + items := []*v1.Secret{} for _, obj := range namespaceSecrets { - secret := obj.(*api.Secret) + secret := obj.(*v1.Secret) if serviceaccount.IsServiceAccountToken(secret, serviceAccount) { items = append(items, secret) @@ -669,14 +670,14 @@ func (e *TokensController) listTokenSecrets(serviceAccount *api.ServiceAccount) // serviceAccountNameAndUID is a helper method to get the ServiceAccount Name and UID from the given secret // Returns "","" if the secret is not a ServiceAccountToken secret // If the name or uid annotation is missing, "" is returned instead -func serviceAccountNameAndUID(secret *api.Secret) (string, string) { - if secret.Type != api.SecretTypeServiceAccountToken { +func serviceAccountNameAndUID(secret *v1.Secret) (string, string) { + if secret.Type != v1.SecretTypeServiceAccountToken { return "", "" } - return secret.Annotations[api.ServiceAccountNameKey], secret.Annotations[api.ServiceAccountUIDKey] + return secret.Annotations[v1.ServiceAccountNameKey], secret.Annotations[v1.ServiceAccountUIDKey] } -func getSecretReferences(serviceAccount *api.ServiceAccount) sets.String { +func getSecretReferences(serviceAccount *v1.ServiceAccount) sets.String { references := sets.NewString() for _, secret := range serviceAccount.Secrets { references.Insert(secret.Name) @@ -693,7 +694,7 @@ type serviceAccountQueueKey struct { uid types.UID } -func makeServiceAccountKey(sa *api.ServiceAccount) interface{} { +func makeServiceAccountKey(sa *v1.ServiceAccount) interface{} { return serviceAccountQueueKey{ namespace: sa.Namespace, name: sa.Name, @@ -721,13 +722,13 @@ type secretQueueKey struct { saUID types.UID } -func makeSecretQueueKey(secret *api.Secret) interface{} { +func makeSecretQueueKey(secret *v1.Secret) interface{} { return secretQueueKey{ namespace: secret.Namespace, name: secret.Name, uid: secret.UID, - saName: secret.Annotations[api.ServiceAccountNameKey], - saUID: types.UID(secret.Annotations[api.ServiceAccountUIDKey]), + saName: secret.Annotations[v1.ServiceAccountNameKey], + saUID: types.UID(secret.Annotations[v1.ServiceAccountUIDKey]), } } diff --git a/pkg/controller/serviceaccount/tokens_controller_test.go b/pkg/controller/serviceaccount/tokens_controller_test.go index 20db534b846..4336cbf0bb5 100644 --- a/pkg/controller/serviceaccount/tokens_controller_test.go +++ b/pkg/controller/serviceaccount/tokens_controller_test.go @@ -27,59 +27,60 @@ import ( "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/runtime" utilrand "k8s.io/kubernetes/pkg/util/rand" ) type testGenerator struct { - GeneratedServiceAccounts []api.ServiceAccount - GeneratedSecrets []api.Secret + GeneratedServiceAccounts []v1.ServiceAccount + GeneratedSecrets []v1.Secret Token string Err error } -func (t *testGenerator) GenerateToken(serviceAccount api.ServiceAccount, secret api.Secret) (string, error) { +func (t *testGenerator) GenerateToken(serviceAccount v1.ServiceAccount, secret v1.Secret) (string, error) { t.GeneratedSecrets = append(t.GeneratedSecrets, secret) t.GeneratedServiceAccounts = append(t.GeneratedServiceAccounts, serviceAccount) return t.Token, t.Err } // emptySecretReferences is used by a service account without any secrets -func emptySecretReferences() []api.ObjectReference { - return []api.ObjectReference{} +func emptySecretReferences() []v1.ObjectReference { + return []v1.ObjectReference{} } // missingSecretReferences is used by a service account that references secrets which do no exist -func missingSecretReferences() []api.ObjectReference { - return []api.ObjectReference{{Name: "missing-secret-1"}} +func missingSecretReferences() []v1.ObjectReference { + return []v1.ObjectReference{{Name: "missing-secret-1"}} } // regularSecretReferences is used by a service account that references secrets which are not ServiceAccountTokens -func regularSecretReferences() []api.ObjectReference { - return []api.ObjectReference{{Name: "regular-secret-1"}} +func regularSecretReferences() []v1.ObjectReference { + return []v1.ObjectReference{{Name: "regular-secret-1"}} } // tokenSecretReferences is used by a service account that references a ServiceAccountToken secret -func tokenSecretReferences() []api.ObjectReference { - return []api.ObjectReference{{Name: "token-secret-1"}} +func tokenSecretReferences() []v1.ObjectReference { + return []v1.ObjectReference{{Name: "token-secret-1"}} } // addTokenSecretReference adds a reference to the ServiceAccountToken that will be created -func addTokenSecretReference(refs []api.ObjectReference) []api.ObjectReference { +func addTokenSecretReference(refs []v1.ObjectReference) []v1.ObjectReference { return addNamedTokenSecretReference(refs, "default-token-fplln") } // addNamedTokenSecretReference adds a reference to the named ServiceAccountToken -func addNamedTokenSecretReference(refs []api.ObjectReference, name string) []api.ObjectReference { - return append(refs, api.ObjectReference{Name: name}) +func addNamedTokenSecretReference(refs []v1.ObjectReference, name string) []v1.ObjectReference { + return append(refs, v1.ObjectReference{Name: name}) } // serviceAccount returns a service account with the given secret refs -func serviceAccount(secretRefs []api.ObjectReference) *api.ServiceAccount { - return &api.ServiceAccount{ - ObjectMeta: api.ObjectMeta{ +func serviceAccount(secretRefs []v1.ObjectReference) *v1.ServiceAccount { + return &v1.ServiceAccount{ + ObjectMeta: v1.ObjectMeta{ Name: "default", UID: "12345", Namespace: "default", @@ -90,16 +91,16 @@ func serviceAccount(secretRefs []api.ObjectReference) *api.ServiceAccount { } // updatedServiceAccount returns a service account with the resource version modified -func updatedServiceAccount(secretRefs []api.ObjectReference) *api.ServiceAccount { +func updatedServiceAccount(secretRefs []v1.ObjectReference) *v1.ServiceAccount { sa := serviceAccount(secretRefs) sa.ResourceVersion = "2" return sa } // opaqueSecret returns a persisted non-ServiceAccountToken secret named "regular-secret-1" -func opaqueSecret() *api.Secret { - return &api.Secret{ - ObjectMeta: api.ObjectMeta{ +func opaqueSecret() *v1.Secret { + return &v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Name: "regular-secret-1", Namespace: "default", UID: "23456", @@ -114,22 +115,22 @@ func opaqueSecret() *api.Secret { // createdTokenSecret returns the ServiceAccountToken secret posted when creating a new token secret. // Named "default-token-fplln", since that is the first generated name after rand.Seed(1) -func createdTokenSecret(overrideName ...string) *api.Secret { +func createdTokenSecret(overrideName ...string) *v1.Secret { return namedCreatedTokenSecret("default-token-fplln") } // namedTokenSecret returns the ServiceAccountToken secret posted when creating a new token secret with the given name. -func namedCreatedTokenSecret(name string) *api.Secret { - return &api.Secret{ - ObjectMeta: api.ObjectMeta{ +func namedCreatedTokenSecret(name string) *v1.Secret { + return &v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Name: name, Namespace: "default", Annotations: map[string]string{ - api.ServiceAccountNameKey: "default", - api.ServiceAccountUIDKey: "12345", + v1.ServiceAccountNameKey: "default", + v1.ServiceAccountUIDKey: "12345", }, }, - Type: api.SecretTypeServiceAccountToken, + Type: v1.SecretTypeServiceAccountToken, Data: map[string][]byte{ "token": []byte("ABC"), "ca.crt": []byte("CA Data"), @@ -139,19 +140,19 @@ func namedCreatedTokenSecret(name string) *api.Secret { } // serviceAccountTokenSecret returns an existing ServiceAccountToken secret named "token-secret-1" -func serviceAccountTokenSecret() *api.Secret { - return &api.Secret{ - ObjectMeta: api.ObjectMeta{ +func serviceAccountTokenSecret() *v1.Secret { + return &v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Name: "token-secret-1", Namespace: "default", UID: "23456", ResourceVersion: "1", Annotations: map[string]string{ - api.ServiceAccountNameKey: "default", - api.ServiceAccountUIDKey: "12345", + v1.ServiceAccountNameKey: "default", + v1.ServiceAccountUIDKey: "12345", }, }, - Type: api.SecretTypeServiceAccountToken, + Type: v1.SecretTypeServiceAccountToken, Data: map[string][]byte{ "token": []byte("ABC"), "ca.crt": []byte("CA Data"), @@ -161,37 +162,37 @@ func serviceAccountTokenSecret() *api.Secret { } // serviceAccountTokenSecretWithoutTokenData returns an existing ServiceAccountToken secret that lacks token data -func serviceAccountTokenSecretWithoutTokenData() *api.Secret { +func serviceAccountTokenSecretWithoutTokenData() *v1.Secret { secret := serviceAccountTokenSecret() - delete(secret.Data, api.ServiceAccountTokenKey) + delete(secret.Data, v1.ServiceAccountTokenKey) return secret } // serviceAccountTokenSecretWithoutCAData returns an existing ServiceAccountToken secret that lacks ca data -func serviceAccountTokenSecretWithoutCAData() *api.Secret { +func serviceAccountTokenSecretWithoutCAData() *v1.Secret { secret := serviceAccountTokenSecret() - delete(secret.Data, api.ServiceAccountRootCAKey) + delete(secret.Data, v1.ServiceAccountRootCAKey) return secret } // serviceAccountTokenSecretWithCAData returns an existing ServiceAccountToken secret with the specified ca data -func serviceAccountTokenSecretWithCAData(data []byte) *api.Secret { +func serviceAccountTokenSecretWithCAData(data []byte) *v1.Secret { secret := serviceAccountTokenSecret() - secret.Data[api.ServiceAccountRootCAKey] = data + secret.Data[v1.ServiceAccountRootCAKey] = data return secret } // serviceAccountTokenSecretWithoutNamespaceData returns an existing ServiceAccountToken secret that lacks namespace data -func serviceAccountTokenSecretWithoutNamespaceData() *api.Secret { +func serviceAccountTokenSecretWithoutNamespaceData() *v1.Secret { secret := serviceAccountTokenSecret() - delete(secret.Data, api.ServiceAccountNamespaceKey) + delete(secret.Data, v1.ServiceAccountNamespaceKey) return secret } // serviceAccountTokenSecretWithNamespaceData returns an existing ServiceAccountToken secret with the specified namespace data -func serviceAccountTokenSecretWithNamespaceData(data []byte) *api.Secret { +func serviceAccountTokenSecretWithNamespaceData(data []byte) *v1.Secret { secret := serviceAccountTokenSecret() - secret.Data[api.ServiceAccountNamespaceKey] = data + secret.Data[v1.ServiceAccountNamespaceKey] = data return secret } @@ -210,15 +211,15 @@ func TestTokenCreation(t *testing.T) { Reactors []reaction - ExistingServiceAccount *api.ServiceAccount - ExistingSecrets []*api.Secret + ExistingServiceAccount *v1.ServiceAccount + ExistingSecrets []*v1.Secret - AddedServiceAccount *api.ServiceAccount - UpdatedServiceAccount *api.ServiceAccount - DeletedServiceAccount *api.ServiceAccount - AddedSecret *api.Secret - UpdatedSecret *api.Secret - DeletedSecret *api.Secret + AddedServiceAccount *v1.ServiceAccount + UpdatedServiceAccount *v1.ServiceAccount + DeletedServiceAccount *v1.ServiceAccount + AddedSecret *v1.Secret + UpdatedSecret *v1.Secret + DeletedSecret *v1.Secret ExpectedActions []core.Action }{ @@ -227,9 +228,9 @@ func TestTokenCreation(t *testing.T) { AddedServiceAccount: serviceAccount(emptySecretReferences()), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, createdTokenSecret()), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, serviceAccount(addTokenSecretReference(emptySecretReferences()))), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, createdTokenSecret()), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, serviceAccount(addTokenSecretReference(emptySecretReferences()))), }, }, "new serviceaccount with no secrets encountering create error": { @@ -253,17 +254,17 @@ func TestTokenCreation(t *testing.T) { AddedServiceAccount: serviceAccount(emptySecretReferences()), ExpectedActions: []core.Action{ // Attempt 1 - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, createdTokenSecret()), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, createdTokenSecret()), // Attempt 2 - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, namedCreatedTokenSecret("default-token-gziey")), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, namedCreatedTokenSecret("default-token-gziey")), // Attempt 3 - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, namedCreatedTokenSecret("default-token-oh43e")), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, serviceAccount(addNamedTokenSecretReference(emptySecretReferences(), "default-token-oh43e"))), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, namedCreatedTokenSecret("default-token-oh43e")), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, serviceAccount(addNamedTokenSecretReference(emptySecretReferences(), "default-token-oh43e"))), }, }, "new serviceaccount with no secrets encountering unending create error": { @@ -283,14 +284,14 @@ func TestTokenCreation(t *testing.T) { AddedServiceAccount: serviceAccount(emptySecretReferences()), ExpectedActions: []core.Action{ // Attempt - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, createdTokenSecret()), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, createdTokenSecret()), // Retry 1 - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, namedCreatedTokenSecret("default-token-gziey")), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, namedCreatedTokenSecret("default-token-gziey")), // Retry 2 - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, namedCreatedTokenSecret("default-token-oh43e")), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, namedCreatedTokenSecret("default-token-oh43e")), }, }, "new serviceaccount with missing secrets": { @@ -298,9 +299,9 @@ func TestTokenCreation(t *testing.T) { AddedServiceAccount: serviceAccount(missingSecretReferences()), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, createdTokenSecret()), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, serviceAccount(addTokenSecretReference(missingSecretReferences()))), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, createdTokenSecret()), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, serviceAccount(addTokenSecretReference(missingSecretReferences()))), }, }, "new serviceaccount with non-token secrets": { @@ -308,14 +309,14 @@ func TestTokenCreation(t *testing.T) { AddedServiceAccount: serviceAccount(regularSecretReferences()), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, createdTokenSecret()), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, serviceAccount(addTokenSecretReference(regularSecretReferences()))), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, createdTokenSecret()), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, serviceAccount(addTokenSecretReference(regularSecretReferences()))), }, }, "new serviceaccount with token secrets": { ClientObjects: []runtime.Object{serviceAccount(tokenSecretReferences()), serviceAccountTokenSecret()}, - ExistingSecrets: []*api.Secret{serviceAccountTokenSecret()}, + ExistingSecrets: []*v1.Secret{serviceAccountTokenSecret()}, AddedServiceAccount: serviceAccount(tokenSecretReferences()), ExpectedActions: []core.Action{}, @@ -325,7 +326,7 @@ func TestTokenCreation(t *testing.T) { AddedServiceAccount: serviceAccount(emptySecretReferences()), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), }, }, "updated serviceaccount with no secrets": { @@ -333,9 +334,9 @@ func TestTokenCreation(t *testing.T) { UpdatedServiceAccount: serviceAccount(emptySecretReferences()), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, createdTokenSecret()), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, serviceAccount(addTokenSecretReference(emptySecretReferences()))), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, createdTokenSecret()), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, serviceAccount(addTokenSecretReference(emptySecretReferences()))), }, }, "updated serviceaccount with missing secrets": { @@ -343,9 +344,9 @@ func TestTokenCreation(t *testing.T) { UpdatedServiceAccount: serviceAccount(missingSecretReferences()), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, createdTokenSecret()), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, serviceAccount(addTokenSecretReference(missingSecretReferences()))), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, createdTokenSecret()), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, serviceAccount(addTokenSecretReference(missingSecretReferences()))), }, }, "updated serviceaccount with non-token secrets": { @@ -353,13 +354,13 @@ func TestTokenCreation(t *testing.T) { UpdatedServiceAccount: serviceAccount(regularSecretReferences()), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewCreateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, createdTokenSecret()), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, serviceAccount(addTokenSecretReference(regularSecretReferences()))), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewCreateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, createdTokenSecret()), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, serviceAccount(addTokenSecretReference(regularSecretReferences()))), }, }, "updated serviceaccount with token secrets": { - ExistingSecrets: []*api.Secret{serviceAccountTokenSecret()}, + ExistingSecrets: []*v1.Secret{serviceAccountTokenSecret()}, UpdatedServiceAccount: serviceAccount(tokenSecretReferences()), ExpectedActions: []core.Action{}, @@ -369,7 +370,7 @@ func TestTokenCreation(t *testing.T) { UpdatedServiceAccount: serviceAccount(emptySecretReferences()), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), }, }, @@ -389,11 +390,11 @@ func TestTokenCreation(t *testing.T) { }, "deleted serviceaccount with token secrets": { ClientObjects: []runtime.Object{serviceAccountTokenSecret()}, - ExistingSecrets: []*api.Secret{serviceAccountTokenSecret()}, + ExistingSecrets: []*v1.Secret{serviceAccountTokenSecret()}, DeletedServiceAccount: serviceAccount(tokenSecretReferences()), ExpectedActions: []core.Action{ - core.NewDeleteAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, "token-secret-1"), + core.NewDeleteAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, "token-secret-1"), }, }, @@ -402,8 +403,8 @@ func TestTokenCreation(t *testing.T) { AddedSecret: serviceAccountTokenSecret(), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewDeleteAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, "token-secret-1"), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewDeleteAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, "token-secret-1"), }, }, "added secret with serviceaccount": { @@ -418,8 +419,8 @@ func TestTokenCreation(t *testing.T) { AddedSecret: serviceAccountTokenSecretWithoutTokenData(), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, "token-secret-1"), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, serviceAccountTokenSecret()), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, "token-secret-1"), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, serviceAccountTokenSecret()), }, }, "added token secret without ca data": { @@ -428,8 +429,8 @@ func TestTokenCreation(t *testing.T) { AddedSecret: serviceAccountTokenSecretWithoutCAData(), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, "token-secret-1"), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, serviceAccountTokenSecret()), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, "token-secret-1"), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, serviceAccountTokenSecret()), }, }, "added token secret with mismatched ca data": { @@ -438,8 +439,8 @@ func TestTokenCreation(t *testing.T) { AddedSecret: serviceAccountTokenSecretWithCAData([]byte("mismatched")), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, "token-secret-1"), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, serviceAccountTokenSecret()), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, "token-secret-1"), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, serviceAccountTokenSecret()), }, }, "added token secret without namespace data": { @@ -448,8 +449,8 @@ func TestTokenCreation(t *testing.T) { AddedSecret: serviceAccountTokenSecretWithoutNamespaceData(), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, "token-secret-1"), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, serviceAccountTokenSecret()), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, "token-secret-1"), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, serviceAccountTokenSecret()), }, }, "added token secret with custom namespace data": { @@ -467,8 +468,8 @@ func TestTokenCreation(t *testing.T) { UpdatedSecret: serviceAccountTokenSecret(), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewDeleteAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, "token-secret-1"), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewDeleteAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, "token-secret-1"), }, }, "updated secret with serviceaccount": { @@ -483,8 +484,8 @@ func TestTokenCreation(t *testing.T) { UpdatedSecret: serviceAccountTokenSecretWithoutTokenData(), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, "token-secret-1"), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, serviceAccountTokenSecret()), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, "token-secret-1"), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, serviceAccountTokenSecret()), }, }, "updated token secret without ca data": { @@ -493,8 +494,8 @@ func TestTokenCreation(t *testing.T) { UpdatedSecret: serviceAccountTokenSecretWithoutCAData(), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, "token-secret-1"), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, serviceAccountTokenSecret()), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, "token-secret-1"), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, serviceAccountTokenSecret()), }, }, "updated token secret with mismatched ca data": { @@ -503,8 +504,8 @@ func TestTokenCreation(t *testing.T) { UpdatedSecret: serviceAccountTokenSecretWithCAData([]byte("mismatched")), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, "token-secret-1"), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, serviceAccountTokenSecret()), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, "token-secret-1"), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, serviceAccountTokenSecret()), }, }, "updated token secret without namespace data": { @@ -513,8 +514,8 @@ func TestTokenCreation(t *testing.T) { UpdatedSecret: serviceAccountTokenSecretWithoutNamespaceData(), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, "token-secret-1"), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "secrets"}, api.NamespaceDefault, serviceAccountTokenSecret()), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, "token-secret-1"), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "secrets"}, v1.NamespaceDefault, serviceAccountTokenSecret()), }, }, "updated token secret with custom namespace data": { @@ -537,8 +538,8 @@ func TestTokenCreation(t *testing.T) { DeletedSecret: serviceAccountTokenSecret(), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), - core.NewUpdateAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, serviceAccount(emptySecretReferences())), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), + core.NewUpdateAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, serviceAccount(emptySecretReferences())), }, }, "deleted secret with serviceaccount without reference": { @@ -546,7 +547,7 @@ func TestTokenCreation(t *testing.T) { DeletedSecret: serviceAccountTokenSecret(), ExpectedActions: []core.Action{ - core.NewGetAction(unversioned.GroupVersionResource{Resource: "serviceaccounts"}, api.NamespaceDefault, "default"), + core.NewGetAction(unversioned.GroupVersionResource{Version: "v1", Resource: "serviceaccounts"}, v1.NamespaceDefault, "default"), }, }, } diff --git a/pkg/controller/volume/attachdetach/BUILD b/pkg/controller/volume/attachdetach/BUILD index 1a7fb6991ae..bcc22df9d49 100644 --- a/pkg/controller/volume/attachdetach/BUILD +++ b/pkg/controller/volume/attachdetach/BUILD @@ -16,8 +16,9 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/record:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/controller/volume/attachdetach/cache:go_default_library", diff --git a/pkg/controller/volume/attachdetach/attach_detach_controller.go b/pkg/controller/volume/attachdetach/attach_detach_controller.go index 359de53fb72..fb3c40c2d14 100644 --- a/pkg/controller/volume/attachdetach/attach_detach_controller.go +++ b/pkg/controller/volume/attachdetach/attach_detach_controller.go @@ -25,8 +25,9 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kcache "k8s.io/kubernetes/pkg/client/cache" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache" @@ -69,7 +70,7 @@ type AttachDetachController interface { // NewAttachDetachController returns a new instance of AttachDetachController. func NewAttachDetachController( - kubeClient internalclientset.Interface, + kubeClient clientset.Interface, podInformer kcache.SharedInformer, nodeInformer kcache.SharedInformer, pvcInformer kcache.SharedInformer, @@ -144,7 +145,7 @@ func NewAttachDetachController( type attachDetachController struct { // kubeClient is the kube API client used by volumehost to communicate with // the API server. - kubeClient internalclientset.Interface + kubeClient clientset.Interface // pvcInformer is the shared PVC informer used to fetch and store PVC // objects from the API server. It is shared with other controllers and @@ -210,7 +211,7 @@ func (adc *attachDetachController) Run(stopCh <-chan struct{}) { } func (adc *attachDetachController) podAdd(obj interface{}) { - pod, ok := obj.(*api.Pod) + pod, ok := obj.(*v1.Pod) if pod == nil || !ok { return } @@ -229,7 +230,7 @@ func (adc *attachDetachController) podUpdate(oldObj, newObj interface{}) { } func (adc *attachDetachController) podDelete(obj interface{}) { - pod, ok := obj.(*api.Pod) + pod, ok := obj.(*v1.Pod) if pod == nil || !ok { return } @@ -238,7 +239,7 @@ func (adc *attachDetachController) podDelete(obj interface{}) { } func (adc *attachDetachController) nodeAdd(obj interface{}) { - node, ok := obj.(*api.Node) + node, ok := obj.(*v1.Node) if node == nil || !ok { return } @@ -259,7 +260,7 @@ func (adc *attachDetachController) nodeUpdate(oldObj, newObj interface{}) { } func (adc *attachDetachController) nodeDelete(obj interface{}) { - node, ok := obj.(*api.Node) + node, ok := obj.(*v1.Node) if node == nil || !ok { return } @@ -275,7 +276,7 @@ func (adc *attachDetachController) nodeDelete(obj interface{}) { // processPodVolumes processes the volumes in the given pod and adds them to the // desired state of the world if addVolumes is true, otherwise it removes them. func (adc *attachDetachController) processPodVolumes( - pod *api.Pod, addVolumes bool) { + pod *v1.Pod, addVolumes bool) { if pod == nil { return } @@ -363,7 +364,7 @@ func (adc *attachDetachController) processPodVolumes( // createVolumeSpec creates and returns a mutatable volume.Spec object for the // specified volume. It dereference any PVC to get PV objects, if needed. func (adc *attachDetachController) createVolumeSpec( - podVolume api.Volume, podNamespace string) (*volume.Spec, error) { + podVolume v1.Volume, podNamespace string) (*volume.Spec, error) { if pvcSource := podVolume.VolumeSource.PersistentVolumeClaim; pvcSource != nil { glog.V(10).Infof( "Found PVC, ClaimName: %q/%q", @@ -418,9 +419,9 @@ func (adc *attachDetachController) createVolumeSpec( "failed to deep copy %q volume object. err=%v", podVolume.Name, err) } - clonedPodVolume, ok := clonedPodVolumeObj.(api.Volume) + clonedPodVolume, ok := clonedPodVolumeObj.(v1.Volume) if !ok { - return nil, fmt.Errorf("failed to cast clonedPodVolume %#v to api.Volume", clonedPodVolumeObj) + return nil, fmt.Errorf("failed to cast clonedPodVolume %#v to v1.Volume", clonedPodVolumeObj) } return volume.NewSpecFromVolume(&clonedPodVolume), nil @@ -447,7 +448,7 @@ func (adc *attachDetachController) getPVCFromCacheExtractPV( err) } - pvc, ok := pvcObj.(*api.PersistentVolumeClaim) + pvc, ok := pvcObj.(*v1.PersistentVolumeClaim) if !ok || pvc == nil { return "", "", fmt.Errorf( "failed to cast %q object %#v to PersistentVolumeClaim", @@ -455,7 +456,7 @@ func (adc *attachDetachController) getPVCFromCacheExtractPV( pvcObj) } - if pvc.Status.Phase != api.ClaimBound || pvc.Spec.VolumeName == "" { + if pvc.Status.Phase != v1.ClaimBound || pvc.Spec.VolumeName == "" { return "", "", fmt.Errorf( "PVC %q has non-bound phase (%q) or empty pvc.Spec.VolumeName (%q)", key, @@ -482,7 +483,7 @@ func (adc *attachDetachController) getPVSpecFromCache( "failed to find PV %q in PVInformer cache. %v", name, err) } - pv, ok := pvObj.(*api.PersistentVolume) + pv, ok := pvObj.(*v1.PersistentVolume) if !ok || pv == nil { return nil, fmt.Errorf( "failed to cast %q object %#v to PersistentVolume", name, pvObj) @@ -510,7 +511,7 @@ func (adc *attachDetachController) getPVSpecFromCache( "failed to deep copy %q PV object. err=%v", name, err) } - clonedPV, ok := clonedPVObj.(api.PersistentVolume) + clonedPV, ok := clonedPVObj.(v1.PersistentVolume) if !ok { return nil, fmt.Errorf( "failed to cast %q clonedPV %#v to PersistentVolume", name, pvObj) @@ -524,7 +525,7 @@ func (adc *attachDetachController) getPVSpecFromCache( // corresponding volume in the actual state of the world to indicate that it is // mounted. func (adc *attachDetachController) processVolumesInUse( - nodeName types.NodeName, volumesInUse []api.UniqueVolumeName) { + nodeName types.NodeName, volumesInUse []v1.UniqueVolumeName) { glog.V(4).Infof("processVolumesInUse for node %q", nodeName) for _, attachedVolume := range adc.actualStateOfWorld.GetAttachedVolumesForNode(nodeName) { mounted := false @@ -562,11 +563,11 @@ func (adc *attachDetachController) GetPodPluginDir(podUID types.UID, pluginName return "" } -func (adc *attachDetachController) GetKubeClient() internalclientset.Interface { +func (adc *attachDetachController) GetKubeClient() clientset.Interface { return adc.kubeClient } -func (adc *attachDetachController) NewWrapperMounter(volName string, spec volume.Spec, pod *api.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { +func (adc *attachDetachController) NewWrapperMounter(volName string, spec volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { return nil, fmt.Errorf("NewWrapperMounter not supported by Attach/Detach controller's VolumeHost implementation") } @@ -594,6 +595,6 @@ func (adc *attachDetachController) GetHostIP() (net.IP, error) { return nil, fmt.Errorf("GetHostIP() not supported by Attach/Detach controller's VolumeHost implementation") } -func (adc *attachDetachController) GetNodeAllocatable() (api.ResourceList, error) { - return api.ResourceList{}, nil +func (adc *attachDetachController) GetNodeAllocatable() (v1.ResourceList, error) { + return v1.ResourceList{}, nil } diff --git a/pkg/controller/volume/attachdetach/cache/BUILD b/pkg/controller/volume/attachdetach/cache/BUILD index 69c0850ab49..1a052afecb3 100644 --- a/pkg/controller/volume/attachdetach/cache/BUILD +++ b/pkg/controller/volume/attachdetach/cache/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/volume:go_default_library", "//pkg/volume/util/operationexecutor:go_default_library", @@ -37,7 +37,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/controller/volume/attachdetach/testing:go_default_library", "//pkg/types:go_default_library", "//pkg/volume/testing:go_default_library", diff --git a/pkg/controller/volume/attachdetach/cache/actual_state_of_world.go b/pkg/controller/volume/attachdetach/cache/actual_state_of_world.go index 3c203bbcd2f..3bf7ff1756a 100644 --- a/pkg/controller/volume/attachdetach/cache/actual_state_of_world.go +++ b/pkg/controller/volume/attachdetach/cache/actual_state_of_world.go @@ -28,7 +28,7 @@ import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/util/operationexecutor" @@ -56,7 +56,7 @@ type ActualStateOfWorld interface { // added. // If no node with the name nodeName exists in list of attached nodes for // the specified volume, the node is added. - AddVolumeNode(volumeSpec *volume.Spec, nodeName types.NodeName, devicePath string) (api.UniqueVolumeName, error) + AddVolumeNode(volumeSpec *volume.Spec, nodeName types.NodeName, devicePath string) (v1.UniqueVolumeName, error) // SetVolumeMountedByNode sets the MountedByNode value for the given volume // and node. When set to true this value indicates the volume is mounted by @@ -65,7 +65,7 @@ type ActualStateOfWorld interface { // returned. // If no node with the name nodeName exists in list of attached nodes for // the specified volume, an error is returned. - SetVolumeMountedByNode(volumeName api.UniqueVolumeName, nodeName types.NodeName, mounted bool) error + SetVolumeMountedByNode(volumeName v1.UniqueVolumeName, nodeName types.NodeName, mounted bool) error // SetNodeStatusUpdateNeeded sets statusUpdateNeeded for the specified // node to true indicating the AttachedVolume field in the Node's Status @@ -76,12 +76,12 @@ type ActualStateOfWorld interface { // ResetDetachRequestTime resets the detachRequestTime to 0 which indicates there is no detach // request any more for the volume - ResetDetachRequestTime(volumeName api.UniqueVolumeName, nodeName types.NodeName) + ResetDetachRequestTime(volumeName v1.UniqueVolumeName, nodeName types.NodeName) // SetDetachRequestTime sets the detachRequestedTime to current time if this is no // previous request (the previous detachRequestedTime is zero) and return the time elapsed // since last request - SetDetachRequestTime(volumeName api.UniqueVolumeName, nodeName types.NodeName) (time.Duration, error) + SetDetachRequestTime(volumeName v1.UniqueVolumeName, nodeName types.NodeName) (time.Duration, error) // DeleteVolumeNode removes the given volume and node from the underlying // store indicating the specified volume is no longer attached to the @@ -89,12 +89,12 @@ type ActualStateOfWorld interface { // If the volume/node combo does not exist, this is a no-op. // If after deleting the node, the specified volume contains no other child // nodes, the volume is also deleted. - DeleteVolumeNode(volumeName api.UniqueVolumeName, nodeName types.NodeName) + DeleteVolumeNode(volumeName v1.UniqueVolumeName, nodeName types.NodeName) // VolumeNodeExists returns true if the specified volume/node combo exists // in the underlying store indicating the specified volume is attached to // the specified node. - VolumeNodeExists(volumeName api.UniqueVolumeName, nodeName types.NodeName) bool + VolumeNodeExists(volumeName v1.UniqueVolumeName, nodeName types.NodeName) bool // GetAttachedVolumes generates and returns a list of volumes/node pairs // reflecting which volumes are attached to which nodes based on the @@ -115,7 +115,7 @@ type ActualStateOfWorld interface { // this may differ from the actual list of attached volumes for the node // since volumes should be removed from this list as soon a detach operation // is considered, before the detach operation is triggered). - GetVolumesToReportAttached() map[types.NodeName][]api.AttachedVolume + GetVolumesToReportAttached() map[types.NodeName][]v1.AttachedVolume } // AttachedVolume represents a volume that is attached to a node. @@ -138,7 +138,7 @@ type AttachedVolume struct { // NewActualStateOfWorld returns a new instance of ActualStateOfWorld. func NewActualStateOfWorld(volumePluginMgr *volume.VolumePluginMgr) ActualStateOfWorld { return &actualStateOfWorld{ - attachedVolumes: make(map[api.UniqueVolumeName]attachedVolume), + attachedVolumes: make(map[v1.UniqueVolumeName]attachedVolume), nodesToUpdateStatusFor: make(map[types.NodeName]nodeToUpdateStatusFor), volumePluginMgr: volumePluginMgr, } @@ -149,7 +149,7 @@ type actualStateOfWorld struct { // controller believes to be successfully attached to the nodes it is // managing. The key in this map is the name of the volume and the value is // an object containing more information about the attached volume. - attachedVolumes map[api.UniqueVolumeName]attachedVolume + attachedVolumes map[v1.UniqueVolumeName]attachedVolume // nodesToUpdateStatusFor is a map containing the set of nodes for which to // update the VolumesAttached Status field. The key in this map is the name @@ -168,7 +168,7 @@ type actualStateOfWorld struct { // believes to be successfully attached to a node it is managing. type attachedVolume struct { // volumeName contains the unique identifier for this volume. - volumeName api.UniqueVolumeName + volumeName v1.UniqueVolumeName // spec is the volume spec containing the specification for this volume. // Used to generate the volume plugin object, and passed to attach/detach @@ -223,36 +223,36 @@ type nodeToUpdateStatusFor struct { // actual list of attached volumes since volumes should be removed from this // list as soon a detach operation is considered, before the detach // operation is triggered). - volumesToReportAsAttached map[api.UniqueVolumeName]api.UniqueVolumeName + volumesToReportAsAttached map[v1.UniqueVolumeName]v1.UniqueVolumeName } func (asw *actualStateOfWorld) MarkVolumeAsAttached( - _ api.UniqueVolumeName, volumeSpec *volume.Spec, nodeName types.NodeName, devicePath string) error { + _ v1.UniqueVolumeName, volumeSpec *volume.Spec, nodeName types.NodeName, devicePath string) error { _, err := asw.AddVolumeNode(volumeSpec, nodeName, devicePath) return err } func (asw *actualStateOfWorld) MarkVolumeAsDetached( - volumeName api.UniqueVolumeName, nodeName types.NodeName) { + volumeName v1.UniqueVolumeName, nodeName types.NodeName) { asw.DeleteVolumeNode(volumeName, nodeName) } func (asw *actualStateOfWorld) RemoveVolumeFromReportAsAttached( - volumeName api.UniqueVolumeName, nodeName types.NodeName) error { + volumeName v1.UniqueVolumeName, nodeName types.NodeName) error { asw.Lock() defer asw.Unlock() return asw.removeVolumeFromReportAsAttached(volumeName, nodeName) } func (asw *actualStateOfWorld) AddVolumeToReportAsAttached( - volumeName api.UniqueVolumeName, nodeName types.NodeName) { + volumeName v1.UniqueVolumeName, nodeName types.NodeName) { asw.Lock() defer asw.Unlock() asw.addVolumeToReportAsAttached(volumeName, nodeName) } func (asw *actualStateOfWorld) AddVolumeNode( - volumeSpec *volume.Spec, nodeName types.NodeName, devicePath string) (api.UniqueVolumeName, error) { + volumeSpec *volume.Spec, nodeName types.NodeName, devicePath string) (v1.UniqueVolumeName, error) { asw.Lock() defer asw.Unlock() @@ -313,7 +313,7 @@ func (asw *actualStateOfWorld) AddVolumeNode( } func (asw *actualStateOfWorld) SetVolumeMountedByNode( - volumeName api.UniqueVolumeName, nodeName types.NodeName, mounted bool) error { + volumeName v1.UniqueVolumeName, nodeName types.NodeName, mounted bool) error { asw.Lock() defer asw.Unlock() @@ -342,7 +342,7 @@ func (asw *actualStateOfWorld) SetVolumeMountedByNode( } func (asw *actualStateOfWorld) ResetDetachRequestTime( - volumeName api.UniqueVolumeName, nodeName types.NodeName) { + volumeName v1.UniqueVolumeName, nodeName types.NodeName) { asw.Lock() defer asw.Unlock() @@ -356,7 +356,7 @@ func (asw *actualStateOfWorld) ResetDetachRequestTime( } func (asw *actualStateOfWorld) SetDetachRequestTime( - volumeName api.UniqueVolumeName, nodeName types.NodeName) (time.Duration, error) { + volumeName v1.UniqueVolumeName, nodeName types.NodeName) (time.Duration, error) { asw.Lock() defer asw.Unlock() @@ -378,7 +378,7 @@ func (asw *actualStateOfWorld) SetDetachRequestTime( // Get the volume and node object from actual state of world // This is an internal function and caller should acquire and release the lock func (asw *actualStateOfWorld) getNodeAndVolume( - volumeName api.UniqueVolumeName, nodeName types.NodeName) (attachedVolume, nodeAttachedTo, error) { + volumeName v1.UniqueVolumeName, nodeName types.NodeName) (attachedVolume, nodeAttachedTo, error) { volumeObj, volumeExists := asw.attachedVolumes[volumeName] if volumeExists { @@ -396,7 +396,7 @@ func (asw *actualStateOfWorld) getNodeAndVolume( // Remove the volumeName from the node's volumesToReportAsAttached list // This is an internal function and caller should acquire and release the lock func (asw *actualStateOfWorld) removeVolumeFromReportAsAttached( - volumeName api.UniqueVolumeName, nodeName types.NodeName) error { + volumeName v1.UniqueVolumeName, nodeName types.NodeName) error { nodeToUpdate, nodeToUpdateExists := asw.nodesToUpdateStatusFor[nodeName] if nodeToUpdateExists { @@ -418,7 +418,7 @@ func (asw *actualStateOfWorld) removeVolumeFromReportAsAttached( // Add the volumeName to the node's volumesToReportAsAttached list // This is an internal function and caller should acquire and release the lock func (asw *actualStateOfWorld) addVolumeToReportAsAttached( - volumeName api.UniqueVolumeName, nodeName types.NodeName) { + volumeName v1.UniqueVolumeName, nodeName types.NodeName) { // In case the volume/node entry is no longer in attachedVolume list, skip the rest if _, _, err := asw.getNodeAndVolume(volumeName, nodeName); err != nil { glog.V(4).Infof("Volume %q is no longer attached to node %q", volumeName, nodeName) @@ -430,7 +430,7 @@ func (asw *actualStateOfWorld) addVolumeToReportAsAttached( nodeToUpdate = nodeToUpdateStatusFor{ nodeName: nodeName, statusUpdateNeeded: true, - volumesToReportAsAttached: make(map[api.UniqueVolumeName]api.UniqueVolumeName), + volumesToReportAsAttached: make(map[v1.UniqueVolumeName]v1.UniqueVolumeName), } asw.nodesToUpdateStatusFor[nodeName] = nodeToUpdate glog.V(4).Infof("Add new node %q to nodesToUpdateStatusFor", nodeName) @@ -470,7 +470,7 @@ func (asw *actualStateOfWorld) SetNodeStatusUpdateNeeded(nodeName types.NodeName } func (asw *actualStateOfWorld) DeleteVolumeNode( - volumeName api.UniqueVolumeName, nodeName types.NodeName) { + volumeName v1.UniqueVolumeName, nodeName types.NodeName) { asw.Lock() defer asw.Unlock() @@ -493,7 +493,7 @@ func (asw *actualStateOfWorld) DeleteVolumeNode( } func (asw *actualStateOfWorld) VolumeNodeExists( - volumeName api.UniqueVolumeName, nodeName types.NodeName) bool { + volumeName v1.UniqueVolumeName, nodeName types.NodeName) bool { asw.RLock() defer asw.RUnlock() @@ -562,19 +562,19 @@ func (asw *actualStateOfWorld) GetAttachedVolumesPerNode() map[types.NodeName][] return attachedVolumesPerNode } -func (asw *actualStateOfWorld) GetVolumesToReportAttached() map[types.NodeName][]api.AttachedVolume { +func (asw *actualStateOfWorld) GetVolumesToReportAttached() map[types.NodeName][]v1.AttachedVolume { asw.RLock() defer asw.RUnlock() - volumesToReportAttached := make(map[types.NodeName][]api.AttachedVolume) + volumesToReportAttached := make(map[types.NodeName][]v1.AttachedVolume) for nodeName, nodeToUpdateObj := range asw.nodesToUpdateStatusFor { if nodeToUpdateObj.statusUpdateNeeded { attachedVolumes := make( - []api.AttachedVolume, + []v1.AttachedVolume, len(nodeToUpdateObj.volumesToReportAsAttached) /* len */) i := 0 for _, volume := range nodeToUpdateObj.volumesToReportAsAttached { - attachedVolumes[i] = api.AttachedVolume{ + attachedVolumes[i] = v1.AttachedVolume{ Name: volume, DevicePath: asw.attachedVolumes[volume].devicePath, } diff --git a/pkg/controller/volume/attachdetach/cache/actual_state_of_world_test.go b/pkg/controller/volume/attachdetach/cache/actual_state_of_world_test.go index 456cd0c32e5..9c0e05e66e0 100644 --- a/pkg/controller/volume/attachdetach/cache/actual_state_of_world_test.go +++ b/pkg/controller/volume/attachdetach/cache/actual_state_of_world_test.go @@ -20,7 +20,7 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" controllervolumetesting "k8s.io/kubernetes/pkg/controller/volume/attachdetach/testing" "k8s.io/kubernetes/pkg/types" volumetesting "k8s.io/kubernetes/pkg/volume/testing" @@ -32,7 +32,7 @@ func Test_AddVolumeNode_Positive_NewVolumeNewNode(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") @@ -65,7 +65,7 @@ func Test_AddVolumeNode_Positive_ExistingVolumeNewNode(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) node1Name := types.NodeName("node1-name") node2Name := types.NodeName("node2-name") @@ -115,7 +115,7 @@ func Test_AddVolumeNode_Positive_ExistingVolumeExistingNode(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -159,7 +159,7 @@ func Test_DeleteVolumeNode_Positive_VolumeExistsNodeExists(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -189,7 +189,7 @@ func Test_DeleteVolumeNode_Positive_VolumeDoesntExistNodeDoesntExist(t *testing. // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") nodeName := types.NodeName("node-name") // Act @@ -215,7 +215,7 @@ func Test_DeleteVolumeNode_Positive_TwoNodesOneDeleted(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) node1Name := types.NodeName("node1-name") node2Name := types.NodeName("node2-name") @@ -264,7 +264,7 @@ func Test_VolumeNodeExists_Positive_VolumeExistsNodeExists(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -296,7 +296,7 @@ func Test_VolumeNodeExists_Positive_VolumeExistsNodeDoesntExist(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) node1Name := types.NodeName("node1-name") node2Name := types.NodeName("node2-name") @@ -328,7 +328,7 @@ func Test_VolumeNodeExists_Positive_VolumeAndNodeDontExist(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") nodeName := types.NodeName("node-name") // Act @@ -368,7 +368,7 @@ func Test_GetAttachedVolumes_Positive_OneVolumeOneNode(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -395,7 +395,7 @@ func Test_GetAttachedVolumes_Positive_TwoVolumeTwoNodes(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volume1Name := api.UniqueVolumeName("volume1-name") + volume1Name := v1.UniqueVolumeName("volume1-name") volume1Spec := controllervolumetesting.GetTestVolumeSpec(string(volume1Name), volume1Name) node1Name := types.NodeName("node1-name") devicePath := "fake/device/path" @@ -403,7 +403,7 @@ func Test_GetAttachedVolumes_Positive_TwoVolumeTwoNodes(t *testing.T) { if add1Err != nil { t.Fatalf("AddVolumeNode failed. Expected: Actual: <%v>", add1Err) } - volume2Name := api.UniqueVolumeName("volume2-name") + volume2Name := v1.UniqueVolumeName("volume2-name") volume2Spec := controllervolumetesting.GetTestVolumeSpec(string(volume2Name), volume2Name) node2Name := types.NodeName("node2-name") generatedVolumeName2, add2Err := asw.AddVolumeNode(volume2Spec, node2Name, devicePath) @@ -430,7 +430,7 @@ func Test_GetAttachedVolumes_Positive_OneVolumeTwoNodes(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) node1Name := types.NodeName("node1-name") devicePath := "fake/device/path" @@ -469,7 +469,7 @@ func Test_SetVolumeMountedByNode_Positive_Set(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -496,7 +496,7 @@ func Test_SetVolumeMountedByNode_Positive_UnsetWithInitialSet(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -532,7 +532,7 @@ func Test_SetVolumeMountedByNode_Positive_UnsetWithoutInitialSet(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -565,7 +565,7 @@ func Test_SetVolumeMountedByNode_Positive_UnsetWithInitialSetAddVolumeNodeNotRes // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -606,7 +606,7 @@ func Test_SetVolumeMountedByNode_Positive_UnsetWithInitialSetVerifyDetachRequest // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -653,7 +653,7 @@ func Test_RemoveVolumeFromReportAsAttached_Positive_Set(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") devicePath := "fake/device/path" volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") @@ -680,7 +680,7 @@ func Test_RemoveVolumeFromReportAsAttached_Positive_Marked(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -716,7 +716,7 @@ func Test_MarkDesireToDetach_Positive_MarkedAddVolumeNodeReset(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -759,7 +759,7 @@ func Test_RemoveVolumeFromReportAsAttached_Positive_UnsetWithInitialSetVolumeMou // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -802,7 +802,7 @@ func Test_RemoveVolumeFromReportAsAttached(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -835,7 +835,7 @@ func Test_RemoveVolumeFromReportAsAttached_AddVolumeToReportAsAttached_Positive( // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -878,7 +878,7 @@ func Test_RemoveVolumeFromReportAsAttached_Delete_AddVolumeNode(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -923,7 +923,7 @@ func Test_SetDetachRequestTime_Positive(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -970,7 +970,7 @@ func Test_GetAttachedVolumesForNode_Positive_OneVolumeOneNode(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := types.NodeName("node-name") devicePath := "fake/device/path" @@ -994,7 +994,7 @@ func Test_GetAttachedVolumesForNode_Positive_TwoVolumeTwoNodes(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volume1Name := api.UniqueVolumeName("volume1-name") + volume1Name := v1.UniqueVolumeName("volume1-name") volume1Spec := controllervolumetesting.GetTestVolumeSpec(string(volume1Name), volume1Name) node1Name := types.NodeName("node1-name") devicePath := "fake/device/path" @@ -1002,7 +1002,7 @@ func Test_GetAttachedVolumesForNode_Positive_TwoVolumeTwoNodes(t *testing.T) { if add1Err != nil { t.Fatalf("AddVolumeNode failed. Expected: Actual: <%v>", add1Err) } - volume2Name := api.UniqueVolumeName("volume2-name") + volume2Name := v1.UniqueVolumeName("volume2-name") volume2Spec := controllervolumetesting.GetTestVolumeSpec(string(volume2Name), volume2Name) node2Name := types.NodeName("node2-name") generatedVolumeName2, add2Err := asw.AddVolumeNode(volume2Spec, node2Name, devicePath) @@ -1025,7 +1025,7 @@ func Test_GetAttachedVolumesForNode_Positive_OneVolumeTwoNodes(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) node1Name := types.NodeName("node1-name") devicePath := "fake/device/path" @@ -1061,7 +1061,7 @@ func Test_OneVolumeTwoNodes_TwoDevicePaths(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) node1Name := types.NodeName("node1-name") devicePath1 := "fake/device/path1" @@ -1097,7 +1097,7 @@ func Test_OneVolumeTwoNodes_TwoDevicePaths(t *testing.T) { func verifyAttachedVolume( t *testing.T, attachedVolumes []AttachedVolume, - expectedVolumeName api.UniqueVolumeName, + expectedVolumeName v1.UniqueVolumeName, expectedVolumeSpecName string, expectedNodeName types.NodeName, expectedDevicePath string, diff --git a/pkg/controller/volume/attachdetach/cache/desired_state_of_world.go b/pkg/controller/volume/attachdetach/cache/desired_state_of_world.go index f082266e818..4b331557293 100644 --- a/pkg/controller/volume/attachdetach/cache/desired_state_of_world.go +++ b/pkg/controller/volume/attachdetach/cache/desired_state_of_world.go @@ -25,7 +25,7 @@ import ( "fmt" "sync" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" k8stypes "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/util/operationexecutor" @@ -58,7 +58,7 @@ type DesiredStateOfWorld interface { // should be attached to the specified node, the volume is implicitly added. // If no node with the name nodeName exists in list of nodes managed by the // attach/detach attached controller, an error is returned. - AddPod(podName types.UniquePodName, pod *api.Pod, volumeSpec *volume.Spec, nodeName k8stypes.NodeName) (api.UniqueVolumeName, error) + AddPod(podName types.UniquePodName, pod *v1.Pod, volumeSpec *volume.Spec, nodeName k8stypes.NodeName) (v1.UniqueVolumeName, error) // DeleteNode removes the given node from the list of nodes managed by the // attach/detach controller. @@ -76,7 +76,7 @@ type DesiredStateOfWorld interface { // volumes under the specified node, this is a no-op. // If after deleting the pod, the specified volume contains no other child // pods, the volume is also deleted. - DeletePod(podName types.UniquePodName, volumeName api.UniqueVolumeName, nodeName k8stypes.NodeName) + DeletePod(podName types.UniquePodName, volumeName v1.UniqueVolumeName, nodeName k8stypes.NodeName) // NodeExists returns true if the node with the specified name exists in // the list of nodes managed by the attach/detach controller. @@ -85,7 +85,7 @@ type DesiredStateOfWorld interface { // VolumeExists returns true if the volume with the specified name exists // in the list of volumes that should be attached to the specified node by // the attach detach controller. - VolumeExists(volumeName api.UniqueVolumeName, nodeName k8stypes.NodeName) bool + VolumeExists(volumeName v1.UniqueVolumeName, nodeName k8stypes.NodeName) bool // GetVolumesToAttach generates and returns a list of volumes to attach // and the nodes they should be attached to based on the current desired @@ -106,10 +106,10 @@ type VolumeToAttach struct { // scheduled to the underlying node. type PodToAdd struct { // pod contains the api object of pod - Pod *api.Pod + Pod *v1.Pod // volumeName contains the unique identifier for this volume. - VolumeName api.UniqueVolumeName + VolumeName v1.UniqueVolumeName // nodeName contains the name of this node. NodeName k8stypes.NodeName @@ -143,13 +143,13 @@ type nodeManaged struct { // volumesToAttach is a map containing the set of volumes that should be // attached to this node. The key in the map is the name of the volume and // the value is a pod object containing more information about the volume. - volumesToAttach map[api.UniqueVolumeName]volumeToAttach + volumesToAttach map[v1.UniqueVolumeName]volumeToAttach } // The volume object represents a volume that should be attached to a node. type volumeToAttach struct { // volumeName contains the unique identifier for this volume. - volumeName api.UniqueVolumeName + volumeName v1.UniqueVolumeName // spec is the volume spec containing the specification for this volume. // Used to generate the volume plugin object, and passed to attach/detach @@ -170,7 +170,7 @@ type pod struct { podName types.UniquePodName // pod object contains the api object of pod - podObj *api.Pod + podObj *v1.Pod } func (dsw *desiredStateOfWorld) AddNode(nodeName k8stypes.NodeName) { @@ -180,16 +180,16 @@ func (dsw *desiredStateOfWorld) AddNode(nodeName k8stypes.NodeName) { if _, nodeExists := dsw.nodesManaged[nodeName]; !nodeExists { dsw.nodesManaged[nodeName] = nodeManaged{ nodeName: nodeName, - volumesToAttach: make(map[api.UniqueVolumeName]volumeToAttach), + volumesToAttach: make(map[v1.UniqueVolumeName]volumeToAttach), } } } func (dsw *desiredStateOfWorld) AddPod( podName types.UniquePodName, - podToAdd *api.Pod, + podToAdd *v1.Pod, volumeSpec *volume.Spec, - nodeName k8stypes.NodeName) (api.UniqueVolumeName, error) { + nodeName k8stypes.NodeName) (v1.UniqueVolumeName, error) { dsw.Lock() defer dsw.Unlock() @@ -261,7 +261,7 @@ func (dsw *desiredStateOfWorld) DeleteNode(nodeName k8stypes.NodeName) error { func (dsw *desiredStateOfWorld) DeletePod( podName types.UniquePodName, - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, nodeName k8stypes.NodeName) { dsw.Lock() defer dsw.Unlock() @@ -299,7 +299,7 @@ func (dsw *desiredStateOfWorld) NodeExists(nodeName k8stypes.NodeName) bool { } func (dsw *desiredStateOfWorld) VolumeExists( - volumeName api.UniqueVolumeName, nodeName k8stypes.NodeName) bool { + volumeName v1.UniqueVolumeName, nodeName k8stypes.NodeName) bool { dsw.RLock() defer dsw.RUnlock() @@ -334,9 +334,9 @@ func (dsw *desiredStateOfWorld) GetVolumesToAttach() []VolumeToAttach { return volumesToAttach } -// Construct a list of api.Pod objects from the given pod map -func getPodsFromMap(podMap map[types.UniquePodName]pod) []*api.Pod { - pods := make([]*api.Pod, 0, len(podMap)) +// Construct a list of v1.Pod objects from the given pod map +func getPodsFromMap(podMap map[types.UniquePodName]pod) []*v1.Pod { + pods := make([]*v1.Pod, 0, len(podMap)) for _, pod := range podMap { pods = append(pods, pod.podObj) } diff --git a/pkg/controller/volume/attachdetach/cache/desired_state_of_world_test.go b/pkg/controller/volume/attachdetach/cache/desired_state_of_world_test.go index bbf3920be0f..e6b07c79ed7 100644 --- a/pkg/controller/volume/attachdetach/cache/desired_state_of_world_test.go +++ b/pkg/controller/volume/attachdetach/cache/desired_state_of_world_test.go @@ -19,7 +19,7 @@ package cache import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" controllervolumetesting "k8s.io/kubernetes/pkg/controller/volume/attachdetach/testing" k8stypes "k8s.io/kubernetes/pkg/types" volumetesting "k8s.io/kubernetes/pkg/volume/testing" @@ -91,7 +91,7 @@ func Test_AddPod_Positive_NewPodNodeExistsVolumeDoesntExist(t *testing.T) { podName := "pod-uid" volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) dsw := NewDesiredStateOfWorld(volumePluginMgr) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) @@ -139,7 +139,7 @@ func Test_AddPod_Positive_NewPodNodeExistsVolumeExists(t *testing.T) { dsw := NewDesiredStateOfWorld(volumePluginMgr) pod1Name := "pod1-uid" pod2Name := "pod2-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) @@ -212,7 +212,7 @@ func Test_AddPod_Positive_PodExistsNodeExistsVolumeExists(t *testing.T) { volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) dsw := NewDesiredStateOfWorld(volumePluginMgr) podName := "pod-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) @@ -278,7 +278,7 @@ func Test_AddPod_Negative_NewPodNodeDoesntExistVolumeDoesntExist(t *testing.T) { volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) dsw := NewDesiredStateOfWorld(volumePluginMgr) podName := "pod-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName("node-name") volumeExists := dsw.VolumeExists(volumeName, nodeName) @@ -377,7 +377,7 @@ func Test_DeleteNode_Negative_NodeExistsHasChildVolumes(t *testing.T) { nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) podName := "pod-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) generatedVolumeName, podAddErr := dsw.AddPod(types.UniquePodName(podName), controllervolumetesting.NewPod(podName, podName), volumeSpec, nodeName) if podAddErr != nil { @@ -416,7 +416,7 @@ func Test_DeletePod_Positive_PodExistsNodeExistsVolumeExists(t *testing.T) { volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) dsw := NewDesiredStateOfWorld(volumePluginMgr) podName := "pod-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) @@ -464,7 +464,7 @@ func Test_DeletePod_Positive_2PodsExistNodeExistsVolumesExist(t *testing.T) { dsw := NewDesiredStateOfWorld(volumePluginMgr) pod1Name := "pod1-uid" pod2Name := "pod2-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) @@ -525,7 +525,7 @@ func Test_DeletePod_Positive_PodDoesNotExist(t *testing.T) { dsw := NewDesiredStateOfWorld(volumePluginMgr) pod1Name := "pod1-uid" pod2Name := "pod2-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) @@ -573,7 +573,7 @@ func Test_DeletePod_Positive_NodeDoesNotExist(t *testing.T) { volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) dsw := NewDesiredStateOfWorld(volumePluginMgr) podName := "pod-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) node1Name := k8stypes.NodeName("node1-name") dsw.AddNode(node1Name) @@ -628,7 +628,7 @@ func Test_DeletePod_Positive_VolumeDoesNotExist(t *testing.T) { volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) dsw := NewDesiredStateOfWorld(volumePluginMgr) podName := "pod-uid" - volume1Name := api.UniqueVolumeName("volume1-name") + volume1Name := v1.UniqueVolumeName("volume1-name") volume1Spec := controllervolumetesting.GetTestVolumeSpec(string(volume1Name), volume1Name) nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) @@ -647,7 +647,7 @@ func Test_DeletePod_Positive_VolumeDoesNotExist(t *testing.T) { generatedVolume1Name, nodeName) } - volume2Name := api.UniqueVolumeName("volume2-name") + volume2Name := v1.UniqueVolumeName("volume2-name") // Act dsw.DeletePod(types.UniquePodName(podName), volume2Name, nodeName) @@ -731,7 +731,7 @@ func Test_VolumeExists_Positive_VolumeExistsNodeExists(t *testing.T) { nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) podName := "pod-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) generatedVolumeName, _ := dsw.AddPod(types.UniquePodName(podName), controllervolumetesting.NewPod(podName, podName), volumeSpec, nodeName) @@ -761,7 +761,7 @@ func Test_VolumeExists_Positive_VolumeDoesntExistNodeExists(t *testing.T) { nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) podName := "pod-uid" - volume1Name := api.UniqueVolumeName("volume1-name") + volume1Name := v1.UniqueVolumeName("volume1-name") volume1Spec := controllervolumetesting.GetTestVolumeSpec(string(volume1Name), volume1Name) generatedVolume1Name, podAddErr := dsw.AddPod(types.UniquePodName(podName), controllervolumetesting.NewPod(podName, podName), volume1Spec, nodeName) if podAddErr != nil { @@ -770,7 +770,7 @@ func Test_VolumeExists_Positive_VolumeDoesntExistNodeExists(t *testing.T) { podName, podAddErr) } - volume2Name := api.UniqueVolumeName("volume2-name") + volume2Name := v1.UniqueVolumeName("volume2-name") // Act volumeExists := dsw.VolumeExists(volume2Name, nodeName) @@ -795,7 +795,7 @@ func Test_VolumeExists_Positive_VolumeDoesntExistNodeDoesntExists(t *testing.T) volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) dsw := NewDesiredStateOfWorld(volumePluginMgr) nodeName := k8stypes.NodeName("node-name") - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") // Act volumeExists := dsw.VolumeExists(volumeName, nodeName) @@ -857,7 +857,7 @@ func Test_GetVolumesToAttach_Positive_TwoNodesOneVolumeEach(t *testing.T) { dsw := NewDesiredStateOfWorld(volumePluginMgr) node1Name := k8stypes.NodeName("node1-name") pod1Name := "pod1-uid" - volume1Name := api.UniqueVolumeName("volume1-name") + volume1Name := v1.UniqueVolumeName("volume1-name") volume1Spec := controllervolumetesting.GetTestVolumeSpec(string(volume1Name), volume1Name) dsw.AddNode(node1Name) generatedVolume1Name, podAddErr := dsw.AddPod(types.UniquePodName(pod1Name), controllervolumetesting.NewPod(pod1Name, pod1Name), volume1Spec, node1Name) @@ -869,7 +869,7 @@ func Test_GetVolumesToAttach_Positive_TwoNodesOneVolumeEach(t *testing.T) { } node2Name := k8stypes.NodeName("node2-name") pod2Name := "pod2-uid" - volume2Name := api.UniqueVolumeName("volume2-name") + volume2Name := v1.UniqueVolumeName("volume2-name") volume2Spec := controllervolumetesting.GetTestVolumeSpec(string(volume2Name), volume2Name) dsw.AddNode(node2Name) generatedVolume2Name, podAddErr := dsw.AddPod(types.UniquePodName(pod2Name), controllervolumetesting.NewPod(pod2Name, pod2Name), volume2Spec, node2Name) @@ -902,7 +902,7 @@ func Test_GetVolumesToAttach_Positive_TwoNodesOneVolumeEachExtraPod(t *testing.T dsw := NewDesiredStateOfWorld(volumePluginMgr) node1Name := k8stypes.NodeName("node1-name") pod1Name := "pod1-uid" - volume1Name := api.UniqueVolumeName("volume1-name") + volume1Name := v1.UniqueVolumeName("volume1-name") volume1Spec := controllervolumetesting.GetTestVolumeSpec(string(volume1Name), volume1Name) dsw.AddNode(node1Name) generatedVolume1Name, podAddErr := dsw.AddPod(types.UniquePodName(pod1Name), controllervolumetesting.NewPod(pod1Name, pod1Name), volume1Spec, node1Name) @@ -914,7 +914,7 @@ func Test_GetVolumesToAttach_Positive_TwoNodesOneVolumeEachExtraPod(t *testing.T } node2Name := k8stypes.NodeName("node2-name") pod2Name := "pod2-uid" - volume2Name := api.UniqueVolumeName("volume2-name") + volume2Name := v1.UniqueVolumeName("volume2-name") volume2Spec := controllervolumetesting.GetTestVolumeSpec(string(volume2Name), volume2Name) dsw.AddNode(node2Name) generatedVolume2Name, podAddErr := dsw.AddPod(types.UniquePodName(pod2Name), controllervolumetesting.NewPod(pod2Name, pod2Name), volume2Spec, node2Name) @@ -956,7 +956,7 @@ func Test_GetVolumesToAttach_Positive_TwoNodesThreeVolumes(t *testing.T) { dsw := NewDesiredStateOfWorld(volumePluginMgr) node1Name := k8stypes.NodeName("node1-name") pod1Name := "pod1-uid" - volume1Name := api.UniqueVolumeName("volume1-name") + volume1Name := v1.UniqueVolumeName("volume1-name") volume1Spec := controllervolumetesting.GetTestVolumeSpec(string(volume1Name), volume1Name) dsw.AddNode(node1Name) generatedVolume1Name, podAddErr := dsw.AddPod(types.UniquePodName(pod1Name), controllervolumetesting.NewPod(pod1Name, pod1Name), volume1Spec, node1Name) @@ -968,7 +968,7 @@ func Test_GetVolumesToAttach_Positive_TwoNodesThreeVolumes(t *testing.T) { } node2Name := k8stypes.NodeName("node2-name") pod2aName := "pod2a-name" - volume2Name := api.UniqueVolumeName("volume2-name") + volume2Name := v1.UniqueVolumeName("volume2-name") volume2Spec := controllervolumetesting.GetTestVolumeSpec(string(volume2Name), volume2Name) dsw.AddNode(node2Name) generatedVolume2Name1, podAddErr := dsw.AddPod(types.UniquePodName(pod2aName), controllervolumetesting.NewPod(pod2aName, pod2aName), volume2Spec, node2Name) @@ -993,7 +993,7 @@ func Test_GetVolumesToAttach_Positive_TwoNodesThreeVolumes(t *testing.T) { generatedVolume2Name2) } pod3Name := "pod3-uid" - volume3Name := api.UniqueVolumeName("volume3-name") + volume3Name := v1.UniqueVolumeName("volume3-name") volume3Spec := controllervolumetesting.GetTestVolumeSpec(string(volume3Name), volume3Name) generatedVolume3Name, podAddErr := dsw.AddPod(types.UniquePodName(pod3Name), controllervolumetesting.NewPod(pod3Name, pod3Name), volume3Spec, node1Name) if podAddErr != nil { @@ -1020,7 +1020,7 @@ func verifyVolumeToAttach( t *testing.T, volumesToAttach []VolumeToAttach, expectedNodeName k8stypes.NodeName, - expectedVolumeName api.UniqueVolumeName, + expectedVolumeName v1.UniqueVolumeName, expectedVolumeSpecName string) { for _, volumeToAttach := range volumesToAttach { if volumeToAttach.NodeName == expectedNodeName && diff --git a/pkg/controller/volume/attachdetach/populator/BUILD b/pkg/controller/volume/attachdetach/populator/BUILD index 212d6eb08c3..bc77b8f774e 100644 --- a/pkg/controller/volume/attachdetach/populator/BUILD +++ b/pkg/controller/volume/attachdetach/populator/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["desired_state_of_world_populator.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/controller/volume/attachdetach/cache:go_default_library", "//pkg/util/wait:go_default_library", diff --git a/pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go b/pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go index d74ef32681b..95871570ae2 100644 --- a/pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go +++ b/pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go @@ -23,7 +23,7 @@ import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kcache "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache" "k8s.io/kubernetes/pkg/util/wait" @@ -102,7 +102,7 @@ func (dswp *desiredStateOfWorldPopulator) findAndRemoveDeletedPods() { } if exists { - informerPod, ok := informerPodObj.(*api.Pod) + informerPod, ok := informerPodObj.(*v1.Pod) if !ok { glog.Errorf("Failed to cast obj %#v to pod object for pod %q (UID %q)", informerPod, dswPodKey, dswPodUID) continue diff --git a/pkg/controller/volume/attachdetach/reconciler/BUILD b/pkg/controller/volume/attachdetach/reconciler/BUILD index 7962649c4aa..a377d7b5e4e 100644 --- a/pkg/controller/volume/attachdetach/reconciler/BUILD +++ b/pkg/controller/volume/attachdetach/reconciler/BUILD @@ -31,7 +31,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/controller/informers:go_default_library", "//pkg/controller/volume/attachdetach/cache:go_default_library", diff --git a/pkg/controller/volume/attachdetach/reconciler/reconciler_test.go b/pkg/controller/volume/attachdetach/reconciler/reconciler_test.go index 31b051f6a1b..877b6fdc1a2 100644 --- a/pkg/controller/volume/attachdetach/reconciler/reconciler_test.go +++ b/pkg/controller/volume/attachdetach/reconciler/reconciler_test.go @@ -20,7 +20,7 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller/informers" "k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache" @@ -86,7 +86,7 @@ func Test_Run_Positive_OneDesiredVolumeAttach(t *testing.T) { reconciler := NewReconciler( reconcilerLoopPeriod, maxWaitForUnmountDuration, syncLoopPeriod, dsw, asw, ad, nsu) podName := "pod-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) @@ -132,7 +132,7 @@ func Test_Run_Positive_OneDesiredVolumeAttachThenDetachWithUnmountedVolume(t *te reconciler := NewReconciler( reconcilerLoopPeriod, maxWaitForUnmountDuration, syncLoopPeriod, dsw, asw, ad, nsu) podName := "pod-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) @@ -199,7 +199,7 @@ func Test_Run_Positive_OneDesiredVolumeAttachThenDetachWithMountedVolume(t *test reconciler := NewReconciler( reconcilerLoopPeriod, maxWaitForUnmountDuration, syncLoopPeriod, dsw, asw, ad, nsu) podName := "pod-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) @@ -266,7 +266,7 @@ func Test_Run_Negative_OneDesiredVolumeAttachThenDetachWithUnmountedVolumeUpdate reconciler := NewReconciler( reconcilerLoopPeriod, maxWaitForUnmountDuration, syncLoopPeriod, dsw, asw, ad, nsu) podName := "pod-uid" - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName("node-name") dsw.AddNode(nodeName) diff --git a/pkg/controller/volume/attachdetach/statusupdater/BUILD b/pkg/controller/volume/attachdetach/statusupdater/BUILD index c3a9b2180a9..4c37c350520 100644 --- a/pkg/controller/volume/attachdetach/statusupdater/BUILD +++ b/pkg/controller/volume/attachdetach/statusupdater/BUILD @@ -18,9 +18,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/controller/volume/attachdetach/cache:go_default_library", "//pkg/conversion:go_default_library", "//pkg/util/strategicpatch:go_default_library", diff --git a/pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go b/pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go index 0cca9f1464c..90f85f99aad 100644 --- a/pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go +++ b/pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go @@ -24,9 +24,9 @@ import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kcache "k8s.io/kubernetes/pkg/client/cache" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache" "k8s.io/kubernetes/pkg/conversion" "k8s.io/kubernetes/pkg/util/strategicpatch" @@ -42,7 +42,7 @@ type NodeStatusUpdater interface { // NewNodeStatusUpdater returns a new instance of NodeStatusUpdater. func NewNodeStatusUpdater( - kubeClient internalclientset.Interface, + kubeClient clientset.Interface, nodeInformer kcache.SharedInformer, actualStateOfWorld cache.ActualStateOfWorld) NodeStatusUpdater { return &nodeStatusUpdater{ @@ -53,7 +53,7 @@ func NewNodeStatusUpdater( } type nodeStatusUpdater struct { - kubeClient internalclientset.Interface + kubeClient clientset.Interface nodeInformer kcache.SharedInformer actualStateOfWorld cache.ActualStateOfWorld } @@ -81,7 +81,7 @@ func (nsu *nodeStatusUpdater) UpdateNodeStatuses() error { err) } - node, ok := clonedNode.(*api.Node) + node, ok := clonedNode.(*v1.Node) if !ok || node == nil { return fmt.Errorf( "failed to cast %q object %#v to Node", diff --git a/pkg/controller/volume/attachdetach/testing/BUILD b/pkg/controller/volume/attachdetach/testing/BUILD index 0d8b17790b3..77afd152f94 100644 --- a/pkg/controller/volume/attachdetach/testing/BUILD +++ b/pkg/controller/volume/attachdetach/testing/BUILD @@ -15,8 +15,8 @@ go_library( srcs = ["testvolumespec.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/runtime:go_default_library", "//pkg/types:go_default_library", diff --git a/pkg/controller/volume/attachdetach/testing/testvolumespec.go b/pkg/controller/volume/attachdetach/testing/testvolumespec.go index b7e72a2bfee..92467ebbeb9 100644 --- a/pkg/controller/volume/attachdetach/testing/testvolumespec.go +++ b/pkg/controller/volume/attachdetach/testing/testvolumespec.go @@ -19,8 +19,8 @@ package testing import ( "fmt" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/types" @@ -29,12 +29,12 @@ import ( ) // GetTestVolumeSpec returns a test volume spec -func GetTestVolumeSpec(volumeName string, diskName api.UniqueVolumeName) *volume.Spec { +func GetTestVolumeSpec(volumeName string, diskName v1.UniqueVolumeName) *volume.Spec { return &volume.Spec{ - Volume: &api.Volume{ + Volume: &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: string(diskName), FSType: "fake", ReadOnly: false, @@ -48,28 +48,28 @@ func CreateTestClient() *fake.Clientset { fakeClient := &fake.Clientset{} fakeClient.AddReactor("list", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) { - obj := &api.PodList{} + obj := &v1.PodList{} podNamePrefix := "mypod" namespace := "mynamespace" for i := 0; i < 5; i++ { podName := fmt.Sprintf("%s-%d", podNamePrefix, i) - pod := api.Pod{ - Status: api.PodStatus{ - Phase: api.PodRunning, + pod := v1.Pod{ + Status: v1.PodStatus{ + Phase: v1.PodRunning, }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Namespace: namespace, Labels: map[string]string{ "name": podName, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "containerName", Image: "containerImage", - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "volumeMountName", ReadOnly: false, @@ -78,11 +78,11 @@ func CreateTestClient() *fake.Clientset { }, }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: "volumeName", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "pdName", FSType: "ext4", ReadOnly: false, @@ -104,9 +104,9 @@ func CreateTestClient() *fake.Clientset { } // NewPod returns a test pod object -func NewPod(uid, name string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func NewPod(uid, name string) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: types.UID(uid), Name: name, Namespace: name, diff --git a/pkg/controller/volume/persistentvolume/BUILD b/pkg/controller/volume/persistentvolume/BUILD index fb998828424..fe4d8b7064a 100644 --- a/pkg/controller/volume/persistentvolume/BUILD +++ b/pkg/controller/volume/persistentvolume/BUILD @@ -20,15 +20,15 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/meta:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/storage:go_default_library", - "//pkg/apis/storage/util:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/storage/v1beta1:go_default_library", + "//pkg/apis/storage/v1beta1/util:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/conversion:go_default_library", @@ -58,15 +58,15 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/testapi:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/storage:go_default_library", - "//pkg/apis/storage/util:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/storage/v1beta1:go_default_library", + "//pkg/apis/storage/v1beta1/util:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/testing/cache:go_default_library", "//pkg/client/testing/core:go_default_library", diff --git a/pkg/controller/volume/persistentvolume/binder_test.go b/pkg/controller/volume/persistentvolume/binder_test.go index 72b27c00684..8acea55a084 100644 --- a/pkg/controller/volume/persistentvolume/binder_test.go +++ b/pkg/controller/volume/persistentvolume/binder_test.go @@ -19,9 +19,9 @@ package persistentvolume import ( "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/storage" - storageutil "k8s.io/kubernetes/pkg/apis/storage/util" + "k8s.io/kubernetes/pkg/api/v1" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" + storageutil "k8s.io/kubernetes/pkg/apis/storage/v1beta1/util" ) // Test single call to syncClaim and syncVolume methods. @@ -42,134 +42,134 @@ func TestSync(t *testing.T) { { // syncClaim binds to a matching unbound volume. "1-1 - successful bind", - newVolumeArray("volume1-1", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume1-1", "1Gi", "uid1-1", "claim1-1", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newClaimArray("claim1-1", "uid1-1", "1Gi", "", api.ClaimPending), - newClaimArray("claim1-1", "uid1-1", "1Gi", "volume1-1", api.ClaimBound, annBoundByController, annBindCompleted), + newVolumeArray("volume1-1", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume1-1", "1Gi", "uid1-1", "claim1-1", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newClaimArray("claim1-1", "uid1-1", "1Gi", "", v1.ClaimPending), + newClaimArray("claim1-1", "uid1-1", "1Gi", "volume1-1", v1.ClaimBound, annBoundByController, annBindCompleted), noevents, noerrors, testSyncClaim, }, { // syncClaim does not do anything when there is no matching volume. "1-2 - noop", - newVolumeArray("volume1-2", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume1-2", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newClaimArray("claim1-2", "uid1-2", "10Gi", "", api.ClaimPending), - newClaimArray("claim1-2", "uid1-2", "10Gi", "", api.ClaimPending), + newVolumeArray("volume1-2", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume1-2", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim1-2", "uid1-2", "10Gi", "", v1.ClaimPending), + newClaimArray("claim1-2", "uid1-2", "10Gi", "", v1.ClaimPending), noevents, noerrors, testSyncClaim, }, { // syncClaim resets claim.Status to Pending when there is no // matching volume. "1-3 - reset to Pending", - newVolumeArray("volume1-3", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume1-3", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newClaimArray("claim1-3", "uid1-3", "10Gi", "", api.ClaimBound), - newClaimArray("claim1-3", "uid1-3", "10Gi", "", api.ClaimPending), + newVolumeArray("volume1-3", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume1-3", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim1-3", "uid1-3", "10Gi", "", v1.ClaimBound), + newClaimArray("claim1-3", "uid1-3", "10Gi", "", v1.ClaimPending), noevents, noerrors, testSyncClaim, }, { // syncClaim binds claims to the smallest matching volume "1-4 - smallest volume", - []*api.PersistentVolume{ - newVolume("volume1-4_1", "10Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolume("volume1-4_2", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), + []*v1.PersistentVolume{ + newVolume("volume1-4_1", "10Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolume("volume1-4_2", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), }, - []*api.PersistentVolume{ - newVolume("volume1-4_1", "10Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolume("volume1-4_2", "1Gi", "uid1-4", "claim1-4", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), + []*v1.PersistentVolume{ + newVolume("volume1-4_1", "10Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolume("volume1-4_2", "1Gi", "uid1-4", "claim1-4", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), }, - newClaimArray("claim1-4", "uid1-4", "1Gi", "", api.ClaimPending), - newClaimArray("claim1-4", "uid1-4", "1Gi", "volume1-4_2", api.ClaimBound, annBoundByController, annBindCompleted), + newClaimArray("claim1-4", "uid1-4", "1Gi", "", v1.ClaimPending), + newClaimArray("claim1-4", "uid1-4", "1Gi", "volume1-4_2", v1.ClaimBound, annBoundByController, annBindCompleted), noevents, noerrors, testSyncClaim, }, { // syncClaim binds a claim only to volume that points to it (by // name), even though a smaller one is available. "1-5 - prebound volume by name - success", - []*api.PersistentVolume{ - newVolume("volume1-5_1", "10Gi", "", "claim1-5", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolume("volume1-5_2", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), + []*v1.PersistentVolume{ + newVolume("volume1-5_1", "10Gi", "", "claim1-5", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolume("volume1-5_2", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), }, - []*api.PersistentVolume{ - newVolume("volume1-5_1", "10Gi", "uid1-5", "claim1-5", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newVolume("volume1-5_2", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), + []*v1.PersistentVolume{ + newVolume("volume1-5_1", "10Gi", "uid1-5", "claim1-5", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newVolume("volume1-5_2", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), }, - newClaimArray("claim1-5", "uid1-5", "1Gi", "", api.ClaimPending), - withExpectedCapacity("10Gi", newClaimArray("claim1-5", "uid1-5", "1Gi", "volume1-5_1", api.ClaimBound, annBoundByController, annBindCompleted)), + newClaimArray("claim1-5", "uid1-5", "1Gi", "", v1.ClaimPending), + withExpectedCapacity("10Gi", newClaimArray("claim1-5", "uid1-5", "1Gi", "volume1-5_1", v1.ClaimBound, annBoundByController, annBindCompleted)), noevents, noerrors, testSyncClaim, }, { // syncClaim binds a claim only to volume that points to it (by // UID), even though a smaller one is available. "1-6 - prebound volume by UID - success", - []*api.PersistentVolume{ - newVolume("volume1-6_1", "10Gi", "uid1-6", "claim1-6", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolume("volume1-6_2", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), + []*v1.PersistentVolume{ + newVolume("volume1-6_1", "10Gi", "uid1-6", "claim1-6", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolume("volume1-6_2", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), }, - []*api.PersistentVolume{ - newVolume("volume1-6_1", "10Gi", "uid1-6", "claim1-6", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newVolume("volume1-6_2", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), + []*v1.PersistentVolume{ + newVolume("volume1-6_1", "10Gi", "uid1-6", "claim1-6", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newVolume("volume1-6_2", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), }, - newClaimArray("claim1-6", "uid1-6", "1Gi", "", api.ClaimPending), - withExpectedCapacity("10Gi", newClaimArray("claim1-6", "uid1-6", "1Gi", "volume1-6_1", api.ClaimBound, annBoundByController, annBindCompleted)), + newClaimArray("claim1-6", "uid1-6", "1Gi", "", v1.ClaimPending), + withExpectedCapacity("10Gi", newClaimArray("claim1-6", "uid1-6", "1Gi", "volume1-6_1", v1.ClaimBound, annBoundByController, annBindCompleted)), noevents, noerrors, testSyncClaim, }, { // syncClaim does not bind claim to a volume prebound to a claim with // same name and different UID "1-7 - prebound volume to different claim", - newVolumeArray("volume1-7", "10Gi", "uid1-777", "claim1-7", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume1-7", "10Gi", "uid1-777", "claim1-7", api.VolumePending, api.PersistentVolumeReclaimRetain), - newClaimArray("claim1-7", "uid1-7", "1Gi", "", api.ClaimPending), - newClaimArray("claim1-7", "uid1-7", "1Gi", "", api.ClaimPending), + newVolumeArray("volume1-7", "10Gi", "uid1-777", "claim1-7", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume1-7", "10Gi", "uid1-777", "claim1-7", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim1-7", "uid1-7", "1Gi", "", v1.ClaimPending), + newClaimArray("claim1-7", "uid1-7", "1Gi", "", v1.ClaimPending), noevents, noerrors, testSyncClaim, }, { // syncClaim completes binding - simulates controller crash after // PV.ClaimRef is saved "1-8 - complete bind after crash - PV bound", - newVolumeArray("volume1-8", "1Gi", "uid1-8", "claim1-8", api.VolumePending, api.PersistentVolumeReclaimRetain, annBoundByController), - newVolumeArray("volume1-8", "1Gi", "uid1-8", "claim1-8", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newClaimArray("claim1-8", "uid1-8", "1Gi", "", api.ClaimPending), - newClaimArray("claim1-8", "uid1-8", "1Gi", "volume1-8", api.ClaimBound, annBoundByController, annBindCompleted), + newVolumeArray("volume1-8", "1Gi", "uid1-8", "claim1-8", v1.VolumePending, v1.PersistentVolumeReclaimRetain, annBoundByController), + newVolumeArray("volume1-8", "1Gi", "uid1-8", "claim1-8", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newClaimArray("claim1-8", "uid1-8", "1Gi", "", v1.ClaimPending), + newClaimArray("claim1-8", "uid1-8", "1Gi", "volume1-8", v1.ClaimBound, annBoundByController, annBindCompleted), noevents, noerrors, testSyncClaim, }, { // syncClaim completes binding - simulates controller crash after // PV.Status is saved "1-9 - complete bind after crash - PV status saved", - newVolumeArray("volume1-9", "1Gi", "uid1-9", "claim1-9", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newVolumeArray("volume1-9", "1Gi", "uid1-9", "claim1-9", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newClaimArray("claim1-9", "uid1-9", "1Gi", "", api.ClaimPending), - newClaimArray("claim1-9", "uid1-9", "1Gi", "volume1-9", api.ClaimBound, annBoundByController, annBindCompleted), + newVolumeArray("volume1-9", "1Gi", "uid1-9", "claim1-9", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newVolumeArray("volume1-9", "1Gi", "uid1-9", "claim1-9", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newClaimArray("claim1-9", "uid1-9", "1Gi", "", v1.ClaimPending), + newClaimArray("claim1-9", "uid1-9", "1Gi", "volume1-9", v1.ClaimBound, annBoundByController, annBindCompleted), noevents, noerrors, testSyncClaim, }, { // syncClaim completes binding - simulates controller crash after // PVC.VolumeName is saved "1-10 - complete bind after crash - PVC bound", - newVolumeArray("volume1-10", "1Gi", "uid1-10", "claim1-10", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newVolumeArray("volume1-10", "1Gi", "uid1-10", "claim1-10", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newClaimArray("claim1-10", "uid1-10", "1Gi", "volume1-10", api.ClaimPending, annBoundByController, annBindCompleted), - newClaimArray("claim1-10", "uid1-10", "1Gi", "volume1-10", api.ClaimBound, annBoundByController, annBindCompleted), + newVolumeArray("volume1-10", "1Gi", "uid1-10", "claim1-10", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newVolumeArray("volume1-10", "1Gi", "uid1-10", "claim1-10", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newClaimArray("claim1-10", "uid1-10", "1Gi", "volume1-10", v1.ClaimPending, annBoundByController, annBindCompleted), + newClaimArray("claim1-10", "uid1-10", "1Gi", "volume1-10", v1.ClaimBound, annBoundByController, annBindCompleted), noevents, noerrors, testSyncClaim, }, { // syncClaim binds a claim only when the label selector matches the volume "1-11 - bind when selector matches", - withLabels(labels, newVolumeArray("volume1-1", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain)), - withLabels(labels, newVolumeArray("volume1-1", "1Gi", "uid1-1", "claim1-1", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController)), - withLabelSelector(labels, newClaimArray("claim1-1", "uid1-1", "1Gi", "", api.ClaimPending)), - withLabelSelector(labels, newClaimArray("claim1-1", "uid1-1", "1Gi", "volume1-1", api.ClaimBound, annBoundByController, annBindCompleted)), + withLabels(labels, newVolumeArray("volume1-1", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain)), + withLabels(labels, newVolumeArray("volume1-1", "1Gi", "uid1-1", "claim1-1", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController)), + withLabelSelector(labels, newClaimArray("claim1-1", "uid1-1", "1Gi", "", v1.ClaimPending)), + withLabelSelector(labels, newClaimArray("claim1-1", "uid1-1", "1Gi", "volume1-1", v1.ClaimBound, annBoundByController, annBindCompleted)), noevents, noerrors, testSyncClaim, }, { // syncClaim does not bind a claim when the label selector doesn't match "1-12 - do not bind when selector does not match", - newVolumeArray("volume1-1", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume1-1", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - withLabelSelector(labels, newClaimArray("claim1-1", "uid1-1", "1Gi", "", api.ClaimPending)), - withLabelSelector(labels, newClaimArray("claim1-1", "uid1-1", "1Gi", "", api.ClaimPending)), + newVolumeArray("volume1-1", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume1-1", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + withLabelSelector(labels, newClaimArray("claim1-1", "uid1-1", "1Gi", "", v1.ClaimPending)), + withLabelSelector(labels, newClaimArray("claim1-1", "uid1-1", "1Gi", "", v1.ClaimPending)), noevents, noerrors, testSyncClaim, }, @@ -181,8 +181,8 @@ func TestSync(t *testing.T) { "2-1 - claim prebound to non-existing volume - noop", novolumes, novolumes, - newClaimArray("claim2-1", "uid2-1", "10Gi", "volume2-1", api.ClaimPending), - newClaimArray("claim2-1", "uid2-1", "10Gi", "volume2-1", api.ClaimPending), + newClaimArray("claim2-1", "uid2-1", "10Gi", "volume2-1", v1.ClaimPending), + newClaimArray("claim2-1", "uid2-1", "10Gi", "volume2-1", v1.ClaimPending), noevents, noerrors, testSyncClaim, }, { @@ -191,28 +191,28 @@ func TestSync(t *testing.T) { "2-2 - claim prebound to non-existing volume - reset status", novolumes, novolumes, - newClaimArray("claim2-2", "uid2-2", "10Gi", "volume2-2", api.ClaimBound), - newClaimArray("claim2-2", "uid2-2", "10Gi", "volume2-2", api.ClaimPending), + newClaimArray("claim2-2", "uid2-2", "10Gi", "volume2-2", v1.ClaimBound), + newClaimArray("claim2-2", "uid2-2", "10Gi", "volume2-2", v1.ClaimPending), noevents, noerrors, testSyncClaim, }, { // syncClaim with claim pre-bound to a PV that exists and is // unbound. Check it gets bound and no annBoundByController is set. "2-3 - claim prebound to unbound volume", - newVolumeArray("volume2-3", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume2-3", "1Gi", "uid2-3", "claim2-3", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newClaimArray("claim2-3", "uid2-3", "1Gi", "volume2-3", api.ClaimPending), - newClaimArray("claim2-3", "uid2-3", "1Gi", "volume2-3", api.ClaimBound, annBindCompleted), + newVolumeArray("volume2-3", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume2-3", "1Gi", "uid2-3", "claim2-3", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newClaimArray("claim2-3", "uid2-3", "1Gi", "volume2-3", v1.ClaimPending), + newClaimArray("claim2-3", "uid2-3", "1Gi", "volume2-3", v1.ClaimBound, annBindCompleted), noevents, noerrors, testSyncClaim, }, { // claim with claim pre-bound to a PV that is pre-bound to the claim // by name. Check it gets bound and no annBoundByController is set. "2-4 - claim prebound to prebound volume by name", - newVolumeArray("volume2-4", "1Gi", "", "claim2-4", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume2-4", "1Gi", "uid2-4", "claim2-4", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newClaimArray("claim2-4", "uid2-4", "1Gi", "volume2-4", api.ClaimPending), - newClaimArray("claim2-4", "uid2-4", "1Gi", "volume2-4", api.ClaimBound, annBindCompleted), + newVolumeArray("volume2-4", "1Gi", "", "claim2-4", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume2-4", "1Gi", "uid2-4", "claim2-4", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim2-4", "uid2-4", "1Gi", "volume2-4", v1.ClaimPending), + newClaimArray("claim2-4", "uid2-4", "1Gi", "volume2-4", v1.ClaimBound, annBindCompleted), noevents, noerrors, testSyncClaim, }, { @@ -220,30 +220,30 @@ func TestSync(t *testing.T) { // claim by UID. Check it gets bound and no annBoundByController is // set. "2-5 - claim prebound to prebound volume by UID", - newVolumeArray("volume2-5", "1Gi", "uid2-5", "claim2-5", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume2-5", "1Gi", "uid2-5", "claim2-5", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newClaimArray("claim2-5", "uid2-5", "1Gi", "volume2-5", api.ClaimPending), - newClaimArray("claim2-5", "uid2-5", "1Gi", "volume2-5", api.ClaimBound, annBindCompleted), + newVolumeArray("volume2-5", "1Gi", "uid2-5", "claim2-5", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume2-5", "1Gi", "uid2-5", "claim2-5", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim2-5", "uid2-5", "1Gi", "volume2-5", v1.ClaimPending), + newClaimArray("claim2-5", "uid2-5", "1Gi", "volume2-5", v1.ClaimBound, annBindCompleted), noevents, noerrors, testSyncClaim, }, { // syncClaim with claim pre-bound to a PV that is bound to different // claim. Check it's reset to Pending. "2-6 - claim prebound to already bound volume", - newVolumeArray("volume2-6", "1Gi", "uid2-6_1", "claim2-6_1", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume2-6", "1Gi", "uid2-6_1", "claim2-6_1", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newClaimArray("claim2-6", "uid2-6", "1Gi", "volume2-6", api.ClaimBound), - newClaimArray("claim2-6", "uid2-6", "1Gi", "volume2-6", api.ClaimPending), + newVolumeArray("volume2-6", "1Gi", "uid2-6_1", "claim2-6_1", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume2-6", "1Gi", "uid2-6_1", "claim2-6_1", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim2-6", "uid2-6", "1Gi", "volume2-6", v1.ClaimBound), + newClaimArray("claim2-6", "uid2-6", "1Gi", "volume2-6", v1.ClaimPending), noevents, noerrors, testSyncClaim, }, { // syncClaim with claim bound by controller to a PV that is bound to // different claim. Check it throws an error. "2-7 - claim bound by controller to already bound volume", - newVolumeArray("volume2-7", "1Gi", "uid2-7_1", "claim2-7_1", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume2-7", "1Gi", "uid2-7_1", "claim2-7_1", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newClaimArray("claim2-7", "uid2-7", "1Gi", "volume2-7", api.ClaimBound, annBoundByController), - newClaimArray("claim2-7", "uid2-7", "1Gi", "volume2-7", api.ClaimBound, annBoundByController), + newVolumeArray("volume2-7", "1Gi", "uid2-7_1", "claim2-7_1", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume2-7", "1Gi", "uid2-7_1", "claim2-7_1", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim2-7", "uid2-7", "1Gi", "volume2-7", v1.ClaimBound, annBoundByController), + newClaimArray("claim2-7", "uid2-7", "1Gi", "volume2-7", v1.ClaimBound, annBoundByController), noevents, noerrors, testSyncClaimError, }, { @@ -251,10 +251,10 @@ func TestSync(t *testing.T) { // unbound, but does not match the selector. Check it gets bound // and no annBoundByController is set. "2-8 - claim prebound to unbound volume that does not match the selector", - newVolumeArray("volume2-3", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume2-3", "1Gi", "uid2-3", "claim2-3", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - withLabelSelector(labels, newClaimArray("claim2-3", "uid2-3", "1Gi", "volume2-3", api.ClaimPending)), - withLabelSelector(labels, newClaimArray("claim2-3", "uid2-3", "1Gi", "volume2-3", api.ClaimBound, annBindCompleted)), + newVolumeArray("volume2-3", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume2-3", "1Gi", "uid2-3", "claim2-3", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + withLabelSelector(labels, newClaimArray("claim2-3", "uid2-3", "1Gi", "volume2-3", v1.ClaimPending)), + withLabelSelector(labels, newClaimArray("claim2-3", "uid2-3", "1Gi", "volume2-3", v1.ClaimBound, annBindCompleted)), noevents, noerrors, testSyncClaim, }, @@ -265,8 +265,8 @@ func TestSync(t *testing.T) { "3-1 - bound claim with missing VolumeName", novolumes, novolumes, - newClaimArray("claim3-1", "uid3-1", "10Gi", "", api.ClaimBound, annBoundByController, annBindCompleted), - newClaimArray("claim3-1", "uid3-1", "10Gi", "", api.ClaimLost, annBoundByController, annBindCompleted), + newClaimArray("claim3-1", "uid3-1", "10Gi", "", v1.ClaimBound, annBoundByController, annBindCompleted), + newClaimArray("claim3-1", "uid3-1", "10Gi", "", v1.ClaimLost, annBoundByController, annBindCompleted), []string{"Warning ClaimLost"}, noerrors, testSyncClaim, }, { @@ -275,28 +275,28 @@ func TestSync(t *testing.T) { "3-2 - bound claim with missing volume", novolumes, novolumes, - newClaimArray("claim3-2", "uid3-2", "10Gi", "volume3-2", api.ClaimBound, annBoundByController, annBindCompleted), - newClaimArray("claim3-2", "uid3-2", "10Gi", "volume3-2", api.ClaimLost, annBoundByController, annBindCompleted), + newClaimArray("claim3-2", "uid3-2", "10Gi", "volume3-2", v1.ClaimBound, annBoundByController, annBindCompleted), + newClaimArray("claim3-2", "uid3-2", "10Gi", "volume3-2", v1.ClaimLost, annBoundByController, annBindCompleted), []string{"Warning ClaimLost"}, noerrors, testSyncClaim, }, { // syncClaim with claim bound to unbound volume. Check it's bound. // Also check that Pending phase is set to Bound "3-3 - bound claim with unbound volume", - newVolumeArray("volume3-3", "10Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume3-3", "10Gi", "uid3-3", "claim3-3", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newClaimArray("claim3-3", "uid3-3", "10Gi", "volume3-3", api.ClaimPending, annBoundByController, annBindCompleted), - newClaimArray("claim3-3", "uid3-3", "10Gi", "volume3-3", api.ClaimBound, annBoundByController, annBindCompleted), + newVolumeArray("volume3-3", "10Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume3-3", "10Gi", "uid3-3", "claim3-3", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newClaimArray("claim3-3", "uid3-3", "10Gi", "volume3-3", v1.ClaimPending, annBoundByController, annBindCompleted), + newClaimArray("claim3-3", "uid3-3", "10Gi", "volume3-3", v1.ClaimBound, annBoundByController, annBindCompleted), noevents, noerrors, testSyncClaim, }, { // syncClaim with claim bound to volume with missing (or different) // volume.Spec.ClaimRef.UID. Check that the claim is marked as lost. "3-4 - bound claim with prebound volume", - newVolumeArray("volume3-4", "10Gi", "claim3-4-x", "claim3-4", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume3-4", "10Gi", "claim3-4-x", "claim3-4", api.VolumePending, api.PersistentVolumeReclaimRetain), - newClaimArray("claim3-4", "uid3-4", "10Gi", "volume3-4", api.ClaimPending, annBoundByController, annBindCompleted), - newClaimArray("claim3-4", "uid3-4", "10Gi", "volume3-4", api.ClaimLost, annBoundByController, annBindCompleted), + newVolumeArray("volume3-4", "10Gi", "claim3-4-x", "claim3-4", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume3-4", "10Gi", "claim3-4-x", "claim3-4", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim3-4", "uid3-4", "10Gi", "volume3-4", v1.ClaimPending, annBoundByController, annBindCompleted), + newClaimArray("claim3-4", "uid3-4", "10Gi", "volume3-4", v1.ClaimLost, annBoundByController, annBindCompleted), []string{"Warning ClaimMisbound"}, noerrors, testSyncClaim, }, { @@ -304,10 +304,10 @@ func TestSync(t *testing.T) { // controller does not do anything. Also check that Pending phase is // set to Bound "3-5 - bound claim with bound volume", - newVolumeArray("volume3-5", "10Gi", "uid3-5", "claim3-5", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume3-5", "10Gi", "uid3-5", "claim3-5", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newClaimArray("claim3-5", "uid3-5", "10Gi", "volume3-5", api.ClaimPending, annBindCompleted), - newClaimArray("claim3-5", "uid3-5", "10Gi", "volume3-5", api.ClaimBound, annBindCompleted), + newVolumeArray("volume3-5", "10Gi", "uid3-5", "claim3-5", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume3-5", "10Gi", "uid3-5", "claim3-5", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim3-5", "uid3-5", "10Gi", "volume3-5", v1.ClaimPending, annBindCompleted), + newClaimArray("claim3-5", "uid3-5", "10Gi", "volume3-5", v1.ClaimBound, annBindCompleted), noevents, noerrors, testSyncClaim, }, { @@ -315,10 +315,10 @@ func TestSync(t *testing.T) { // claim. Check that the claim is marked as lost. // TODO: test that an event is emitted "3-6 - bound claim with bound volume", - newVolumeArray("volume3-6", "10Gi", "uid3-6-x", "claim3-6-x", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume3-6", "10Gi", "uid3-6-x", "claim3-6-x", api.VolumePending, api.PersistentVolumeReclaimRetain), - newClaimArray("claim3-6", "uid3-6", "10Gi", "volume3-6", api.ClaimPending, annBindCompleted), - newClaimArray("claim3-6", "uid3-6", "10Gi", "volume3-6", api.ClaimLost, annBindCompleted), + newVolumeArray("volume3-6", "10Gi", "uid3-6-x", "claim3-6-x", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume3-6", "10Gi", "uid3-6-x", "claim3-6-x", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim3-6", "uid3-6", "10Gi", "volume3-6", v1.ClaimPending, annBindCompleted), + newClaimArray("claim3-6", "uid3-6", "10Gi", "volume3-6", v1.ClaimLost, annBindCompleted), []string{"Warning ClaimMisbound"}, noerrors, testSyncClaim, }, { @@ -326,18 +326,18 @@ func TestSync(t *testing.T) { // even if the claim's selector doesn't match the volume. Also // check that Pending phase is set to Bound "3-7 - bound claim with unbound volume where selector doesn't match", - newVolumeArray("volume3-3", "10Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume3-3", "10Gi", "uid3-3", "claim3-3", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - withLabelSelector(labels, newClaimArray("claim3-3", "uid3-3", "10Gi", "volume3-3", api.ClaimPending, annBoundByController, annBindCompleted)), - withLabelSelector(labels, newClaimArray("claim3-3", "uid3-3", "10Gi", "volume3-3", api.ClaimBound, annBoundByController, annBindCompleted)), + newVolumeArray("volume3-3", "10Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume3-3", "10Gi", "uid3-3", "claim3-3", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + withLabelSelector(labels, newClaimArray("claim3-3", "uid3-3", "10Gi", "volume3-3", v1.ClaimPending, annBoundByController, annBindCompleted)), + withLabelSelector(labels, newClaimArray("claim3-3", "uid3-3", "10Gi", "volume3-3", v1.ClaimBound, annBoundByController, annBindCompleted)), noevents, noerrors, testSyncClaim, }, // [Unit test set 4] All syncVolume tests. { // syncVolume with pending volume. Check it's marked as Available. "4-1 - pending volume", - newVolumeArray("volume4-1", "10Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume4-1", "10Gi", "", "", api.VolumeAvailable, api.PersistentVolumeReclaimRetain), + newVolumeArray("volume4-1", "10Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume4-1", "10Gi", "", "", v1.VolumeAvailable, v1.PersistentVolumeReclaimRetain), noclaims, noclaims, noevents, noerrors, testSyncVolume, @@ -346,8 +346,8 @@ func TestSync(t *testing.T) { // syncVolume with prebound pending volume. Check it's marked as // Available. "4-2 - pending prebound volume", - newVolumeArray("volume4-2", "10Gi", "", "claim4-2", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume4-2", "10Gi", "", "claim4-2", api.VolumeAvailable, api.PersistentVolumeReclaimRetain), + newVolumeArray("volume4-2", "10Gi", "", "claim4-2", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume4-2", "10Gi", "", "claim4-2", v1.VolumeAvailable, v1.PersistentVolumeReclaimRetain), noclaims, noclaims, noevents, noerrors, testSyncVolume, @@ -356,8 +356,8 @@ func TestSync(t *testing.T) { // syncVolume with volume bound to missing claim. // Check the volume gets Released "4-3 - bound volume with missing claim", - newVolumeArray("volume4-3", "10Gi", "uid4-3", "claim4-3", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume4-3", "10Gi", "uid4-3", "claim4-3", api.VolumeReleased, api.PersistentVolumeReclaimRetain), + newVolumeArray("volume4-3", "10Gi", "uid4-3", "claim4-3", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume4-3", "10Gi", "uid4-3", "claim4-3", v1.VolumeReleased, v1.PersistentVolumeReclaimRetain), noclaims, noclaims, noevents, noerrors, testSyncVolume, @@ -366,50 +366,50 @@ func TestSync(t *testing.T) { // syncVolume with volume bound to claim with different UID. // Check the volume gets Released. "4-4 - volume bound to claim with different UID", - newVolumeArray("volume4-4", "10Gi", "uid4-4", "claim4-4", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume4-4", "10Gi", "uid4-4", "claim4-4", api.VolumeReleased, api.PersistentVolumeReclaimRetain), - newClaimArray("claim4-4", "uid4-4-x", "10Gi", "volume4-4", api.ClaimBound, annBindCompleted), - newClaimArray("claim4-4", "uid4-4-x", "10Gi", "volume4-4", api.ClaimBound, annBindCompleted), + newVolumeArray("volume4-4", "10Gi", "uid4-4", "claim4-4", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume4-4", "10Gi", "uid4-4", "claim4-4", v1.VolumeReleased, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim4-4", "uid4-4-x", "10Gi", "volume4-4", v1.ClaimBound, annBindCompleted), + newClaimArray("claim4-4", "uid4-4-x", "10Gi", "volume4-4", v1.ClaimBound, annBindCompleted), noevents, noerrors, testSyncVolume, }, { // syncVolume with volume bound by controller to unbound claim. // Check syncVolume does not do anything. "4-5 - volume bound by controller to unbound claim", - newVolumeArray("volume4-5", "10Gi", "uid4-5", "claim4-5", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newVolumeArray("volume4-5", "10Gi", "uid4-5", "claim4-5", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newClaimArray("claim4-5", "uid4-5", "10Gi", "", api.ClaimPending), - newClaimArray("claim4-5", "uid4-5", "10Gi", "", api.ClaimPending), + newVolumeArray("volume4-5", "10Gi", "uid4-5", "claim4-5", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newVolumeArray("volume4-5", "10Gi", "uid4-5", "claim4-5", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newClaimArray("claim4-5", "uid4-5", "10Gi", "", v1.ClaimPending), + newClaimArray("claim4-5", "uid4-5", "10Gi", "", v1.ClaimPending), noevents, noerrors, testSyncVolume, }, { // syncVolume with volume bound by user to unbound claim. // Check syncVolume does not do anything. "4-5 - volume bound by user to bound claim", - newVolumeArray("volume4-5", "10Gi", "uid4-5", "claim4-5", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume4-5", "10Gi", "uid4-5", "claim4-5", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newClaimArray("claim4-5", "uid4-5", "10Gi", "", api.ClaimPending), - newClaimArray("claim4-5", "uid4-5", "10Gi", "", api.ClaimPending), + newVolumeArray("volume4-5", "10Gi", "uid4-5", "claim4-5", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume4-5", "10Gi", "uid4-5", "claim4-5", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim4-5", "uid4-5", "10Gi", "", v1.ClaimPending), + newClaimArray("claim4-5", "uid4-5", "10Gi", "", v1.ClaimPending), noevents, noerrors, testSyncVolume, }, { // syncVolume with volume bound to bound claim. // Check that the volume is marked as Bound. "4-6 - volume bound by to bound claim", - newVolumeArray("volume4-6", "10Gi", "uid4-6", "claim4-6", api.VolumeAvailable, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume4-6", "10Gi", "uid4-6", "claim4-6", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newClaimArray("claim4-6", "uid4-6", "10Gi", "volume4-6", api.ClaimBound), - newClaimArray("claim4-6", "uid4-6", "10Gi", "volume4-6", api.ClaimBound), + newVolumeArray("volume4-6", "10Gi", "uid4-6", "claim4-6", v1.VolumeAvailable, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume4-6", "10Gi", "uid4-6", "claim4-6", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim4-6", "uid4-6", "10Gi", "volume4-6", v1.ClaimBound), + newClaimArray("claim4-6", "uid4-6", "10Gi", "volume4-6", v1.ClaimBound), noevents, noerrors, testSyncVolume, }, { // syncVolume with volume bound by controller to claim bound to // another volume. Check that the volume is rolled back. "4-7 - volume bound by controller to claim bound somewhere else", - newVolumeArray("volume4-7", "10Gi", "uid4-7", "claim4-7", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newVolumeArray("volume4-7", "10Gi", "", "", api.VolumeAvailable, api.PersistentVolumeReclaimRetain), - newClaimArray("claim4-7", "uid4-7", "10Gi", "volume4-7-x", api.ClaimBound), - newClaimArray("claim4-7", "uid4-7", "10Gi", "volume4-7-x", api.ClaimBound), + newVolumeArray("volume4-7", "10Gi", "uid4-7", "claim4-7", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newVolumeArray("volume4-7", "10Gi", "", "", v1.VolumeAvailable, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim4-7", "uid4-7", "10Gi", "volume4-7-x", v1.ClaimBound), + newClaimArray("claim4-7", "uid4-7", "10Gi", "volume4-7-x", v1.ClaimBound), noevents, noerrors, testSyncVolume, }, { @@ -417,10 +417,10 @@ func TestSync(t *testing.T) { // another volume. Check that the volume is marked as Available // and its UID is reset. "4-8 - volume bound by user to claim bound somewhere else", - newVolumeArray("volume4-8", "10Gi", "uid4-8", "claim4-8", api.VolumeBound, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume4-8", "10Gi", "", "claim4-8", api.VolumeAvailable, api.PersistentVolumeReclaimRetain), - newClaimArray("claim4-8", "uid4-8", "10Gi", "volume4-8-x", api.ClaimBound), - newClaimArray("claim4-8", "uid4-8", "10Gi", "volume4-8-x", api.ClaimBound), + newVolumeArray("volume4-8", "10Gi", "uid4-8", "claim4-8", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume4-8", "10Gi", "", "claim4-8", v1.VolumeAvailable, v1.PersistentVolumeReclaimRetain), + newClaimArray("claim4-8", "uid4-8", "10Gi", "volume4-8-x", v1.ClaimBound), + newClaimArray("claim4-8", "uid4-8", "10Gi", "volume4-8-x", v1.ClaimBound), noevents, noerrors, testSyncVolume, }, @@ -429,78 +429,78 @@ func TestSync(t *testing.T) { // syncVolume binds a claim to requested class even if there is a // smaller PV available "13-1 - binding to class", - []*api.PersistentVolume{ - newVolume("volume13-1-1", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolume("volume13-1-2", "10Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain, storageutil.StorageClassAnnotation), + []*v1.PersistentVolume{ + newVolume("volume13-1-1", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolume("volume13-1-2", "10Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain, storageutil.StorageClassAnnotation), }, - []*api.PersistentVolume{ - newVolume("volume13-1-1", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolume("volume13-1-2", "10Gi", "uid13-1", "claim13-1", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController, storageutil.StorageClassAnnotation), + []*v1.PersistentVolume{ + newVolume("volume13-1-1", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolume("volume13-1-2", "10Gi", "uid13-1", "claim13-1", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController, storageutil.StorageClassAnnotation), }, - newClaimArray("claim13-1", "uid13-1", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), - withExpectedCapacity("10Gi", newClaimArray("claim13-1", "uid13-1", "1Gi", "volume13-1-2", api.ClaimBound, annBoundByController, storageutil.StorageClassAnnotation, annBindCompleted)), + newClaimArray("claim13-1", "uid13-1", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), + withExpectedCapacity("10Gi", newClaimArray("claim13-1", "uid13-1", "1Gi", "volume13-1-2", v1.ClaimBound, annBoundByController, storageutil.StorageClassAnnotation, annBindCompleted)), noevents, noerrors, testSyncClaim, }, { // syncVolume binds a claim without a class even if there is a // smaller PV with a class available "13-2 - binding without a class", - []*api.PersistentVolume{ - newVolume("volume13-2-1", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain, storageutil.StorageClassAnnotation), - newVolume("volume13-2-2", "10Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), + []*v1.PersistentVolume{ + newVolume("volume13-2-1", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain, storageutil.StorageClassAnnotation), + newVolume("volume13-2-2", "10Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), }, - []*api.PersistentVolume{ - newVolume("volume13-2-1", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain, storageutil.StorageClassAnnotation), - newVolume("volume13-2-2", "10Gi", "uid13-2", "claim13-2", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), + []*v1.PersistentVolume{ + newVolume("volume13-2-1", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain, storageutil.StorageClassAnnotation), + newVolume("volume13-2-2", "10Gi", "uid13-2", "claim13-2", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), }, - newClaimArray("claim13-2", "uid13-2", "1Gi", "", api.ClaimPending), - withExpectedCapacity("10Gi", newClaimArray("claim13-2", "uid13-2", "1Gi", "volume13-2-2", api.ClaimBound, annBoundByController, annBindCompleted)), + newClaimArray("claim13-2", "uid13-2", "1Gi", "", v1.ClaimPending), + withExpectedCapacity("10Gi", newClaimArray("claim13-2", "uid13-2", "1Gi", "volume13-2-2", v1.ClaimBound, annBoundByController, annBindCompleted)), noevents, noerrors, testSyncClaim, }, { // syncVolume binds a claim with given class even if there is a // smaller PV with different class available "13-3 - binding to specific a class", - volumeWithClass("silver", []*api.PersistentVolume{ - newVolume("volume13-3-1", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolume("volume13-3-2", "10Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain, storageutil.StorageClassAnnotation), + volumeWithClass("silver", []*v1.PersistentVolume{ + newVolume("volume13-3-1", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolume("volume13-3-2", "10Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain, storageutil.StorageClassAnnotation), }), - volumeWithClass("silver", []*api.PersistentVolume{ - newVolume("volume13-3-1", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolume("volume13-3-2", "10Gi", "uid13-3", "claim13-3", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController, storageutil.StorageClassAnnotation), + volumeWithClass("silver", []*v1.PersistentVolume{ + newVolume("volume13-3-1", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolume("volume13-3-2", "10Gi", "uid13-3", "claim13-3", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController, storageutil.StorageClassAnnotation), }), - newClaimArray("claim13-3", "uid13-3", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), - withExpectedCapacity("10Gi", newClaimArray("claim13-3", "uid13-3", "1Gi", "volume13-3-2", api.ClaimBound, annBoundByController, annBindCompleted, storageutil.StorageClassAnnotation)), + newClaimArray("claim13-3", "uid13-3", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), + withExpectedCapacity("10Gi", newClaimArray("claim13-3", "uid13-3", "1Gi", "volume13-3-2", v1.ClaimBound, annBoundByController, annBindCompleted, storageutil.StorageClassAnnotation)), noevents, noerrors, testSyncClaim, }, { // syncVolume binds claim requesting class "" to claim to PV with // class="" "13-4 - empty class", - volumeWithClass("", newVolumeArray("volume13-4", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain)), - volumeWithClass("", newVolumeArray("volume13-4", "1Gi", "uid13-4", "claim13-4", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController)), - claimWithClass("", newClaimArray("claim13-4", "uid13-4", "1Gi", "", api.ClaimPending)), - claimWithClass("", newClaimArray("claim13-4", "uid13-4", "1Gi", "volume13-4", api.ClaimBound, annBoundByController, annBindCompleted)), + volumeWithClass("", newVolumeArray("volume13-4", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain)), + volumeWithClass("", newVolumeArray("volume13-4", "1Gi", "uid13-4", "claim13-4", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController)), + claimWithClass("", newClaimArray("claim13-4", "uid13-4", "1Gi", "", v1.ClaimPending)), + claimWithClass("", newClaimArray("claim13-4", "uid13-4", "1Gi", "volume13-4", v1.ClaimBound, annBoundByController, annBindCompleted)), noevents, noerrors, testSyncClaim, }, { // syncVolume binds claim requesting class nil to claim to PV with // class = "" "13-5 - nil class", - volumeWithClass("", newVolumeArray("volume13-5", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain)), - volumeWithClass("", newVolumeArray("volume13-5", "1Gi", "uid13-5", "claim13-5", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController)), - newClaimArray("claim13-5", "uid13-5", "1Gi", "", api.ClaimPending), - newClaimArray("claim13-5", "uid13-5", "1Gi", "volume13-5", api.ClaimBound, annBoundByController, annBindCompleted), + volumeWithClass("", newVolumeArray("volume13-5", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain)), + volumeWithClass("", newVolumeArray("volume13-5", "1Gi", "uid13-5", "claim13-5", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController)), + newClaimArray("claim13-5", "uid13-5", "1Gi", "", v1.ClaimPending), + newClaimArray("claim13-5", "uid13-5", "1Gi", "volume13-5", v1.ClaimBound, annBoundByController, annBindCompleted), noevents, noerrors, testSyncClaim, }, { // syncVolume binds claim requesting class "" to claim to PV with // class=nil "13-6 - nil class in PV, '' class in claim", - newVolumeArray("volume13-6", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume13-6", "1Gi", "uid13-6", "claim13-6", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - claimWithClass("", newClaimArray("claim13-6", "uid13-6", "1Gi", "", api.ClaimPending)), - claimWithClass("", newClaimArray("claim13-6", "uid13-6", "1Gi", "volume13-6", api.ClaimBound, annBoundByController, annBindCompleted)), + newVolumeArray("volume13-6", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume13-6", "1Gi", "uid13-6", "claim13-6", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + claimWithClass("", newClaimArray("claim13-6", "uid13-6", "1Gi", "", v1.ClaimPending)), + claimWithClass("", newClaimArray("claim13-6", "uid13-6", "1Gi", "volume13-6", v1.ClaimBound, annBoundByController, annBindCompleted)), noevents, noerrors, testSyncClaim, }, } @@ -527,26 +527,26 @@ func TestMultiSync(t *testing.T) { { // syncClaim binds to a matching unbound volume. "10-1 - successful bind", - newVolumeArray("volume10-1", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume10-1", "1Gi", "uid10-1", "claim10-1", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newClaimArray("claim10-1", "uid10-1", "1Gi", "", api.ClaimPending), - newClaimArray("claim10-1", "uid10-1", "1Gi", "volume10-1", api.ClaimBound, annBoundByController, annBindCompleted), + newVolumeArray("volume10-1", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume10-1", "1Gi", "uid10-1", "claim10-1", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newClaimArray("claim10-1", "uid10-1", "1Gi", "", v1.ClaimPending), + newClaimArray("claim10-1", "uid10-1", "1Gi", "volume10-1", v1.ClaimBound, annBoundByController, annBindCompleted), noevents, noerrors, testSyncClaim, }, { // Two controllers bound two PVs to single claim. Test one of them // wins and the second rolls back. "10-2 - bind PV race", - []*api.PersistentVolume{ - newVolume("volume10-2-1", "1Gi", "uid10-2", "claim10-2", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newVolume("volume10-2-2", "1Gi", "uid10-2", "claim10-2", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), + []*v1.PersistentVolume{ + newVolume("volume10-2-1", "1Gi", "uid10-2", "claim10-2", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newVolume("volume10-2-2", "1Gi", "uid10-2", "claim10-2", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), }, - []*api.PersistentVolume{ - newVolume("volume10-2-1", "1Gi", "uid10-2", "claim10-2", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newVolume("volume10-2-2", "1Gi", "", "", api.VolumeAvailable, api.PersistentVolumeReclaimRetain), + []*v1.PersistentVolume{ + newVolume("volume10-2-1", "1Gi", "uid10-2", "claim10-2", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newVolume("volume10-2-2", "1Gi", "", "", v1.VolumeAvailable, v1.PersistentVolumeReclaimRetain), }, - newClaimArray("claim10-2", "uid10-2", "1Gi", "volume10-2-1", api.ClaimBound, annBoundByController, annBindCompleted), - newClaimArray("claim10-2", "uid10-2", "1Gi", "volume10-2-1", api.ClaimBound, annBoundByController, annBindCompleted), + newClaimArray("claim10-2", "uid10-2", "1Gi", "volume10-2-1", v1.ClaimBound, annBoundByController, annBindCompleted), + newClaimArray("claim10-2", "uid10-2", "1Gi", "volume10-2-1", v1.ClaimBound, annBoundByController, annBindCompleted), noevents, noerrors, testSyncClaim, }, } diff --git a/pkg/controller/volume/persistentvolume/delete_test.go b/pkg/controller/volume/persistentvolume/delete_test.go index 59a968c98de..b4c3effc420 100644 --- a/pkg/controller/volume/persistentvolume/delete_test.go +++ b/pkg/controller/volume/persistentvolume/delete_test.go @@ -20,8 +20,8 @@ import ( "errors" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/storage" + "k8s.io/kubernetes/pkg/api/v1" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" ) // Test single call to syncVolume, expecting recycling to happen. @@ -33,7 +33,7 @@ func TestDeleteSync(t *testing.T) { { // delete volume bound by controller "8-1 - successful delete", - newVolumeArray("volume8-1", "1Gi", "uid8-1", "claim8-1", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController), + newVolumeArray("volume8-1", "1Gi", "uid8-1", "claim8-1", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController), novolumes, noclaims, noclaims, @@ -45,7 +45,7 @@ func TestDeleteSync(t *testing.T) { { // delete volume bound by user "8-2 - successful delete with prebound volume", - newVolumeArray("volume8-2", "1Gi", "uid8-2", "claim8-2", api.VolumeBound, api.PersistentVolumeReclaimDelete), + newVolumeArray("volume8-2", "1Gi", "uid8-2", "claim8-2", v1.VolumeBound, v1.PersistentVolumeReclaimDelete), novolumes, noclaims, noclaims, @@ -57,8 +57,8 @@ func TestDeleteSync(t *testing.T) { { // delete failure - plugin not found "8-3 - plugin not found", - newVolumeArray("volume8-3", "1Gi", "uid8-3", "claim8-3", api.VolumeBound, api.PersistentVolumeReclaimDelete), - withMessage("Error getting deleter volume plugin for volume \"volume8-3\": no volume plugin matched", newVolumeArray("volume8-3", "1Gi", "uid8-3", "claim8-3", api.VolumeFailed, api.PersistentVolumeReclaimDelete)), + newVolumeArray("volume8-3", "1Gi", "uid8-3", "claim8-3", v1.VolumeBound, v1.PersistentVolumeReclaimDelete), + withMessage("Error getting deleter volume plugin for volume \"volume8-3\": no volume plugin matched", newVolumeArray("volume8-3", "1Gi", "uid8-3", "claim8-3", v1.VolumeFailed, v1.PersistentVolumeReclaimDelete)), noclaims, noclaims, []string{"Warning VolumeFailedDelete"}, noerrors, testSyncVolume, @@ -66,8 +66,8 @@ func TestDeleteSync(t *testing.T) { { // delete failure - newDeleter returns error "8-4 - newDeleter returns error", - newVolumeArray("volume8-4", "1Gi", "uid8-4", "claim8-4", api.VolumeBound, api.PersistentVolumeReclaimDelete), - withMessage("Failed to create deleter for volume \"volume8-4\": Mock plugin error: no deleteCalls configured", newVolumeArray("volume8-4", "1Gi", "uid8-4", "claim8-4", api.VolumeFailed, api.PersistentVolumeReclaimDelete)), + newVolumeArray("volume8-4", "1Gi", "uid8-4", "claim8-4", v1.VolumeBound, v1.PersistentVolumeReclaimDelete), + withMessage("Failed to create deleter for volume \"volume8-4\": Mock plugin error: no deleteCalls configured", newVolumeArray("volume8-4", "1Gi", "uid8-4", "claim8-4", v1.VolumeFailed, v1.PersistentVolumeReclaimDelete)), noclaims, noclaims, []string{"Warning VolumeFailedDelete"}, noerrors, @@ -76,8 +76,8 @@ func TestDeleteSync(t *testing.T) { { // delete failure - delete() returns error "8-5 - delete returns error", - newVolumeArray("volume8-5", "1Gi", "uid8-5", "claim8-5", api.VolumeBound, api.PersistentVolumeReclaimDelete), - withMessage("Mock delete error", newVolumeArray("volume8-5", "1Gi", "uid8-5", "claim8-5", api.VolumeFailed, api.PersistentVolumeReclaimDelete)), + newVolumeArray("volume8-5", "1Gi", "uid8-5", "claim8-5", v1.VolumeBound, v1.PersistentVolumeReclaimDelete), + withMessage("Mock delete error", newVolumeArray("volume8-5", "1Gi", "uid8-5", "claim8-5", v1.VolumeFailed, v1.PersistentVolumeReclaimDelete)), noclaims, noclaims, []string{"Warning VolumeFailedDelete"}, noerrors, @@ -86,7 +86,7 @@ func TestDeleteSync(t *testing.T) { { // delete success(?) - volume is deleted before doDelete() starts "8-6 - volume is deleted before deleting", - newVolumeArray("volume8-6", "1Gi", "uid8-6", "claim8-6", api.VolumeBound, api.PersistentVolumeReclaimDelete), + newVolumeArray("volume8-6", "1Gi", "uid8-6", "claim8-6", v1.VolumeBound, v1.PersistentVolumeReclaimDelete), novolumes, noclaims, noclaims, @@ -103,31 +103,31 @@ func TestDeleteSync(t *testing.T) { // starts. This simulates "volume no longer needs recycling, // skipping". "8-7 - volume is bound before deleting", - newVolumeArray("volume8-7", "1Gi", "uid8-7", "claim8-7", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController), - newVolumeArray("volume8-7", "1Gi", "uid8-7", "claim8-7", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController), + newVolumeArray("volume8-7", "1Gi", "uid8-7", "claim8-7", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController), + newVolumeArray("volume8-7", "1Gi", "uid8-7", "claim8-7", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController), noclaims, - newClaimArray("claim8-7", "uid8-7", "10Gi", "volume8-7", api.ClaimBound), + newClaimArray("claim8-7", "uid8-7", "10Gi", "volume8-7", v1.ClaimBound), noevents, noerrors, wrapTestWithInjectedOperation(wrapTestWithReclaimCalls(operationDelete, []error{}, testSyncVolume), func(ctrl *PersistentVolumeController, reactor *volumeReactor) { reactor.lock.Lock() defer reactor.lock.Unlock() // Bind the volume to resurrected claim (this should never // happen) - claim := newClaim("claim8-7", "uid8-7", "10Gi", "volume8-7", api.ClaimBound) + claim := newClaim("claim8-7", "uid8-7", "10Gi", "volume8-7", v1.ClaimBound) reactor.claims[claim.Name] = claim ctrl.claims.Add(claim) volume := reactor.volumes["volume8-7"] - volume.Status.Phase = api.VolumeBound + volume.Status.Phase = v1.VolumeBound }), }, { // delete success - volume bound by user is deleted, while a new // claim is created with another UID. "8-9 - prebound volume is deleted while the claim exists", - newVolumeArray("volume8-9", "1Gi", "uid8-9", "claim8-9", api.VolumeBound, api.PersistentVolumeReclaimDelete), + newVolumeArray("volume8-9", "1Gi", "uid8-9", "claim8-9", v1.VolumeBound, v1.PersistentVolumeReclaimDelete), novolumes, - newClaimArray("claim8-9", "uid8-9-x", "10Gi", "", api.ClaimPending), - newClaimArray("claim8-9", "uid8-9-x", "10Gi", "", api.ClaimPending), + newClaimArray("claim8-9", "uid8-9-x", "10Gi", "", v1.ClaimPending), + newClaimArray("claim8-9", "uid8-9-x", "10Gi", "", v1.ClaimPending), noevents, noerrors, // Inject deleter into the controller and call syncVolume. The // deleter simulates one delete() call that succeeds. @@ -136,8 +136,8 @@ func TestDeleteSync(t *testing.T) { { // PV requires external deleter "8-10 - external deleter", - newVolumeArray("volume8-10", "1Gi", "uid10-1", "claim10-1", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController), - newVolumeArray("volume8-10", "1Gi", "uid10-1", "claim10-1", api.VolumeReleased, api.PersistentVolumeReclaimDelete, annBoundByController), + newVolumeArray("volume8-10", "1Gi", "uid10-1", "claim10-1", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController), + newVolumeArray("volume8-10", "1Gi", "uid10-1", "claim10-1", v1.VolumeReleased, v1.PersistentVolumeReclaimDelete, annBoundByController), noclaims, noclaims, noevents, noerrors, @@ -152,16 +152,16 @@ func TestDeleteSync(t *testing.T) { // delete success - two PVs are provisioned for a single claim. // One of the PVs is deleted. "8-11 - two PVs provisioned for a single claim", - []*api.PersistentVolume{ - newVolume("volume8-11-1", "1Gi", "uid8-11", "claim8-11", api.VolumeBound, api.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), - newVolume("volume8-11-2", "1Gi", "uid8-11", "claim8-11", api.VolumeBound, api.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), + []*v1.PersistentVolume{ + newVolume("volume8-11-1", "1Gi", "uid8-11", "claim8-11", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), + newVolume("volume8-11-2", "1Gi", "uid8-11", "claim8-11", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), }, - []*api.PersistentVolume{ - newVolume("volume8-11-2", "1Gi", "uid8-11", "claim8-11", api.VolumeBound, api.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), + []*v1.PersistentVolume{ + newVolume("volume8-11-2", "1Gi", "uid8-11", "claim8-11", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), }, // the claim is bound to volume8-11-2 -> volume8-11-1 has lost the race and will be deleted - newClaimArray("claim8-11", "uid8-11", "10Gi", "volume8-11-2", api.ClaimBound), - newClaimArray("claim8-11", "uid8-11", "10Gi", "volume8-11-2", api.ClaimBound), + newClaimArray("claim8-11", "uid8-11", "10Gi", "volume8-11-2", v1.ClaimBound), + newClaimArray("claim8-11", "uid8-11", "10Gi", "volume8-11-2", v1.ClaimBound), noevents, noerrors, // Inject deleter into the controller and call syncVolume. The // deleter simulates one delete() call that succeeds. @@ -172,17 +172,17 @@ func TestDeleteSync(t *testing.T) { // claim. One of the PVs is marked as Released to be deleted by the // external provisioner. "8-12 - two PVs externally provisioned for a single claim", - []*api.PersistentVolume{ - newVolume("volume8-12-1", "1Gi", "uid8-12", "claim8-12", api.VolumeBound, api.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), - newVolume("volume8-12-2", "1Gi", "uid8-12", "claim8-12", api.VolumeBound, api.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), + []*v1.PersistentVolume{ + newVolume("volume8-12-1", "1Gi", "uid8-12", "claim8-12", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), + newVolume("volume8-12-2", "1Gi", "uid8-12", "claim8-12", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), }, - []*api.PersistentVolume{ - newVolume("volume8-12-1", "1Gi", "uid8-12", "claim8-12", api.VolumeReleased, api.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), - newVolume("volume8-12-2", "1Gi", "uid8-12", "claim8-12", api.VolumeBound, api.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), + []*v1.PersistentVolume{ + newVolume("volume8-12-1", "1Gi", "uid8-12", "claim8-12", v1.VolumeReleased, v1.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), + newVolume("volume8-12-2", "1Gi", "uid8-12", "claim8-12", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annDynamicallyProvisioned), }, // the claim is bound to volume8-12-2 -> volume8-12-1 has lost the race and will be "Released" - newClaimArray("claim8-12", "uid8-12", "10Gi", "volume8-12-2", api.ClaimBound), - newClaimArray("claim8-12", "uid8-12", "10Gi", "volume8-12-2", api.ClaimBound), + newClaimArray("claim8-12", "uid8-12", "10Gi", "volume8-12-2", v1.ClaimBound), + newClaimArray("claim8-12", "uid8-12", "10Gi", "volume8-12-2", v1.ClaimBound), noevents, noerrors, func(ctrl *PersistentVolumeController, reactor *volumeReactor, test controllerTest) error { // Inject external deleter annotation @@ -215,7 +215,7 @@ func TestDeleteMultiSync(t *testing.T) { // delete failure - delete returns error. The controller should // try again. "9-1 - delete returns error", - newVolumeArray("volume9-1", "1Gi", "uid9-1", "claim9-1", api.VolumeBound, api.PersistentVolumeReclaimDelete), + newVolumeArray("volume9-1", "1Gi", "uid9-1", "claim9-1", v1.VolumeBound, v1.PersistentVolumeReclaimDelete), novolumes, noclaims, noclaims, diff --git a/pkg/controller/volume/persistentvolume/framework_test.go b/pkg/controller/volume/persistentvolume/framework_test.go index 1048e7b8613..86bd1219474 100644 --- a/pkg/controller/volume/persistentvolume/framework_test.go +++ b/pkg/controller/volume/persistentvolume/framework_test.go @@ -29,15 +29,15 @@ import ( "github.com/golang/glog" - "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/storage" - storageutil "k8s.io/kubernetes/pkg/apis/storage/util" + "k8s.io/kubernetes/pkg/api/v1" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" + storageutil "k8s.io/kubernetes/pkg/apis/storage/v1beta1/util" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/record" fcache "k8s.io/kubernetes/pkg/client/testing/cache" "k8s.io/kubernetes/pkg/client/testing/core" @@ -77,13 +77,13 @@ type controllerTest struct { // Name of the test, for logging name string // Initial content of controller volume cache. - initialVolumes []*api.PersistentVolume + initialVolumes []*v1.PersistentVolume // Expected content of controller volume cache at the end of the test. - expectedVolumes []*api.PersistentVolume + expectedVolumes []*v1.PersistentVolume // Initial content of controller claim cache. - initialClaims []*api.PersistentVolumeClaim + initialClaims []*v1.PersistentVolumeClaim // Expected content of controller claim cache at the end of the test. - expectedClaims []*api.PersistentVolumeClaim + expectedClaims []*v1.PersistentVolumeClaim // Expected events - any event with prefix will pass, we don't check full // event message. expectedEvents []string @@ -99,8 +99,8 @@ const testNamespace = "default" const mockPluginName = "kubernetes.io/mock-volume" var versionConflictError = errors.New("VersionError") -var novolumes []*api.PersistentVolume -var noclaims []*api.PersistentVolumeClaim +var novolumes []*v1.PersistentVolume +var noclaims []*v1.PersistentVolumeClaim var noevents = []string{} var noerrors = []reactorError{} @@ -121,8 +121,8 @@ var noerrors = []reactorError{} // reactorError, it return appropriate error and removes the reactorError from // the list. type volumeReactor struct { - volumes map[string]*api.PersistentVolume - claims map[string]*api.PersistentVolumeClaim + volumes map[string]*v1.PersistentVolume + claims map[string]*v1.PersistentVolumeClaim changedObjects []interface{} changedSinceLastSync int ctrl *PersistentVolumeController @@ -167,7 +167,7 @@ func (r *volumeReactor) React(action core.Action) (handled bool, ret runtime.Obj switch { case action.Matches("create", "persistentvolumes"): obj := action.(core.UpdateAction).GetObject() - volume := obj.(*api.PersistentVolume) + volume := obj.(*v1.PersistentVolume) // check the volume does not exist _, found := r.volumes[volume.Name] @@ -187,7 +187,7 @@ func (r *volumeReactor) React(action core.Action) (handled bool, ret runtime.Obj case action.Matches("update", "persistentvolumes"): obj := action.(core.UpdateAction).GetObject() - volume := obj.(*api.PersistentVolume) + volume := obj.(*v1.PersistentVolume) // Check and bump object version storedVolume, found := r.volumes[volume.Name] @@ -214,7 +214,7 @@ func (r *volumeReactor) React(action core.Action) (handled bool, ret runtime.Obj case action.Matches("update", "persistentvolumeclaims"): obj := action.(core.UpdateAction).GetObject() - claim := obj.(*api.PersistentVolumeClaim) + claim := obj.(*v1.PersistentVolumeClaim) // Check and bump object version storedClaim, found := r.claims[claim.Name] @@ -300,12 +300,12 @@ func (r *volumeReactor) injectReactError(action core.Action) error { // checkVolumes compares all expectedVolumes with set of volumes at the end of // the test and reports differences. -func (r *volumeReactor) checkVolumes(expectedVolumes []*api.PersistentVolume) error { +func (r *volumeReactor) checkVolumes(expectedVolumes []*v1.PersistentVolume) error { r.lock.Lock() defer r.lock.Unlock() - expectedMap := make(map[string]*api.PersistentVolume) - gotMap := make(map[string]*api.PersistentVolume) + expectedMap := make(map[string]*v1.PersistentVolume) + gotMap := make(map[string]*v1.PersistentVolume) // Clear any ResourceVersion from both sets for _, v := range expectedVolumes { v.ResourceVersion = "" @@ -315,7 +315,7 @@ func (r *volumeReactor) checkVolumes(expectedVolumes []*api.PersistentVolume) er // We must clone the volume because of golang race check - it was // written by the controller without any locks on it. clone, _ := conversion.NewCloner().DeepCopy(v) - v = clone.(*api.PersistentVolume) + v = clone.(*v1.PersistentVolume) v.ResourceVersion = "" if v.Spec.ClaimRef != nil { v.Spec.ClaimRef.ResourceVersion = "" @@ -332,12 +332,12 @@ func (r *volumeReactor) checkVolumes(expectedVolumes []*api.PersistentVolume) er // checkClaims compares all expectedClaims with set of claims at the end of the // test and reports differences. -func (r *volumeReactor) checkClaims(expectedClaims []*api.PersistentVolumeClaim) error { +func (r *volumeReactor) checkClaims(expectedClaims []*v1.PersistentVolumeClaim) error { r.lock.Lock() defer r.lock.Unlock() - expectedMap := make(map[string]*api.PersistentVolumeClaim) - gotMap := make(map[string]*api.PersistentVolumeClaim) + expectedMap := make(map[string]*v1.PersistentVolumeClaim) + gotMap := make(map[string]*v1.PersistentVolumeClaim) for _, c := range expectedClaims { c.ResourceVersion = "" expectedMap[c.Name] = c @@ -346,7 +346,7 @@ func (r *volumeReactor) checkClaims(expectedClaims []*api.PersistentVolumeClaim) // We must clone the claim because of golang race check - it was // written by the controller without any locks on it. clone, _ := conversion.NewCloner().DeepCopy(c) - c = clone.(*api.PersistentVolumeClaim) + c = clone.(*v1.PersistentVolumeClaim) c.ResourceVersion = "" gotMap[c.Name] = c } @@ -407,8 +407,8 @@ func checkEvents(t *testing.T, expectedEvents []string, ctrl *PersistentVolumeCo return err } -// popChange returns one recorded updated object, either *api.PersistentVolume -// or *api.PersistentVolumeClaim. Returns nil when there are no changes. +// popChange returns one recorded updated object, either *v1.PersistentVolume +// or *v1.PersistentVolumeClaim. Returns nil when there are no changes. func (r *volumeReactor) popChange() interface{} { r.lock.Lock() defer r.lock.Unlock() @@ -420,11 +420,11 @@ func (r *volumeReactor) popChange() interface{} { // For debugging purposes, print the queue for _, obj := range r.changedObjects { switch obj.(type) { - case *api.PersistentVolume: - vol, _ := obj.(*api.PersistentVolume) + case *v1.PersistentVolume: + vol, _ := obj.(*v1.PersistentVolume) glog.V(4).Infof("reactor queue: %s", vol.Name) - case *api.PersistentVolumeClaim: - claim, _ := obj.(*api.PersistentVolumeClaim) + case *v1.PersistentVolumeClaim: + claim, _ := obj.(*v1.PersistentVolumeClaim) glog.V(4).Infof("reactor queue: %s", claim.Name) } } @@ -504,7 +504,7 @@ func (r *volumeReactor) waitTest(test controllerTest) error { // deleteVolumeEvent simulates that a volume has been deleted in etcd and // the controller receives 'volume deleted' event. -func (r *volumeReactor) deleteVolumeEvent(volume *api.PersistentVolume) { +func (r *volumeReactor) deleteVolumeEvent(volume *v1.PersistentVolume) { r.lock.Lock() defer r.lock.Unlock() @@ -514,13 +514,13 @@ func (r *volumeReactor) deleteVolumeEvent(volume *api.PersistentVolume) { // Generate deletion event. Cloned volume is needed to prevent races (and we // would get a clone from etcd too). clone, _ := conversion.NewCloner().DeepCopy(volume) - volumeClone := clone.(*api.PersistentVolume) + volumeClone := clone.(*v1.PersistentVolume) r.volumeSource.Delete(volumeClone) } // deleteClaimEvent simulates that a claim has been deleted in etcd and the // controller receives 'claim deleted' event. -func (r *volumeReactor) deleteClaimEvent(claim *api.PersistentVolumeClaim) { +func (r *volumeReactor) deleteClaimEvent(claim *v1.PersistentVolumeClaim) { r.lock.Lock() defer r.lock.Unlock() @@ -530,13 +530,13 @@ func (r *volumeReactor) deleteClaimEvent(claim *api.PersistentVolumeClaim) { // Generate deletion event. Cloned volume is needed to prevent races (and we // would get a clone from etcd too). clone, _ := conversion.NewCloner().DeepCopy(claim) - claimClone := clone.(*api.PersistentVolumeClaim) + claimClone := clone.(*v1.PersistentVolumeClaim) r.claimSource.Delete(claimClone) } // addVolumeEvent simulates that a volume has been added in etcd and the // controller receives 'volume added' event. -func (r *volumeReactor) addVolumeEvent(volume *api.PersistentVolume) { +func (r *volumeReactor) addVolumeEvent(volume *v1.PersistentVolume) { r.lock.Lock() defer r.lock.Unlock() @@ -548,7 +548,7 @@ func (r *volumeReactor) addVolumeEvent(volume *api.PersistentVolume) { // modifyVolumeEvent simulates that a volume has been modified in etcd and the // controller receives 'volume modified' event. -func (r *volumeReactor) modifyVolumeEvent(volume *api.PersistentVolume) { +func (r *volumeReactor) modifyVolumeEvent(volume *v1.PersistentVolume) { r.lock.Lock() defer r.lock.Unlock() @@ -556,13 +556,13 @@ func (r *volumeReactor) modifyVolumeEvent(volume *api.PersistentVolume) { // Generate deletion event. Cloned volume is needed to prevent races (and we // would get a clone from etcd too). clone, _ := conversion.NewCloner().DeepCopy(volume) - volumeClone := clone.(*api.PersistentVolume) + volumeClone := clone.(*v1.PersistentVolume) r.volumeSource.Modify(volumeClone) } // addClaimEvent simulates that a claim has been deleted in etcd and the // controller receives 'claim added' event. -func (r *volumeReactor) addClaimEvent(claim *api.PersistentVolumeClaim) { +func (r *volumeReactor) addClaimEvent(claim *v1.PersistentVolumeClaim) { r.lock.Lock() defer r.lock.Unlock() @@ -574,8 +574,8 @@ func (r *volumeReactor) addClaimEvent(claim *api.PersistentVolumeClaim) { func newVolumeReactor(client *fake.Clientset, ctrl *PersistentVolumeController, volumeSource *fcache.FakePVControllerSource, claimSource *fcache.FakePVCControllerSource, errors []reactorError) *volumeReactor { reactor := &volumeReactor{ - volumes: make(map[string]*api.PersistentVolume), - claims: make(map[string]*api.PersistentVolumeClaim), + volumes: make(map[string]*v1.PersistentVolume), + claims: make(map[string]*v1.PersistentVolumeClaim), ctrl: ctrl, volumeSource: volumeSource, claimSource: claimSource, @@ -614,29 +614,29 @@ func newTestController(kubeClient clientset.Interface, volumeSource, claimSource } // newVolume returns a new volume with given attributes -func newVolume(name, capacity, boundToClaimUID, boundToClaimName string, phase api.PersistentVolumePhase, reclaimPolicy api.PersistentVolumeReclaimPolicy, annotations ...string) *api.PersistentVolume { - volume := api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ +func newVolume(name, capacity, boundToClaimUID, boundToClaimName string, phase v1.PersistentVolumePhase, reclaimPolicy v1.PersistentVolumeReclaimPolicy, annotations ...string) *v1.PersistentVolume { + volume := v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: name, ResourceVersion: "1", }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(capacity), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(capacity), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce, api.ReadOnlyMany}, + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce, v1.ReadOnlyMany}, PersistentVolumeReclaimPolicy: reclaimPolicy, }, - Status: api.PersistentVolumeStatus{ + Status: v1.PersistentVolumeStatus{ Phase: phase, }, } if boundToClaimName != "" { - volume.Spec.ClaimRef = &api.ObjectReference{ + volume.Spec.ClaimRef = &v1.ObjectReference{ Kind: "PersistentVolumeClaim", APIVersion: "v1", UID: types.UID(boundToClaimUID), @@ -665,7 +665,7 @@ func newVolume(name, capacity, boundToClaimUID, boundToClaimName string, phase a // withLabels applies the given labels to the first volume in the array and // returns the array. Meant to be used to compose volumes specified inline in // a test. -func withLabels(labels map[string]string, volumes []*api.PersistentVolume) []*api.PersistentVolume { +func withLabels(labels map[string]string, volumes []*v1.PersistentVolume) []*v1.PersistentVolume { volumes[0].Labels = labels return volumes } @@ -673,7 +673,7 @@ func withLabels(labels map[string]string, volumes []*api.PersistentVolume) []*ap // withLabelSelector sets the label selector of the first claim in the array // to be MatchLabels of the given label set and returns the array. Meant // to be used to compose claims specified inline in a test. -func withLabelSelector(labels map[string]string, claims []*api.PersistentVolumeClaim) []*api.PersistentVolumeClaim { +func withLabelSelector(labels map[string]string, claims []*v1.PersistentVolumeClaim) []*v1.PersistentVolumeClaim { claims[0].Spec.Selector = &unversioned.LabelSelector{ MatchLabels: labels, } @@ -684,9 +684,9 @@ func withLabelSelector(labels map[string]string, claims []*api.PersistentVolumeC // withExpectedCapacity sets the claim.Spec.Capacity of the first claim in the // array to given value and returns the array. Meant to be used to compose // claims specified inline in a test. -func withExpectedCapacity(capacity string, claims []*api.PersistentVolumeClaim) []*api.PersistentVolumeClaim { - claims[0].Status.Capacity = api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(capacity), +func withExpectedCapacity(capacity string, claims []*v1.PersistentVolumeClaim) []*v1.PersistentVolumeClaim { + claims[0].Status.Capacity = v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(capacity), } return claims @@ -695,14 +695,14 @@ func withExpectedCapacity(capacity string, claims []*api.PersistentVolumeClaim) // withMessage saves given message into volume.Status.Message of the first // volume in the array and returns the array. Meant to be used to compose // volumes specified inline in a test. -func withMessage(message string, volumes []*api.PersistentVolume) []*api.PersistentVolume { +func withMessage(message string, volumes []*v1.PersistentVolume) []*v1.PersistentVolume { volumes[0].Status.Message = message return volumes } // volumeWithClass saves given class into storage.StorageClassAnnotation annotation. // Meant to be used to compose claims specified inline in a test. -func volumeWithClass(className string, volumes []*api.PersistentVolume) []*api.PersistentVolume { +func volumeWithClass(className string, volumes []*v1.PersistentVolume) []*v1.PersistentVolume { if volumes[0].Annotations == nil { volumes[0].Annotations = map[string]string{storageutil.StorageClassAnnotation: className} } else { @@ -713,35 +713,35 @@ func volumeWithClass(className string, volumes []*api.PersistentVolume) []*api.P // newVolumeArray returns array with a single volume that would be returned by // newVolume() with the same parameters. -func newVolumeArray(name, capacity, boundToClaimUID, boundToClaimName string, phase api.PersistentVolumePhase, reclaimPolicy api.PersistentVolumeReclaimPolicy, annotations ...string) []*api.PersistentVolume { - return []*api.PersistentVolume{ +func newVolumeArray(name, capacity, boundToClaimUID, boundToClaimName string, phase v1.PersistentVolumePhase, reclaimPolicy v1.PersistentVolumeReclaimPolicy, annotations ...string) []*v1.PersistentVolume { + return []*v1.PersistentVolume{ newVolume(name, capacity, boundToClaimUID, boundToClaimName, phase, reclaimPolicy, annotations...), } } // newClaim returns a new claim with given attributes -func newClaim(name, claimUID, capacity, boundToVolume string, phase api.PersistentVolumeClaimPhase, annotations ...string) *api.PersistentVolumeClaim { - claim := api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ +func newClaim(name, claimUID, capacity, boundToVolume string, phase v1.PersistentVolumeClaimPhase, annotations ...string) *v1.PersistentVolumeClaim { + claim := v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: name, Namespace: testNamespace, UID: types.UID(claimUID), ResourceVersion: "1", }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce, api.ReadOnlyMany}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(capacity), + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce, v1.ReadOnlyMany}, + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(capacity), }, }, VolumeName: boundToVolume, }, - Status: api.PersistentVolumeClaimStatus{ + Status: v1.PersistentVolumeClaimStatus{ Phase: phase, }, } - // Make sure api.GetReference(claim) works + // Make sure v1.GetReference(claim) works claim.ObjectMeta.SelfLink = testapi.Default.SelfLink("pvc", name) if len(annotations) > 0 { @@ -759,7 +759,7 @@ func newClaim(name, claimUID, capacity, boundToVolume string, phase api.Persiste } // Bound claims must have proper Status. - if phase == api.ClaimBound { + if phase == v1.ClaimBound { claim.Status.AccessModes = claim.Spec.AccessModes // For most of the tests it's enough to copy claim's requested capacity, // individual tests can adjust it using withExpectedCapacity() @@ -771,15 +771,15 @@ func newClaim(name, claimUID, capacity, boundToVolume string, phase api.Persiste // newClaimArray returns array with a single claim that would be returned by // newClaim() with the same parameters. -func newClaimArray(name, claimUID, capacity, boundToVolume string, phase api.PersistentVolumeClaimPhase, annotations ...string) []*api.PersistentVolumeClaim { - return []*api.PersistentVolumeClaim{ +func newClaimArray(name, claimUID, capacity, boundToVolume string, phase v1.PersistentVolumeClaimPhase, annotations ...string) []*v1.PersistentVolumeClaim { + return []*v1.PersistentVolumeClaim{ newClaim(name, claimUID, capacity, boundToVolume, phase, annotations...), } } // claimWithClass saves given class into storage.StorageClassAnnotation annotation. // Meant to be used to compose claims specified inline in a test. -func claimWithClass(className string, claims []*api.PersistentVolumeClaim) []*api.PersistentVolumeClaim { +func claimWithClass(className string, claims []*v1.PersistentVolumeClaim) []*v1.PersistentVolumeClaim { if claims[0].Annotations == nil { claims[0].Annotations = map[string]string{storageutil.StorageClassAnnotation: className} } else { @@ -790,7 +790,7 @@ func claimWithClass(className string, claims []*api.PersistentVolumeClaim) []*ap // claimWithAnnotation saves given annotation into given claims. // Meant to be used to compose claims specified inline in a test. -func claimWithAnnotation(name, value string, claims []*api.PersistentVolumeClaim) []*api.PersistentVolumeClaim { +func claimWithAnnotation(name, value string, claims []*v1.PersistentVolumeClaim) []*v1.PersistentVolumeClaim { if claims[0].Annotations == nil { claims[0].Annotations = map[string]string{name: value} } else { @@ -1041,8 +1041,8 @@ func runMultisyncTests(t *testing.T, tests []controllerTest, storageClasses []*s // There were some changes, process them switch obj.(type) { - case *api.PersistentVolumeClaim: - claim := obj.(*api.PersistentVolumeClaim) + case *v1.PersistentVolumeClaim: + claim := obj.(*v1.PersistentVolumeClaim) // Simulate "claim updated" event ctrl.claims.Update(claim) err = ctrl.syncClaim(claim) @@ -1058,8 +1058,8 @@ func runMultisyncTests(t *testing.T, tests []controllerTest, storageClasses []*s } // Process generated changes continue - case *api.PersistentVolume: - volume := obj.(*api.PersistentVolume) + case *v1.PersistentVolume: + volume := obj.(*v1.PersistentVolume) // Simulate "volume updated" event ctrl.volumes.store.Update(volume) err = ctrl.syncVolume(volume) @@ -1128,7 +1128,7 @@ func (plugin *mockVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string return nil, nil } -func (plugin *mockVolumePlugin) NewMounter(spec *vol.Spec, podRef *api.Pod, opts vol.VolumeOptions) (vol.Mounter, error) { +func (plugin *mockVolumePlugin) NewMounter(spec *vol.Spec, podRef *v1.Pod, opts vol.VolumeOptions) (vol.Mounter, error) { return nil, fmt.Errorf("Mounter is not supported by this plugin") } @@ -1149,12 +1149,12 @@ func (plugin *mockVolumePlugin) NewProvisioner(options vol.VolumeOptions) (vol.P } } -func (plugin *mockVolumePlugin) Provision() (*api.PersistentVolume, error) { +func (plugin *mockVolumePlugin) Provision() (*v1.PersistentVolume, error) { if len(plugin.provisionCalls) <= plugin.provisionCallCounter { return nil, fmt.Errorf("Mock plugin error: unexpected provisioner call %d", plugin.provisionCallCounter) } - var pv *api.PersistentVolume + var pv *v1.PersistentVolume call := plugin.provisionCalls[plugin.provisionCallCounter] if !reflect.DeepEqual(call.expectedParameters, plugin.provisionOptions.Parameters) { glog.Errorf("invalid provisioner call, expected options: %+v, got: %+v", call.expectedParameters, plugin.provisionOptions.Parameters) @@ -1162,20 +1162,20 @@ func (plugin *mockVolumePlugin) Provision() (*api.PersistentVolume, error) { } if call.ret == nil { // Create a fake PV with known GCE volume (to match expected volume) - capacity := plugin.provisionOptions.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] + capacity := plugin.provisionOptions.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] accessModes := plugin.provisionOptions.PVC.Spec.AccessModes - pv = &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv = &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: plugin.provisionOptions.PVName, }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): capacity, + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): capacity, }, AccessModes: accessModes, PersistentVolumeReclaimPolicy: plugin.provisionOptions.PersistentVolumeReclaimPolicy, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, }, } diff --git a/pkg/controller/volume/persistentvolume/index.go b/pkg/controller/volume/persistentvolume/index.go index 176c4b228fe..90705c8138b 100644 --- a/pkg/controller/volume/persistentvolume/index.go +++ b/pkg/controller/volume/persistentvolume/index.go @@ -20,9 +20,9 @@ import ( "fmt" "sort" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - storageutil "k8s.io/kubernetes/pkg/apis/storage/util" + "k8s.io/kubernetes/pkg/api/v1" + storageutil "k8s.io/kubernetes/pkg/apis/storage/v1beta1/util" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/labels" ) @@ -40,8 +40,8 @@ func newPersistentVolumeOrderedIndex() persistentVolumeOrderedIndex { // accessModesIndexFunc is an indexing function that returns a persistent // volume's AccessModes as a string func accessModesIndexFunc(obj interface{}) ([]string, error) { - if pv, ok := obj.(*api.PersistentVolume); ok { - modes := api.GetAccessModesAsString(pv.Spec.AccessModes) + if pv, ok := obj.(*v1.PersistentVolume); ok { + modes := v1.GetAccessModesAsString(pv.Spec.AccessModes) return []string{modes}, nil } return []string{""}, fmt.Errorf("object is not a persistent volume: %v", obj) @@ -49,9 +49,9 @@ func accessModesIndexFunc(obj interface{}) ([]string, error) { // listByAccessModes returns all volumes with the given set of // AccessModeTypes. The list is unsorted! -func (pvIndex *persistentVolumeOrderedIndex) listByAccessModes(modes []api.PersistentVolumeAccessMode) ([]*api.PersistentVolume, error) { - pv := &api.PersistentVolume{ - Spec: api.PersistentVolumeSpec{ +func (pvIndex *persistentVolumeOrderedIndex) listByAccessModes(modes []v1.PersistentVolumeAccessMode) ([]*v1.PersistentVolume, error) { + pv := &v1.PersistentVolume{ + Spec: v1.PersistentVolumeSpec{ AccessModes: modes, }, } @@ -61,19 +61,19 @@ func (pvIndex *persistentVolumeOrderedIndex) listByAccessModes(modes []api.Persi return nil, err } - volumes := make([]*api.PersistentVolume, len(objs)) + volumes := make([]*v1.PersistentVolume, len(objs)) for i, obj := range objs { - volumes[i] = obj.(*api.PersistentVolume) + volumes[i] = obj.(*v1.PersistentVolume) } return volumes, nil } // matchPredicate is a function that indicates that a persistent volume matches another -type matchPredicate func(compareThis, toThis *api.PersistentVolume) bool +type matchPredicate func(compareThis, toThis *v1.PersistentVolume) bool // find returns the nearest PV from the ordered list or nil if a match is not found -func (pvIndex *persistentVolumeOrderedIndex) findByClaim(claim *api.PersistentVolumeClaim, matchPredicate matchPredicate) (*api.PersistentVolume, error) { +func (pvIndex *persistentVolumeOrderedIndex) findByClaim(claim *v1.PersistentVolumeClaim, matchPredicate matchPredicate) (*v1.PersistentVolume, error) { // PVs are indexed by their access modes to allow easier searching. Each // index is the string representation of a set of access modes. There is a // finite number of possible sets and PVs will only be indexed in one of @@ -89,9 +89,9 @@ func (pvIndex *persistentVolumeOrderedIndex) findByClaim(claim *api.PersistentVo // example above). allPossibleModes := pvIndex.allPossibleMatchingAccessModes(claim.Spec.AccessModes) - var smallestVolume *api.PersistentVolume + var smallestVolume *v1.PersistentVolume var smallestVolumeSize int64 - requestedQty := claim.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] + requestedQty := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] requestedSize := requestedQty.Value() requestedClass := storageutil.GetClaimStorageClass(claim) @@ -122,7 +122,7 @@ func (pvIndex *persistentVolumeOrderedIndex) findByClaim(claim *api.PersistentVo // this claim and volume are pre-bound; return // the volume if the size request is satisfied, // otherwise continue searching for a match - volumeQty := volume.Spec.Capacity[api.ResourceStorage] + volumeQty := volume.Spec.Capacity[v1.ResourceStorage] volumeSize := volumeQty.Value() if volumeSize < requestedSize { continue @@ -134,7 +134,7 @@ func (pvIndex *persistentVolumeOrderedIndex) findByClaim(claim *api.PersistentVo // with existing PVs, findByClaim must find only PVs that are // pre-bound to the claim (by dynamic provisioning). TODO: remove in // 1.5 - if api.HasAnnotation(claim.ObjectMeta, storageutil.AlphaStorageClassAnnotation) { + if v1.HasAnnotation(claim.ObjectMeta, storageutil.AlphaStorageClassAnnotation) { continue } @@ -151,7 +151,7 @@ func (pvIndex *persistentVolumeOrderedIndex) findByClaim(claim *api.PersistentVo continue } - volumeQty := volume.Spec.Capacity[api.ResourceStorage] + volumeQty := volume.Spec.Capacity[v1.ResourceStorage] volumeSize := volumeQty.Value() if volumeSize >= requestedSize { if smallestVolume == nil || smallestVolumeSize > volumeSize { @@ -170,14 +170,14 @@ func (pvIndex *persistentVolumeOrderedIndex) findByClaim(claim *api.PersistentVo } // findBestMatchForClaim is a convenience method that finds a volume by the claim's AccessModes and requests for Storage -func (pvIndex *persistentVolumeOrderedIndex) findBestMatchForClaim(claim *api.PersistentVolumeClaim) (*api.PersistentVolume, error) { +func (pvIndex *persistentVolumeOrderedIndex) findBestMatchForClaim(claim *v1.PersistentVolumeClaim) (*v1.PersistentVolume, error) { return pvIndex.findByClaim(claim, matchStorageCapacity) } // matchStorageCapacity is a matchPredicate used to sort and find volumes -func matchStorageCapacity(pvA, pvB *api.PersistentVolume) bool { - aQty := pvA.Spec.Capacity[api.ResourceStorage] - bQty := pvB.Spec.Capacity[api.ResourceStorage] +func matchStorageCapacity(pvA, pvB *v1.PersistentVolume) bool { + aQty := pvA.Spec.Capacity[v1.ResourceStorage] + bQty := pvB.Spec.Capacity[v1.ResourceStorage] aSize := aQty.Value() bSize := bQty.Value() return aSize <= bSize @@ -201,31 +201,31 @@ func matchStorageCapacity(pvA, pvB *api.PersistentVolume) bool { // A request for RWO could be satisfied by both sets of indexed volumes, so // allPossibleMatchingAccessModes returns: // -// [][]api.PersistentVolumeAccessMode { -// []api.PersistentVolumeAccessMode { -// api.ReadWriteOnce, api.ReadOnlyMany, +// [][]v1.PersistentVolumeAccessMode { +// []v1.PersistentVolumeAccessMode { +// v1.ReadWriteOnce, v1.ReadOnlyMany, // }, -// []api.PersistentVolumeAccessMode { -// api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany, +// []v1.PersistentVolumeAccessMode { +// v1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadWriteMany, // }, // } // // A request for RWX can be satisfied by only one set of indexed volumes, so // the return is: // -// [][]api.PersistentVolumeAccessMode { -// []api.PersistentVolumeAccessMode { -// api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany, +// [][]v1.PersistentVolumeAccessMode { +// []v1.PersistentVolumeAccessMode { +// v1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadWriteMany, // }, // } // // This func returns modes with ascending levels of modes to give the user // what is closest to what they actually asked for. -func (pvIndex *persistentVolumeOrderedIndex) allPossibleMatchingAccessModes(requestedModes []api.PersistentVolumeAccessMode) [][]api.PersistentVolumeAccessMode { - matchedModes := [][]api.PersistentVolumeAccessMode{} +func (pvIndex *persistentVolumeOrderedIndex) allPossibleMatchingAccessModes(requestedModes []v1.PersistentVolumeAccessMode) [][]v1.PersistentVolumeAccessMode { + matchedModes := [][]v1.PersistentVolumeAccessMode{} keys := pvIndex.store.ListIndexFuncValues("accessmodes") for _, key := range keys { - indexedModes := api.GetAccessModesFromString(key) + indexedModes := v1.GetAccessModesFromString(key) if containedInAll(indexedModes, requestedModes) { matchedModes = append(matchedModes, indexedModes) } @@ -238,7 +238,7 @@ func (pvIndex *persistentVolumeOrderedIndex) allPossibleMatchingAccessModes(requ return matchedModes } -func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { +func contains(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true @@ -247,7 +247,7 @@ func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeA return false } -func containedInAll(indexedModes []api.PersistentVolumeAccessMode, requestedModes []api.PersistentVolumeAccessMode) bool { +func containedInAll(indexedModes []v1.PersistentVolumeAccessMode, requestedModes []v1.PersistentVolumeAccessMode) bool { for _, mode := range requestedModes { if !contains(indexedModes, mode) { return false @@ -258,7 +258,7 @@ func containedInAll(indexedModes []api.PersistentVolumeAccessMode, requestedMode // byAccessModes is used to order access modes by size, with the fewest modes first type byAccessModes struct { - modes [][]api.PersistentVolumeAccessMode + modes [][]v1.PersistentVolumeAccessMode } func (c byAccessModes) Less(i, j int) bool { @@ -273,10 +273,10 @@ func (c byAccessModes) Len() int { return len(c.modes) } -func claimToClaimKey(claim *api.PersistentVolumeClaim) string { +func claimToClaimKey(claim *v1.PersistentVolumeClaim) string { return fmt.Sprintf("%s/%s", claim.Namespace, claim.Name) } -func claimrefToClaimKey(claimref *api.ObjectReference) string { +func claimrefToClaimKey(claimref *v1.ObjectReference) string { return fmt.Sprintf("%s/%s", claimref.Namespace, claimref.Name) } diff --git a/pkg/controller/volume/persistentvolume/index_test.go b/pkg/controller/volume/persistentvolume/index_test.go index ddb084e4304..45d9d641301 100644 --- a/pkg/controller/volume/persistentvolume/index_test.go +++ b/pkg/controller/volume/persistentvolume/index_test.go @@ -20,11 +20,11 @@ import ( "sort" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/api/unversioned" - storageutil "k8s.io/kubernetes/pkg/apis/storage/util" + "k8s.io/kubernetes/pkg/api/v1" + storageutil "k8s.io/kubernetes/pkg/apis/storage/v1beta1/util" ) func TestMatchVolume(t *testing.T) { @@ -35,20 +35,20 @@ func TestMatchVolume(t *testing.T) { scenarios := map[string]struct { expectedMatch string - claim *api.PersistentVolumeClaim + claim *v1.PersistentVolumeClaim }{ "successful-match-gce-10": { expectedMatch: "gce-pd-10", - claim: &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim: &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{api.ReadOnlyMany, api.ReadWriteOnce}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("8G"), + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadOnlyMany, v1.ReadWriteOnce}, + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("8G"), }, }, }, @@ -56,16 +56,16 @@ func TestMatchVolume(t *testing.T) { }, "successful-match-nfs-5": { expectedMatch: "nfs-5", - claim: &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim: &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{api.ReadOnlyMany, api.ReadWriteOnce, api.ReadWriteMany}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("5G"), + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadOnlyMany, v1.ReadWriteOnce, v1.ReadWriteMany}, + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("5G"), }, }, }, @@ -73,16 +73,16 @@ func TestMatchVolume(t *testing.T) { }, "successful-skip-1g-bound-volume": { expectedMatch: "gce-pd-5", - claim: &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim: &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{api.ReadOnlyMany, api.ReadWriteOnce}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("1G"), + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadOnlyMany, v1.ReadWriteOnce}, + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("1G"), }, }, }, @@ -90,16 +90,16 @@ func TestMatchVolume(t *testing.T) { }, "successful-no-match": { expectedMatch: "", - claim: &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim: &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{api.ReadOnlyMany, api.ReadWriteOnce}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("999G"), + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadOnlyMany, v1.ReadWriteOnce}, + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("999G"), }, }, }, @@ -107,21 +107,21 @@ func TestMatchVolume(t *testing.T) { }, "successful-no-match-due-to-label": { expectedMatch: "", - claim: &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim: &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ Selector: &unversioned.LabelSelector{ MatchLabels: map[string]string{ "should-not-exist": "true", }, }, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadOnlyMany, api.ReadWriteOnce}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("999G"), + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadOnlyMany, v1.ReadWriteOnce}, + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("999G"), }, }, }, @@ -129,21 +129,21 @@ func TestMatchVolume(t *testing.T) { }, "successful-no-match-due-to-size-constraint-with-label-selector": { expectedMatch: "", - claim: &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim: &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ Selector: &unversioned.LabelSelector{ MatchLabels: map[string]string{ "should-exist": "true", }, }, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadOnlyMany, api.ReadWriteOnce}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("20000G"), + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadOnlyMany, v1.ReadWriteOnce}, + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("20000G"), }, }, }, @@ -151,21 +151,21 @@ func TestMatchVolume(t *testing.T) { }, "successful-match-due-with-constraint-and-label-selector": { expectedMatch: "gce-pd-2", - claim: &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim: &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ Selector: &unversioned.LabelSelector{ MatchLabels: map[string]string{ "should-exist": "true", }, }, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("20000G"), + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("20000G"), }, }, }, @@ -173,24 +173,24 @@ func TestMatchVolume(t *testing.T) { }, "successful-match-with-class": { expectedMatch: "gce-pd-silver1", - claim: &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim: &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", Annotations: map[string]string{ storageutil.StorageClassAnnotation: "silver", }, }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, Selector: &unversioned.LabelSelector{ MatchLabels: map[string]string{ "should-exist": "true", }, }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("1G"), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("1G"), }, }, }, @@ -198,19 +198,19 @@ func TestMatchVolume(t *testing.T) { }, "successful-match-with-class-and-labels": { expectedMatch: "gce-pd-silver2", - claim: &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim: &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", Annotations: map[string]string{ storageutil.StorageClassAnnotation: "silver", }, }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("1G"), + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("1G"), }, }, }, @@ -238,53 +238,53 @@ func TestMatchVolume(t *testing.T) { func TestMatchingWithBoundVolumes(t *testing.T) { volumeIndex := newPersistentVolumeOrderedIndex() // two similar volumes, one is bound - pv1 := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv1 := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ UID: "gce-pd-1", Name: "gce001", }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("1G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("1G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce, api.ReadOnlyMany}, + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce, v1.ReadOnlyMany}, // this one we're pretending is already bound - ClaimRef: &api.ObjectReference{UID: "abc123"}, + ClaimRef: &v1.ObjectReference{UID: "abc123"}, }, } - pv2 := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv2 := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ UID: "gce-pd-2", Name: "gce002", }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("1G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("1G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce, api.ReadOnlyMany}, + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce, v1.ReadOnlyMany}, }, } volumeIndex.store.Add(pv1) volumeIndex.store.Add(pv2) - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{api.ReadOnlyMany, api.ReadWriteOnce}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("1G"), + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadOnlyMany, v1.ReadWriteOnce}, + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("1G"), }, }, }, @@ -308,7 +308,7 @@ func TestListByAccessModes(t *testing.T) { volList.store.Add(pv) } - volumes, err := volList.listByAccessModes([]api.PersistentVolumeAccessMode{api.ReadWriteOnce, api.ReadOnlyMany}) + volumes, err := volList.listByAccessModes([]v1.PersistentVolumeAccessMode{v1.ReadWriteOnce, v1.ReadOnlyMany}) if err != nil { t.Error("Unexpected error retrieving volumes by access modes:", err) } @@ -320,7 +320,7 @@ func TestListByAccessModes(t *testing.T) { } } - volumes, err = volList.listByAccessModes([]api.PersistentVolumeAccessMode{api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany}) + volumes, err = volList.listByAccessModes([]v1.PersistentVolumeAccessMode{v1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadWriteMany}) if err != nil { t.Error("Unexpected error retrieving volumes by access modes:", err) } @@ -340,71 +340,71 @@ func TestAllPossibleAccessModes(t *testing.T) { } // the mock PVs creates contain 2 types of accessmodes: RWO+ROX and RWO+ROW+RWX - possibleModes := index.allPossibleMatchingAccessModes([]api.PersistentVolumeAccessMode{api.ReadWriteOnce}) + possibleModes := index.allPossibleMatchingAccessModes([]v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}) if len(possibleModes) != 3 { t.Errorf("Expected 3 arrays of modes that match RWO, but got %v", len(possibleModes)) } for _, m := range possibleModes { - if !contains(m, api.ReadWriteOnce) { - t.Errorf("AccessModes does not contain %s", api.ReadWriteOnce) + if !contains(m, v1.ReadWriteOnce) { + t.Errorf("AccessModes does not contain %s", v1.ReadWriteOnce) } } - possibleModes = index.allPossibleMatchingAccessModes([]api.PersistentVolumeAccessMode{api.ReadWriteMany}) + possibleModes = index.allPossibleMatchingAccessModes([]v1.PersistentVolumeAccessMode{v1.ReadWriteMany}) if len(possibleModes) != 1 { t.Errorf("Expected 1 array of modes that match RWX, but got %v", len(possibleModes)) } - if !contains(possibleModes[0], api.ReadWriteMany) { - t.Errorf("AccessModes does not contain %s", api.ReadWriteOnce) + if !contains(possibleModes[0], v1.ReadWriteMany) { + t.Errorf("AccessModes does not contain %s", v1.ReadWriteOnce) } } func TestFindingVolumeWithDifferentAccessModes(t *testing.T) { - gce := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{UID: "001", Name: "gce"}, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{api.ResourceName(api.ResourceStorage): resource.MustParse("10G")}, - PersistentVolumeSource: api.PersistentVolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}}, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, + gce := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{UID: "001", Name: "gce"}, + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{v1.ResourceName(v1.ResourceStorage): resource.MustParse("10G")}, + PersistentVolumeSource: v1.PersistentVolumeSource{GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}}, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, }, }, } - ebs := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{UID: "002", Name: "ebs"}, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{api.ResourceName(api.ResourceStorage): resource.MustParse("10G")}, - PersistentVolumeSource: api.PersistentVolumeSource{AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{}}, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, + ebs := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{UID: "002", Name: "ebs"}, + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{v1.ResourceName(v1.ResourceStorage): resource.MustParse("10G")}, + PersistentVolumeSource: v1.PersistentVolumeSource{AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{}}, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, }, }, } - nfs := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{UID: "003", Name: "nfs"}, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{api.ResourceName(api.ResourceStorage): resource.MustParse("10G")}, - PersistentVolumeSource: api.PersistentVolumeSource{NFS: &api.NFSVolumeSource{}}, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, + nfs := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{UID: "003", Name: "nfs"}, + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{v1.ResourceName(v1.ResourceStorage): resource.MustParse("10G")}, + PersistentVolumeSource: v1.PersistentVolumeSource{NFS: &v1.NFSVolumeSource{}}, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, - Resources: api.ResourceRequirements{Requests: api.ResourceList{api.ResourceName(api.ResourceStorage): resource.MustParse("1G")}}, + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, + Resources: v1.ResourceRequirements{Requests: v1.ResourceList{v1.ResourceName(v1.ResourceStorage): resource.MustParse("1G")}}, }, } @@ -418,37 +418,37 @@ func TestFindingVolumeWithDifferentAccessModes(t *testing.T) { t.Errorf("Expected %s but got volume %s instead", ebs.Name, volume.Name) } - claim.Spec.AccessModes = []api.PersistentVolumeAccessMode{api.ReadWriteOnce, api.ReadOnlyMany} + claim.Spec.AccessModes = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce, v1.ReadOnlyMany} volume, _ = index.findBestMatchForClaim(claim) if volume.Name != gce.Name { t.Errorf("Expected %s but got volume %s instead", gce.Name, volume.Name) } // order of the requested modes should not matter - claim.Spec.AccessModes = []api.PersistentVolumeAccessMode{api.ReadWriteMany, api.ReadWriteOnce, api.ReadOnlyMany} + claim.Spec.AccessModes = []v1.PersistentVolumeAccessMode{v1.ReadWriteMany, v1.ReadWriteOnce, v1.ReadOnlyMany} volume, _ = index.findBestMatchForClaim(claim) if volume.Name != nfs.Name { t.Errorf("Expected %s but got volume %s instead", nfs.Name, volume.Name) } // fewer modes requested should still match - claim.Spec.AccessModes = []api.PersistentVolumeAccessMode{api.ReadWriteMany} + claim.Spec.AccessModes = []v1.PersistentVolumeAccessMode{v1.ReadWriteMany} volume, _ = index.findBestMatchForClaim(claim) if volume.Name != nfs.Name { t.Errorf("Expected %s but got volume %s instead", nfs.Name, volume.Name) } // pretend the exact match is bound. should get the next level up of modes. - ebs.Spec.ClaimRef = &api.ObjectReference{} - claim.Spec.AccessModes = []api.PersistentVolumeAccessMode{api.ReadWriteOnce} + ebs.Spec.ClaimRef = &v1.ObjectReference{} + claim.Spec.AccessModes = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce} volume, _ = index.findBestMatchForClaim(claim) if volume.Name != gce.Name { t.Errorf("Expected %s but got volume %s instead", gce.Name, volume.Name) } // continue up the levels of modes. - gce.Spec.ClaimRef = &api.ObjectReference{} - claim.Spec.AccessModes = []api.PersistentVolumeAccessMode{api.ReadWriteOnce} + gce.Spec.ClaimRef = &v1.ObjectReference{} + claim.Spec.AccessModes = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce} volume, _ = index.findBestMatchForClaim(claim) if volume.Name != nfs.Name { t.Errorf("Expected %s but got volume %s instead", nfs.Name, volume.Name) @@ -456,171 +456,171 @@ func TestFindingVolumeWithDifferentAccessModes(t *testing.T) { // partial mode request gce.Spec.ClaimRef = nil - claim.Spec.AccessModes = []api.PersistentVolumeAccessMode{api.ReadOnlyMany} + claim.Spec.AccessModes = []v1.PersistentVolumeAccessMode{v1.ReadOnlyMany} volume, _ = index.findBestMatchForClaim(claim) if volume.Name != gce.Name { t.Errorf("Expected %s but got volume %s instead", gce.Name, volume.Name) } } -func createTestVolumes() []*api.PersistentVolume { +func createTestVolumes() []*v1.PersistentVolume { // these volumes are deliberately out-of-order to test indexing and sorting - return []*api.PersistentVolume{ + return []*v1.PersistentVolume{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "gce-pd-10", Name: "gce003", }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("10G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, }, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "gce-pd-20", Name: "gce004", }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("20G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("20G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, }, // this one we're pretending is already bound - ClaimRef: &api.ObjectReference{UID: "def456"}, + ClaimRef: &v1.ObjectReference{UID: "def456"}, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "nfs-5", Name: "nfs002", }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("5G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("5G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - Glusterfs: &api.GlusterfsVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + Glusterfs: &v1.GlusterfsVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, }, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "gce-pd-1", Name: "gce001", }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("1G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("1G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, }, // this one we're pretending is already bound - ClaimRef: &api.ObjectReference{UID: "abc123"}, + ClaimRef: &v1.ObjectReference{UID: "abc123"}, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "nfs-10", Name: "nfs003", }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("10G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - Glusterfs: &api.GlusterfsVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + Glusterfs: &v1.GlusterfsVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, }, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "gce-pd-5", Name: "gce002", }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("5G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("5G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, }, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "nfs-1", Name: "nfs001", }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("1G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("1G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - Glusterfs: &api.GlusterfsVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + Glusterfs: &v1.GlusterfsVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, }, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "gce-pd-2", Name: "gce0022", Labels: map[string]string{ "should-exist": "true", }, }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("20000G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("20000G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, }, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "gce-pd-silver1", Name: "gce0023", Labels: map[string]string{ @@ -630,88 +630,88 @@ func createTestVolumes() []*api.PersistentVolume { storageutil.StorageClassAnnotation: "silver", }, }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10000G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("10000G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, }, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "gce-pd-silver2", Name: "gce0024", Annotations: map[string]string{ storageutil.StorageClassAnnotation: "silver", }, }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("100G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("100G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, }, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "gce-pd-gold", Name: "gce0025", Annotations: map[string]string{ storageutil.StorageClassAnnotation: "gold", }, }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("50G"), + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("50G"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, }, }, }, } } -func testVolume(name, size string) *api.PersistentVolume { - return &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ +func testVolume(name, size string) *v1.PersistentVolume { + return &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: name, Annotations: map[string]string{}, }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{api.ResourceName(api.ResourceStorage): resource.MustParse(size)}, - PersistentVolumeSource: api.PersistentVolumeSource{HostPath: &api.HostPathVolumeSource{}}, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{v1.ResourceName(v1.ResourceStorage): resource.MustParse(size)}, + PersistentVolumeSource: v1.PersistentVolumeSource{HostPath: &v1.HostPathVolumeSource{}}, + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, }, } } func TestFindingPreboundVolumes(t *testing.T) { - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claim01", Namespace: "myns", SelfLink: testapi.Default.SelfLink("pvc", ""), }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, - Resources: api.ResourceRequirements{Requests: api.ResourceList{api.ResourceName(api.ResourceStorage): resource.MustParse("1Gi")}}, + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, + Resources: v1.ResourceRequirements{Requests: v1.ResourceList{v1.ResourceName(v1.ResourceStorage): resource.MustParse("1Gi")}}, }, } - claimRef, err := api.GetReference(claim) + claimRef, err := v1.GetReference(claim) if err != nil { t.Errorf("error getting claimRef: %v", err) } @@ -721,7 +721,7 @@ func TestFindingPreboundVolumes(t *testing.T) { pv8 := testVolume("pv8", "8Gi") pvBadSize := testVolume("pvBadSize", "1Mi") pvBadMode := testVolume("pvBadMode", "1Gi") - pvBadMode.Spec.AccessModes = []api.PersistentVolumeAccessMode{api.ReadOnlyMany} + pvBadMode.Spec.AccessModes = []v1.PersistentVolumeAccessMode{v1.ReadOnlyMany} index := newPersistentVolumeOrderedIndex() index.store.Add(pv1) @@ -737,7 +737,7 @@ func TestFindingPreboundVolumes(t *testing.T) { } // pretend the exact match is pre-bound. should get the next size up. - pv1.Spec.ClaimRef = &api.ObjectReference{Name: "foo", Namespace: "bar"} + pv1.Spec.ClaimRef = &v1.ObjectReference{Name: "foo", Namespace: "bar"} volume, _ = index.findBestMatchForClaim(claim) if volume.Name != pv5.Name { t.Errorf("Expected %s but got volume %s instead", pv5.Name, volume.Name) @@ -770,7 +770,7 @@ func TestFindingPreboundVolumes(t *testing.T) { // byCapacity is used to order volumes by ascending storage size type byCapacity struct { - volumes []*api.PersistentVolume + volumes []*v1.PersistentVolume } func (c byCapacity) Less(i, j int) bool { diff --git a/pkg/controller/volume/persistentvolume/provision_test.go b/pkg/controller/volume/persistentvolume/provision_test.go index 2f253d9e35f..fac6186b3e5 100644 --- a/pkg/controller/volume/persistentvolume/provision_test.go +++ b/pkg/controller/volume/persistentvolume/provision_test.go @@ -20,10 +20,10 @@ import ( "errors" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/storage" - storageutil "k8s.io/kubernetes/pkg/apis/storage/util" + "k8s.io/kubernetes/pkg/api/v1" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" + storageutil "k8s.io/kubernetes/pkg/apis/storage/v1beta1/util" ) var class1Parameters = map[string]string{ @@ -38,7 +38,7 @@ var storageClasses = []*storage.StorageClass{ Kind: "StorageClass", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "gold", }, @@ -49,7 +49,7 @@ var storageClasses = []*storage.StorageClass{ TypeMeta: unversioned.TypeMeta{ Kind: "StorageClass", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "silver", }, Provisioner: mockPluginName, @@ -59,7 +59,7 @@ var storageClasses = []*storage.StorageClass{ TypeMeta: unversioned.TypeMeta{ Kind: "StorageClass", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "external", }, Provisioner: "vendor.com/my-volume", @@ -69,7 +69,7 @@ var storageClasses = []*storage.StorageClass{ TypeMeta: unversioned.TypeMeta{ Kind: "StorageClass", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "unknown-internal", }, Provisioner: "kubernetes.io/unknown", @@ -109,10 +109,10 @@ func TestProvisionSync(t *testing.T) { // Provision a volume (with a default class) "11-1 - successful provision with storage class 1", novolumes, - newVolumeArray("pvc-uid11-1", "1Gi", "uid11-1", "claim11-1", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned, storageutil.StorageClassAnnotation), - newClaimArray("claim11-1", "uid11-1", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), + newVolumeArray("pvc-uid11-1", "1Gi", "uid11-1", "claim11-1", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned, storageutil.StorageClassAnnotation), + newClaimArray("claim11-1", "uid11-1", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), // Binding will be completed in the next syncClaim - newClaimArray("claim11-1", "uid11-1", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), + newClaimArray("claim11-1", "uid11-1", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), noevents, noerrors, wrapTestWithProvisionCalls([]provisionCall{provision1Success}, testSyncClaim), }, { @@ -120,8 +120,8 @@ func TestProvisionSync(t *testing.T) { "11-2 - plugin not found", novolumes, novolumes, - newClaimArray("claim11-2", "uid11-2", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), - newClaimArray("claim11-2", "uid11-2", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), + newClaimArray("claim11-2", "uid11-2", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), + newClaimArray("claim11-2", "uid11-2", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), []string{"Warning ProvisioningFailed"}, noerrors, testSyncClaim, }, @@ -130,8 +130,8 @@ func TestProvisionSync(t *testing.T) { "11-3 - newProvisioner failure", novolumes, novolumes, - newClaimArray("claim11-3", "uid11-3", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), - newClaimArray("claim11-3", "uid11-3", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), + newClaimArray("claim11-3", "uid11-3", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), + newClaimArray("claim11-3", "uid11-3", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), []string{"Warning ProvisioningFailed"}, noerrors, wrapTestWithProvisionCalls([]provisionCall{}, testSyncClaim), }, @@ -140,18 +140,18 @@ func TestProvisionSync(t *testing.T) { "11-4 - provision failure", novolumes, novolumes, - newClaimArray("claim11-4", "uid11-4", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), - newClaimArray("claim11-4", "uid11-4", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), + newClaimArray("claim11-4", "uid11-4", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), + newClaimArray("claim11-4", "uid11-4", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), []string{"Warning ProvisioningFailed"}, noerrors, wrapTestWithProvisionCalls([]provisionCall{provision1Error}, testSyncClaim), }, { // No provisioning if there is a matching volume available "11-6 - provisioning when there is a volume available", - newVolumeArray("volume11-6", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain, storageutil.StorageClassAnnotation), - newVolumeArray("volume11-6", "1Gi", "uid11-6", "claim11-6", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController, storageutil.StorageClassAnnotation), - newClaimArray("claim11-6", "uid11-6", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), - newClaimArray("claim11-6", "uid11-6", "1Gi", "volume11-6", api.ClaimBound, storageutil.StorageClassAnnotation, annBoundByController, annBindCompleted), + newVolumeArray("volume11-6", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain, storageutil.StorageClassAnnotation), + newVolumeArray("volume11-6", "1Gi", "uid11-6", "claim11-6", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController, storageutil.StorageClassAnnotation), + newClaimArray("claim11-6", "uid11-6", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), + newClaimArray("claim11-6", "uid11-6", "1Gi", "volume11-6", v1.ClaimBound, storageutil.StorageClassAnnotation, annBoundByController, annBindCompleted), noevents, noerrors, // No provisioning plugin confingure - makes the test fail when // the controller errorneously tries to provision something @@ -162,16 +162,16 @@ func TestProvisionSync(t *testing.T) { // a volume. "11-7 - claim is bound before provisioning", novolumes, - newVolumeArray("pvc-uid11-7", "1Gi", "uid11-7", "claim11-7", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned, storageutil.StorageClassAnnotation), - newClaimArray("claim11-7", "uid11-7", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), + newVolumeArray("pvc-uid11-7", "1Gi", "uid11-7", "claim11-7", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned, storageutil.StorageClassAnnotation), + newClaimArray("claim11-7", "uid11-7", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), // The claim would be bound in next syncClaim - newClaimArray("claim11-7", "uid11-7", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), + newClaimArray("claim11-7", "uid11-7", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), noevents, noerrors, wrapTestWithInjectedOperation(wrapTestWithProvisionCalls([]provisionCall{}, testSyncClaim), func(ctrl *PersistentVolumeController, reactor *volumeReactor) { // Create a volume before provisionClaimOperation starts. // This similates a parallel controller provisioning the volume. reactor.lock.Lock() - volume := newVolume("pvc-uid11-7", "1Gi", "uid11-7", "claim11-7", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned, storageutil.StorageClassAnnotation) + volume := newVolume("pvc-uid11-7", "1Gi", "uid11-7", "claim11-7", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned, storageutil.StorageClassAnnotation) reactor.volumes[volume.Name] = volume reactor.lock.Unlock() }), @@ -181,10 +181,10 @@ func TestProvisionSync(t *testing.T) { // second retry succeeds "11-8 - cannot save provisioned volume", novolumes, - newVolumeArray("pvc-uid11-8", "1Gi", "uid11-8", "claim11-8", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned, storageutil.StorageClassAnnotation), - newClaimArray("claim11-8", "uid11-8", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), + newVolumeArray("pvc-uid11-8", "1Gi", "uid11-8", "claim11-8", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned, storageutil.StorageClassAnnotation), + newClaimArray("claim11-8", "uid11-8", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), // Binding will be completed in the next syncClaim - newClaimArray("claim11-8", "uid11-8", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), + newClaimArray("claim11-8", "uid11-8", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), noevents, []reactorError{ // Inject error to the first @@ -200,8 +200,8 @@ func TestProvisionSync(t *testing.T) { "11-9 - cannot save provisioned volume, delete succeeds", novolumes, novolumes, - newClaimArray("claim11-9", "uid11-9", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), - newClaimArray("claim11-9", "uid11-9", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), + newClaimArray("claim11-9", "uid11-9", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), + newClaimArray("claim11-9", "uid11-9", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), []string{"Warning ProvisioningFailed"}, []reactorError{ // Inject error to five kubeclient.PersistentVolumes.Create() @@ -225,8 +225,8 @@ func TestProvisionSync(t *testing.T) { "11-10 - cannot save provisioned volume, no delete plugin found", novolumes, novolumes, - newClaimArray("claim11-10", "uid11-10", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), - newClaimArray("claim11-10", "uid11-10", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), + newClaimArray("claim11-10", "uid11-10", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), + newClaimArray("claim11-10", "uid11-10", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), []string{"Warning ProvisioningFailed", "Warning ProvisioningCleanupFailed"}, []reactorError{ // Inject error to five kubeclient.PersistentVolumes.Create() @@ -246,8 +246,8 @@ func TestProvisionSync(t *testing.T) { "11-11 - cannot save provisioned volume, deleter fails", novolumes, novolumes, - newClaimArray("claim11-11", "uid11-11", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), - newClaimArray("claim11-11", "uid11-11", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), + newClaimArray("claim11-11", "uid11-11", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), + newClaimArray("claim11-11", "uid11-11", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), []string{"Warning ProvisioningFailed", "Warning ProvisioningCleanupFailed"}, []reactorError{ // Inject error to five kubeclient.PersistentVolumes.Create() @@ -276,8 +276,8 @@ func TestProvisionSync(t *testing.T) { "11-12 - cannot save provisioned volume, delete succeeds 2nd time", novolumes, novolumes, - newClaimArray("claim11-12", "uid11-12", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), - newClaimArray("claim11-12", "uid11-12", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), + newClaimArray("claim11-12", "uid11-12", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), + newClaimArray("claim11-12", "uid11-12", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation, annStorageProvisioner), []string{"Warning ProvisioningFailed"}, []reactorError{ // Inject error to five kubeclient.PersistentVolumes.Create() @@ -302,10 +302,10 @@ func TestProvisionSync(t *testing.T) { // Provision a volume (with non-default class) "11-13 - successful provision with storage class 2", novolumes, - volumeWithClass("silver", newVolumeArray("pvc-uid11-13", "1Gi", "uid11-13", "claim11-13", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned)), - claimWithClass("silver", newClaimArray("claim11-13", "uid11-13", "1Gi", "", api.ClaimPending)), + volumeWithClass("silver", newVolumeArray("pvc-uid11-13", "1Gi", "uid11-13", "claim11-13", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned)), + claimWithClass("silver", newClaimArray("claim11-13", "uid11-13", "1Gi", "", v1.ClaimPending)), // Binding will be completed in the next syncClaim - claimWithClass("silver", newClaimArray("claim11-13", "uid11-13", "1Gi", "", api.ClaimPending, annStorageProvisioner)), + claimWithClass("silver", newClaimArray("claim11-13", "uid11-13", "1Gi", "", v1.ClaimPending, annStorageProvisioner)), noevents, noerrors, wrapTestWithProvisionCalls([]provisionCall{provision2Success}, testSyncClaim), }, { @@ -313,8 +313,8 @@ func TestProvisionSync(t *testing.T) { "11-14 - fail due to non-existing class", novolumes, novolumes, - claimWithClass("non-existing", newClaimArray("claim11-14", "uid11-14", "1Gi", "", api.ClaimPending)), - claimWithClass("non-existing", newClaimArray("claim11-14", "uid11-14", "1Gi", "", api.ClaimPending)), + claimWithClass("non-existing", newClaimArray("claim11-14", "uid11-14", "1Gi", "", v1.ClaimPending)), + claimWithClass("non-existing", newClaimArray("claim11-14", "uid11-14", "1Gi", "", v1.ClaimPending)), noevents, noerrors, wrapTestWithProvisionCalls([]provisionCall{}, testSyncClaim), }, { @@ -322,8 +322,8 @@ func TestProvisionSync(t *testing.T) { "11-15 - no provisioning with class=''", novolumes, novolumes, - claimWithClass("", newClaimArray("claim11-15", "uid11-15", "1Gi", "", api.ClaimPending)), - claimWithClass("", newClaimArray("claim11-15", "uid11-15", "1Gi", "", api.ClaimPending)), + claimWithClass("", newClaimArray("claim11-15", "uid11-15", "1Gi", "", v1.ClaimPending)), + claimWithClass("", newClaimArray("claim11-15", "uid11-15", "1Gi", "", v1.ClaimPending)), noevents, noerrors, wrapTestWithProvisionCalls([]provisionCall{}, testSyncClaim), }, { @@ -331,8 +331,8 @@ func TestProvisionSync(t *testing.T) { "11-16 - no provisioning with class=nil", novolumes, novolumes, - newClaimArray("claim11-15", "uid11-15", "1Gi", "", api.ClaimPending), - newClaimArray("claim11-15", "uid11-15", "1Gi", "", api.ClaimPending), + newClaimArray("claim11-15", "uid11-15", "1Gi", "", v1.ClaimPending), + newClaimArray("claim11-15", "uid11-15", "1Gi", "", v1.ClaimPending), noevents, noerrors, wrapTestWithProvisionCalls([]provisionCall{}, testSyncClaim), }, { @@ -340,9 +340,9 @@ func TestProvisionSync(t *testing.T) { "11-17 - external provisioner", novolumes, novolumes, - claimWithClass("external", newClaimArray("claim11-17", "uid11-17", "1Gi", "", api.ClaimPending)), + claimWithClass("external", newClaimArray("claim11-17", "uid11-17", "1Gi", "", v1.ClaimPending)), claimWithAnnotation(annStorageProvisioner, "vendor.com/my-volume", - claimWithClass("external", newClaimArray("claim11-17", "uid11-17", "1Gi", "", api.ClaimPending))), + claimWithClass("external", newClaimArray("claim11-17", "uid11-17", "1Gi", "", v1.ClaimPending))), []string{"Normal ExternalProvisioning"}, noerrors, wrapTestWithProvisionCalls([]provisionCall{}, testSyncClaim), }, @@ -351,8 +351,8 @@ func TestProvisionSync(t *testing.T) { "11-18 - unknown internal provisioner", novolumes, novolumes, - claimWithClass("unknown-internal", newClaimArray("claim11-18", "uid11-18", "1Gi", "", api.ClaimPending)), - claimWithClass("unknown-internal", newClaimArray("claim11-18", "uid11-18", "1Gi", "", api.ClaimPending)), + claimWithClass("unknown-internal", newClaimArray("claim11-18", "uid11-18", "1Gi", "", v1.ClaimPending)), + claimWithClass("unknown-internal", newClaimArray("claim11-18", "uid11-18", "1Gi", "", v1.ClaimPending)), []string{"Warning ProvisioningFailed"}, noerrors, wrapTestWithProvisionCalls([]provisionCall{}, testSyncClaim), }, @@ -366,24 +366,24 @@ func TestAlphaProvisionSync(t *testing.T) { // Provision a volume with alpha annotation "14-1 - successful alpha provisioning", novolumes, - newVolumeArray("pvc-uid14-1", "1Gi", "uid14-1", "claim14-1", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned), - newClaimArray("claim14-1", "uid14-1", "1Gi", "", api.ClaimPending, storageutil.AlphaStorageClassAnnotation), + newVolumeArray("pvc-uid14-1", "1Gi", "uid14-1", "claim14-1", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned), + newClaimArray("claim14-1", "uid14-1", "1Gi", "", v1.ClaimPending, storageutil.AlphaStorageClassAnnotation), // Binding will be completed in the next syncClaim - newClaimArray("claim14-1", "uid14-1", "1Gi", "", api.ClaimPending, storageutil.AlphaStorageClassAnnotation, annStorageProvisioner), + newClaimArray("claim14-1", "uid14-1", "1Gi", "", v1.ClaimPending, storageutil.AlphaStorageClassAnnotation, annStorageProvisioner), noevents, noerrors, wrapTestWithProvisionCalls([]provisionCall{provisionAlphaSuccess}, testSyncClaim), }, { // Provision success - there is already a volume available, still // we provision a new one when requested. "14-2 - no alpha provisioning when there is a volume available", - newVolumeArray("volume14-2", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - []*api.PersistentVolume{ - newVolume("volume14-2", "1Gi", "", "", api.VolumePending, api.PersistentVolumeReclaimRetain), - newVolume("pvc-uid14-2", "1Gi", "uid14-2", "claim14-2", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned), + newVolumeArray("volume14-2", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + []*v1.PersistentVolume{ + newVolume("volume14-2", "1Gi", "", "", v1.VolumePending, v1.PersistentVolumeReclaimRetain), + newVolume("pvc-uid14-2", "1Gi", "uid14-2", "claim14-2", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned), }, - newClaimArray("claim14-2", "uid14-2", "1Gi", "", api.ClaimPending, storageutil.AlphaStorageClassAnnotation), + newClaimArray("claim14-2", "uid14-2", "1Gi", "", v1.ClaimPending, storageutil.AlphaStorageClassAnnotation), // Binding will be completed in the next syncClaim - newClaimArray("claim14-2", "uid14-2", "1Gi", "", api.ClaimPending, storageutil.AlphaStorageClassAnnotation, annStorageProvisioner), + newClaimArray("claim14-2", "uid14-2", "1Gi", "", v1.ClaimPending, storageutil.AlphaStorageClassAnnotation, annStorageProvisioner), noevents, noerrors, wrapTestWithProvisionCalls([]provisionCall{provisionAlphaSuccess}, testSyncClaim), }, } @@ -410,9 +410,9 @@ func TestProvisionMultiSync(t *testing.T) { // Provision a volume with binding "12-1 - successful provision", novolumes, - newVolumeArray("pvc-uid12-1", "1Gi", "uid12-1", "claim12-1", api.VolumeBound, api.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned, storageutil.StorageClassAnnotation), - newClaimArray("claim12-1", "uid12-1", "1Gi", "", api.ClaimPending, storageutil.StorageClassAnnotation), - newClaimArray("claim12-1", "uid12-1", "1Gi", "pvc-uid12-1", api.ClaimBound, storageutil.StorageClassAnnotation, annBoundByController, annBindCompleted, annStorageProvisioner), + newVolumeArray("pvc-uid12-1", "1Gi", "uid12-1", "claim12-1", v1.VolumeBound, v1.PersistentVolumeReclaimDelete, annBoundByController, annDynamicallyProvisioned, storageutil.StorageClassAnnotation), + newClaimArray("claim12-1", "uid12-1", "1Gi", "", v1.ClaimPending, storageutil.StorageClassAnnotation), + newClaimArray("claim12-1", "uid12-1", "1Gi", "pvc-uid12-1", v1.ClaimBound, storageutil.StorageClassAnnotation, annBoundByController, annBindCompleted, annStorageProvisioner), noevents, noerrors, wrapTestWithProvisionCalls([]provisionCall{provision1Success}, testSyncClaim), }, } diff --git a/pkg/controller/volume/persistentvolume/pv_controller.go b/pkg/controller/volume/persistentvolume/pv_controller.go index 8a555498e2b..e15d6a8d76f 100644 --- a/pkg/controller/volume/persistentvolume/pv_controller.go +++ b/pkg/controller/volume/persistentvolume/pv_controller.go @@ -22,12 +22,12 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/storage" - storageutil "k8s.io/kubernetes/pkg/apis/storage/util" + "k8s.io/kubernetes/pkg/api/v1" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" + storageutil "k8s.io/kubernetes/pkg/apis/storage/v1beta1/util" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/conversion" @@ -188,10 +188,10 @@ type PersistentVolumeController struct { // these events. // For easier readability, it was split into syncUnboundClaim and syncBoundClaim // methods. -func (ctrl *PersistentVolumeController) syncClaim(claim *api.PersistentVolumeClaim) error { +func (ctrl *PersistentVolumeController) syncClaim(claim *v1.PersistentVolumeClaim) error { glog.V(4).Infof("synchronizing PersistentVolumeClaim[%s]: %s", claimToClaimKey(claim), getClaimStatusForLogging(claim)) - if !api.HasAnnotation(claim.ObjectMeta, annBindCompleted) { + if !v1.HasAnnotation(claim.ObjectMeta, annBindCompleted) { return ctrl.syncUnboundClaim(claim) } else { return ctrl.syncBoundClaim(claim) @@ -200,7 +200,7 @@ func (ctrl *PersistentVolumeController) syncClaim(claim *api.PersistentVolumeCla // syncUnboundClaim is the main controller method to decide what to do with an // unbound claim. -func (ctrl *PersistentVolumeController) syncUnboundClaim(claim *api.PersistentVolumeClaim) error { +func (ctrl *PersistentVolumeController) syncUnboundClaim(claim *v1.PersistentVolumeClaim) error { // This is a new PVC that has not completed binding // OBSERVATION: pvc is "Pending" if claim.Spec.VolumeName == "" { @@ -216,7 +216,7 @@ func (ctrl *PersistentVolumeController) syncUnboundClaim(claim *api.PersistentVo glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: no volume found", claimToClaimKey(claim)) // No PV could be found // OBSERVATION: pvc is "Pending", will retry - if storageutil.GetClaimStorageClass(claim) != "" || api.HasAnnotation(claim.ObjectMeta, storageutil.AlphaStorageClassAnnotation) { + if storageutil.GetClaimStorageClass(claim) != "" || v1.HasAnnotation(claim.ObjectMeta, storageutil.AlphaStorageClassAnnotation) { if err = ctrl.provisionClaim(claim); err != nil { return err } @@ -224,7 +224,7 @@ func (ctrl *PersistentVolumeController) syncUnboundClaim(claim *api.PersistentVo } // Mark the claim as Pending and try to find a match in the next // periodic syncClaim - if _, err = ctrl.updateClaimStatus(claim, api.ClaimPending, nil); err != nil { + if _, err = ctrl.updateClaimStatus(claim, v1.ClaimPending, nil); err != nil { return err } return nil @@ -253,12 +253,12 @@ func (ctrl *PersistentVolumeController) syncUnboundClaim(claim *api.PersistentVo // OBSERVATION: pvc is "Pending" // Retry later. glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume %q requested and not found, will try again next time", claimToClaimKey(claim), claim.Spec.VolumeName) - if _, err = ctrl.updateClaimStatus(claim, api.ClaimPending, nil); err != nil { + if _, err = ctrl.updateClaimStatus(claim, v1.ClaimPending, nil); err != nil { return err } return nil } else { - volume, ok := obj.(*api.PersistentVolume) + volume, ok := obj.(*v1.PersistentVolume) if !ok { return fmt.Errorf("Cannot convert object from volume cache to volume %q!?: %+v", claim.Spec.VolumeName, obj) } @@ -288,10 +288,10 @@ func (ctrl *PersistentVolumeController) syncUnboundClaim(claim *api.PersistentVo } else { // User asked for a PV that is claimed by someone else // OBSERVATION: pvc is "Pending", pv is "Bound" - if !api.HasAnnotation(claim.ObjectMeta, annBoundByController) { + if !v1.HasAnnotation(claim.ObjectMeta, annBoundByController) { glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume already bound to different claim by user, will retry later", claimToClaimKey(claim)) // User asked for a specific PV, retry later - if _, err = ctrl.updateClaimStatus(claim, api.ClaimPending, nil); err != nil { + if _, err = ctrl.updateClaimStatus(claim, v1.ClaimPending, nil); err != nil { return err } return nil @@ -308,14 +308,14 @@ func (ctrl *PersistentVolumeController) syncUnboundClaim(claim *api.PersistentVo // syncBoundClaim is the main controller method to decide what to do with a // bound claim. -func (ctrl *PersistentVolumeController) syncBoundClaim(claim *api.PersistentVolumeClaim) error { +func (ctrl *PersistentVolumeController) syncBoundClaim(claim *v1.PersistentVolumeClaim) error { // HasAnnotation(pvc, annBindCompleted) // This PVC has previously been bound // OBSERVATION: pvc is not "Pending" // [Unit test set 3] if claim.Spec.VolumeName == "" { // Claim was bound before but not any more. - if _, err := ctrl.updateClaimStatusWithEvent(claim, api.ClaimLost, nil, api.EventTypeWarning, "ClaimLost", "Bound claim has lost reference to PersistentVolume. Data on the volume is lost!"); err != nil { + if _, err := ctrl.updateClaimStatusWithEvent(claim, v1.ClaimLost, nil, v1.EventTypeWarning, "ClaimLost", "Bound claim has lost reference to PersistentVolume. Data on the volume is lost!"); err != nil { return err } return nil @@ -326,12 +326,12 @@ func (ctrl *PersistentVolumeController) syncBoundClaim(claim *api.PersistentVolu } if !found { // Claim is bound to a non-existing volume. - if _, err = ctrl.updateClaimStatusWithEvent(claim, api.ClaimLost, nil, api.EventTypeWarning, "ClaimLost", "Bound claim has lost its PersistentVolume. Data on the volume is lost!"); err != nil { + if _, err = ctrl.updateClaimStatusWithEvent(claim, v1.ClaimLost, nil, v1.EventTypeWarning, "ClaimLost", "Bound claim has lost its PersistentVolume. Data on the volume is lost!"); err != nil { return err } return nil } else { - volume, ok := obj.(*api.PersistentVolume) + volume, ok := obj.(*v1.PersistentVolume) if !ok { return fmt.Errorf("Cannot convert object from volume cache to volume %q!?: %#v", claim.Spec.VolumeName, obj) } @@ -363,7 +363,7 @@ func (ctrl *PersistentVolumeController) syncBoundClaim(claim *api.PersistentVolu // Claim is bound but volume has a different claimant. // Set the claim phase to 'Lost', which is a terminal // phase. - if _, err = ctrl.updateClaimStatusWithEvent(claim, api.ClaimLost, nil, api.EventTypeWarning, "ClaimMisbound", "Two claims are bound to the same volume, this one is bound incorrectly"); err != nil { + if _, err = ctrl.updateClaimStatusWithEvent(claim, v1.ClaimLost, nil, v1.EventTypeWarning, "ClaimMisbound", "Two claims are bound to the same volume, this one is bound incorrectly"); err != nil { return err } return nil @@ -375,14 +375,14 @@ func (ctrl *PersistentVolumeController) syncBoundClaim(claim *api.PersistentVolu // It's invoked by appropriate cache.Controller callbacks when a volume is // created, updated or periodically synced. We do not differentiate between // these events. -func (ctrl *PersistentVolumeController) syncVolume(volume *api.PersistentVolume) error { +func (ctrl *PersistentVolumeController) syncVolume(volume *v1.PersistentVolume) error { glog.V(4).Infof("synchronizing PersistentVolume[%s]: %s", volume.Name, getVolumeStatusForLogging(volume)) // [Unit test set 4] if volume.Spec.ClaimRef == nil { // Volume is unused glog.V(4).Infof("synchronizing PersistentVolume[%s]: volume is unused", volume.Name) - if _, err := ctrl.updateVolumePhase(volume, api.VolumeAvailable, ""); err != nil { + if _, err := ctrl.updateVolumePhase(volume, v1.VolumeAvailable, ""); err != nil { // Nothing was saved; we will fall back into the same // condition in the next call to this method return err @@ -394,7 +394,7 @@ func (ctrl *PersistentVolumeController) syncVolume(volume *api.PersistentVolume) // The PV is reserved for a PVC; that PVC has not yet been // bound to this PV; the PVC sync will handle it. glog.V(4).Infof("synchronizing PersistentVolume[%s]: volume is pre-bound to claim %s", volume.Name, claimrefToClaimKey(volume.Spec.ClaimRef)) - if _, err := ctrl.updateVolumePhase(volume, api.VolumeAvailable, ""); err != nil { + if _, err := ctrl.updateVolumePhase(volume, v1.VolumeAvailable, ""); err != nil { // Nothing was saved; we will fall back into the same // condition in the next call to this method return err @@ -403,7 +403,7 @@ func (ctrl *PersistentVolumeController) syncVolume(volume *api.PersistentVolume) } glog.V(4).Infof("synchronizing PersistentVolume[%s]: volume is bound to claim %s", volume.Name, claimrefToClaimKey(volume.Spec.ClaimRef)) // Get the PVC by _name_ - var claim *api.PersistentVolumeClaim + var claim *v1.PersistentVolumeClaim claimName := claimrefToClaimKey(volume.Spec.ClaimRef) obj, found, err := ctrl.claims.GetByKey(claimName) if err != nil { @@ -414,7 +414,7 @@ func (ctrl *PersistentVolumeController) syncVolume(volume *api.PersistentVolume) // Fall through with claim = nil } else { var ok bool - claim, ok = obj.(*api.PersistentVolumeClaim) + claim, ok = obj.(*v1.PersistentVolumeClaim) if !ok { return fmt.Errorf("Cannot convert object from volume cache to volume %q!?: %#v", claim.Spec.VolumeName, obj) } @@ -436,10 +436,10 @@ func (ctrl *PersistentVolumeController) syncVolume(volume *api.PersistentVolume) // Do not overwrite previous Failed state - let the user see that // something went wrong, while we still re-try to reclaim the // volume. - if volume.Status.Phase != api.VolumeReleased && volume.Status.Phase != api.VolumeFailed { + if volume.Status.Phase != v1.VolumeReleased && volume.Status.Phase != v1.VolumeFailed { // Also, log this only once: glog.V(2).Infof("volume %q is released and reclaim policy %q will be executed", volume.Name, volume.Spec.PersistentVolumeReclaimPolicy) - if volume, err = ctrl.updateVolumePhase(volume, api.VolumeReleased, ""); err != nil { + if volume, err = ctrl.updateVolumePhase(volume, v1.VolumeReleased, ""); err != nil { // Nothing was saved; we will fall back into the same condition // in the next call to this method return err @@ -453,7 +453,7 @@ func (ctrl *PersistentVolumeController) syncVolume(volume *api.PersistentVolume) } return nil } else if claim.Spec.VolumeName == "" { - if api.HasAnnotation(volume.ObjectMeta, annBoundByController) { + if v1.HasAnnotation(volume.ObjectMeta, annBoundByController) { // The binding is not completed; let PVC sync handle it glog.V(4).Infof("synchronizing PersistentVolume[%s]: volume not bound yet, waiting for syncClaim to fix it", volume.Name) } else { @@ -480,7 +480,7 @@ func (ctrl *PersistentVolumeController) syncVolume(volume *api.PersistentVolume) } else if claim.Spec.VolumeName == volume.Name { // Volume is bound to a claim properly, update status if necessary glog.V(4).Infof("synchronizing PersistentVolume[%s]: all is bound", volume.Name) - if _, err = ctrl.updateVolumePhase(volume, api.VolumeBound, ""); err != nil { + if _, err = ctrl.updateVolumePhase(volume, v1.VolumeBound, ""); err != nil { // Nothing was saved; we will fall back into the same // condition in the next call to this method return err @@ -488,16 +488,16 @@ func (ctrl *PersistentVolumeController) syncVolume(volume *api.PersistentVolume) return nil } else { // Volume is bound to a claim, but the claim is bound elsewhere - if api.HasAnnotation(volume.ObjectMeta, annDynamicallyProvisioned) && volume.Spec.PersistentVolumeReclaimPolicy == api.PersistentVolumeReclaimDelete { + if v1.HasAnnotation(volume.ObjectMeta, annDynamicallyProvisioned) && volume.Spec.PersistentVolumeReclaimPolicy == v1.PersistentVolumeReclaimDelete { // This volume was dynamically provisioned for this claim. The // claim got bound elsewhere, and thus this volume is not // needed. Delete it. // Mark the volume as Released for external deleters and to let // the user know. Don't overwrite existing Failed status! - if volume.Status.Phase != api.VolumeReleased && volume.Status.Phase != api.VolumeFailed { + if volume.Status.Phase != v1.VolumeReleased && volume.Status.Phase != v1.VolumeFailed { // Also, log this only once: glog.V(2).Infof("dynamically volume %q is released and it will be deleted", volume.Name) - if volume, err = ctrl.updateVolumePhase(volume, api.VolumeReleased, ""); err != nil { + if volume, err = ctrl.updateVolumePhase(volume, v1.VolumeReleased, ""); err != nil { // Nothing was saved; we will fall back into the same condition // in the next call to this method return err @@ -512,7 +512,7 @@ func (ctrl *PersistentVolumeController) syncVolume(volume *api.PersistentVolume) } else { // Volume is bound to a claim, but the claim is bound elsewhere // and it's not dynamically provisioned. - if api.HasAnnotation(volume.ObjectMeta, annBoundByController) { + if v1.HasAnnotation(volume.ObjectMeta, annBoundByController) { // This is part of the normal operation of the controller; the // controller tried to use this volume for a claim but the claim // was fulfilled by another volume. We did this; fix it. @@ -542,7 +542,7 @@ func (ctrl *PersistentVolumeController) syncVolume(volume *api.PersistentVolume) // claim - claim to update // phasephase - phase to set // volume - volume which Capacity is set into claim.Status.Capacity -func (ctrl *PersistentVolumeController) updateClaimStatus(claim *api.PersistentVolumeClaim, phase api.PersistentVolumeClaimPhase, volume *api.PersistentVolume) (*api.PersistentVolumeClaim, error) { +func (ctrl *PersistentVolumeController) updateClaimStatus(claim *v1.PersistentVolumeClaim, phase v1.PersistentVolumeClaimPhase, volume *v1.PersistentVolume) (*v1.PersistentVolumeClaim, error) { glog.V(4).Infof("updating PersistentVolumeClaim[%s] status: set phase %s", claimToClaimKey(claim), phase) dirty := false @@ -551,7 +551,7 @@ func (ctrl *PersistentVolumeController) updateClaimStatus(claim *api.PersistentV if err != nil { return nil, fmt.Errorf("Error cloning claim: %v", err) } - claimClone, ok := clone.(*api.PersistentVolumeClaim) + claimClone, ok := clone.(*v1.PersistentVolumeClaim) if !ok { return nil, fmt.Errorf("Unexpected claim cast error : %v", claimClone) } @@ -578,11 +578,11 @@ func (ctrl *PersistentVolumeController) updateClaimStatus(claim *api.PersistentV dirty = true } - volumeCap, ok := volume.Spec.Capacity[api.ResourceStorage] + volumeCap, ok := volume.Spec.Capacity[v1.ResourceStorage] if !ok { return nil, fmt.Errorf("PersistentVolume %q is without a storage capacity", volume.Name) } - claimCap, ok := claim.Status.Capacity[api.ResourceStorage] + claimCap, ok := claim.Status.Capacity[v1.ResourceStorage] if !ok || volumeCap.Cmp(claimCap) != 0 { claimClone.Status.Capacity = volume.Spec.Capacity dirty = true @@ -617,7 +617,7 @@ func (ctrl *PersistentVolumeController) updateClaimStatus(claim *api.PersistentV // phasephase - phase to set // volume - volume which Capacity is set into claim.Status.Capacity // eventtype, reason, message - event to send, see EventRecorder.Event() -func (ctrl *PersistentVolumeController) updateClaimStatusWithEvent(claim *api.PersistentVolumeClaim, phase api.PersistentVolumeClaimPhase, volume *api.PersistentVolume, eventtype, reason, message string) (*api.PersistentVolumeClaim, error) { +func (ctrl *PersistentVolumeController) updateClaimStatusWithEvent(claim *v1.PersistentVolumeClaim, phase v1.PersistentVolumeClaimPhase, volume *v1.PersistentVolume, eventtype, reason, message string) (*v1.PersistentVolumeClaim, error) { glog.V(4).Infof("updating updateClaimStatusWithEvent[%s]: set phase %s", claimToClaimKey(claim), phase) if claim.Status.Phase == phase { // Nothing to do. @@ -639,7 +639,7 @@ func (ctrl *PersistentVolumeController) updateClaimStatusWithEvent(claim *api.Pe } // updateVolumePhase saves new volume phase to API server. -func (ctrl *PersistentVolumeController) updateVolumePhase(volume *api.PersistentVolume, phase api.PersistentVolumePhase, message string) (*api.PersistentVolume, error) { +func (ctrl *PersistentVolumeController) updateVolumePhase(volume *v1.PersistentVolume, phase v1.PersistentVolumePhase, message string) (*v1.PersistentVolume, error) { glog.V(4).Infof("updating PersistentVolume[%s]: set phase %s", volume.Name, phase) if volume.Status.Phase == phase { // Nothing to do. @@ -651,7 +651,7 @@ func (ctrl *PersistentVolumeController) updateVolumePhase(volume *api.Persistent if err != nil { return nil, fmt.Errorf("Error cloning claim: %v", err) } - volumeClone, ok := clone.(*api.PersistentVolume) + volumeClone, ok := clone.(*v1.PersistentVolume) if !ok { return nil, fmt.Errorf("Unexpected volume cast error : %v", volumeClone) } @@ -676,7 +676,7 @@ func (ctrl *PersistentVolumeController) updateVolumePhase(volume *api.Persistent // updateVolumePhaseWithEvent saves new volume phase to API server and emits // given event on the volume. It saves the phase and emits the event only when // the phase has actually changed from the version saved in API server. -func (ctrl *PersistentVolumeController) updateVolumePhaseWithEvent(volume *api.PersistentVolume, phase api.PersistentVolumePhase, eventtype, reason, message string) (*api.PersistentVolume, error) { +func (ctrl *PersistentVolumeController) updateVolumePhaseWithEvent(volume *v1.PersistentVolume, phase v1.PersistentVolumePhase, eventtype, reason, message string) (*v1.PersistentVolume, error) { glog.V(4).Infof("updating updateVolumePhaseWithEvent[%s]: set phase %s", volume.Name, phase) if volume.Status.Phase == phase { // Nothing to do. @@ -699,7 +699,7 @@ func (ctrl *PersistentVolumeController) updateVolumePhaseWithEvent(volume *api.P // bindVolumeToClaim modifes given volume to be bound to a claim and saves it to // API server. The claim is not modified in this method! -func (ctrl *PersistentVolumeController) bindVolumeToClaim(volume *api.PersistentVolume, claim *api.PersistentVolumeClaim) (*api.PersistentVolume, error) { +func (ctrl *PersistentVolumeController) bindVolumeToClaim(volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) (*v1.PersistentVolume, error) { glog.V(4).Infof("updating PersistentVolume[%s]: binding to %q", volume.Name, claimToClaimKey(claim)) dirty := false @@ -716,7 +716,7 @@ func (ctrl *PersistentVolumeController) bindVolumeToClaim(volume *api.Persistent if err != nil { return nil, fmt.Errorf("Error cloning pv: %v", err) } - volumeClone, ok := clone.(*api.PersistentVolume) + volumeClone, ok := clone.(*v1.PersistentVolume) if !ok { return nil, fmt.Errorf("Unexpected volume cast error : %v", volumeClone) } @@ -727,7 +727,7 @@ func (ctrl *PersistentVolumeController) bindVolumeToClaim(volume *api.Persistent volume.Spec.ClaimRef.Namespace != claim.Namespace || volume.Spec.ClaimRef.UID != claim.UID { - claimRef, err := api.GetReference(claim) + claimRef, err := v1.GetReference(claim) if err != nil { return nil, fmt.Errorf("Unexpected error getting claim reference: %v", err) } @@ -736,8 +736,8 @@ func (ctrl *PersistentVolumeController) bindVolumeToClaim(volume *api.Persistent } // Set annBoundByController if it is not set yet - if shouldSetBoundByController && !api.HasAnnotation(volumeClone.ObjectMeta, annBoundByController) { - api.SetMetaDataAnnotation(&volumeClone.ObjectMeta, annBoundByController, "yes") + if shouldSetBoundByController && !v1.HasAnnotation(volumeClone.ObjectMeta, annBoundByController) { + v1.SetMetaDataAnnotation(&volumeClone.ObjectMeta, annBoundByController, "yes") dirty = true } @@ -764,7 +764,7 @@ func (ctrl *PersistentVolumeController) bindVolumeToClaim(volume *api.Persistent // bindClaimToVolume modifies the given claim to be bound to a volume and // saves it to API server. The volume is not modified in this method! -func (ctrl *PersistentVolumeController) bindClaimToVolume(claim *api.PersistentVolumeClaim, volume *api.PersistentVolume) (*api.PersistentVolumeClaim, error) { +func (ctrl *PersistentVolumeController) bindClaimToVolume(claim *v1.PersistentVolumeClaim, volume *v1.PersistentVolume) (*v1.PersistentVolumeClaim, error) { glog.V(4).Infof("updating PersistentVolumeClaim[%s]: binding to %q", claimToClaimKey(claim), volume.Name) dirty := false @@ -781,7 +781,7 @@ func (ctrl *PersistentVolumeController) bindClaimToVolume(claim *api.PersistentV if err != nil { return nil, fmt.Errorf("Error cloning claim: %v", err) } - claimClone, ok := clone.(*api.PersistentVolumeClaim) + claimClone, ok := clone.(*v1.PersistentVolumeClaim) if !ok { return nil, fmt.Errorf("Unexpected claim cast error : %v", claimClone) } @@ -793,14 +793,14 @@ func (ctrl *PersistentVolumeController) bindClaimToVolume(claim *api.PersistentV } // Set annBoundByController if it is not set yet - if shouldSetBoundByController && !api.HasAnnotation(claimClone.ObjectMeta, annBoundByController) { - api.SetMetaDataAnnotation(&claimClone.ObjectMeta, annBoundByController, "yes") + if shouldSetBoundByController && !v1.HasAnnotation(claimClone.ObjectMeta, annBoundByController) { + v1.SetMetaDataAnnotation(&claimClone.ObjectMeta, annBoundByController, "yes") dirty = true } // Set annBindCompleted if it is not set yet - if !api.HasAnnotation(claimClone.ObjectMeta, annBindCompleted) { - api.SetMetaDataAnnotation(&claimClone.ObjectMeta, annBindCompleted, "yes") + if !v1.HasAnnotation(claimClone.ObjectMeta, annBindCompleted) { + v1.SetMetaDataAnnotation(&claimClone.ObjectMeta, annBindCompleted, "yes") dirty = true } @@ -828,12 +828,12 @@ func (ctrl *PersistentVolumeController) bindClaimToVolume(claim *api.PersistentV // both objects as Bound. Volume is saved first. // It returns on first error, it's up to the caller to implement some retry // mechanism. -func (ctrl *PersistentVolumeController) bind(volume *api.PersistentVolume, claim *api.PersistentVolumeClaim) error { +func (ctrl *PersistentVolumeController) bind(volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) error { var err error // use updateClaim/updatedVolume to keep the original claim/volume for // logging in error cases. - var updatedClaim *api.PersistentVolumeClaim - var updatedVolume *api.PersistentVolume + var updatedClaim *v1.PersistentVolumeClaim + var updatedVolume *v1.PersistentVolume glog.V(4).Infof("binding volume %q to claim %q", volume.Name, claimToClaimKey(claim)) @@ -843,7 +843,7 @@ func (ctrl *PersistentVolumeController) bind(volume *api.PersistentVolume, claim } volume = updatedVolume - if updatedVolume, err = ctrl.updateVolumePhase(volume, api.VolumeBound, ""); err != nil { + if updatedVolume, err = ctrl.updateVolumePhase(volume, v1.VolumeBound, ""); err != nil { glog.V(3).Infof("error binding volume %q to claim %q: failed saving the volume status: %v", volume.Name, claimToClaimKey(claim), err) return err } @@ -855,7 +855,7 @@ func (ctrl *PersistentVolumeController) bind(volume *api.PersistentVolume, claim } claim = updatedClaim - if updatedClaim, err = ctrl.updateClaimStatus(claim, api.ClaimBound, volume); err != nil { + if updatedClaim, err = ctrl.updateClaimStatus(claim, v1.ClaimBound, volume); err != nil { glog.V(3).Infof("error binding volume %q to claim %q: failed saving the claim status: %v", volume.Name, claimToClaimKey(claim), err) return err } @@ -873,7 +873,7 @@ func (ctrl *PersistentVolumeController) bind(volume *api.PersistentVolume, claim // This method updates both Spec and Status. // It returns on first error, it's up to the caller to implement some retry // mechanism. -func (ctrl *PersistentVolumeController) unbindVolume(volume *api.PersistentVolume) error { +func (ctrl *PersistentVolumeController) unbindVolume(volume *v1.PersistentVolume) error { glog.V(4).Infof("updating PersistentVolume[%s]: rolling back binding from %q", volume.Name, claimrefToClaimKey(volume.Spec.ClaimRef)) // Save the PV only when any modification is neccessary. @@ -881,12 +881,12 @@ func (ctrl *PersistentVolumeController) unbindVolume(volume *api.PersistentVolum if err != nil { return fmt.Errorf("Error cloning pv: %v", err) } - volumeClone, ok := clone.(*api.PersistentVolume) + volumeClone, ok := clone.(*v1.PersistentVolume) if !ok { return fmt.Errorf("Unexpected volume cast error : %v", volumeClone) } - if api.HasAnnotation(volume.ObjectMeta, annBoundByController) { + if v1.HasAnnotation(volume.ObjectMeta, annBoundByController) { // The volume was bound by the controller. volumeClone.Spec.ClaimRef = nil delete(volumeClone.Annotations, annBoundByController) @@ -913,18 +913,18 @@ func (ctrl *PersistentVolumeController) unbindVolume(volume *api.PersistentVolum glog.V(4).Infof("updating PersistentVolume[%s]: rolled back", newVol.Name) // Update the status - _, err = ctrl.updateVolumePhase(newVol, api.VolumeAvailable, "") + _, err = ctrl.updateVolumePhase(newVol, v1.VolumeAvailable, "") return err } // reclaimVolume implements volume.Spec.PersistentVolumeReclaimPolicy and // starts appropriate reclaim action. -func (ctrl *PersistentVolumeController) reclaimVolume(volume *api.PersistentVolume) error { +func (ctrl *PersistentVolumeController) reclaimVolume(volume *v1.PersistentVolume) error { switch volume.Spec.PersistentVolumeReclaimPolicy { - case api.PersistentVolumeReclaimRetain: + case v1.PersistentVolumeReclaimRetain: glog.V(4).Infof("reclaimVolume[%s]: policy is Retain, nothing to do", volume.Name) - case api.PersistentVolumeReclaimRecycle: + case v1.PersistentVolumeReclaimRecycle: glog.V(4).Infof("reclaimVolume[%s]: policy is Recycle", volume.Name) opName := fmt.Sprintf("recycle-%s[%s]", volume.Name, string(volume.UID)) ctrl.scheduleOperation(opName, func() error { @@ -932,7 +932,7 @@ func (ctrl *PersistentVolumeController) reclaimVolume(volume *api.PersistentVolu return nil }) - case api.PersistentVolumeReclaimDelete: + case v1.PersistentVolumeReclaimDelete: glog.V(4).Infof("reclaimVolume[%s]: policy is Delete", volume.Name) opName := fmt.Sprintf("delete-%s[%s]", volume.Name, string(volume.UID)) ctrl.scheduleOperation(opName, func() error { @@ -942,7 +942,7 @@ func (ctrl *PersistentVolumeController) reclaimVolume(volume *api.PersistentVolu default: // Unknown PersistentVolumeReclaimPolicy - if _, err := ctrl.updateVolumePhaseWithEvent(volume, api.VolumeFailed, api.EventTypeWarning, "VolumeUnknownReclaimPolicy", "Volume has unrecognized PersistentVolumeReclaimPolicy"); err != nil { + if _, err := ctrl.updateVolumePhaseWithEvent(volume, v1.VolumeFailed, v1.EventTypeWarning, "VolumeUnknownReclaimPolicy", "Volume has unrecognized PersistentVolumeReclaimPolicy"); err != nil { return err } } @@ -952,7 +952,7 @@ func (ctrl *PersistentVolumeController) reclaimVolume(volume *api.PersistentVolu // doRerecycleVolumeOperationcycleVolume recycles a volume. This method is // running in standalone goroutine and already has all necessary locks. func (ctrl *PersistentVolumeController) recycleVolumeOperation(arg interface{}) { - volume, ok := arg.(*api.PersistentVolume) + volume, ok := arg.(*v1.PersistentVolume) if !ok { glog.Errorf("Cannot convert recycleVolumeOperation argument to volume, got %#v", arg) return @@ -986,7 +986,7 @@ func (ctrl *PersistentVolumeController) recycleVolumeOperation(arg interface{}) plugin, err := ctrl.volumePluginMgr.FindRecyclablePluginBySpec(spec) if err != nil { // No recycler found. Emit an event and mark the volume Failed. - if _, err = ctrl.updateVolumePhaseWithEvent(volume, api.VolumeFailed, api.EventTypeWarning, "VolumeFailedRecycle", "No recycler plugin found for the volume!"); err != nil { + if _, err = ctrl.updateVolumePhaseWithEvent(volume, v1.VolumeFailed, v1.EventTypeWarning, "VolumeFailedRecycle", "No recycler plugin found for the volume!"); err != nil { glog.V(4).Infof("recycleVolumeOperation [%s]: failed to mark volume as failed: %v", volume.Name, err) // Save failed, retry on the next deletion attempt return @@ -1002,7 +1002,7 @@ func (ctrl *PersistentVolumeController) recycleVolumeOperation(arg interface{}) if err != nil { // Cannot create recycler strerr := fmt.Sprintf("Failed to create recycler: %v", err) - if _, err = ctrl.updateVolumePhaseWithEvent(volume, api.VolumeFailed, api.EventTypeWarning, "VolumeFailedRecycle", strerr); err != nil { + if _, err = ctrl.updateVolumePhaseWithEvent(volume, v1.VolumeFailed, v1.EventTypeWarning, "VolumeFailedRecycle", strerr); err != nil { glog.V(4).Infof("recycleVolumeOperation [%s]: failed to mark volume as failed: %v", volume.Name, err) // Save failed, retry on the next deletion attempt return @@ -1015,7 +1015,7 @@ func (ctrl *PersistentVolumeController) recycleVolumeOperation(arg interface{}) if err = recycler.Recycle(); err != nil { // Recycler failed strerr := fmt.Sprintf("Recycler failed: %s", err) - if _, err = ctrl.updateVolumePhaseWithEvent(volume, api.VolumeFailed, api.EventTypeWarning, "VolumeFailedRecycle", strerr); err != nil { + if _, err = ctrl.updateVolumePhaseWithEvent(volume, v1.VolumeFailed, v1.EventTypeWarning, "VolumeFailedRecycle", strerr); err != nil { glog.V(4).Infof("recycleVolumeOperation [%s]: failed to mark volume as failed: %v", volume.Name, err) // Save failed, retry on the next deletion attempt return @@ -1027,7 +1027,7 @@ func (ctrl *PersistentVolumeController) recycleVolumeOperation(arg interface{}) glog.V(2).Infof("volume %q recycled", volume.Name) // Send an event - ctrl.eventRecorder.Event(volume, api.EventTypeNormal, "VolumeRecycled", "Volume recycled") + ctrl.eventRecorder.Event(volume, v1.EventTypeNormal, "VolumeRecycled", "Volume recycled") // Make the volume available again if err = ctrl.unbindVolume(volume); err != nil { // Oops, could not save the volume and therefore the controller will @@ -1043,7 +1043,7 @@ func (ctrl *PersistentVolumeController) recycleVolumeOperation(arg interface{}) // deleteVolumeOperation deletes a volume. This method is running in standalone // goroutine and already has all necessary locks. func (ctrl *PersistentVolumeController) deleteVolumeOperation(arg interface{}) { - volume, ok := arg.(*api.PersistentVolume) + volume, ok := arg.(*v1.PersistentVolume) if !ok { glog.Errorf("Cannot convert deleteVolumeOperation argument to volume, got %#v", arg) return @@ -1075,11 +1075,11 @@ func (ctrl *PersistentVolumeController) deleteVolumeOperation(arg interface{}) { if vol.IsDeletedVolumeInUse(err) { // The plugin needs more time, don't mark the volume as Failed // and send Normal event only - ctrl.eventRecorder.Event(volume, api.EventTypeNormal, "VolumeDelete", err.Error()) + ctrl.eventRecorder.Event(volume, v1.EventTypeNormal, "VolumeDelete", err.Error()) } else { // The plugin failed, mark the volume as Failed and send Warning // event - if _, err = ctrl.updateVolumePhaseWithEvent(volume, api.VolumeFailed, api.EventTypeWarning, "VolumeFailedDelete", err.Error()); err != nil { + if _, err = ctrl.updateVolumePhaseWithEvent(volume, v1.VolumeFailed, v1.EventTypeWarning, "VolumeFailedDelete", err.Error()); err != nil { glog.V(4).Infof("deleteVolumeOperation [%s]: failed to mark volume as failed: %v", volume.Name, err) // Save failed, retry on the next deletion attempt return @@ -1111,7 +1111,7 @@ func (ctrl *PersistentVolumeController) deleteVolumeOperation(arg interface{}) { // isVolumeReleased returns true if given volume is released and can be recycled // or deleted, based on its retain policy. I.e. the volume is bound to a claim // and the claim does not exist or exists and is bound to different volume. -func (ctrl *PersistentVolumeController) isVolumeReleased(volume *api.PersistentVolume) (bool, error) { +func (ctrl *PersistentVolumeController) isVolumeReleased(volume *v1.PersistentVolume) (bool, error) { // A volume needs reclaim if it has ClaimRef and appropriate claim does not // exist. if volume.Spec.ClaimRef == nil { @@ -1125,7 +1125,7 @@ func (ctrl *PersistentVolumeController) isVolumeReleased(volume *api.PersistentV return false, nil } - var claim *api.PersistentVolumeClaim + var claim *v1.PersistentVolumeClaim claimName := claimrefToClaimKey(volume.Spec.ClaimRef) obj, found, err := ctrl.claims.GetByKey(claimName) if err != nil { @@ -1135,7 +1135,7 @@ func (ctrl *PersistentVolumeController) isVolumeReleased(volume *api.PersistentV // Fall through with claim = nil } else { var ok bool - claim, ok = obj.(*api.PersistentVolumeClaim) + claim, ok = obj.(*v1.PersistentVolumeClaim) if !ok { return false, fmt.Errorf("Cannot convert object from claim cache to claim!?: %#v", obj) } @@ -1160,7 +1160,7 @@ func (ctrl *PersistentVolumeController) isVolumeReleased(volume *api.PersistentV // returns 'true', when the volume was deleted and 'false' when the volume // cannot be deleted because of the deleter is external. No error should be // reported in this case. -func (ctrl *PersistentVolumeController) doDeleteVolume(volume *api.PersistentVolume) (bool, error) { +func (ctrl *PersistentVolumeController) doDeleteVolume(volume *v1.PersistentVolume) (bool, error) { glog.V(4).Infof("doDeleteVolume [%s]", volume.Name) var err error @@ -1194,7 +1194,7 @@ func (ctrl *PersistentVolumeController) doDeleteVolume(volume *api.PersistentVol // provisionClaim starts new asynchronous operation to provision a claim if // provisioning is enabled. -func (ctrl *PersistentVolumeController) provisionClaim(claim *api.PersistentVolumeClaim) error { +func (ctrl *PersistentVolumeController) provisionClaim(claim *v1.PersistentVolumeClaim) error { if !ctrl.enableDynamicProvisioning { return nil } @@ -1210,7 +1210,7 @@ func (ctrl *PersistentVolumeController) provisionClaim(claim *api.PersistentVolu // provisionClaimOperation provisions a volume. This method is running in // standalone goroutine and already has all necessary locks. func (ctrl *PersistentVolumeController) provisionClaimOperation(claimObj interface{}) { - claim, ok := claimObj.(*api.PersistentVolumeClaim) + claim, ok := claimObj.(*v1.PersistentVolumeClaim) if !ok { glog.Errorf("Cannot convert provisionClaimOperation argument to claim, got %#v", claimObj) return @@ -1221,7 +1221,7 @@ func (ctrl *PersistentVolumeController) provisionClaimOperation(claimObj interfa plugin, storageClass, err := ctrl.findProvisionablePlugin(claim) if err != nil { - ctrl.eventRecorder.Event(claim, api.EventTypeWarning, "ProvisioningFailed", err.Error()) + ctrl.eventRecorder.Event(claim, v1.EventTypeWarning, "ProvisioningFailed", err.Error()) glog.V(2).Infof("error finding provisioning plugin for claim %s: %v", claimToClaimKey(claim), err) // The controller will retry provisioning the volume in every // syncVolume() call. @@ -1245,7 +1245,7 @@ func (ctrl *PersistentVolumeController) provisionClaimOperation(claimObj interfa // and wait for the external provisioner if storageClass != nil { msg := fmt.Sprintf("cannot find provisioner %q, expecting that a volume for the claim is provisioned either manually or via external software", storageClass.Provisioner) - ctrl.eventRecorder.Event(claim, api.EventTypeNormal, "ExternalProvisioning", msg) + ctrl.eventRecorder.Event(claim, v1.EventTypeNormal, "ExternalProvisioning", msg) glog.V(3).Infof("provisioning claim %q: %s", claimToClaimKey(claim), msg) } else { glog.V(3).Infof("cannot find storage class for claim %q", claimToClaimKey(claim)) @@ -1269,7 +1269,7 @@ func (ctrl *PersistentVolumeController) provisionClaimOperation(claimObj interfa // Prepare a claimRef to the claim early (to fail before a volume is // provisioned) - claimRef, err := api.GetReference(claim) + claimRef, err := v1.GetReference(claim) if err != nil { glog.V(3).Infof("unexpected error getting claim reference: %v", err) return @@ -1282,7 +1282,7 @@ func (ctrl *PersistentVolumeController) provisionClaimOperation(claimObj interfa tags[cloudVolumeCreatedForVolumeNameTag] = pvName options := vol.VolumeOptions{ - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete, + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, CloudTags: &tags, ClusterName: ctrl.clusterName, PVName: pvName, @@ -1295,7 +1295,7 @@ func (ctrl *PersistentVolumeController) provisionClaimOperation(claimObj interfa if err != nil { strerr := fmt.Sprintf("Failed to create provisioner: %v", err) glog.V(2).Infof("failed to create provisioner for claim %q with StorageClass %q: %v", claimToClaimKey(claim), storageClass.Name, err) - ctrl.eventRecorder.Event(claim, api.EventTypeWarning, "ProvisioningFailed", strerr) + ctrl.eventRecorder.Event(claim, v1.EventTypeWarning, "ProvisioningFailed", strerr) return } @@ -1303,7 +1303,7 @@ func (ctrl *PersistentVolumeController) provisionClaimOperation(claimObj interfa if err != nil { strerr := fmt.Sprintf("Failed to provision volume with StorageClass %q: %v", storageClass.Name, err) glog.V(2).Infof("failed to provision volume for claim %q with StorageClass %q: %v", claimToClaimKey(claim), storageClass.Name, err) - ctrl.eventRecorder.Event(claim, api.EventTypeWarning, "ProvisioningFailed", strerr) + ctrl.eventRecorder.Event(claim, v1.EventTypeWarning, "ProvisioningFailed", strerr) return } @@ -1313,22 +1313,22 @@ func (ctrl *PersistentVolumeController) provisionClaimOperation(claimObj interfa volume.Name = pvName // Bind it to the claim volume.Spec.ClaimRef = claimRef - volume.Status.Phase = api.VolumeBound + volume.Status.Phase = v1.VolumeBound // Add annBoundByController (used in deleting the volume) - api.SetMetaDataAnnotation(&volume.ObjectMeta, annBoundByController, "yes") - api.SetMetaDataAnnotation(&volume.ObjectMeta, annDynamicallyProvisioned, plugin.GetPluginName()) + v1.SetMetaDataAnnotation(&volume.ObjectMeta, annBoundByController, "yes") + v1.SetMetaDataAnnotation(&volume.ObjectMeta, annDynamicallyProvisioned, plugin.GetPluginName()) // For Alpha provisioning behavior, do not add storage.BetaStorageClassAnnotations for volumes created // by storage.AlphaStorageClassAnnotation // TODO: remove this check in 1.5, storage.StorageClassAnnotation will be always non-empty there. if claimClass != "" { - api.SetMetaDataAnnotation(&volume.ObjectMeta, storageutil.StorageClassAnnotation, claimClass) + v1.SetMetaDataAnnotation(&volume.ObjectMeta, storageutil.StorageClassAnnotation, claimClass) } // Try to create the PV object several times for i := 0; i < ctrl.createProvisionedPVRetryCount; i++ { glog.V(4).Infof("provisionClaimOperation [%s]: trying to save volume %s", claimToClaimKey(claim), volume.Name) - var newVol *api.PersistentVolume + var newVol *v1.PersistentVolume if newVol, err = ctrl.kubeClient.Core().PersistentVolumes().Create(volume); err == nil { // Save succeeded. glog.V(3).Infof("volume %q for claim %q saved", volume.Name, claimToClaimKey(claim)) @@ -1352,7 +1352,7 @@ func (ctrl *PersistentVolumeController) provisionClaimOperation(claimObj interfa // times. strerr := fmt.Sprintf("Error creating provisioned PV object for claim %s: %v. Deleting the volume.", claimToClaimKey(claim), err) glog.V(3).Info(strerr) - ctrl.eventRecorder.Event(claim, api.EventTypeWarning, "ProvisioningFailed", strerr) + ctrl.eventRecorder.Event(claim, v1.EventTypeWarning, "ProvisioningFailed", strerr) for i := 0; i < ctrl.createProvisionedPVRetryCount; i++ { deleted, err := ctrl.doDeleteVolume(volume) @@ -1378,7 +1378,7 @@ func (ctrl *PersistentVolumeController) provisionClaimOperation(claimObj interfa // is nothing we can do about it. strerr := fmt.Sprintf("Error cleaning provisioned volume for claim %s: %v. Please delete manually.", claimToClaimKey(claim), err) glog.V(2).Info(strerr) - ctrl.eventRecorder.Event(claim, api.EventTypeWarning, "ProvisioningCleanupFailed", strerr) + ctrl.eventRecorder.Event(claim, v1.EventTypeWarning, "ProvisioningCleanupFailed", strerr) } } else { glog.V(2).Infof("volume %q provisioned for claim %q", volume.Name, claimToClaimKey(claim)) @@ -1387,7 +1387,7 @@ func (ctrl *PersistentVolumeController) provisionClaimOperation(claimObj interfa // getProvisionedVolumeNameForClaim returns PV.Name for the provisioned volume. // The name must be unique. -func (ctrl *PersistentVolumeController) getProvisionedVolumeNameForClaim(claim *api.PersistentVolumeClaim) string { +func (ctrl *PersistentVolumeController) getProvisionedVolumeNameForClaim(claim *v1.PersistentVolumeClaim) string { return "pvc-" + string(claim.UID) } @@ -1413,7 +1413,7 @@ func (ctrl *PersistentVolumeController) scheduleOperation(operationName string, // newRecyclerEventRecorder returns a RecycleEventRecorder that sends all events // to given volume. -func (ctrl *PersistentVolumeController) newRecyclerEventRecorder(volume *api.PersistentVolume) vol.RecycleEventRecorder { +func (ctrl *PersistentVolumeController) newRecyclerEventRecorder(volume *v1.PersistentVolume) vol.RecycleEventRecorder { return func(eventtype, message string) { ctrl.eventRecorder.Eventf(volume, eventtype, "RecyclerPod", "Recycler pod: %s", message) } @@ -1422,15 +1422,15 @@ func (ctrl *PersistentVolumeController) newRecyclerEventRecorder(volume *api.Per // findProvisionablePlugin finds a provisioner plugin for a given claim. // It returns either the provisioning plugin or nil when an external // provisioner is requested. -func (ctrl *PersistentVolumeController) findProvisionablePlugin(claim *api.PersistentVolumeClaim) (vol.ProvisionableVolumePlugin, *storage.StorageClass, error) { +func (ctrl *PersistentVolumeController) findProvisionablePlugin(claim *v1.PersistentVolumeClaim) (vol.ProvisionableVolumePlugin, *storage.StorageClass, error) { // TODO: remove this alpha behavior in 1.5 - alpha := api.HasAnnotation(claim.ObjectMeta, storageutil.AlphaStorageClassAnnotation) - beta := api.HasAnnotation(claim.ObjectMeta, storageutil.BetaStorageClassAnnotation) + alpha := v1.HasAnnotation(claim.ObjectMeta, storageutil.AlphaStorageClassAnnotation) + beta := v1.HasAnnotation(claim.ObjectMeta, storageutil.BetaStorageClassAnnotation) if alpha && beta { // Both Alpha and Beta annotations are set. Do beta. alpha = false msg := fmt.Sprintf("both %q and %q annotations are present, using %q", storageutil.AlphaStorageClassAnnotation, storageutil.BetaStorageClassAnnotation, storageutil.BetaStorageClassAnnotation) - ctrl.eventRecorder.Event(claim, api.EventTypeNormal, "ProvisioningIgnoreAlpha", msg) + ctrl.eventRecorder.Event(claim, v1.EventTypeNormal, "ProvisioningIgnoreAlpha", msg) } if alpha { // Fall back to fixed list of provisioner plugins @@ -1477,7 +1477,7 @@ func (ctrl *PersistentVolumeController) findAlphaProvisionablePlugin() (vol.Prov TypeMeta: unversioned.TypeMeta{ Kind: "StorageClass", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "", }, Provisioner: ctrl.alphaProvisioner.GetPluginName(), @@ -1488,10 +1488,10 @@ func (ctrl *PersistentVolumeController) findAlphaProvisionablePlugin() (vol.Prov // findDeletablePlugin finds a deleter plugin for a given volume. It returns // either the deleter plugin or nil when an external deleter is requested. -func (ctrl *PersistentVolumeController) findDeletablePlugin(volume *api.PersistentVolume) (vol.DeletableVolumePlugin, error) { +func (ctrl *PersistentVolumeController) findDeletablePlugin(volume *v1.PersistentVolume) (vol.DeletableVolumePlugin, error) { // Find a plugin. Try to find the same plugin that provisioned the volume var plugin vol.DeletableVolumePlugin - if api.HasAnnotation(volume.ObjectMeta, annDynamicallyProvisioned) { + if v1.HasAnnotation(volume.ObjectMeta, annDynamicallyProvisioned) { provisionPluginName := volume.Annotations[annDynamicallyProvisioned] if provisionPluginName != "" { plugin, err := ctrl.volumePluginMgr.FindDeletablePluginByName(provisionPluginName) diff --git a/pkg/controller/volume/persistentvolume/pv_controller_base.go b/pkg/controller/volume/persistentvolume/pv_controller_base.go index 2706da0fe70..eec55704096 100644 --- a/pkg/controller/volume/persistentvolume/pv_controller_base.go +++ b/pkg/controller/volume/persistentvolume/pv_controller_base.go @@ -21,13 +21,13 @@ import ( "strconv" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/apis/storage" + "k8s.io/kubernetes/pkg/api/v1" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversioned_core "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + unversioned_core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/conversion" @@ -63,7 +63,7 @@ func NewController(p ControllerParameters) *PersistentVolumeController { if eventRecorder == nil { broadcaster := record.NewBroadcaster() broadcaster.StartRecordingToSink(&unversioned_core.EventSinkImpl{Interface: p.KubeClient.Core().Events("")}) - eventRecorder = broadcaster.NewRecorder(api.EventSource{Component: "persistentvolume-controller"}) + eventRecorder = broadcaster.NewRecorder(v1.EventSource{Component: "persistentvolume-controller"}) } controller := &PersistentVolumeController{ @@ -90,10 +90,10 @@ func NewController(p ControllerParameters) *PersistentVolumeController { volumeSource := p.VolumeSource if volumeSource == nil { volumeSource = &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return p.KubeClient.Core().PersistentVolumes().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return p.KubeClient.Core().PersistentVolumes().Watch(options) }, } @@ -103,11 +103,11 @@ func NewController(p ControllerParameters) *PersistentVolumeController { claimSource := p.ClaimSource if claimSource == nil { claimSource = &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return p.KubeClient.Core().PersistentVolumeClaims(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return p.KubeClient.Core().PersistentVolumeClaims(v1.NamespaceAll).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return p.KubeClient.Core().PersistentVolumeClaims(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return p.KubeClient.Core().PersistentVolumeClaims(v1.NamespaceAll).Watch(options) }, } } @@ -116,10 +116,10 @@ func NewController(p ControllerParameters) *PersistentVolumeController { classSource := p.ClassSource if classSource == nil { classSource = &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return p.KubeClient.Storage().StorageClasses().List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return p.KubeClient.Storage().StorageClasses().Watch(options) }, } @@ -128,7 +128,7 @@ func NewController(p ControllerParameters) *PersistentVolumeController { _, controller.volumeController = cache.NewIndexerInformer( volumeSource, - &api.PersistentVolume{}, + &v1.PersistentVolume{}, p.SyncPeriod, cache.ResourceEventHandlerFuncs{ AddFunc: controller.addVolume, @@ -139,7 +139,7 @@ func NewController(p ControllerParameters) *PersistentVolumeController { ) _, controller.claimController = cache.NewInformer( claimSource, - &api.PersistentVolumeClaim{}, + &v1.PersistentVolumeClaim{}, p.SyncPeriod, cache.ResourceEventHandlerFuncs{ AddFunc: controller.addClaim, @@ -164,12 +164,12 @@ func NewController(p ControllerParameters) *PersistentVolumeController { // order to have the caches already filled when first addClaim/addVolume to // perform initial synchronization of the controller. func (ctrl *PersistentVolumeController) initializeCaches(volumeSource, claimSource cache.ListerWatcher) { - volumeListObj, err := volumeSource.List(api.ListOptions{}) + volumeListObj, err := volumeSource.List(v1.ListOptions{}) if err != nil { glog.Errorf("PersistentVolumeController can't initialize caches: %v", err) return } - volumeList, ok := volumeListObj.(*api.PersistentVolumeList) + volumeList, ok := volumeListObj.(*v1.PersistentVolumeList) if !ok { glog.Errorf("PersistentVolumeController can't initialize caches, expected list of volumes, got: %#v", volumeListObj) return @@ -183,17 +183,17 @@ func (ctrl *PersistentVolumeController) initializeCaches(volumeSource, claimSour glog.Errorf("error cloning volume %q: %v", volume.Name, err) continue } - volumeClone := clone.(*api.PersistentVolume) + volumeClone := clone.(*v1.PersistentVolume) ctrl.storeVolumeUpdate(volumeClone) } } - claimListObj, err := claimSource.List(api.ListOptions{}) + claimListObj, err := claimSource.List(v1.ListOptions{}) if err != nil { glog.Errorf("PersistentVolumeController can't initialize caches: %v", err) return } - claimList, ok := claimListObj.(*api.PersistentVolumeClaimList) + claimList, ok := claimListObj.(*v1.PersistentVolumeClaimList) if !ok { glog.Errorf("PersistentVolumeController can't initialize caches, expected list of claims, got: %#v", claimListObj) return @@ -204,24 +204,24 @@ func (ctrl *PersistentVolumeController) initializeCaches(volumeSource, claimSour glog.Errorf("error cloning claim %q: %v", claimToClaimKey(&claim), err) continue } - claimClone := clone.(*api.PersistentVolumeClaim) + claimClone := clone.(*v1.PersistentVolumeClaim) ctrl.storeClaimUpdate(claimClone) } glog.V(4).Infof("controller initialized") } -func (ctrl *PersistentVolumeController) storeVolumeUpdate(volume *api.PersistentVolume) (bool, error) { +func (ctrl *PersistentVolumeController) storeVolumeUpdate(volume *v1.PersistentVolume) (bool, error) { return storeObjectUpdate(ctrl.volumes.store, volume, "volume") } -func (ctrl *PersistentVolumeController) storeClaimUpdate(claim *api.PersistentVolumeClaim) (bool, error) { +func (ctrl *PersistentVolumeController) storeClaimUpdate(claim *v1.PersistentVolumeClaim) (bool, error) { return storeObjectUpdate(ctrl.claims, claim, "claim") } // addVolume is callback from cache.Controller watching PersistentVolume // events. func (ctrl *PersistentVolumeController) addVolume(obj interface{}) { - pv, ok := obj.(*api.PersistentVolume) + pv, ok := obj.(*v1.PersistentVolume) if !ok { glog.Errorf("expected PersistentVolume but handler received %#v", obj) return @@ -256,7 +256,7 @@ func (ctrl *PersistentVolumeController) addVolume(obj interface{}) { // updateVolume is callback from cache.Controller watching PersistentVolume // events. func (ctrl *PersistentVolumeController) updateVolume(oldObj, newObj interface{}) { - newVolume, ok := newObj.(*api.PersistentVolume) + newVolume, ok := newObj.(*v1.PersistentVolume) if !ok { glog.Errorf("Expected PersistentVolume but handler received %#v", newObj) return @@ -293,12 +293,12 @@ func (ctrl *PersistentVolumeController) updateVolume(oldObj, newObj interface{}) func (ctrl *PersistentVolumeController) deleteVolume(obj interface{}) { _ = ctrl.volumes.store.Delete(obj) - var volume *api.PersistentVolume + var volume *v1.PersistentVolume var ok bool - volume, ok = obj.(*api.PersistentVolume) + volume, ok = obj.(*v1.PersistentVolume) if !ok { if unknown, ok := obj.(cache.DeletedFinalStateUnknown); ok && unknown.Obj != nil { - volume, ok = unknown.Obj.(*api.PersistentVolume) + volume, ok = unknown.Obj.(*v1.PersistentVolume) if !ok { glog.Errorf("Expected PersistentVolume but deleteVolume received %#v", unknown.Obj) return @@ -316,7 +316,7 @@ func (ctrl *PersistentVolumeController) deleteVolume(obj interface{}) { glog.V(4).Infof("volume %q deleted", volume.Name) if claimObj, exists, _ := ctrl.claims.GetByKey(claimrefToClaimKey(volume.Spec.ClaimRef)); exists { - if claim, ok := claimObj.(*api.PersistentVolumeClaim); ok && claim != nil { + if claim, ok := claimObj.(*v1.PersistentVolumeClaim); ok && claim != nil { // sync the claim when its volume is deleted. Explicitly syncing the // claim here in response to volume deletion prevents the claim from // waiting until the next sync period for its Lost status. @@ -341,7 +341,7 @@ func (ctrl *PersistentVolumeController) deleteVolume(obj interface{}) { func (ctrl *PersistentVolumeController) addClaim(obj interface{}) { // Store the new claim version in the cache and do not process it if this is // an old version. - claim, ok := obj.(*api.PersistentVolumeClaim) + claim, ok := obj.(*v1.PersistentVolumeClaim) if !ok { glog.Errorf("Expected PersistentVolumeClaim but addClaim received %+v", obj) return @@ -371,7 +371,7 @@ func (ctrl *PersistentVolumeController) addClaim(obj interface{}) { func (ctrl *PersistentVolumeController) updateClaim(oldObj, newObj interface{}) { // Store the new claim version in the cache and do not process it if this is // an old version. - newClaim, ok := newObj.(*api.PersistentVolumeClaim) + newClaim, ok := newObj.(*v1.PersistentVolumeClaim) if !ok { glog.Errorf("Expected PersistentVolumeClaim but updateClaim received %+v", newObj) return @@ -401,14 +401,14 @@ func (ctrl *PersistentVolumeController) updateClaim(oldObj, newObj interface{}) func (ctrl *PersistentVolumeController) deleteClaim(obj interface{}) { _ = ctrl.claims.Delete(obj) - var volume *api.PersistentVolume - var claim *api.PersistentVolumeClaim + var volume *v1.PersistentVolume + var claim *v1.PersistentVolumeClaim var ok bool - claim, ok = obj.(*api.PersistentVolumeClaim) + claim, ok = obj.(*v1.PersistentVolumeClaim) if !ok { if unknown, ok := obj.(cache.DeletedFinalStateUnknown); ok && unknown.Obj != nil { - claim, ok = unknown.Obj.(*api.PersistentVolumeClaim) + claim, ok = unknown.Obj.(*v1.PersistentVolumeClaim) if !ok { glog.Errorf("Expected PersistentVolumeClaim but deleteClaim received %#v", unknown.Obj) return @@ -425,7 +425,7 @@ func (ctrl *PersistentVolumeController) deleteClaim(obj interface{}) { glog.V(4).Infof("claim %q deleted", claimToClaimKey(claim)) if pvObj, exists, _ := ctrl.volumes.store.GetByKey(claim.Spec.VolumeName); exists { - if volume, ok = pvObj.(*api.PersistentVolume); ok { + if volume, ok = pvObj.(*v1.PersistentVolume); ok { // sync the volume when its claim is deleted. Explicitly sync'ing the // volume here in response to claim deletion prevents the volume from // waiting until the next sync period for its Release. @@ -468,7 +468,7 @@ const ( // make the controller to provision a new PV. // It returns true if the volume was deleted. // TODO: remove this function when upgrade from 1.2 becomes unsupported. -func (ctrl *PersistentVolumeController) upgradeVolumeFrom1_2(volume *api.PersistentVolume) bool { +func (ctrl *PersistentVolumeController) upgradeVolumeFrom1_2(volume *v1.PersistentVolume) bool { annValue, found := volume.Annotations[pvProvisioningRequiredAnnotationKey] if !found { // The volume is not template @@ -496,7 +496,7 @@ func (ctrl *PersistentVolumeController) upgradeVolumeFrom1_2(volume *api.Persist // setClaimProvisioner saves // claim.Annotations[annStorageProvisioner] = class.Provisioner -func (ctrl *PersistentVolumeController) setClaimProvisioner(claim *api.PersistentVolumeClaim, class *storage.StorageClass) (*api.PersistentVolumeClaim, error) { +func (ctrl *PersistentVolumeController) setClaimProvisioner(claim *v1.PersistentVolumeClaim, class *storage.StorageClass) (*v1.PersistentVolumeClaim, error) { if val, ok := claim.Annotations[annDynamicallyProvisioned]; ok && val == class.Provisioner { // annotation is already set, nothing to do return claim, nil @@ -508,11 +508,11 @@ func (ctrl *PersistentVolumeController) setClaimProvisioner(claim *api.Persisten if err != nil { return nil, fmt.Errorf("Error cloning pv: %v", err) } - claimClone, ok := clone.(*api.PersistentVolumeClaim) + claimClone, ok := clone.(*v1.PersistentVolumeClaim) if !ok { return nil, fmt.Errorf("Unexpected claim cast error : %v", claimClone) } - api.SetMetaDataAnnotation(&claimClone.ObjectMeta, annStorageProvisioner, class.Provisioner) + v1.SetMetaDataAnnotation(&claimClone.ObjectMeta, annStorageProvisioner, class.Provisioner) newClaim, err := ctrl.kubeClient.Core().PersistentVolumeClaims(claim.Namespace).Update(claimClone) if err != nil { return newClaim, err @@ -526,15 +526,15 @@ func (ctrl *PersistentVolumeController) setClaimProvisioner(claim *api.Persisten // Stateless functions -func getClaimStatusForLogging(claim *api.PersistentVolumeClaim) string { - bound := api.HasAnnotation(claim.ObjectMeta, annBindCompleted) - boundByController := api.HasAnnotation(claim.ObjectMeta, annBoundByController) +func getClaimStatusForLogging(claim *v1.PersistentVolumeClaim) string { + bound := v1.HasAnnotation(claim.ObjectMeta, annBindCompleted) + boundByController := v1.HasAnnotation(claim.ObjectMeta, annBoundByController) return fmt.Sprintf("phase: %s, bound to: %q, bindCompleted: %v, boundByController: %v", claim.Status.Phase, claim.Spec.VolumeName, bound, boundByController) } -func getVolumeStatusForLogging(volume *api.PersistentVolume) string { - boundByController := api.HasAnnotation(volume.ObjectMeta, annBoundByController) +func getVolumeStatusForLogging(volume *v1.PersistentVolume) string { + boundByController := v1.HasAnnotation(volume.ObjectMeta, annBoundByController) claimName := "" if volume.Spec.ClaimRef != nil { claimName = fmt.Sprintf("%s/%s (uid: %s)", volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name, volume.Spec.ClaimRef.UID) @@ -545,7 +545,7 @@ func getVolumeStatusForLogging(volume *api.PersistentVolume) string { // isVolumeBoundToClaim returns true, if given volume is pre-bound or bound // to specific claim. Both claim.Name and claim.Namespace must be equal. // If claim.UID is present in volume.Spec.ClaimRef, it must be equal too. -func isVolumeBoundToClaim(volume *api.PersistentVolume, claim *api.PersistentVolumeClaim) bool { +func isVolumeBoundToClaim(volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) bool { if volume.Spec.ClaimRef == nil { return false } diff --git a/pkg/controller/volume/persistentvolume/pv_controller_test.go b/pkg/controller/volume/persistentvolume/pv_controller_test.go index 29865c932f7..556a53f88d4 100644 --- a/pkg/controller/volume/persistentvolume/pv_controller_test.go +++ b/pkg/controller/volume/persistentvolume/pv_controller_test.go @@ -21,9 +21,9 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" fcache "k8s.io/kubernetes/pkg/client/testing/cache" ) @@ -42,14 +42,14 @@ func TestControllerSync(t *testing.T) { { // addClaim gets a new claim. Check it's bound to a volume. "5-2 - complete bind", - newVolumeArray("volume5-2", "1Gi", "", "", api.VolumeAvailable, api.PersistentVolumeReclaimRetain), - newVolumeArray("volume5-2", "1Gi", "uid5-2", "claim5-2", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), + newVolumeArray("volume5-2", "1Gi", "", "", v1.VolumeAvailable, v1.PersistentVolumeReclaimRetain), + newVolumeArray("volume5-2", "1Gi", "uid5-2", "claim5-2", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), noclaims, /* added in testAddClaim5_2 */ - newClaimArray("claim5-2", "uid5-2", "1Gi", "volume5-2", api.ClaimBound, annBoundByController, annBindCompleted), + newClaimArray("claim5-2", "uid5-2", "1Gi", "volume5-2", v1.ClaimBound, annBoundByController, annBindCompleted), noevents, noerrors, // Custom test function that generates an add event func(ctrl *PersistentVolumeController, reactor *volumeReactor, test controllerTest) error { - claim := newClaim("claim5-2", "uid5-2", "1Gi", "", api.ClaimPending) + claim := newClaim("claim5-2", "uid5-2", "1Gi", "", v1.ClaimPending) reactor.addClaimEvent(claim) return nil }, @@ -57,15 +57,15 @@ func TestControllerSync(t *testing.T) { { // deleteClaim with a bound claim makes bound volume released. "5-3 - delete claim", - newVolumeArray("volume5-3", "10Gi", "uid5-3", "claim5-3", api.VolumeBound, api.PersistentVolumeReclaimRetain, annBoundByController), - newVolumeArray("volume5-3", "10Gi", "uid5-3", "claim5-3", api.VolumeReleased, api.PersistentVolumeReclaimRetain, annBoundByController), - newClaimArray("claim5-3", "uid5-3", "1Gi", "volume5-3", api.ClaimBound, annBoundByController, annBindCompleted), + newVolumeArray("volume5-3", "10Gi", "uid5-3", "claim5-3", v1.VolumeBound, v1.PersistentVolumeReclaimRetain, annBoundByController), + newVolumeArray("volume5-3", "10Gi", "uid5-3", "claim5-3", v1.VolumeReleased, v1.PersistentVolumeReclaimRetain, annBoundByController), + newClaimArray("claim5-3", "uid5-3", "1Gi", "volume5-3", v1.ClaimBound, annBoundByController, annBindCompleted), noclaims, noevents, noerrors, // Custom test function that generates a delete event func(ctrl *PersistentVolumeController, reactor *volumeReactor, test controllerTest) error { obj := ctrl.claims.List()[0] - claim := obj.(*api.PersistentVolumeClaim) + claim := obj.(*v1.PersistentVolumeClaim) reactor.deleteClaimEvent(claim) return nil }, @@ -73,15 +73,15 @@ func TestControllerSync(t *testing.T) { { // deleteVolume with a bound volume. Check the claim is Lost. "5-4 - delete volume", - newVolumeArray("volume5-4", "1Gi", "uid5-4", "claim5-4", api.VolumeBound, api.PersistentVolumeReclaimRetain), + newVolumeArray("volume5-4", "1Gi", "uid5-4", "claim5-4", v1.VolumeBound, v1.PersistentVolumeReclaimRetain), novolumes, - newClaimArray("claim5-4", "uid5-4", "1Gi", "volume5-4", api.ClaimBound, annBoundByController, annBindCompleted), - newClaimArray("claim5-4", "uid5-4", "1Gi", "volume5-4", api.ClaimLost, annBoundByController, annBindCompleted), + newClaimArray("claim5-4", "uid5-4", "1Gi", "volume5-4", v1.ClaimBound, annBoundByController, annBindCompleted), + newClaimArray("claim5-4", "uid5-4", "1Gi", "volume5-4", v1.ClaimLost, annBoundByController, annBindCompleted), []string{"Warning ClaimLost"}, noerrors, // Custom test function that generates a delete event func(ctrl *PersistentVolumeController, reactor *volumeReactor, test controllerTest) error { obj := ctrl.volumes.store.List()[0] - volume := obj.(*api.PersistentVolume) + volume := obj.(*v1.PersistentVolume) reactor.deleteVolumeEvent(volume) return nil }, @@ -91,13 +91,13 @@ func TestControllerSync(t *testing.T) { // is expected - it should stay bound. "5-5 - add bound volume from 1.2", novolumes, - []*api.PersistentVolume{addVolumeAnnotation(newVolume("volume5-5", "1Gi", "uid5-5", "claim5-5", api.VolumeBound, api.PersistentVolumeReclaimDelete), pvProvisioningRequiredAnnotationKey, pvProvisioningCompletedAnnotationValue)}, - newClaimArray("claim5-5", "uid5-5", "1Gi", "", api.ClaimPending), - newClaimArray("claim5-5", "uid5-5", "1Gi", "volume5-5", api.ClaimBound, annBindCompleted, annBoundByController), + []*v1.PersistentVolume{addVolumeAnnotation(newVolume("volume5-5", "1Gi", "uid5-5", "claim5-5", v1.VolumeBound, v1.PersistentVolumeReclaimDelete), pvProvisioningRequiredAnnotationKey, pvProvisioningCompletedAnnotationValue)}, + newClaimArray("claim5-5", "uid5-5", "1Gi", "", v1.ClaimPending), + newClaimArray("claim5-5", "uid5-5", "1Gi", "volume5-5", v1.ClaimBound, annBindCompleted, annBoundByController), noevents, noerrors, // Custom test function that generates a add event func(ctrl *PersistentVolumeController, reactor *volumeReactor, test controllerTest) error { - volume := newVolume("volume5-5", "1Gi", "uid5-5", "claim5-5", api.VolumeBound, api.PersistentVolumeReclaimDelete) + volume := newVolume("volume5-5", "1Gi", "uid5-5", "claim5-5", v1.VolumeBound, v1.PersistentVolumeReclaimDelete) volume = addVolumeAnnotation(volume, pvProvisioningRequiredAnnotationKey, pvProvisioningCompletedAnnotationValue) reactor.addVolumeEvent(volume) return nil @@ -107,14 +107,14 @@ func TestControllerSync(t *testing.T) { // updateVolume with provisioned volume from Kubernetes 1.2. No // "action" is expected - it should stay bound. "5-6 - update bound volume from 1.2", - []*api.PersistentVolume{addVolumeAnnotation(newVolume("volume5-6", "1Gi", "uid5-6", "claim5-6", api.VolumeBound, api.PersistentVolumeReclaimDelete), pvProvisioningRequiredAnnotationKey, pvProvisioningCompletedAnnotationValue)}, - []*api.PersistentVolume{addVolumeAnnotation(newVolume("volume5-6", "1Gi", "uid5-6", "claim5-6", api.VolumeBound, api.PersistentVolumeReclaimDelete), pvProvisioningRequiredAnnotationKey, pvProvisioningCompletedAnnotationValue)}, - newClaimArray("claim5-6", "uid5-6", "1Gi", "volume5-6", api.ClaimBound), - newClaimArray("claim5-6", "uid5-6", "1Gi", "volume5-6", api.ClaimBound, annBindCompleted), + []*v1.PersistentVolume{addVolumeAnnotation(newVolume("volume5-6", "1Gi", "uid5-6", "claim5-6", v1.VolumeBound, v1.PersistentVolumeReclaimDelete), pvProvisioningRequiredAnnotationKey, pvProvisioningCompletedAnnotationValue)}, + []*v1.PersistentVolume{addVolumeAnnotation(newVolume("volume5-6", "1Gi", "uid5-6", "claim5-6", v1.VolumeBound, v1.PersistentVolumeReclaimDelete), pvProvisioningRequiredAnnotationKey, pvProvisioningCompletedAnnotationValue)}, + newClaimArray("claim5-6", "uid5-6", "1Gi", "volume5-6", v1.ClaimBound), + newClaimArray("claim5-6", "uid5-6", "1Gi", "volume5-6", v1.ClaimBound, annBindCompleted), noevents, noerrors, // Custom test function that generates a add event func(ctrl *PersistentVolumeController, reactor *volumeReactor, test controllerTest) error { - volume := newVolume("volume5-6", "1Gi", "uid5-6", "claim5-6", api.VolumeBound, api.PersistentVolumeReclaimDelete) + volume := newVolume("volume5-6", "1Gi", "uid5-6", "claim5-6", v1.VolumeBound, v1.PersistentVolumeReclaimDelete) volume = addVolumeAnnotation(volume, pvProvisioningRequiredAnnotationKey, pvProvisioningCompletedAnnotationValue) reactor.modifyVolumeEvent(volume) return nil @@ -126,12 +126,12 @@ func TestControllerSync(t *testing.T) { "5-7 - add unprovisioned volume from 1.2", novolumes, novolumes, - newClaimArray("claim5-7", "uid5-7", "1Gi", "", api.ClaimPending), - newClaimArray("claim5-7", "uid5-7", "1Gi", "", api.ClaimPending), + newClaimArray("claim5-7", "uid5-7", "1Gi", "", v1.ClaimPending), + newClaimArray("claim5-7", "uid5-7", "1Gi", "", v1.ClaimPending), noevents, noerrors, // Custom test function that generates a add event func(ctrl *PersistentVolumeController, reactor *volumeReactor, test controllerTest) error { - volume := newVolume("volume5-7", "1Gi", "uid5-7", "claim5-7", api.VolumeBound, api.PersistentVolumeReclaimDelete) + volume := newVolume("volume5-7", "1Gi", "uid5-7", "claim5-7", v1.VolumeBound, v1.PersistentVolumeReclaimDelete) volume = addVolumeAnnotation(volume, pvProvisioningRequiredAnnotationKey, "yes") reactor.addVolumeEvent(volume) return nil @@ -143,12 +143,12 @@ func TestControllerSync(t *testing.T) { "5-8 - update bound volume from 1.2", novolumes, novolumes, - newClaimArray("claim5-8", "uid5-8", "1Gi", "", api.ClaimPending), - newClaimArray("claim5-8", "uid5-8", "1Gi", "", api.ClaimPending), + newClaimArray("claim5-8", "uid5-8", "1Gi", "", v1.ClaimPending), + newClaimArray("claim5-8", "uid5-8", "1Gi", "", v1.ClaimPending), noevents, noerrors, // Custom test function that generates a add event func(ctrl *PersistentVolumeController, reactor *volumeReactor, test controllerTest) error { - volume := newVolume("volume5-8", "1Gi", "uid5-8", "claim5-8", api.VolumeBound, api.PersistentVolumeReclaimDelete) + volume := newVolume("volume5-8", "1Gi", "uid5-8", "claim5-8", v1.VolumeBound, v1.PersistentVolumeReclaimDelete) volume = addVolumeAnnotation(volume, pvProvisioningRequiredAnnotationKey, "yes") reactor.modifyVolumeEvent(volume) return nil @@ -209,7 +209,7 @@ func TestControllerSync(t *testing.T) { } func storeVersion(t *testing.T, prefix string, c cache.Store, version string, expectedReturn bool) { - pv := newVolume("pvName", "1Gi", "", "", api.VolumeAvailable, api.PersistentVolumeReclaimDelete) + pv := newVolume("pvName", "1Gi", "", "", v1.VolumeAvailable, v1.PersistentVolumeReclaimDelete) pv.ResourceVersion = version ret, err := storeObjectUpdate(c, pv, "volume") if err != nil { @@ -228,7 +228,7 @@ func storeVersion(t *testing.T, prefix string, c cache.Store, version string, ex if !found { t.Errorf("expected volume 'pvName' in the cache but it was not found") } - pv, ok := pvObj.(*api.PersistentVolume) + pv, ok := pvObj.(*v1.PersistentVolume) if !ok { t.Errorf("expected volume in the cache, got different object instead: %#v", pvObj) } @@ -268,7 +268,7 @@ func TestControllerCacheParsingError(t *testing.T) { // There must be something in the cache to compare with storeVersion(t, "Step1", c, "1", true) - pv := newVolume("pvName", "1Gi", "", "", api.VolumeAvailable, api.PersistentVolumeReclaimDelete) + pv := newVolume("pvName", "1Gi", "", "", v1.VolumeAvailable, v1.PersistentVolumeReclaimDelete) pv.ResourceVersion = "xxx" _, err := storeObjectUpdate(c, pv, "volume") if err == nil { @@ -276,7 +276,7 @@ func TestControllerCacheParsingError(t *testing.T) { } } -func addVolumeAnnotation(volume *api.PersistentVolume, annName, annValue string) *api.PersistentVolume { +func addVolumeAnnotation(volume *v1.PersistentVolume, annName, annValue string) *v1.PersistentVolume { if volume.Annotations == nil { volume.Annotations = make(map[string]string) } diff --git a/pkg/controller/volume/persistentvolume/recycle_test.go b/pkg/controller/volume/persistentvolume/recycle_test.go index 4fe26061f8b..edf0a548d55 100644 --- a/pkg/controller/volume/persistentvolume/recycle_test.go +++ b/pkg/controller/volume/persistentvolume/recycle_test.go @@ -20,8 +20,8 @@ import ( "errors" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/storage" + "k8s.io/kubernetes/pkg/api/v1" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" ) // Test single call to syncVolume, expecting recycling to happen. @@ -33,8 +33,8 @@ func TestRecycleSync(t *testing.T) { { // recycle volume bound by controller "6-1 - successful recycle", - newVolumeArray("volume6-1", "1Gi", "uid6-1", "claim6-1", api.VolumeBound, api.PersistentVolumeReclaimRecycle, annBoundByController), - newVolumeArray("volume6-1", "1Gi", "", "", api.VolumeAvailable, api.PersistentVolumeReclaimRecycle), + newVolumeArray("volume6-1", "1Gi", "uid6-1", "claim6-1", v1.VolumeBound, v1.PersistentVolumeReclaimRecycle, annBoundByController), + newVolumeArray("volume6-1", "1Gi", "", "", v1.VolumeAvailable, v1.PersistentVolumeReclaimRecycle), noclaims, noclaims, noevents, noerrors, @@ -45,8 +45,8 @@ func TestRecycleSync(t *testing.T) { { // recycle volume bound by user "6-2 - successful recycle with prebound volume", - newVolumeArray("volume6-2", "1Gi", "uid6-2", "claim6-2", api.VolumeBound, api.PersistentVolumeReclaimRecycle), - newVolumeArray("volume6-2", "1Gi", "", "claim6-2", api.VolumeAvailable, api.PersistentVolumeReclaimRecycle), + newVolumeArray("volume6-2", "1Gi", "uid6-2", "claim6-2", v1.VolumeBound, v1.PersistentVolumeReclaimRecycle), + newVolumeArray("volume6-2", "1Gi", "", "claim6-2", v1.VolumeAvailable, v1.PersistentVolumeReclaimRecycle), noclaims, noclaims, noevents, noerrors, @@ -57,8 +57,8 @@ func TestRecycleSync(t *testing.T) { { // recycle failure - plugin not found "6-3 - plugin not found", - newVolumeArray("volume6-3", "1Gi", "uid6-3", "claim6-3", api.VolumeBound, api.PersistentVolumeReclaimRecycle), - withMessage("No recycler plugin found for the volume!", newVolumeArray("volume6-3", "1Gi", "uid6-3", "claim6-3", api.VolumeFailed, api.PersistentVolumeReclaimRecycle)), + newVolumeArray("volume6-3", "1Gi", "uid6-3", "claim6-3", v1.VolumeBound, v1.PersistentVolumeReclaimRecycle), + withMessage("No recycler plugin found for the volume!", newVolumeArray("volume6-3", "1Gi", "uid6-3", "claim6-3", v1.VolumeFailed, v1.PersistentVolumeReclaimRecycle)), noclaims, noclaims, []string{"Warning VolumeFailedRecycle"}, noerrors, testSyncVolume, @@ -66,8 +66,8 @@ func TestRecycleSync(t *testing.T) { { // recycle failure - newRecycler returns error "6-4 - newRecycler returns error", - newVolumeArray("volume6-4", "1Gi", "uid6-4", "claim6-4", api.VolumeBound, api.PersistentVolumeReclaimRecycle), - withMessage("Failed to create recycler: Mock plugin error: no recycleCalls configured", newVolumeArray("volume6-4", "1Gi", "uid6-4", "claim6-4", api.VolumeFailed, api.PersistentVolumeReclaimRecycle)), + newVolumeArray("volume6-4", "1Gi", "uid6-4", "claim6-4", v1.VolumeBound, v1.PersistentVolumeReclaimRecycle), + withMessage("Failed to create recycler: Mock plugin error: no recycleCalls configured", newVolumeArray("volume6-4", "1Gi", "uid6-4", "claim6-4", v1.VolumeFailed, v1.PersistentVolumeReclaimRecycle)), noclaims, noclaims, []string{"Warning VolumeFailedRecycle"}, noerrors, @@ -76,8 +76,8 @@ func TestRecycleSync(t *testing.T) { { // recycle failure - recycle returns error "6-5 - recycle returns error", - newVolumeArray("volume6-5", "1Gi", "uid6-5", "claim6-5", api.VolumeBound, api.PersistentVolumeReclaimRecycle), - withMessage("Recycler failed: Mock recycle error", newVolumeArray("volume6-5", "1Gi", "uid6-5", "claim6-5", api.VolumeFailed, api.PersistentVolumeReclaimRecycle)), + newVolumeArray("volume6-5", "1Gi", "uid6-5", "claim6-5", v1.VolumeBound, v1.PersistentVolumeReclaimRecycle), + withMessage("Recycler failed: Mock recycle error", newVolumeArray("volume6-5", "1Gi", "uid6-5", "claim6-5", v1.VolumeFailed, v1.PersistentVolumeReclaimRecycle)), noclaims, noclaims, []string{"Warning VolumeFailedRecycle"}, noerrors, @@ -86,7 +86,7 @@ func TestRecycleSync(t *testing.T) { { // recycle success(?) - volume is deleted before doRecycle() starts "6-6 - volume is deleted before recycling", - newVolumeArray("volume6-6", "1Gi", "uid6-6", "claim6-6", api.VolumeBound, api.PersistentVolumeReclaimRecycle), + newVolumeArray("volume6-6", "1Gi", "uid6-6", "claim6-6", v1.VolumeBound, v1.PersistentVolumeReclaimRecycle), novolumes, noclaims, noclaims, @@ -103,8 +103,8 @@ func TestRecycleSync(t *testing.T) { // at the time new doRecycle() starts. This simulates "volume no // longer needs recycling, skipping". "6-7 - volume is deleted before recycling", - newVolumeArray("volume6-7", "1Gi", "uid6-7", "claim6-7", api.VolumeBound, api.PersistentVolumeReclaimRecycle, annBoundByController), - newVolumeArray("volume6-7", "1Gi", "", "", api.VolumeAvailable, api.PersistentVolumeReclaimRecycle), + newVolumeArray("volume6-7", "1Gi", "uid6-7", "claim6-7", v1.VolumeBound, v1.PersistentVolumeReclaimRecycle, annBoundByController), + newVolumeArray("volume6-7", "1Gi", "", "", v1.VolumeAvailable, v1.PersistentVolumeReclaimRecycle), noclaims, noclaims, noevents, noerrors, @@ -113,7 +113,7 @@ func TestRecycleSync(t *testing.T) { reactor.lock.Lock() volume := reactor.volumes["volume6-7"] volume.Spec.ClaimRef = nil - volume.Status.Phase = api.VolumeAvailable + volume.Status.Phase = v1.VolumeAvailable volume.Annotations = nil reactor.lock.Unlock() }), @@ -124,8 +124,8 @@ func TestRecycleSync(t *testing.T) { // "volume no longer needs recycling, skipping" with volume bound by // user. "6-8 - prebound volume is deleted before recycling", - newVolumeArray("volume6-8", "1Gi", "uid6-8", "claim6-8", api.VolumeBound, api.PersistentVolumeReclaimRecycle), - newVolumeArray("volume6-8", "1Gi", "", "claim6-8", api.VolumeAvailable, api.PersistentVolumeReclaimRecycle), + newVolumeArray("volume6-8", "1Gi", "uid6-8", "claim6-8", v1.VolumeBound, v1.PersistentVolumeReclaimRecycle), + newVolumeArray("volume6-8", "1Gi", "", "claim6-8", v1.VolumeAvailable, v1.PersistentVolumeReclaimRecycle), noclaims, noclaims, noevents, noerrors, @@ -134,7 +134,7 @@ func TestRecycleSync(t *testing.T) { reactor.lock.Lock() volume := reactor.volumes["volume6-8"] volume.Spec.ClaimRef.UID = "" - volume.Status.Phase = api.VolumeAvailable + volume.Status.Phase = v1.VolumeAvailable reactor.lock.Unlock() }), }, @@ -142,10 +142,10 @@ func TestRecycleSync(t *testing.T) { // recycle success - volume bound by user is recycled, while a new // claim is created with another UID. "6-9 - prebound volume is recycled while the claim exists", - newVolumeArray("volume6-9", "1Gi", "uid6-9", "claim6-9", api.VolumeBound, api.PersistentVolumeReclaimRecycle), - newVolumeArray("volume6-9", "1Gi", "", "claim6-9", api.VolumeAvailable, api.PersistentVolumeReclaimRecycle), - newClaimArray("claim6-9", "uid6-9-x", "10Gi", "", api.ClaimPending), - newClaimArray("claim6-9", "uid6-9-x", "10Gi", "", api.ClaimPending), + newVolumeArray("volume6-9", "1Gi", "uid6-9", "claim6-9", v1.VolumeBound, v1.PersistentVolumeReclaimRecycle), + newVolumeArray("volume6-9", "1Gi", "", "claim6-9", v1.VolumeAvailable, v1.PersistentVolumeReclaimRecycle), + newClaimArray("claim6-9", "uid6-9-x", "10Gi", "", v1.ClaimPending), + newClaimArray("claim6-9", "uid6-9-x", "10Gi", "", v1.ClaimPending), noevents, noerrors, // Inject recycler into the controller and call syncVolume. The // recycler simulates one recycle() call that succeeds. @@ -154,8 +154,8 @@ func TestRecycleSync(t *testing.T) { { // volume has unknown reclaim policy - failure expected "6-10 - unknown reclaim policy", - newVolumeArray("volume6-10", "1Gi", "uid6-10", "claim6-10", api.VolumeBound, "Unknown"), - withMessage("Volume has unrecognized PersistentVolumeReclaimPolicy", newVolumeArray("volume6-10", "1Gi", "uid6-10", "claim6-10", api.VolumeFailed, "Unknown")), + newVolumeArray("volume6-10", "1Gi", "uid6-10", "claim6-10", v1.VolumeBound, "Unknown"), + withMessage("Volume has unrecognized PersistentVolumeReclaimPolicy", newVolumeArray("volume6-10", "1Gi", "uid6-10", "claim6-10", v1.VolumeFailed, "Unknown")), noclaims, noclaims, []string{"Warning VolumeUnknownReclaimPolicy"}, noerrors, testSyncVolume, @@ -184,8 +184,8 @@ func TestRecycleMultiSync(t *testing.T) { // recycle failure - recycle returns error. The controller should // try again. "7-1 - recycle returns error", - newVolumeArray("volume7-1", "1Gi", "uid7-1", "claim7-1", api.VolumeBound, api.PersistentVolumeReclaimRecycle), - newVolumeArray("volume7-1", "1Gi", "", "claim7-1", api.VolumeAvailable, api.PersistentVolumeReclaimRecycle), + newVolumeArray("volume7-1", "1Gi", "uid7-1", "claim7-1", v1.VolumeBound, v1.PersistentVolumeReclaimRecycle), + newVolumeArray("volume7-1", "1Gi", "", "claim7-1", v1.VolumeAvailable, v1.PersistentVolumeReclaimRecycle), noclaims, noclaims, []string{"Warning VolumeFailedRecycle"}, noerrors, diff --git a/pkg/controller/volume/persistentvolume/volume_host.go b/pkg/controller/volume/persistentvolume/volume_host.go index 3ea581db274..2a5e5968937 100644 --- a/pkg/controller/volume/persistentvolume/volume_host.go +++ b/pkg/controller/volume/persistentvolume/volume_host.go @@ -20,8 +20,8 @@ import ( "fmt" "net" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/io" @@ -49,7 +49,7 @@ func (ctrl *PersistentVolumeController) GetKubeClient() clientset.Interface { return ctrl.kubeClient } -func (ctrl *PersistentVolumeController) NewWrapperMounter(volName string, spec vol.Spec, pod *api.Pod, opts vol.VolumeOptions) (vol.Mounter, error) { +func (ctrl *PersistentVolumeController) NewWrapperMounter(volName string, spec vol.Spec, pod *v1.Pod, opts vol.VolumeOptions) (vol.Mounter, error) { return nil, fmt.Errorf("PersistentVolumeController.NewWrapperMounter is not implemented") } @@ -77,6 +77,6 @@ func (ctrl *PersistentVolumeController) GetHostIP() (net.IP, error) { return nil, fmt.Errorf("PersistentVolumeController.GetHostIP() is not implemented") } -func (ctrl *PersistentVolumeController) GetNodeAllocatable() (api.ResourceList, error) { - return api.ResourceList{}, nil +func (ctrl *PersistentVolumeController) GetNodeAllocatable() (v1.ResourceList, error) { + return v1.ResourceList{}, nil } diff --git a/pkg/credentialprovider/BUILD b/pkg/credentialprovider/BUILD index 9e1a82064f7..3fbbcc93f7b 100644 --- a/pkg/credentialprovider/BUILD +++ b/pkg/credentialprovider/BUILD @@ -21,7 +21,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/util/sets:go_default_library", "//vendor:github.com/docker/engine-api/types", "//vendor:github.com/golang/glog", diff --git a/pkg/credentialprovider/keyring.go b/pkg/credentialprovider/keyring.go index ed712ccfdc7..635e03f06b5 100644 --- a/pkg/credentialprovider/keyring.go +++ b/pkg/credentialprovider/keyring.go @@ -27,7 +27,7 @@ import ( "github.com/golang/glog" dockertypes "github.com/docker/engine-api/types" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/sets" ) @@ -306,17 +306,17 @@ func (k *unionDockerKeyring) Lookup(image string) ([]LazyAuthConfiguration, bool // MakeDockerKeyring inspects the passedSecrets to see if they contain any DockerConfig secrets. If they do, // then a DockerKeyring is built based on every hit and unioned with the defaultKeyring. // If they do not, then the default keyring is returned -func MakeDockerKeyring(passedSecrets []api.Secret, defaultKeyring DockerKeyring) (DockerKeyring, error) { +func MakeDockerKeyring(passedSecrets []v1.Secret, defaultKeyring DockerKeyring) (DockerKeyring, error) { passedCredentials := []DockerConfig{} for _, passedSecret := range passedSecrets { - if dockerConfigJsonBytes, dockerConfigJsonExists := passedSecret.Data[api.DockerConfigJsonKey]; (passedSecret.Type == api.SecretTypeDockerConfigJson) && dockerConfigJsonExists && (len(dockerConfigJsonBytes) > 0) { + if dockerConfigJsonBytes, dockerConfigJsonExists := passedSecret.Data[v1.DockerConfigJsonKey]; (passedSecret.Type == v1.SecretTypeDockerConfigJson) && dockerConfigJsonExists && (len(dockerConfigJsonBytes) > 0) { dockerConfigJson := DockerConfigJson{} if err := json.Unmarshal(dockerConfigJsonBytes, &dockerConfigJson); err != nil { return nil, err } passedCredentials = append(passedCredentials, dockerConfigJson.Auths) - } else if dockercfgBytes, dockercfgExists := passedSecret.Data[api.DockerConfigKey]; (passedSecret.Type == api.SecretTypeDockercfg) && dockercfgExists && (len(dockercfgBytes) > 0) { + } else if dockercfgBytes, dockercfgExists := passedSecret.Data[v1.DockerConfigKey]; (passedSecret.Type == v1.SecretTypeDockercfg) && dockercfgExists && (len(dockercfgBytes) > 0) { dockercfg := DockerConfig{} if err := json.Unmarshal(dockercfgBytes, &dockercfg); err != nil { return nil, err diff --git a/pkg/dns/BUILD b/pkg/dns/BUILD index e54128a6f1e..7134f0b4bd4 100644 --- a/pkg/dns/BUILD +++ b/pkg/dns/BUILD @@ -18,11 +18,11 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/api/endpoints:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/endpoints:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/dns/config:go_default_library", "//pkg/dns/treecache:go_default_library", "//pkg/dns/util:go_default_library", @@ -43,11 +43,11 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/api/endpoints:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/endpoints:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/dns/config:go_default_library", "//pkg/dns/treecache:go_default_library", "//pkg/dns/util:go_default_library", diff --git a/pkg/dns/config/BUILD b/pkg/dns/config/BUILD index 8b8da0d165e..f3a4bedbb7b 100644 --- a/pkg/dns/config/BUILD +++ b/pkg/dns/config/BUILD @@ -20,10 +20,10 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/dns/federation:go_default_library", "//pkg/fields:go_default_library", "//pkg/runtime:go_default_library", diff --git a/pkg/dns/config/config_test.go b/pkg/dns/config/config_test.go index 8c751bb0458..45a5753b66c 100644 --- a/pkg/dns/config/config_test.go +++ b/pkg/dns/config/config_test.go @@ -17,8 +17,9 @@ limitations under the License. package config import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) func TestValidate(t *testing.T) { diff --git a/pkg/dns/config/sync.go b/pkg/dns/config/sync.go index 9022051fd9d..77f9234823e 100644 --- a/pkg/dns/config/sync.go +++ b/pkg/dns/config/sync.go @@ -18,9 +18,9 @@ package config import ( "k8s.io/client-go/pkg/util/wait" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" fed "k8s.io/kubernetes/pkg/dns/federation" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/runtime" @@ -55,19 +55,19 @@ func NewSync(client clientset.Interface, ns string, name string) Sync { } listWatch := &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - options.FieldSelector = fields.Set{"metadata.name": name}.AsSelector() + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + options.FieldSelector = fields.Set{"metadata.name": name}.AsSelector().String() return client.Core().ConfigMaps(ns).List(options) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - options.FieldSelector = fields.Set{"metadata.name": name}.AsSelector() + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + options.FieldSelector = fields.Set{"metadata.name": name}.AsSelector().String() return client.Core().ConfigMaps(ns).Watch(options) }, } store, controller := cache.NewInformer( listWatch, - &api.ConfigMap{}, + &v1.ConfigMap{}, time.Duration(0), cache.ResourceEventHandlerFuncs{ AddFunc: sync.onAdd, @@ -115,8 +115,8 @@ func (sync *kubeSync) Periodic() <-chan *Config { return sync.channel } -func (sync *kubeSync) toConfigMap(obj interface{}) *api.ConfigMap { - cm, ok := obj.(*api.ConfigMap) +func (sync *kubeSync) toConfigMap(obj interface{}) *v1.ConfigMap { + cm, ok := obj.(*v1.ConfigMap) if !ok { glog.Fatalf("Expected ConfigMap, got %T", obj) } @@ -154,7 +154,7 @@ func (sync *kubeSync) onUpdate(_, obj interface{}) { } } -func (sync *kubeSync) processUpdate(cm *api.ConfigMap) (config *Config, changed bool, err error) { +func (sync *kubeSync) processUpdate(cm *v1.ConfigMap) (config *Config, changed bool, err error) { glog.V(4).Infof("processUpdate ConfigMap %+v", *cm) if cm.ObjectMeta.ResourceVersion != sync.latestVersion { @@ -184,7 +184,7 @@ func (sync *kubeSync) processUpdate(cm *api.ConfigMap) (config *Config, changed return } -func (sync *kubeSync) updateFederations(cm *api.ConfigMap, config *Config) (err error) { +func (sync *kubeSync) updateFederations(cm *v1.ConfigMap, config *Config) (err error) { if flagValue, ok := cm.Data["federations"]; ok { config.Federations = make(map[string]string) if err = fed.ParseFederationsFlag(flagValue, config.Federations); err != nil { diff --git a/pkg/dns/dns.go b/pkg/dns/dns.go index 9d52ec74848..c44ddfc4856 100644 --- a/pkg/dns/dns.go +++ b/pkg/dns/dns.go @@ -27,11 +27,11 @@ import ( etcd "github.com/coreos/etcd/client" "github.com/miekg/dns" skymsg "github.com/skynetservices/skydns/msg" - kapi "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/endpoints" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/api/v1/endpoints" kcache "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/dns/config" "k8s.io/kubernetes/pkg/dns/treecache" "k8s.io/kubernetes/pkg/dns/util" @@ -94,7 +94,7 @@ type KubeDNS struct { // IP. Access to this is coordinated using cacheLock. We use the // same lock for cache and this map to ensure that they don't get // out of sync. - clusterIPServiceMap map[string]*kapi.Service + clusterIPServiceMap map[string]*v1.Service // cacheLock protecting the cache. caller is responsible for using // the cacheLock before invoking methods on cache the cache is not // thread-safe, and the caller can guarantee thread safety by using @@ -127,7 +127,7 @@ func NewKubeDNS(client clientset.Interface, clusterDomain string, configSync con cacheLock: sync.RWMutex{}, nodesStore: kcache.NewStore(kcache.MetaNamespaceKeyFunc), reverseRecordMap: make(map[string]*skymsg.Service), - clusterIPServiceMap: make(map[string]*kapi.Service), + clusterIPServiceMap: make(map[string]*v1.Service), domainPath: util.ReverseArray(strings.Split(strings.TrimRight(clusterDomain, "."), ".")), configLock: sync.RWMutex{}, @@ -165,11 +165,11 @@ func (kd *KubeDNS) waitForKubernetesService() { const kubernetesSvcName = "kubernetes" const servicePollInterval = 1 * time.Second - name := fmt.Sprintf("%v/%v", kapi.NamespaceDefault, kubernetesSvcName) + name := fmt.Sprintf("%v/%v", v1.NamespaceDefault, kubernetesSvcName) glog.V(2).Infof("Waiting for service: %v", name) for { - svc, err := kd.kubeClient.Core().Services(kapi.NamespaceDefault).Get(kubernetesSvcName) + svc, err := kd.kubeClient.Core().Services(v1.NamespaceDefault).Get(kubernetesSvcName) if err != nil || svc == nil { glog.V(3).Infof( "Ignoring error while waiting for service %v: %v. Sleeping %v before retrying.", @@ -218,14 +218,14 @@ func (kd *KubeDNS) setServicesStore() { // Returns a cache.ListWatch that gets all changes to services. kd.servicesStore, kd.serviceController = kcache.NewInformer( &kcache.ListWatch{ - ListFunc: func(options kapi.ListOptions) (runtime.Object, error) { - return kd.kubeClient.Core().Services(kapi.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return kd.kubeClient.Core().Services(v1.NamespaceAll).List(options) }, - WatchFunc: func(options kapi.ListOptions) (watch.Interface, error) { - return kd.kubeClient.Core().Services(kapi.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return kd.kubeClient.Core().Services(v1.NamespaceAll).Watch(options) }, }, - &kapi.Service{}, + &v1.Service{}, resyncPeriod, kcache.ResourceEventHandlerFuncs{ AddFunc: kd.newService, @@ -239,14 +239,14 @@ func (kd *KubeDNS) setEndpointsStore() { // Returns a cache.ListWatch that gets all changes to endpoints. kd.endpointsStore, kd.endpointsController = kcache.NewInformer( &kcache.ListWatch{ - ListFunc: func(options kapi.ListOptions) (runtime.Object, error) { - return kd.kubeClient.Core().Endpoints(kapi.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + return kd.kubeClient.Core().Endpoints(v1.NamespaceAll).List(options) }, - WatchFunc: func(options kapi.ListOptions) (watch.Interface, error) { - return kd.kubeClient.Core().Endpoints(kapi.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + return kd.kubeClient.Core().Endpoints(v1.NamespaceAll).Watch(options) }, }, - &kapi.Endpoints{}, + &v1.Endpoints{}, resyncPeriod, kcache.ResourceEventHandlerFuncs{ AddFunc: kd.handleEndpointAdd, @@ -260,8 +260,8 @@ func (kd *KubeDNS) setEndpointsStore() { ) } -func assertIsService(obj interface{}) (*kapi.Service, bool) { - if service, ok := obj.(*kapi.Service); ok { +func assertIsService(obj interface{}) (*v1.Service, bool) { + if service, ok := obj.(*v1.Service); ok { return service, ok } else { glog.Errorf("Type assertion failed! Expected 'Service', got %T", service) @@ -275,12 +275,12 @@ func (kd *KubeDNS) newService(obj interface{}) { glog.V(4).Infof("Service details: %v", service) // ExternalName services are a special kind that return CNAME records - if service.Spec.Type == kapi.ServiceTypeExternalName { + if service.Spec.Type == v1.ServiceTypeExternalName { kd.newExternalNameService(service) return } // if ClusterIP is not set, a DNS entry should not be created - if !kapi.IsServiceIPSet(service) { + if !v1.IsServiceIPSet(service) { kd.newHeadlessService(service) return } @@ -303,7 +303,7 @@ func (kd *KubeDNS) removeService(obj interface{}) { s.Name, subCachePath, success) // ExternalName services have no IP - if kapi.IsServiceIPSet(s) { + if v1.IsServiceIPSet(s) { delete(kd.reverseRecordMap, s.Spec.ClusterIP) delete(kd.clusterIPServiceMap, s.Spec.ClusterIP) } @@ -315,8 +315,8 @@ func (kd *KubeDNS) updateService(oldObj, newObj interface{}) { if old, ok := assertIsService(oldObj); ok { // Remove old cache path only if changing type to/from ExternalName. // In all other cases, we'll update records in place. - if (new.Spec.Type == kapi.ServiceTypeExternalName) != - (old.Spec.Type == kapi.ServiceTypeExternalName) { + if (new.Spec.Type == v1.ServiceTypeExternalName) != + (old.Spec.Type == v1.ServiceTypeExternalName) { kd.removeService(oldObj) } kd.newService(newObj) @@ -325,24 +325,24 @@ func (kd *KubeDNS) updateService(oldObj, newObj interface{}) { } func (kd *KubeDNS) handleEndpointAdd(obj interface{}) { - if e, ok := obj.(*kapi.Endpoints); ok { + if e, ok := obj.(*v1.Endpoints); ok { kd.addDNSUsingEndpoints(e) } } -func (kd *KubeDNS) addDNSUsingEndpoints(e *kapi.Endpoints) error { +func (kd *KubeDNS) addDNSUsingEndpoints(e *v1.Endpoints) error { svc, err := kd.getServiceFromEndpoints(e) if err != nil { return err } - if svc == nil || kapi.IsServiceIPSet(svc) { + if svc == nil || v1.IsServiceIPSet(svc) { // No headless service found corresponding to endpoints object. return nil } return kd.generateRecordsForHeadlessService(e, svc) } -func (kd *KubeDNS) getServiceFromEndpoints(e *kapi.Endpoints) (*kapi.Service, error) { +func (kd *KubeDNS) getServiceFromEndpoints(e *v1.Endpoints) (*v1.Service, error) { key, err := kcache.MetaNamespaceKeyFunc(e) if err != nil { return nil, err @@ -364,12 +364,12 @@ func (kd *KubeDNS) getServiceFromEndpoints(e *kapi.Endpoints) (*kapi.Service, er // fqdn constructs the fqdn for the given service. subpaths is a list of path // elements rooted at the given service, ending at a service record. -func (kd *KubeDNS) fqdn(service *kapi.Service, subpaths ...string) string { +func (kd *KubeDNS) fqdn(service *v1.Service, subpaths ...string) string { domainLabels := append(append(kd.domainPath, serviceSubdomain, service.Namespace, service.Name), subpaths...) return dns.Fqdn(strings.Join(util.ReverseArray(domainLabels), ".")) } -func (kd *KubeDNS) newPortalService(service *kapi.Service) { +func (kd *KubeDNS) newPortalService(service *v1.Service) { subCache := treecache.NewTreeCache() recordValue, recordLabel := util.GetSkyMsg(service.Spec.ClusterIP, 0) subCache.SetEntry(recordLabel, recordValue, kd.fqdn(service, recordLabel)) @@ -397,7 +397,7 @@ func (kd *KubeDNS) newPortalService(service *kapi.Service) { kd.clusterIPServiceMap[service.Spec.ClusterIP] = service } -func (kd *KubeDNS) generateRecordsForHeadlessService(e *kapi.Endpoints, svc *kapi.Service) error { +func (kd *KubeDNS) generateRecordsForHeadlessService(e *v1.Endpoints, svc *v1.Service) error { // TODO: remove this after v1.4 is released and the old annotations are EOL podHostnames, err := getPodHostnamesFromAnnotation(e.Annotations) if err != nil { @@ -433,7 +433,7 @@ func (kd *KubeDNS) generateRecordsForHeadlessService(e *kapi.Endpoints, svc *kap return nil } -func getHostname(address *kapi.EndpointAddress, podHostnames map[string]endpoints.HostRecord) (string, bool) { +func getHostname(address *v1.EndpointAddress, podHostnames map[string]endpoints.HostRecord) (string, bool) { if len(address.Hostname) > 0 { return address.Hostname, true } @@ -457,7 +457,7 @@ func getPodHostnamesFromAnnotation(annotations map[string]string) (map[string]en return hostnames, nil } -func (kd *KubeDNS) generateSRVRecordValue(svc *kapi.Service, portNumber int, labels ...string) *skymsg.Service { +func (kd *KubeDNS) generateSRVRecordValue(svc *v1.Service, portNumber int, labels ...string) *skymsg.Service { host := strings.Join([]string{svc.Name, svc.Namespace, serviceSubdomain, kd.domain}, ".") for _, cNameLabel := range labels { host = cNameLabel + "." + host @@ -467,7 +467,7 @@ func (kd *KubeDNS) generateSRVRecordValue(svc *kapi.Service, portNumber int, lab } // Generates skydns records for a headless service. -func (kd *KubeDNS) newHeadlessService(service *kapi.Service) error { +func (kd *KubeDNS) newHeadlessService(service *v1.Service) error { // Create an A record for every pod in the service. // This record must be periodically updated. // Format is as follows: @@ -486,14 +486,14 @@ func (kd *KubeDNS) newHeadlessService(service *kapi.Service) error { service.Name, service.Namespace) return nil } - if e, ok := e.(*kapi.Endpoints); ok { + if e, ok := e.(*v1.Endpoints); ok { return kd.generateRecordsForHeadlessService(e, service) } return nil } // Generates skydns records for an ExternalName service. -func (kd *KubeDNS) newExternalNameService(service *kapi.Service) { +func (kd *KubeDNS) newExternalNameService(service *v1.Service) { // Create a CNAME record for the service's ExternalName. // TODO: TTL? recordValue, _ := util.GetSkyMsg(service.Spec.ExternalName, 0) @@ -675,7 +675,7 @@ func (kd *KubeDNS) serviceWithClusterIPHasEndpoints(msg *skymsg.Service) (bool, if !exists { return false, nil } - if e, ok := e.(*kapi.Endpoints); ok { + if e, ok := e.(*v1.Endpoints); ok { return len(e.Subsets) > 0, nil } return false, fmt.Errorf("unexpected: found non-endpoint object in endpoint store: %v", e) @@ -840,12 +840,12 @@ func (kd *KubeDNS) federationRecords(queryPath []string) ([]skymsg.Service, erro // Also note that zone here means the zone in cloud provider terminology, not // the DNS zone. func (kd *KubeDNS) getClusterZoneAndRegion() (string, string, error) { - var node *kapi.Node + var node *v1.Node objs := kd.nodesStore.List() if len(objs) > 0 { var ok bool - if node, ok = objs[0].(*kapi.Node); !ok { + if node, ok = objs[0].(*v1.Node); !ok { return "", "", fmt.Errorf("expected node object, got: %T", objs[0]) } } else { @@ -853,7 +853,7 @@ func (kd *KubeDNS) getClusterZoneAndRegion() (string, string, error) { // wasteful in case of non-federated independent Kubernetes clusters. So carefully // proceeding here. // TODO(madhusudancs): Move this to external/v1 API. - nodeList, err := kd.kubeClient.Core().Nodes().List(kapi.ListOptions{}) + nodeList, err := kd.kubeClient.Core().Nodes().List(v1.ListOptions{}) if err != nil || len(nodeList.Items) == 0 { return "", "", fmt.Errorf("failed to retrieve the cluster nodes: %v", err) } @@ -891,7 +891,7 @@ func (kd *KubeDNS) getClusterZoneAndRegion() (string, string, error) { return zone, region, nil } -func getServiceFQDN(domain string, service *kapi.Service) string { +func getServiceFQDN(domain string, service *v1.Service) string { return strings.Join( []string{service.Name, service.Namespace, serviceSubdomain, domain}, ".") } diff --git a/pkg/dns/dns_test.go b/pkg/dns/dns_test.go index 7849c4d016d..fb5c9328ff2 100644 --- a/pkg/dns/dns_test.go +++ b/pkg/dns/dns_test.go @@ -32,11 +32,11 @@ import ( skyServer "github.com/skynetservices/skydns/server" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - kapi "k8s.io/kubernetes/pkg/api" - endpointsapi "k8s.io/kubernetes/pkg/api/endpoints" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + endpointsapi "k8s.io/kubernetes/pkg/api/v1/endpoints" "k8s.io/kubernetes/pkg/client/cache" - fake "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + fake "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/dns/config" "k8s.io/kubernetes/pkg/dns/treecache" "k8s.io/kubernetes/pkg/dns/util" @@ -61,7 +61,7 @@ func newKubeDNS() *KubeDNS { cache: treecache.NewTreeCache(), reverseRecordMap: make(map[string]*skymsg.Service), - clusterIPServiceMap: make(map[string]*kapi.Service), + clusterIPServiceMap: make(map[string]*v1.Service), cacheLock: sync.RWMutex{}, config: config.NewDefaultConfig(), @@ -339,7 +339,7 @@ func TestHeadlessServiceEndpointsUpdate(t *testing.T) { assertDNSForHeadlessService(t, kd, endpoints) // remove all endpoints - endpoints.Subsets = []kapi.EndpointSubset{} + endpoints.Subsets = []v1.EndpointSubset{} kd.handleEndpointAdd(endpoints) assertNoDNSForHeadlessService(t, kd, service) @@ -419,7 +419,7 @@ func TestFederationHeadlessService(t *testing.T) { "testservice.default.svc.cluster.local.", t, kd) // Delete the endpoint. - endpoints.Subsets = []kapi.EndpointSubset{} + endpoints.Subsets = []v1.EndpointSubset{} kd.handleEndpointAdd(endpoints) kd.updateService(s, s) @@ -461,7 +461,7 @@ func TestFederationService(t *testing.T) { "testservice.default.svc.cluster.local.", t, kd) // Remove the endpoint. - endpoints.Subsets = []kapi.EndpointSubset{} + endpoints.Subsets = []v1.EndpointSubset{} kd.handleEndpointAdd(endpoints) kd.updateService(s, s) @@ -590,17 +590,17 @@ func TestConfigSyncInitialMap(t *testing.T) { checkConfigEqual(t, kd, &config.Config{Federations: map[string]string{"name3": "domain3"}}) } -func newNodes() *kapi.NodeList { - return &kapi.NodeList{ - Items: []kapi.Node{ +func newNodes() *v1.NodeList { + return &v1.NodeList{ + Items: []v1.Node{ // Node without annotation. { - ObjectMeta: kapi.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "testnode-0", }, }, { - ObjectMeta: kapi.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "testnode-1", Labels: map[string]string{ // Note: The zone name here is an arbitrary string and doesn't exactly follow the @@ -615,15 +615,15 @@ func newNodes() *kapi.NodeList { } } -func newService(namespace, serviceName, clusterIP, portName string, portNumber int32) *kapi.Service { - service := kapi.Service{ - ObjectMeta: kapi.ObjectMeta{ +func newService(namespace, serviceName, clusterIP, portName string, portNumber int32) *v1.Service { + service := v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: serviceName, Namespace: namespace, }, - Spec: kapi.ServiceSpec{ + Spec: v1.ServiceSpec{ ClusterIP: clusterIP, - Ports: []kapi.ServicePort{ + Ports: []v1.ServicePort{ {Port: portNumber, Name: portName, Protocol: "TCP"}, }, }, @@ -631,17 +631,17 @@ func newService(namespace, serviceName, clusterIP, portName string, portNumber i return &service } -func newExternalNameService() *kapi.Service { - service := kapi.Service{ - ObjectMeta: kapi.ObjectMeta{ +func newExternalNameService() *v1.Service { + service := v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: testService, Namespace: testNamespace, }, - Spec: kapi.ServiceSpec{ + Spec: v1.ServiceSpec{ ClusterIP: "None", - Type: kapi.ServiceTypeExternalName, + Type: v1.ServiceTypeExternalName, ExternalName: testExternalName, - Ports: []kapi.ServicePort{ + Ports: []v1.ServicePort{ {Port: 0}, }, }, @@ -649,15 +649,15 @@ func newExternalNameService() *kapi.Service { return &service } -func newHeadlessService() *kapi.Service { - service := kapi.Service{ - ObjectMeta: kapi.ObjectMeta{ +func newHeadlessService() *v1.Service { + service := v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: testService, Namespace: testNamespace, }, - Spec: kapi.ServiceSpec{ + Spec: v1.ServiceSpec{ ClusterIP: "None", - Ports: []kapi.ServicePort{ + Ports: []v1.ServicePort{ {Port: 0}, }, }, @@ -665,40 +665,40 @@ func newHeadlessService() *kapi.Service { return &service } -func newEndpoints(service *kapi.Service, subsets ...kapi.EndpointSubset) *kapi.Endpoints { - endpoints := kapi.Endpoints{ +func newEndpoints(service *v1.Service, subsets ...v1.EndpointSubset) *v1.Endpoints { + endpoints := v1.Endpoints{ ObjectMeta: service.ObjectMeta, - Subsets: []kapi.EndpointSubset{}, + Subsets: []v1.EndpointSubset{}, } endpoints.Subsets = append(endpoints.Subsets, subsets...) return &endpoints } -func newSubsetWithOnePort(portName string, port int32, ips ...string) kapi.EndpointSubset { +func newSubsetWithOnePort(portName string, port int32, ips ...string) v1.EndpointSubset { subset := newSubset() - subset.Ports = append(subset.Ports, kapi.EndpointPort{Port: port, Name: portName, Protocol: "TCP"}) + subset.Ports = append(subset.Ports, v1.EndpointPort{Port: port, Name: portName, Protocol: "TCP"}) for _, ip := range ips { - subset.Addresses = append(subset.Addresses, kapi.EndpointAddress{IP: ip}) + subset.Addresses = append(subset.Addresses, v1.EndpointAddress{IP: ip}) } return subset } -func newSubsetWithTwoPorts(portName1 string, portNumber1 int32, portName2 string, portNumber2 int32, ips ...string) kapi.EndpointSubset { +func newSubsetWithTwoPorts(portName1 string, portNumber1 int32, portName2 string, portNumber2 int32, ips ...string) v1.EndpointSubset { subset := newSubsetWithOnePort(portName1, portNumber1, ips...) - subset.Ports = append(subset.Ports, kapi.EndpointPort{Port: portNumber2, Name: portName2, Protocol: "TCP"}) + subset.Ports = append(subset.Ports, v1.EndpointPort{Port: portNumber2, Name: portName2, Protocol: "TCP"}) return subset } -func newSubset() kapi.EndpointSubset { - subset := kapi.EndpointSubset{ - Addresses: []kapi.EndpointAddress{}, - Ports: []kapi.EndpointPort{}, +func newSubset() v1.EndpointSubset { + subset := v1.EndpointSubset{ + Addresses: []v1.EndpointAddress{}, + Ports: []v1.EndpointPort{}, } return subset } -func assertSRVForHeadlessService(t *testing.T, kd *KubeDNS, s *kapi.Service, e *kapi.Endpoints) { +func assertSRVForHeadlessService(t *testing.T, kd *KubeDNS, s *v1.Service, e *v1.Endpoints) { for _, subset := range e.Subsets { for _, port := range subset.Ports { records, err := kd.Records(getSRVFQDN(kd, s, port.Name), false) @@ -709,7 +709,7 @@ func assertSRVForHeadlessService(t *testing.T, kd *KubeDNS, s *kapi.Service, e * } } -func assertDNSForHeadlessService(t *testing.T, kd *KubeDNS, e *kapi.Endpoints) { +func assertDNSForHeadlessService(t *testing.T, kd *KubeDNS, e *v1.Endpoints) { records, err := kd.Records(getEndpointsFQDN(kd, e), false) require.NoError(t, err) endpoints := map[string]bool{} @@ -725,7 +725,7 @@ func assertDNSForHeadlessService(t *testing.T, kd *KubeDNS, e *kapi.Endpoints) { } } -func assertDNSForExternalService(t *testing.T, kd *KubeDNS, s *kapi.Service) { +func assertDNSForExternalService(t *testing.T, kd *KubeDNS, s *v1.Service) { records, err := kd.Records(getServiceFQDN(kd.domain, s), false) require.NoError(t, err) assert.Equal(t, 1, len(records)) @@ -738,7 +738,7 @@ func assertRecordPortsMatchPort(t *testing.T, port int32, records []skymsg.Servi } } -func assertCNameRecordsMatchEndpointIPs(t *testing.T, kd *KubeDNS, e []kapi.EndpointAddress, records []skymsg.Service) { +func assertCNameRecordsMatchEndpointIPs(t *testing.T, kd *KubeDNS, e []v1.EndpointAddress, records []skymsg.Service) { endpoints := map[string]bool{} for _, endpointAddress := range e { endpoints[endpointAddress.IP] = true @@ -758,32 +758,32 @@ func getIPForCName(t *testing.T, kd *KubeDNS, cname string) string { return records[0].Host } -func assertNoDNSForHeadlessService(t *testing.T, kd *KubeDNS, s *kapi.Service) { +func assertNoDNSForHeadlessService(t *testing.T, kd *KubeDNS, s *v1.Service) { records, err := kd.Records(getServiceFQDN(kd.domain, s), false) require.Error(t, err) assert.Equal(t, 0, len(records)) } -func assertNoDNSForExternalService(t *testing.T, kd *KubeDNS, s *kapi.Service) { +func assertNoDNSForExternalService(t *testing.T, kd *KubeDNS, s *v1.Service) { records, err := kd.Records(getServiceFQDN(kd.domain, s), false) require.Error(t, err) assert.Equal(t, 0, len(records)) } -func assertSRVForNamedPort(t *testing.T, kd *KubeDNS, s *kapi.Service, portName string) { +func assertSRVForNamedPort(t *testing.T, kd *KubeDNS, s *v1.Service, portName string) { records, err := kd.Records(getSRVFQDN(kd, s, portName), false) require.NoError(t, err) assert.Equal(t, 1, len(records)) assert.Equal(t, getServiceFQDN(kd.domain, s), records[0].Host) } -func assertNoSRVForNamedPort(t *testing.T, kd *KubeDNS, s *kapi.Service, portName string) { +func assertNoSRVForNamedPort(t *testing.T, kd *KubeDNS, s *v1.Service, portName string) { records, err := kd.Records(getSRVFQDN(kd, s, portName), false) require.Error(t, err) assert.Equal(t, 0, len(records)) } -func assertNoDNSForClusterIP(t *testing.T, kd *KubeDNS, s *kapi.Service) { +func assertNoDNSForClusterIP(t *testing.T, kd *KubeDNS, s *v1.Service) { serviceFQDN := getServiceFQDN(kd.domain, s) queries := getEquivalentQueries(serviceFQDN, s.Namespace) for _, query := range queries { @@ -793,7 +793,7 @@ func assertNoDNSForClusterIP(t *testing.T, kd *KubeDNS, s *kapi.Service) { } } -func assertDNSForClusterIP(t *testing.T, kd *KubeDNS, s *kapi.Service) { +func assertDNSForClusterIP(t *testing.T, kd *KubeDNS, s *v1.Service) { serviceFQDN := getServiceFQDN(kd.domain, s) queries := getEquivalentQueries(serviceFQDN, s.Namespace) for _, query := range queries { @@ -804,7 +804,7 @@ func assertDNSForClusterIP(t *testing.T, kd *KubeDNS, s *kapi.Service) { } } -func assertReverseRecord(t *testing.T, kd *KubeDNS, s *kapi.Service) { +func assertReverseRecord(t *testing.T, kd *KubeDNS, s *v1.Service) { segments := util.ReverseArray(strings.Split(s.Spec.ClusterIP, ".")) reverseLookup := fmt.Sprintf("%s%s", strings.Join(segments, "."), util.ArpaSuffix) reverseRecord, err := kd.ReverseRecord(reverseLookup) @@ -812,7 +812,7 @@ func assertReverseRecord(t *testing.T, kd *KubeDNS, s *kapi.Service) { assert.Equal(t, getServiceFQDN(kd.domain, s), reverseRecord.Host) } -func assertNoReverseRecord(t *testing.T, kd *KubeDNS, s *kapi.Service) { +func assertNoReverseRecord(t *testing.T, kd *KubeDNS, s *v1.Service) { segments := util.ReverseArray(strings.Split(s.Spec.ClusterIP, ".")) reverseLookup := fmt.Sprintf("%s%s", strings.Join(segments, "."), util.ArpaSuffix) reverseRecord, err := kd.ReverseRecord(reverseLookup) @@ -830,14 +830,14 @@ func getEquivalentQueries(serviceFQDN, namespace string) []string { } } -func getFederationServiceFQDN(kd *KubeDNS, s *kapi.Service, federationName string) string { +func getFederationServiceFQDN(kd *KubeDNS, s *v1.Service, federationName string) string { return fmt.Sprintf("%s.%s.%s.svc.%s", s.Name, s.Namespace, federationName, kd.domain) } -func getEndpointsFQDN(kd *KubeDNS, e *kapi.Endpoints) string { +func getEndpointsFQDN(kd *KubeDNS, e *v1.Endpoints) string { return fmt.Sprintf("%s.%s.svc.%s", e.Name, e.Namespace, kd.domain) } -func getSRVFQDN(kd *KubeDNS, s *kapi.Service, portName string) string { +func getSRVFQDN(kd *KubeDNS, s *v1.Service, portName string) string { return fmt.Sprintf("_%s._tcp.%s.%s.svc.%s", portName, s.Name, s.Namespace, kd.domain) } diff --git a/pkg/fieldpath/BUILD b/pkg/fieldpath/BUILD index e621102ae65..c027f55dada 100644 --- a/pkg/fieldpath/BUILD +++ b/pkg/fieldpath/BUILD @@ -21,6 +21,7 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/meta:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", ], ) @@ -30,8 +31,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//vendor:github.com/stretchr/testify/assert", ], ) diff --git a/pkg/fieldpath/fieldpath.go b/pkg/fieldpath/fieldpath.go index 08460c00ee8..429aea5b727 100644 --- a/pkg/fieldpath/fieldpath.go +++ b/pkg/fieldpath/fieldpath.go @@ -25,6 +25,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" ) // formatMap formats map[string]string to a string. @@ -65,9 +66,10 @@ func ExtractFieldPathAsString(obj interface{}, fieldPath string) (string, error) return "", fmt.Errorf("Unsupported fieldPath: %v", fieldPath) } +// TODO: move the functions below to pkg/api/util/resources // ExtractResourceValueByContainerName extracts the value of a resource // by providing container name -func ExtractResourceValueByContainerName(fs *api.ResourceFieldSelector, pod *api.Pod, containerName string) (string, error) { +func ExtractResourceValueByContainerName(fs *v1.ResourceFieldSelector, pod *v1.Pod, containerName string) (string, error) { container, err := findContainerInPod(pod, containerName) if err != nil { return "", err @@ -77,7 +79,7 @@ func ExtractResourceValueByContainerName(fs *api.ResourceFieldSelector, pod *api // ExtractResourceValueByContainerNameAndNodeAllocatable extracts the value of a resource // by providing container name and node allocatable -func ExtractResourceValueByContainerNameAndNodeAllocatable(fs *api.ResourceFieldSelector, pod *api.Pod, containerName string, nodeAllocatable api.ResourceList) (string, error) { +func ExtractResourceValueByContainerNameAndNodeAllocatable(fs *v1.ResourceFieldSelector, pod *v1.Pod, containerName string, nodeAllocatable v1.ResourceList) (string, error) { realContainer, err := findContainerInPod(pod, containerName) if err != nil { return "", err @@ -88,7 +90,7 @@ func ExtractResourceValueByContainerNameAndNodeAllocatable(fs *api.ResourceField return "", fmt.Errorf("failed to perform a deep copy of container object: %v", err) } - container, ok := containerCopy.(*api.Container) + container, ok := containerCopy.(*v1.Container) if !ok { return "", fmt.Errorf("unexpected type returned from deep copy of container object") } @@ -100,7 +102,32 @@ func ExtractResourceValueByContainerNameAndNodeAllocatable(fs *api.ResourceField // ExtractContainerResourceValue extracts the value of a resource // in an already known container -func ExtractContainerResourceValue(fs *api.ResourceFieldSelector, container *api.Container) (string, error) { +func ExtractContainerResourceValue(fs *v1.ResourceFieldSelector, container *v1.Container) (string, error) { + divisor := resource.Quantity{} + if divisor.Cmp(fs.Divisor) == 0 { + divisor = resource.MustParse("1") + } else { + divisor = fs.Divisor + } + + switch fs.Resource { + case "limits.cpu": + return convertResourceCPUToString(container.Resources.Limits.Cpu(), divisor) + case "limits.memory": + return convertResourceMemoryToString(container.Resources.Limits.Memory(), divisor) + case "requests.cpu": + return convertResourceCPUToString(container.Resources.Requests.Cpu(), divisor) + case "requests.memory": + return convertResourceMemoryToString(container.Resources.Requests.Memory(), divisor) + } + + return "", fmt.Errorf("Unsupported container resource : %v", fs.Resource) +} + +// TODO: remove this duplicate +// InternalExtractContainerResourceValue extracts the value of a resource +// in an already known container +func InternalExtractContainerResourceValue(fs *api.ResourceFieldSelector, container *api.Container) (string, error) { divisor := resource.Quantity{} if divisor.Cmp(fs.Divisor) == 0 { divisor = resource.MustParse("1") @@ -123,7 +150,7 @@ func ExtractContainerResourceValue(fs *api.ResourceFieldSelector, container *api } // findContainerInPod finds a container by its name in the provided pod -func findContainerInPod(pod *api.Pod, containerName string) (*api.Container, error) { +func findContainerInPod(pod *v1.Pod, containerName string) (*v1.Container, error) { for _, container := range pod.Spec.Containers { if container.Name == containerName { return &container, nil @@ -148,12 +175,12 @@ func convertResourceMemoryToString(memory *resource.Quantity, divisor resource.Q // MergeContainerResourceLimits checks if a limit is applied for // the container, and if not, it sets the limit to the passed resource list. -func MergeContainerResourceLimits(container *api.Container, - allocatable api.ResourceList) { +func MergeContainerResourceLimits(container *v1.Container, + allocatable v1.ResourceList) { if container.Resources.Limits == nil { - container.Resources.Limits = make(api.ResourceList) + container.Resources.Limits = make(v1.ResourceList) } - for _, resource := range []api.ResourceName{api.ResourceCPU, api.ResourceMemory} { + for _, resource := range []v1.ResourceName{v1.ResourceCPU, v1.ResourceMemory} { if quantity, exists := container.Resources.Limits[resource]; !exists || quantity.IsZero() { if cap, exists := allocatable[resource]; exists { container.Resources.Limits[resource] = *cap.Copy() diff --git a/pkg/fieldpath/fieldpath_test.go b/pkg/fieldpath/fieldpath_test.go index 5bfb1061bb7..6fa865edb11 100644 --- a/pkg/fieldpath/fieldpath_test.go +++ b/pkg/fieldpath/fieldpath_test.go @@ -22,8 +22,8 @@ import ( "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" ) func TestExtractFieldPathAsString(t *testing.T) { @@ -43,8 +43,8 @@ func TestExtractFieldPathAsString(t *testing.T) { { name: "ok - namespace", fieldPath: "metadata.namespace", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + obj: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: "object-namespace", }, }, @@ -53,8 +53,8 @@ func TestExtractFieldPathAsString(t *testing.T) { { name: "ok - name", fieldPath: "metadata.name", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + obj: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "object-name", }, }, @@ -63,8 +63,8 @@ func TestExtractFieldPathAsString(t *testing.T) { { name: "ok - labels", fieldPath: "metadata.labels", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + obj: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"key": "value"}, }, }, @@ -73,8 +73,8 @@ func TestExtractFieldPathAsString(t *testing.T) { { name: "ok - labels bslash n", fieldPath: "metadata.labels", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + obj: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"key": "value\n"}, }, }, @@ -83,8 +83,8 @@ func TestExtractFieldPathAsString(t *testing.T) { { name: "ok - annotations", fieldPath: "metadata.annotations", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + obj: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{"builder": "john-doe"}, }, }, @@ -94,8 +94,8 @@ func TestExtractFieldPathAsString(t *testing.T) { { name: "invalid expression", fieldPath: "metadata.whoops", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + obj: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: "object-namespace", }, }, @@ -119,26 +119,26 @@ func TestExtractFieldPathAsString(t *testing.T) { } } -func getPod(cname, cpuRequest, cpuLimit, memoryRequest, memoryLimit string) *api.Pod { - resources := api.ResourceRequirements{ - Limits: make(api.ResourceList), - Requests: make(api.ResourceList), +func getPod(cname, cpuRequest, cpuLimit, memoryRequest, memoryLimit string) *v1.Pod { + resources := v1.ResourceRequirements{ + Limits: make(v1.ResourceList), + Requests: make(v1.ResourceList), } if cpuLimit != "" { - resources.Limits[api.ResourceCPU] = resource.MustParse(cpuLimit) + resources.Limits[v1.ResourceCPU] = resource.MustParse(cpuLimit) } if memoryLimit != "" { - resources.Limits[api.ResourceMemory] = resource.MustParse(memoryLimit) + resources.Limits[v1.ResourceMemory] = resource.MustParse(memoryLimit) } if cpuRequest != "" { - resources.Requests[api.ResourceCPU] = resource.MustParse(cpuRequest) + resources.Requests[v1.ResourceCPU] = resource.MustParse(cpuRequest) } if memoryRequest != "" { - resources.Requests[api.ResourceMemory] = resource.MustParse(memoryRequest) + resources.Requests[v1.ResourceMemory] = resource.MustParse(memoryRequest) } - return &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + return &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: cname, Resources: resources, @@ -150,14 +150,14 @@ func getPod(cname, cpuRequest, cpuLimit, memoryRequest, memoryLimit string) *api func TestExtractResourceValue(t *testing.T) { cases := []struct { - fs *api.ResourceFieldSelector - pod *api.Pod + fs *v1.ResourceFieldSelector + pod *v1.Pod cName string expectedValue string expectedError error }{ { - fs: &api.ResourceFieldSelector{ + fs: &v1.ResourceFieldSelector{ Resource: "limits.cpu", }, cName: "foo", @@ -165,7 +165,7 @@ func TestExtractResourceValue(t *testing.T) { expectedValue: "9", }, { - fs: &api.ResourceFieldSelector{ + fs: &v1.ResourceFieldSelector{ Resource: "requests.cpu", }, cName: "foo", @@ -173,7 +173,7 @@ func TestExtractResourceValue(t *testing.T) { expectedValue: "0", }, { - fs: &api.ResourceFieldSelector{ + fs: &v1.ResourceFieldSelector{ Resource: "requests.cpu", }, cName: "foo", @@ -181,7 +181,7 @@ func TestExtractResourceValue(t *testing.T) { expectedValue: "8", }, { - fs: &api.ResourceFieldSelector{ + fs: &v1.ResourceFieldSelector{ Resource: "requests.cpu", }, cName: "foo", @@ -189,7 +189,7 @@ func TestExtractResourceValue(t *testing.T) { expectedValue: "1", }, { - fs: &api.ResourceFieldSelector{ + fs: &v1.ResourceFieldSelector{ Resource: "requests.cpu", Divisor: resource.MustParse("100m"), }, @@ -198,7 +198,7 @@ func TestExtractResourceValue(t *testing.T) { expectedValue: "12", }, { - fs: &api.ResourceFieldSelector{ + fs: &v1.ResourceFieldSelector{ Resource: "requests.memory", }, cName: "foo", @@ -206,7 +206,7 @@ func TestExtractResourceValue(t *testing.T) { expectedValue: "104857600", }, { - fs: &api.ResourceFieldSelector{ + fs: &v1.ResourceFieldSelector{ Resource: "requests.memory", Divisor: resource.MustParse("1Mi"), }, @@ -215,7 +215,7 @@ func TestExtractResourceValue(t *testing.T) { expectedValue: "100", }, { - fs: &api.ResourceFieldSelector{ + fs: &v1.ResourceFieldSelector{ Resource: "limits.memory", }, cName: "foo", diff --git a/pkg/generated/openapi/zz_generated.openapi.go b/pkg/generated/openapi/zz_generated.openapi.go index 77446165438..cdd05751cd1 100644 --- a/pkg/generated/openapi/zz_generated.openapi.go +++ b/pkg/generated/openapi/zz_generated.openapi.go @@ -9633,6 +9633,31 @@ var OpenAPIDefinitions *common.OpenAPIDefinitions = &common.OpenAPIDefinitions{ }, Dependencies: []string{}, }, + "v1.NodeResources": { + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "NodeResources is an object for conveying resource information about a node. see http://releases.k8s.io/HEAD/docs/design/resources.md for more details.", + Properties: map[string]spec.Schema{ + "Capacity": { + SchemaProps: spec.SchemaProps{ + Description: "Capacity represents the available resources of a node", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Ref: spec.MustCreateRef("#/definitions/resource.Quantity"), + }, + }, + }, + }, + }, + }, + Required: []string{"Capacity"}, + }, + }, + Dependencies: []string{ + "resource.Quantity"}, + }, "v1.NodeSelector": { Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -12841,6 +12866,28 @@ var OpenAPIDefinitions *common.OpenAPIDefinitions = &common.OpenAPIDefinitions{ Dependencies: []string{ "v1.LoadBalancerStatus"}, }, + "v1.Sysctl": { + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Properties: map[string]spec.Schema{ + "Name": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + Format: "", + }, + }, + "Value": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"Name", "Value"}, + }, + }, + Dependencies: []string{}, + }, "v1.TCPSocketAction": { Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -13244,6 +13291,15 @@ var OpenAPIDefinitions *common.OpenAPIDefinitions = &common.OpenAPIDefinitions{ Dependencies: []string{ "v1.PodAffinityTerm"}, }, + "v1.simpleNameGenerator": { + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "simpleNameGenerator generates random names.", + Properties: map[string]spec.Schema{}, + }, + }, + Dependencies: []string{}, + }, "v1alpha1.CertificateSigningRequest": { Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -13480,6 +13536,23 @@ var OpenAPIDefinitions *common.OpenAPIDefinitions = &common.OpenAPIDefinitions{ Dependencies: []string{ "v1.ObjectMeta", "v1alpha1.RoleRef", "v1alpha1.Subject"}, }, + "v1alpha1.ClusterRoleBindingBuilder": { + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterRoleBindingBuilder let's us attach methods. A no-no for API types. We use it to construct bindings in code. It's more compact than trying to write them out in a literal.", + Properties: map[string]spec.Schema{ + "ClusterRoleBinding": { + SchemaProps: spec.SchemaProps{ + Ref: spec.MustCreateRef("#/definitions/v1alpha1.ClusterRoleBinding"), + }, + }, + }, + Required: []string{"ClusterRoleBinding"}, + }, + }, + Dependencies: []string{ + "v1alpha1.ClusterRoleBinding"}, + }, "v1alpha1.ClusterRoleBindingList": { Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -15003,6 +15076,23 @@ var OpenAPIDefinitions *common.OpenAPIDefinitions = &common.OpenAPIDefinitions{ Dependencies: []string{ "runtime.RawExtension"}, }, + "v1alpha1.PolicyRuleBuilder": { + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "PolicyRuleBuilder let's us attach methods. A no-no for API types. We use it to construct rules in code. It's more compact than trying to write them out in a literal and allows us to perform some basic checking during construction", + Properties: map[string]spec.Schema{ + "PolicyRule": { + SchemaProps: spec.SchemaProps{ + Ref: spec.MustCreateRef("#/definitions/v1alpha1.PolicyRule"), + }, + }, + }, + Required: []string{"PolicyRule"}, + }, + }, + Dependencies: []string{ + "v1alpha1.PolicyRule"}, + }, "v1alpha1.Role": { Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ diff --git a/pkg/genericapiserver/BUILD b/pkg/genericapiserver/BUILD index 02050febe24..0d4f979b2ea 100644 --- a/pkg/genericapiserver/BUILD +++ b/pkg/genericapiserver/BUILD @@ -34,6 +34,7 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/rest:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/apiserver:go_default_library", diff --git a/pkg/genericapiserver/config.go b/pkg/genericapiserver/config.go index 098a398c6dc..3f4eb7ef652 100644 --- a/pkg/genericapiserver/config.go +++ b/pkg/genericapiserver/config.go @@ -37,6 +37,7 @@ import ( "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" apiserverfilters "k8s.io/kubernetes/pkg/apiserver/filters" apiserveropenapi "k8s.io/kubernetes/pkg/apiserver/openapi" "k8s.io/kubernetes/pkg/apiserver/request" @@ -522,7 +523,7 @@ func DefaultAndValidateRunOptions(options *options.ServerRunOptions) { glog.Warningf("Unable to obtain external host address from cloud provider: %v", err) } else { for _, addr := range addrs { - if addr.Type == api.NodeExternalIP { + if addr.Type == v1.NodeExternalIP { options.ExternalHost = addr.Address } } diff --git a/pkg/kubectl/BUILD b/pkg/kubectl/BUILD index cc112dd3ef0..3999db0d164 100644 --- a/pkg/kubectl/BUILD +++ b/pkg/kubectl/BUILD @@ -46,6 +46,7 @@ go_library( "sorted_resource_name_list.go", "sorting_printer.go", "stop.go", + "versioned_client.go", ], tags = ["automanaged"], deps = [ @@ -68,6 +69,7 @@ go_library( "//pkg/apis/batch/v2alpha1:go_default_library", "//pkg/apis/certificates:go_default_library", "//pkg/apis/extensions:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/apis/policy:go_default_library", "//pkg/apis/rbac:go_default_library", "//pkg/apis/storage:go_default_library", @@ -77,6 +79,9 @@ go_library( "//pkg/client/clientset_generated/internalclientset/typed/batch/internalversion:go_default_library", "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", "//pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/retry:go_default_library", "//pkg/client/unversioned:go_default_library", @@ -154,6 +159,7 @@ go_test( "//pkg/apimachinery/registered:go_default_library", "//pkg/apis/batch:go_default_library", "//pkg/apis/extensions:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/apis/policy:go_default_library", "//pkg/apis/storage:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", @@ -161,6 +167,7 @@ go_test( "//pkg/client/clientset_generated/internalclientset/typed/batch/internalversion:go_default_library", "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", "//pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/restclient/fake:go_default_library", "//pkg/client/testing/core:go_default_library", diff --git a/pkg/kubectl/cmd/util/BUILD b/pkg/kubectl/cmd/util/BUILD index e567c8eb63d..246ab0edabc 100644 --- a/pkg/kubectl/cmd/util/BUILD +++ b/pkg/kubectl/cmd/util/BUILD @@ -29,6 +29,7 @@ go_library( "//pkg/api/meta:go_default_library", "//pkg/api/service:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/api/validation:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/apis/apps:go_default_library", diff --git a/pkg/kubectl/cmd/util/factory.go b/pkg/kubectl/cmd/util/factory.go index bd5dc146140..cfcd01083fc 100644 --- a/pkg/kubectl/cmd/util/factory.go +++ b/pkg/kubectl/cmd/util/factory.go @@ -42,6 +42,7 @@ import ( "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/service" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/apis/apps" @@ -596,7 +597,7 @@ func (f *factory) LogsForObject(object, options runtime.Object) (*restclient.Req return nil, errors.New("provided options object is not a PodLogOptions") } selector := labels.SelectorFromSet(t.Spec.Selector) - sortBy := func(pods []*api.Pod) sort.Interface { return controller.ByLogging(pods) } + sortBy := func(pods []*v1.Pod) sort.Interface { return controller.ByLogging(pods) } pod, numPods, err := GetFirstPod(clientset.Core(), t.Namespace, selector, 20*time.Second, sortBy) if err != nil { return nil, err @@ -616,7 +617,7 @@ func (f *factory) LogsForObject(object, options runtime.Object) (*restclient.Req if err != nil { return nil, fmt.Errorf("invalid label selector: %v", err) } - sortBy := func(pods []*api.Pod) sort.Interface { return controller.ByLogging(pods) } + sortBy := func(pods []*v1.Pod) sort.Interface { return controller.ByLogging(pods) } pod, numPods, err := GetFirstPod(clientset.Core(), t.Namespace, selector, 20*time.Second, sortBy) if err != nil { return nil, err @@ -797,7 +798,7 @@ func (f *factory) AttachablePodForObject(object runtime.Object) (*api.Pod, error switch t := object.(type) { case *api.ReplicationController: selector := labels.SelectorFromSet(t.Spec.Selector) - sortBy := func(pods []*api.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) } + sortBy := func(pods []*v1.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) } pod, _, err := GetFirstPod(clientset.Core(), t.Namespace, selector, 1*time.Minute, sortBy) return pod, err case *extensions.Deployment: @@ -805,7 +806,7 @@ func (f *factory) AttachablePodForObject(object runtime.Object) (*api.Pod, error if err != nil { return nil, fmt.Errorf("invalid label selector: %v", err) } - sortBy := func(pods []*api.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) } + sortBy := func(pods []*v1.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) } pod, _, err := GetFirstPod(clientset.Core(), t.Namespace, selector, 1*time.Minute, sortBy) return pod, err case *batch.Job: @@ -813,7 +814,7 @@ func (f *factory) AttachablePodForObject(object runtime.Object) (*api.Pod, error if err != nil { return nil, fmt.Errorf("invalid label selector: %v", err) } - sortBy := func(pods []*api.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) } + sortBy := func(pods []*v1.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) } pod, _, err := GetFirstPod(clientset.Core(), t.Namespace, selector, 1*time.Minute, sortBy) return pod, err case *api.Pod: @@ -886,21 +887,25 @@ See http://kubernetes.io/docs/user-guide/services-firewalls for more details. // GetFirstPod returns a pod matching the namespace and label selector // and the number of all pods that match the label selector. -func GetFirstPod(client coreclient.PodsGetter, namespace string, selector labels.Selector, timeout time.Duration, sortBy func([]*api.Pod) sort.Interface) (*api.Pod, int, error) { +func GetFirstPod(client coreclient.PodsGetter, namespace string, selector labels.Selector, timeout time.Duration, sortBy func([]*v1.Pod) sort.Interface) (*api.Pod, int, error) { options := api.ListOptions{LabelSelector: selector} podList, err := client.Pods(namespace).List(options) if err != nil { return nil, 0, err } - pods := []*api.Pod{} + pods := []*v1.Pod{} for i := range podList.Items { pod := podList.Items[i] - pods = append(pods, &pod) + externalPod := &v1.Pod{} + v1.Convert_api_Pod_To_v1_Pod(&pod, externalPod, nil) + pods = append(pods, externalPod) } if len(pods) > 0 { sort.Sort(sortBy(pods)) - return pods[0], len(podList.Items), nil + internalPod := &api.Pod{} + v1.Convert_v1_Pod_To_api_Pod(pods[0], internalPod, nil) + return internalPod, len(podList.Items), nil } // Watch until we observe a pod diff --git a/pkg/kubectl/cmd/util/factory_test.go b/pkg/kubectl/cmd/util/factory_test.go index c5980bdafef..b53bb2bb5d0 100644 --- a/pkg/kubectl/cmd/util/factory_test.go +++ b/pkg/kubectl/cmd/util/factory_test.go @@ -35,6 +35,7 @@ import ( "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/apis/extensions" @@ -471,7 +472,7 @@ func TestGetFirstPod(t *testing.T) { podList *api.PodList watching []watch.Event - sortBy func([]*api.Pod) sort.Interface + sortBy func([]*v1.Pod) sort.Interface expected *api.Pod expectedNum int @@ -480,7 +481,7 @@ func TestGetFirstPod(t *testing.T) { { name: "kubectl logs - two ready pods", podList: newPodList(2, -1, -1, labelSet), - sortBy: func(pods []*api.Pod) sort.Interface { return controller.ByLogging(pods) }, + sortBy: func(pods []*v1.Pod) sort.Interface { return controller.ByLogging(pods) }, expected: &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: "pod-1", @@ -502,7 +503,7 @@ func TestGetFirstPod(t *testing.T) { { name: "kubectl logs - one unhealthy, one healthy", podList: newPodList(2, -1, 1, labelSet), - sortBy: func(pods []*api.Pod) sort.Interface { return controller.ByLogging(pods) }, + sortBy: func(pods []*v1.Pod) sort.Interface { return controller.ByLogging(pods) }, expected: &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: "pod-2", @@ -525,7 +526,7 @@ func TestGetFirstPod(t *testing.T) { { name: "kubectl attach - two ready pods", podList: newPodList(2, -1, -1, labelSet), - sortBy: func(pods []*api.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) }, + sortBy: func(pods []*v1.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) }, expected: &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: "pod-1", @@ -568,7 +569,7 @@ func TestGetFirstPod(t *testing.T) { }, }, }, - sortBy: func(pods []*api.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) }, + sortBy: func(pods []*v1.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) }, expected: &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: "pod-1", @@ -607,6 +608,7 @@ func TestGetFirstPod(t *testing.T) { selector := labels.Set(labelSet).AsSelector() pod, numPods, err := GetFirstPod(fake.Core(), api.NamespaceDefault, selector, 1*time.Minute, test.sortBy) + pod.Spec.SecurityContext = nil if !test.expectedErr && err != nil { t.Errorf("%s: unexpected error: %v", test.name, err) continue diff --git a/pkg/kubectl/describe.go b/pkg/kubectl/describe.go index 023313aa6ff..503db1bb7d7 100644 --- a/pkg/kubectl/describe.go +++ b/pkg/kubectl/describe.go @@ -40,12 +40,14 @@ import ( "k8s.io/kubernetes/pkg/apis/batch" "k8s.io/kubernetes/pkg/apis/certificates" "k8s.io/kubernetes/pkg/apis/extensions" + versionedextension "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/apis/policy" "k8s.io/kubernetes/pkg/apis/storage" storageutil "k8s.io/kubernetes/pkg/apis/storage/util" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" coreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" extensionsclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion" + versionedclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" "k8s.io/kubernetes/pkg/fieldpath" "k8s.io/kubernetes/pkg/fields" @@ -113,7 +115,7 @@ func describerMap(c clientset.Interface) map[unversioned.GroupKind]Describer { extensions.Kind("NetworkPolicy"): &NetworkPolicyDescriber{c}, autoscaling.Kind("HorizontalPodAutoscaler"): &HorizontalPodAutoscalerDescriber{c}, extensions.Kind("DaemonSet"): &DaemonSetDescriber{c}, - extensions.Kind("Deployment"): &DeploymentDescriber{c}, + extensions.Kind("Deployment"): &DeploymentDescriber{c, versionedClientsetForDeployment(c)}, extensions.Kind("Job"): &JobDescriber{c}, extensions.Kind("Ingress"): &IngressDescriber{c}, batch.Kind("Job"): &JobDescriber{c}, @@ -505,7 +507,7 @@ func describePod(pod *api.Pod, events *api.EventList) (string, error) { } } describeVolumes(pod.Spec.Volumes, out, "") - fmt.Fprintf(out, "QoS Class:\t%s\n", qos.GetPodQOS(pod)) + fmt.Fprintf(out, "QoS Class:\t%s\n", qos.InternalGetPodQOS(pod)) printTolerationsInAnnotationMultiline(out, "Tolerations", pod.Annotations) if events != nil { DescribeEvents(events, out) @@ -955,7 +957,7 @@ func describeContainers(label string, containers []api.Container, containerStatu } fmt.Fprintf(out, " %s:\t%s (%s:%s)\n", e.Name, valueFrom, e.ValueFrom.FieldRef.APIVersion, e.ValueFrom.FieldRef.FieldPath) case e.ValueFrom.ResourceFieldRef != nil: - valueFrom, err := fieldpath.ExtractContainerResourceValue(e.ValueFrom.ResourceFieldRef, &container) + valueFrom, err := fieldpath.InternalExtractContainerResourceValue(e.ValueFrom.ResourceFieldRef, &container) if err != nil { valueFrom = "" } @@ -2152,10 +2154,11 @@ func DescribeEvents(el *api.EventList, w io.Writer) { // DeploymentDescriber generates information about a deployment. type DeploymentDescriber struct { clientset.Interface + versionedClient versionedclientset.Interface } func (dd *DeploymentDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) { - d, err := dd.Extensions().Deployments(namespace).Get(name) + d, err := dd.versionedClient.Extensions().Deployments(namespace).Get(name) if err != nil { return "", err } @@ -2183,10 +2186,10 @@ func (dd *DeploymentDescriber) Describe(namespace, name string, describerSetting fmt.Fprintf(out, " %v \t%v\t%v\n", c.Type, c.Status, c.Reason) } } - oldRSs, _, newRS, err := deploymentutil.GetAllReplicaSets(d, dd) + oldRSs, _, newRS, err := deploymentutil.GetAllReplicaSets(d, dd.versionedClient) if err == nil { fmt.Fprintf(out, "OldReplicaSets:\t%s\n", printReplicaSetsByLabels(oldRSs)) - var newRSs []*extensions.ReplicaSet + var newRSs []*versionedextension.ReplicaSet if newRS != nil { newRSs = append(newRSs, newRS) } @@ -2248,7 +2251,7 @@ func printReplicationControllersByLabels(matchingRCs []*api.ReplicationControlle return list } -func printReplicaSetsByLabels(matchingRSs []*extensions.ReplicaSet) string { +func printReplicaSetsByLabels(matchingRSs []*versionedextension.ReplicaSet) string { // Format the matching ReplicaSets into strings. rsStrings := make([]string, 0, len(matchingRSs)) for _, rs := range matchingRSs { diff --git a/pkg/kubectl/describe_test.go b/pkg/kubectl/describe_test.go index 9d7cca87d3b..5ab645fdb33 100644 --- a/pkg/kubectl/describe_test.go +++ b/pkg/kubectl/describe_test.go @@ -30,11 +30,14 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/apis/policy" "k8s.io/kubernetes/pkg/apis/storage" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + versionedfake "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/util/intstr" ) @@ -618,16 +621,18 @@ func TestPersistentVolumeDescriber(t *testing.T) { } func TestDescribeDeployment(t *testing.T) { - fake := fake.NewSimpleClientset(&extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ + fake := fake.NewSimpleClientset() + versionedFake := versionedfake.NewSimpleClientset(&v1beta1.Deployment{ + ObjectMeta: v1.ObjectMeta{ Name: "bar", Namespace: "foo", }, - Spec: extensions.DeploymentSpec{ - Template: api.PodTemplateSpec{}, + Spec: v1beta1.DeploymentSpec{ + Selector: &unversioned.LabelSelector{}, + Template: v1.PodTemplateSpec{}, }, }) - d := DeploymentDescriber{fake} + d := DeploymentDescriber{fake, versionedFake} out, err := d.Describe("foo", "bar", DescriberSettings{ShowEvents: true}) if err != nil { t.Errorf("unexpected error: %v", err) @@ -748,12 +753,16 @@ func TestDescribeEvents(t *testing.T) { }, events), }, "DeploymentDescriber": &DeploymentDescriber{ - fake.NewSimpleClientset(&extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ + fake.NewSimpleClientset(events), + versionedfake.NewSimpleClientset(&v1beta1.Deployment{ + ObjectMeta: v1.ObjectMeta{ Name: "bar", Namespace: "foo", }, - }, events), + Spec: v1beta1.DeploymentSpec{ + Selector: &unversioned.LabelSelector{}, + }, + }), }, "EndpointsDescriber": &EndpointsDescriber{ fake.NewSimpleClientset(&api.Endpoints{ diff --git a/pkg/kubectl/history.go b/pkg/kubectl/history.go index 8485139fe2b..a6522d49165 100644 --- a/pkg/kubectl/history.go +++ b/pkg/kubectl/history.go @@ -24,6 +24,7 @@ import ( "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/apis/extensions" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" @@ -54,11 +55,12 @@ type DeploymentHistoryViewer struct { // ViewHistory returns a revision-to-replicaset map as the revision history of a deployment func (h *DeploymentHistoryViewer) ViewHistory(namespace, name string, revision int64) (string, error) { - deployment, err := h.c.Extensions().Deployments(namespace).Get(name) + versionedClient := versionedClientsetForDeployment(h.c) + deployment, err := versionedClient.Extensions().Deployments(namespace).Get(name) if err != nil { return "", fmt.Errorf("failed to retrieve deployment %s: %v", name, err) } - _, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(deployment, h.c) + _, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(deployment, versionedClient) if err != nil { return "", fmt.Errorf("failed to retrieve replica sets from deployment %s: %v", name, err) } @@ -67,7 +69,7 @@ func (h *DeploymentHistoryViewer) ViewHistory(namespace, name string, revision i allRSs = append(allRSs, newRS) } - historyInfo := make(map[int64]*api.PodTemplateSpec) + historyInfo := make(map[int64]*v1.PodTemplateSpec) for _, rs := range allRSs { v, err := deploymentutil.Revision(rs) if err != nil { @@ -94,7 +96,11 @@ func (h *DeploymentHistoryViewer) ViewHistory(namespace, name string, revision i return "", fmt.Errorf("unable to find the specified revision") } buf := bytes.NewBuffer([]byte{}) - DescribePodTemplate(template, buf) + internalTemplate := &api.PodTemplateSpec{} + if err := v1.Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(template, internalTemplate, nil); err != nil { + return "", fmt.Errorf("failed to convert podtemplate, %v", err) + } + DescribePodTemplate(internalTemplate, buf) return buf.String(), nil } diff --git a/pkg/kubectl/rollback.go b/pkg/kubectl/rollback.go index eb595758881..9b1ddc00570 100644 --- a/pkg/kubectl/rollback.go +++ b/pkg/kubectl/rollback.go @@ -25,7 +25,9 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/extensions" + externalextensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" "k8s.io/kubernetes/pkg/runtime" @@ -130,7 +132,12 @@ func isRollbackEvent(e *api.Event) (bool, string) { } func simpleDryRun(deployment *extensions.Deployment, c clientset.Interface, toRevision int64) (string, error) { - _, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(deployment, c) + externalDeployment := &externalextensions.Deployment{} + if err := api.Scheme.Convert(deployment, externalDeployment, nil); err != nil { + return "", fmt.Errorf("failed to convert deployment, %v", err) + } + versionedClient := versionedClientsetForDeployment(c) + _, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(externalDeployment, versionedClient) if err != nil { return "", fmt.Errorf("failed to retrieve replica sets from deployment %s: %v", deployment.Name, err) } @@ -139,7 +146,7 @@ func simpleDryRun(deployment *extensions.Deployment, c clientset.Interface, toRe allRSs = append(allRSs, newRS) } - revisionToSpec := make(map[int64]*api.PodTemplateSpec) + revisionToSpec := make(map[int64]*v1.PodTemplateSpec) for _, rs := range allRSs { v, err := deploymentutil.Revision(rs) if err != nil { @@ -158,7 +165,11 @@ func simpleDryRun(deployment *extensions.Deployment, c clientset.Interface, toRe return "", fmt.Errorf("unable to find specified revision") } buf := bytes.NewBuffer([]byte{}) - DescribePodTemplate(template, buf) + internalTemplate := &api.PodTemplateSpec{} + if err := v1.Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(template, internalTemplate, nil); err != nil { + return "", fmt.Errorf("failed to convert podtemplate, %v", err) + } + DescribePodTemplate(internalTemplate, buf) return buf.String(), nil } @@ -172,6 +183,10 @@ func simpleDryRun(deployment *extensions.Deployment, c clientset.Interface, toRe template, _ := revisionToSpec[revisions[len(revisions)-1]] buf := bytes.NewBuffer([]byte{}) buf.WriteString("\n") - DescribePodTemplate(template, buf) + internalTemplate := &api.PodTemplateSpec{} + if err := v1.Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(template, internalTemplate, nil); err != nil { + return "", fmt.Errorf("failed to convert podtemplate, %v", err) + } + DescribePodTemplate(internalTemplate, buf) return buf.String(), nil } diff --git a/pkg/kubectl/rolling_updater.go b/pkg/kubectl/rolling_updater.go index 76c14d976f2..67b60e2896c 100644 --- a/pkg/kubectl/rolling_updater.go +++ b/pkg/kubectl/rolling_updater.go @@ -27,6 +27,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" coreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" "k8s.io/kubernetes/pkg/client/retry" client "k8s.io/kubernetes/pkg/client/unversioned" @@ -420,7 +421,11 @@ func (r *RollingUpdater) readyPods(oldRc, newRc *api.ReplicationController, minR return 0, 0, err } for _, pod := range pods.Items { - if !deploymentutil.IsPodAvailable(&pod, minReadySeconds, r.nowFn().Time) { + v1Pod := &v1.Pod{} + if err := v1.Convert_api_Pod_To_v1_Pod(&pod, v1Pod, nil); err != nil { + return 0, 0, err + } + if !deploymentutil.IsPodAvailable(v1Pod, minReadySeconds, r.nowFn().Time) { continue } switch controller.Name { diff --git a/pkg/kubectl/rollout_status.go b/pkg/kubectl/rollout_status.go index 0fbeffaee5d..7f2404b5f7f 100644 --- a/pkg/kubectl/rollout_status.go +++ b/pkg/kubectl/rollout_status.go @@ -59,7 +59,7 @@ func (s *DeploymentStatusViewer) Status(namespace, name string, revision int64) } } if deployment.Generation <= deployment.Status.ObservedGeneration { - cond := util.GetDeploymentCondition(deployment.Status, extensions.DeploymentProgressing) + cond := util.GetDeploymentConditionInternal(deployment.Status, extensions.DeploymentProgressing) if cond != nil && cond.Reason == util.TimedOutReason { return "", false, fmt.Errorf("deployment %q exceeded its progress deadline", name) } diff --git a/pkg/kubectl/sorted_resource_name_list.go b/pkg/kubectl/sorted_resource_name_list.go index aad1d807473..f5f44c86bd4 100644 --- a/pkg/kubectl/sorted_resource_name_list.go +++ b/pkg/kubectl/sorted_resource_name_list.go @@ -79,7 +79,7 @@ func (list SortableVolumeMounts) Less(i, j int) bool { func SortedQoSResourceNames(list qos.QOSList) []api.ResourceName { resources := make([]api.ResourceName, 0, len(list)) for res := range list { - resources = append(resources, res) + resources = append(resources, api.ResourceName(res)) } sort.Sort(SortableResourceNames(resources)) return resources diff --git a/pkg/kubectl/stop.go b/pkg/kubectl/stop.go index deb273b7c86..11def8c030f 100644 --- a/pkg/kubectl/stop.go +++ b/pkg/kubectl/stop.go @@ -429,7 +429,7 @@ func (reaper *DeploymentReaper) Stop(namespace, name string, timeout time.Durati } // Use observedGeneration to determine if the deployment controller noticed the pause. - if err := deploymentutil.WaitForObservedDeployment(func() (*extensions.Deployment, error) { + if err := deploymentutil.WaitForObservedDeploymentInternal(func() (*extensions.Deployment, error) { return deployments.Get(name) }, deployment.Generation, 1*time.Second, 1*time.Minute); err != nil { return err diff --git a/pkg/kubectl/stop_test.go b/pkg/kubectl/stop_test.go index 54c62a148b1..a63090b743d 100644 --- a/pkg/kubectl/stop_test.go +++ b/pkg/kubectl/stop_test.go @@ -438,7 +438,7 @@ func TestDeploymentStop(t *testing.T) { Replicas: 0, }, } - template := deploymentutil.GetNewReplicaSetTemplate(&deployment) + template := deploymentutil.GetNewReplicaSetTemplateInternal(&deployment) tests := []struct { Name string Objs []runtime.Object @@ -675,7 +675,7 @@ func TestDeploymentNotFoundError(t *testing.T) { Replicas: 0, }, } - template := deploymentutil.GetNewReplicaSetTemplate(deployment) + template := deploymentutil.GetNewReplicaSetTemplateInternal(deployment) fake := fake.NewSimpleClientset( deployment, diff --git a/pkg/kubectl/versioned_client.go b/pkg/kubectl/versioned_client.go new file mode 100644 index 00000000000..f0c82d6c3c0 --- /dev/null +++ b/pkg/kubectl/versioned_client.go @@ -0,0 +1,34 @@ +/* +Copyright 2016 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package kubectl + +import ( + internalclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + externalclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" + extensions "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1" +) + +func versionedClientsetForDeployment(internalClient internalclientset.Interface) externalclientset.Interface { + if internalClient == nil { + return &externalclientset.Clientset{} + } + return &externalclientset.Clientset{ + CoreV1Client: core.New(internalClient.Core().RESTClient()), + ExtensionsV1beta1Client: extensions.New(internalClient.Extensions().RESTClient()), + } +} diff --git a/pkg/kubelet/BUILD b/pkg/kubelet/BUILD index eaade638c31..766d7c2c830 100644 --- a/pkg/kubelet/BUILD +++ b/pkg/kubelet/BUILD @@ -39,15 +39,16 @@ go_library( "//cmd/kubelet/app/options:go_default_library", "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", - "//pkg/api/pod:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/api/validation:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/pod:go_default_library", + "//pkg/api/v1/validation:go_default_library", "//pkg/apis/componentconfig:go_default_library", "//pkg/apis/componentconfig/v1alpha1:go_default_library", "//pkg/capabilities:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/record:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/fieldpath:go_default_library", @@ -151,10 +152,11 @@ go_test( "//pkg/api/errors:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/apis/componentconfig:go_default_library", "//pkg/capabilities:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/kubelet/cadvisor/testing:go_default_library", diff --git a/pkg/kubelet/active_deadline.go b/pkg/kubelet/active_deadline.go index 154bbd3bad1..9356f0e31ca 100644 --- a/pkg/kubelet/active_deadline.go +++ b/pkg/kubelet/active_deadline.go @@ -20,7 +20,7 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/kubelet/lifecycle" "k8s.io/kubernetes/pkg/kubelet/status" @@ -61,22 +61,22 @@ func newActiveDeadlineHandler( } // ShouldSync returns true if the pod is past its active deadline. -func (m *activeDeadlineHandler) ShouldSync(pod *api.Pod) bool { +func (m *activeDeadlineHandler) ShouldSync(pod *v1.Pod) bool { return m.pastActiveDeadline(pod) } // ShouldEvict returns true if the pod is past its active deadline. // It dispatches an event that the pod should be evicted if it is past its deadline. -func (m *activeDeadlineHandler) ShouldEvict(pod *api.Pod) lifecycle.ShouldEvictResponse { +func (m *activeDeadlineHandler) ShouldEvict(pod *v1.Pod) lifecycle.ShouldEvictResponse { if !m.pastActiveDeadline(pod) { return lifecycle.ShouldEvictResponse{Evict: false} } - m.recorder.Eventf(pod, api.EventTypeNormal, reason, message) + m.recorder.Eventf(pod, v1.EventTypeNormal, reason, message) return lifecycle.ShouldEvictResponse{Evict: true, Reason: reason, Message: message} } // pastActiveDeadline returns true if the pod has been active for more than its ActiveDeadlineSeconds -func (m *activeDeadlineHandler) pastActiveDeadline(pod *api.Pod) bool { +func (m *activeDeadlineHandler) pastActiveDeadline(pod *v1.Pod) bool { // no active deadline was specified if pod.Spec.ActiveDeadlineSeconds == nil { return false diff --git a/pkg/kubelet/active_deadline_test.go b/pkg/kubelet/active_deadline_test.go index 52ebeafdcb5..c3842f75072 100644 --- a/pkg/kubelet/active_deadline_test.go +++ b/pkg/kubelet/active_deadline_test.go @@ -20,8 +20,8 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/clock" @@ -29,17 +29,17 @@ import ( // mockPodStatusProvider returns the status on the specified pod type mockPodStatusProvider struct { - pods []*api.Pod + pods []*v1.Pod } // GetPodStatus returns the status on the associated pod with matching uid (if found) -func (m *mockPodStatusProvider) GetPodStatus(uid types.UID) (api.PodStatus, bool) { +func (m *mockPodStatusProvider) GetPodStatus(uid types.UID) (v1.PodStatus, bool) { for _, pod := range m.pods { if pod.UID == uid { return pod.Status, true } } - return api.PodStatus{}, false + return v1.PodStatus{}, false } // TestActiveDeadlineHandler verifies the active deadline handler functions as expected. @@ -71,7 +71,7 @@ func TestActiveDeadlineHandler(t *testing.T) { pods[2].Spec.ActiveDeadlineSeconds = nil testCases := []struct { - pod *api.Pod + pod *v1.Pod expected bool }{{pods[0], true}, {pods[1], false}, {pods[2], false}, {pods[3], false}} diff --git a/pkg/kubelet/cadvisor/BUILD b/pkg/kubelet/cadvisor/BUILD index fde1e013da9..20485f3117b 100644 --- a/pkg/kubelet/cadvisor/BUILD +++ b/pkg/kubelet/cadvisor/BUILD @@ -20,8 +20,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/types:go_default_library", "//pkg/util/runtime:go_default_library", "//vendor:github.com/golang/glog", diff --git a/pkg/kubelet/cadvisor/util.go b/pkg/kubelet/cadvisor/util.go index 5fa528a5853..2ab3be4aa9d 100644 --- a/pkg/kubelet/cadvisor/util.go +++ b/pkg/kubelet/cadvisor/util.go @@ -18,16 +18,16 @@ package cadvisor import ( cadvisorApi "github.com/google/cadvisor/info/v1" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" ) -func CapacityFromMachineInfo(info *cadvisorApi.MachineInfo) api.ResourceList { - c := api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity( +func CapacityFromMachineInfo(info *cadvisorApi.MachineInfo) v1.ResourceList { + c := v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity( int64(info.NumCores*1000), resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity( + v1.ResourceMemory: *resource.NewQuantity( int64(info.MemoryCapacity), resource.BinarySI), } diff --git a/pkg/kubelet/client/BUILD b/pkg/kubelet/client/BUILD index 97c356d4468..d37617b0e90 100644 --- a/pkg/kubelet/client/BUILD +++ b/pkg/kubelet/client/BUILD @@ -16,6 +16,7 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/transport:go_default_library", "//pkg/types:go_default_library", @@ -33,7 +34,7 @@ go_test( "skip", ], deps = [ - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/restclient:go_default_library", ], ) diff --git a/pkg/kubelet/client/kubelet_client.go b/pkg/kubelet/client/kubelet_client.go index aa9644b6c96..0e593ccc9aa 100644 --- a/pkg/kubelet/client/kubelet_client.go +++ b/pkg/kubelet/client/kubelet_client.go @@ -23,6 +23,7 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/transport" "k8s.io/kubernetes/pkg/types" @@ -102,13 +103,13 @@ func (c *KubeletClientConfig) transportConfig() *transport.Config { // NodeGetter defines an interface for looking up a node by name type NodeGetter interface { - Get(name string) (*api.Node, error) + Get(name string) (*v1.Node, error) } // NodeGetterFunc allows implementing NodeGetter with a function -type NodeGetterFunc func(name string) (*api.Node, error) +type NodeGetterFunc func(name string) (*v1.Node, error) -func (f NodeGetterFunc) Get(name string) (*api.Node, error) { +func (f NodeGetterFunc) Get(name string) (*v1.Node, error) { return f(name) } @@ -123,7 +124,7 @@ type NodeConnectionInfoGetter struct { // transport is the transport to use to send a request to all kubelets transport http.RoundTripper // preferredAddressTypes specifies the preferred order to use to find a node address - preferredAddressTypes []api.NodeAddressType + preferredAddressTypes []v1.NodeAddressType } func NewNodeConnectionInfoGetter(nodes NodeGetter, config KubeletClientConfig) (ConnectionInfoGetter, error) { @@ -137,9 +138,9 @@ func NewNodeConnectionInfoGetter(nodes NodeGetter, config KubeletClientConfig) ( return nil, err } - types := []api.NodeAddressType{} + types := []v1.NodeAddressType{} for _, t := range config.PreferredAddressTypes { - types = append(types, api.NodeAddressType(t)) + types = append(types, v1.NodeAddressType(t)) } return &NodeConnectionInfoGetter{ diff --git a/pkg/kubelet/client/kubelet_client_test.go b/pkg/kubelet/client/kubelet_client_test.go index c2be5581299..3123c527706 100644 --- a/pkg/kubelet/client/kubelet_client_test.go +++ b/pkg/kubelet/client/kubelet_client_test.go @@ -19,13 +19,13 @@ package client import ( "testing" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/restclient" ) // Ensure a node client can be used as a NodeGetter. // This allows anyone with a node client to easily construct a NewNodeConnectionInfoGetter. -var _ = NodeGetter(internalversion.NodeInterface(nil)) +var _ = NodeGetter(v1core.NodeInterface(nil)) func TestMakeTransportInvalid(t *testing.T) { config := &KubeletClientConfig{ diff --git a/pkg/kubelet/cm/BUILD b/pkg/kubelet/cm/BUILD index ed5f6050537..5414a5b7c2e 100644 --- a/pkg/kubelet/cm/BUILD +++ b/pkg/kubelet/cm/BUILD @@ -24,8 +24,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/cadvisor:go_default_library", "//pkg/kubelet/cm/util:go_default_library", "//pkg/kubelet/qos:go_default_library", @@ -58,8 +58,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/util/mount:go_default_library", "//vendor:github.com/stretchr/testify/assert", "//vendor:github.com/stretchr/testify/require", diff --git a/pkg/kubelet/cm/container_manager.go b/pkg/kubelet/cm/container_manager.go index 1c232c036f2..3e743502658 100644 --- a/pkg/kubelet/cm/container_manager.go +++ b/pkg/kubelet/cm/container_manager.go @@ -16,20 +16,18 @@ limitations under the License. package cm -import ( - "k8s.io/kubernetes/pkg/api" -) +import "k8s.io/kubernetes/pkg/api/v1" // Manages the containers running on a machine. type ContainerManager interface { // Runs the container manager's housekeeping. // - Ensures that the Docker daemon is in a container. // - Creates the system container where all non-containerized processes run. - Start(*api.Node) error + Start(*v1.Node) error // Returns resources allocated to system cgroups in the machine. // These cgroups include the system and Kubernetes services. - SystemCgroupsLimit() api.ResourceList + SystemCgroupsLimit() v1.ResourceList // Returns a NodeConfig that is being used by the container manager. GetNodeConfig() NodeConfig diff --git a/pkg/kubelet/cm/container_manager_linux.go b/pkg/kubelet/cm/container_manager_linux.go index f7546c6e0e6..b12e0e4772d 100644 --- a/pkg/kubelet/cm/container_manager_linux.go +++ b/pkg/kubelet/cm/container_manager_linux.go @@ -34,8 +34,8 @@ import ( "github.com/opencontainers/runc/libcontainer/cgroups" "github.com/opencontainers/runc/libcontainer/cgroups/fs" "github.com/opencontainers/runc/libcontainer/configs" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/cadvisor" cmutil "k8s.io/kubernetes/pkg/kubelet/cm/util" "k8s.io/kubernetes/pkg/kubelet/qos" @@ -104,7 +104,7 @@ type containerManagerImpl struct { periodicTasks []func() // holds all the mounted cgroup subsystems subsystems *CgroupSubsystems - nodeInfo *api.Node + nodeInfo *v1.Node } type features struct { @@ -392,7 +392,7 @@ func (cm *containerManagerImpl) setupNode() error { }) } else if cm.RuntimeCgroupsName != "" { cont := newSystemCgroups(cm.RuntimeCgroupsName) - var capacity = api.ResourceList{} + var capacity = v1.ResourceList{} if info, err := cm.cadvisorInterface.MachineInfo(); err == nil { capacity = cadvisor.CapacityFromMachineInfo(info) } @@ -523,7 +523,7 @@ func (cm *containerManagerImpl) Status() Status { return cm.status } -func (cm *containerManagerImpl) Start(node *api.Node) error { +func (cm *containerManagerImpl) Start(node *v1.Node) error { // cache the node Info including resource capacity and // allocatable of the node cm.nodeInfo = node @@ -566,7 +566,7 @@ func (cm *containerManagerImpl) Start(node *api.Node) error { return nil } -func (cm *containerManagerImpl) SystemCgroupsLimit() api.ResourceList { +func (cm *containerManagerImpl) SystemCgroupsLimit() v1.ResourceList { cpuLimit := int64(0) // Sum up resources of all external containers. @@ -574,8 +574,8 @@ func (cm *containerManagerImpl) SystemCgroupsLimit() api.ResourceList { cpuLimit += cont.cpuMillicores } - return api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity( + return v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity( cpuLimit, resource.DecimalSI), } diff --git a/pkg/kubelet/cm/container_manager_stub.go b/pkg/kubelet/cm/container_manager_stub.go index 186d773dbe9..cce42afcd91 100644 --- a/pkg/kubelet/cm/container_manager_stub.go +++ b/pkg/kubelet/cm/container_manager_stub.go @@ -18,20 +18,20 @@ package cm import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) type containerManagerStub struct{} var _ ContainerManager = &containerManagerStub{} -func (cm *containerManagerStub) Start(_ *api.Node) error { +func (cm *containerManagerStub) Start(_ *v1.Node) error { glog.V(2).Infof("Starting stub container manager") return nil } -func (cm *containerManagerStub) SystemCgroupsLimit() api.ResourceList { - return api.ResourceList{} +func (cm *containerManagerStub) SystemCgroupsLimit() v1.ResourceList { + return v1.ResourceList{} } func (cm *containerManagerStub) GetNodeConfig() NodeConfig { diff --git a/pkg/kubelet/cm/container_manager_unsupported.go b/pkg/kubelet/cm/container_manager_unsupported.go index d57bca69003..5199f6d483f 100644 --- a/pkg/kubelet/cm/container_manager_unsupported.go +++ b/pkg/kubelet/cm/container_manager_unsupported.go @@ -21,7 +21,7 @@ package cm import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/cadvisor" "k8s.io/kubernetes/pkg/util/mount" ) @@ -31,12 +31,12 @@ type unsupportedContainerManager struct { var _ ContainerManager = &unsupportedContainerManager{} -func (unsupportedContainerManager) Start(_ *api.Node) error { +func (unsupportedContainerManager) Start(_ *v1.Node) error { return fmt.Errorf("Container Manager is unsupported in this build") } -func (unsupportedContainerManager) SystemCgroupsLimit() api.ResourceList { - return api.ResourceList{} +func (unsupportedContainerManager) SystemCgroupsLimit() v1.ResourceList { + return v1.ResourceList{} } func (unsupportedContainerManager) GetNodeConfig() NodeConfig { diff --git a/pkg/kubelet/cm/container_manager_windows.go b/pkg/kubelet/cm/container_manager_windows.go index 573df34624e..0578085ca4c 100644 --- a/pkg/kubelet/cm/container_manager_windows.go +++ b/pkg/kubelet/cm/container_manager_windows.go @@ -21,7 +21,7 @@ package cm import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/cadvisor" "k8s.io/kubernetes/pkg/util/mount" ) @@ -32,7 +32,7 @@ type containerManagerImpl struct { var _ ContainerManager = &containerManagerImpl{} -func (cm *containerManagerImpl) Start(_ *api.Node) error { +func (cm *containerManagerImpl) Start(_ *v1.Node) error { glog.V(2).Infof("Starting Windows stub container manager") return nil } diff --git a/pkg/kubelet/cm/helpers_linux.go b/pkg/kubelet/cm/helpers_linux.go index cee55737eec..47d5a2e63b3 100644 --- a/pkg/kubelet/cm/helpers_linux.go +++ b/pkg/kubelet/cm/helpers_linux.go @@ -25,7 +25,7 @@ import ( libcontainercgroups "github.com/opencontainers/runc/libcontainer/cgroups" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/qos" ) @@ -83,7 +83,7 @@ func MilliCPUToShares(milliCPU int64) int64 { } // ResourceConfigForPod takes the input pod and outputs the cgroup resource config. -func ResourceConfigForPod(pod *api.Pod) *ResourceConfig { +func ResourceConfigForPod(pod *v1.Pod) *ResourceConfig { // sum requests and limits, track if limits were applied for each resource. cpuRequests := int64(0) cpuLimits := int64(0) diff --git a/pkg/kubelet/cm/helpers_linux_test.go b/pkg/kubelet/cm/helpers_linux_test.go index 511cd79d05f..4f8038b4492 100644 --- a/pkg/kubelet/cm/helpers_linux_test.go +++ b/pkg/kubelet/cm/helpers_linux_test.go @@ -22,26 +22,26 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" ) // getResourceList returns a ResourceList with the // specified cpu and memory resource values -func getResourceList(cpu, memory string) api.ResourceList { - res := api.ResourceList{} +func getResourceList(cpu, memory string) v1.ResourceList { + res := v1.ResourceList{} if cpu != "" { - res[api.ResourceCPU] = resource.MustParse(cpu) + res[v1.ResourceCPU] = resource.MustParse(cpu) } if memory != "" { - res[api.ResourceMemory] = resource.MustParse(memory) + res[v1.ResourceMemory] = resource.MustParse(memory) } return res } // getResourceRequirements returns a ResourceRequirements object -func getResourceRequirements(requests, limits api.ResourceList) api.ResourceRequirements { - res := api.ResourceRequirements{} +func getResourceRequirements(requests, limits v1.ResourceList) v1.ResourceRequirements { + res := v1.ResourceRequirements{} res.Requests = requests res.Limits = limits return res @@ -59,13 +59,13 @@ func TestResourceConfigForPod(t *testing.T) { memoryQuantity = resource.MustParse("100Mi") guaranteedMemory := memoryQuantity.Value() testCases := map[string]struct { - pod *api.Pod + pod *v1.Pod expected *ResourceConfig }{ "besteffort": { - pod: &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Resources: getResourceRequirements(getResourceList("", ""), getResourceList("", "")), }, @@ -75,9 +75,9 @@ func TestResourceConfigForPod(t *testing.T) { expected: &ResourceConfig{CpuShares: &minShares}, }, "burstable-no-limits": { - pod: &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Resources: getResourceRequirements(getResourceList("100m", "100Mi"), getResourceList("", "")), }, @@ -87,9 +87,9 @@ func TestResourceConfigForPod(t *testing.T) { expected: &ResourceConfig{CpuShares: &burstableShares}, }, "burstable-with-limits": { - pod: &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Resources: getResourceRequirements(getResourceList("100m", "100Mi"), getResourceList("200m", "200Mi")), }, @@ -99,9 +99,9 @@ func TestResourceConfigForPod(t *testing.T) { expected: &ResourceConfig{CpuShares: &burstableShares, CpuQuota: &burstableQuota, CpuPeriod: &burstablePeriod, Memory: &burstableMemory}, }, "burstable-partial-limits": { - pod: &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Resources: getResourceRequirements(getResourceList("100m", "100Mi"), getResourceList("200m", "200Mi")), }, @@ -114,9 +114,9 @@ func TestResourceConfigForPod(t *testing.T) { expected: &ResourceConfig{CpuShares: &burstablePartialShares}, }, "guaranteed": { - pod: &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Resources: getResourceRequirements(getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")), }, diff --git a/pkg/kubelet/cm/helpers_unsupported.go b/pkg/kubelet/cm/helpers_unsupported.go index f60149cb854..ca82984a742 100644 --- a/pkg/kubelet/cm/helpers_unsupported.go +++ b/pkg/kubelet/cm/helpers_unsupported.go @@ -18,7 +18,7 @@ limitations under the License. package cm -import "k8s.io/kubernetes/pkg/api" +import "k8s.io/kubernetes/pkg/api/v1" const ( MinShares = 0 @@ -40,7 +40,7 @@ func MilliCPUToShares(milliCPU int64) int64 { } // ResourceConfigForPod takes the input pod and outputs the cgroup resource config. -func ResourceConfigForPod(pod *api.Pod) *ResourceConfig { +func ResourceConfigForPod(pod *v1.Pod) *ResourceConfig { return nil } diff --git a/pkg/kubelet/cm/pod_container_manager_linux.go b/pkg/kubelet/cm/pod_container_manager_linux.go index e6c54579c1e..eb7e2789669 100644 --- a/pkg/kubelet/cm/pod_container_manager_linux.go +++ b/pkg/kubelet/cm/pod_container_manager_linux.go @@ -24,7 +24,7 @@ import ( "strings" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/qos" "k8s.io/kubernetes/pkg/types" utilerrors "k8s.io/kubernetes/pkg/util/errors" @@ -39,7 +39,7 @@ const ( // management if qos Cgroup is enabled. type podContainerManagerImpl struct { // nodeInfo stores information about the node resource capacity - nodeInfo *api.Node + nodeInfo *v1.Node // qosContainersInfo hold absolute paths of the top level qos containers qosContainersInfo QOSContainersInfo // Stores the mounted cgroup subsystems @@ -54,14 +54,14 @@ var _ PodContainerManager = &podContainerManagerImpl{} // applyLimits sets pod cgroup resource limits // It also updates the resource limits on top level qos containers. -func (m *podContainerManagerImpl) applyLimits(pod *api.Pod) error { +func (m *podContainerManagerImpl) applyLimits(pod *v1.Pod) error { // This function will house the logic for setting the resource parameters // on the pod container config and updating top level qos container configs return nil } // Exists checks if the pod's cgroup already exists -func (m *podContainerManagerImpl) Exists(pod *api.Pod) bool { +func (m *podContainerManagerImpl) Exists(pod *v1.Pod) bool { podContainerName, _ := m.GetPodContainerName(pod) return m.cgroupManager.Exists(podContainerName) } @@ -69,7 +69,7 @@ func (m *podContainerManagerImpl) Exists(pod *api.Pod) bool { // EnsureExists takes a pod as argument and makes sure that // pod cgroup exists if qos cgroup hierarchy flag is enabled. // If the pod level container doesen't already exist it is created. -func (m *podContainerManagerImpl) EnsureExists(pod *api.Pod) error { +func (m *podContainerManagerImpl) EnsureExists(pod *v1.Pod) error { podContainerName, _ := m.GetPodContainerName(pod) // check if container already exist alreadyExists := m.Exists(pod) @@ -94,7 +94,7 @@ func (m *podContainerManagerImpl) EnsureExists(pod *api.Pod) error { } // GetPodContainerName returns the CgroupName identifer, and its literal cgroupfs form on the host. -func (m *podContainerManagerImpl) GetPodContainerName(pod *api.Pod) (CgroupName, string) { +func (m *podContainerManagerImpl) GetPodContainerName(pod *v1.Pod) (CgroupName, string) { podQOS := qos.GetPodQOS(pod) // Get the parent QOS container name var parentContainer string @@ -233,19 +233,19 @@ type podContainerManagerNoop struct { // Make sure that podContainerManagerStub implements the PodContainerManager interface var _ PodContainerManager = &podContainerManagerNoop{} -func (m *podContainerManagerNoop) Exists(_ *api.Pod) bool { +func (m *podContainerManagerNoop) Exists(_ *v1.Pod) bool { return true } -func (m *podContainerManagerNoop) EnsureExists(_ *api.Pod) error { +func (m *podContainerManagerNoop) EnsureExists(_ *v1.Pod) error { return nil } -func (m *podContainerManagerNoop) GetPodContainerName(_ *api.Pod) (CgroupName, string) { +func (m *podContainerManagerNoop) GetPodContainerName(_ *v1.Pod) (CgroupName, string) { return m.cgroupRoot, string(m.cgroupRoot) } -func (m *podContainerManagerNoop) GetPodContainerNameForDriver(_ *api.Pod) string { +func (m *podContainerManagerNoop) GetPodContainerNameForDriver(_ *v1.Pod) string { return "" } diff --git a/pkg/kubelet/cm/pod_container_manager_stub.go b/pkg/kubelet/cm/pod_container_manager_stub.go index dec1c7b1bad..893ecbd1159 100644 --- a/pkg/kubelet/cm/pod_container_manager_stub.go +++ b/pkg/kubelet/cm/pod_container_manager_stub.go @@ -17,7 +17,7 @@ limitations under the License. package cm import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" ) @@ -26,15 +26,15 @@ type podContainerManagerStub struct { var _ PodContainerManager = &podContainerManagerStub{} -func (m *podContainerManagerStub) Exists(_ *api.Pod) bool { +func (m *podContainerManagerStub) Exists(_ *v1.Pod) bool { return true } -func (m *podContainerManagerStub) EnsureExists(_ *api.Pod) error { +func (m *podContainerManagerStub) EnsureExists(_ *v1.Pod) error { return nil } -func (m *podContainerManagerStub) GetPodContainerName(_ *api.Pod) (CgroupName, string) { +func (m *podContainerManagerStub) GetPodContainerName(_ *v1.Pod) (CgroupName, string) { return "", "" } diff --git a/pkg/kubelet/cm/pod_container_manager_unsupported.go b/pkg/kubelet/cm/pod_container_manager_unsupported.go index 164278ccb2f..c97d793f398 100644 --- a/pkg/kubelet/cm/pod_container_manager_unsupported.go +++ b/pkg/kubelet/cm/pod_container_manager_unsupported.go @@ -19,7 +19,7 @@ limitations under the License. package cm import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" ) @@ -28,15 +28,15 @@ type unsupportedPodContainerManager struct { var _ PodContainerManager = &unsupportedPodContainerManager{} -func (m *unsupportedPodContainerManager) Exists(_ *api.Pod) bool { +func (m *unsupportedPodContainerManager) Exists(_ *v1.Pod) bool { return true } -func (m *unsupportedPodContainerManager) EnsureExists(_ *api.Pod) error { +func (m *unsupportedPodContainerManager) EnsureExists(_ *v1.Pod) error { return nil } -func (m *unsupportedPodContainerManager) GetPodContainerName(_ *api.Pod) (CgroupName, string) { +func (m *unsupportedPodContainerManager) GetPodContainerName(_ *v1.Pod) (CgroupName, string) { return "", "" } diff --git a/pkg/kubelet/cm/types.go b/pkg/kubelet/cm/types.go index 48f940f72e6..d7dbaed2957 100644 --- a/pkg/kubelet/cm/types.go +++ b/pkg/kubelet/cm/types.go @@ -17,7 +17,7 @@ limitations under the License. package cm import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" ) @@ -86,15 +86,15 @@ type QOSContainersInfo struct { // containers for the pod. type PodContainerManager interface { // GetPodContainerName returns the CgroupName identifer, and its literal cgroupfs form on the host. - GetPodContainerName(*api.Pod) (CgroupName, string) + GetPodContainerName(*v1.Pod) (CgroupName, string) // EnsureExists takes a pod as argument and makes sure that // pod cgroup exists if qos cgroup hierarchy flag is enabled. // If the pod cgroup doesen't already exist this method creates it. - EnsureExists(*api.Pod) error + EnsureExists(*v1.Pod) error // Exists returns true if the pod cgroup exists. - Exists(*api.Pod) bool + Exists(*v1.Pod) bool // Destroy takes a pod Cgroup name as argument and destroys the pod's container. Destroy(name CgroupName) error diff --git a/pkg/kubelet/config/BUILD b/pkg/kubelet/config/BUILD index 4497b2e916d..bece9f47177 100644 --- a/pkg/kubelet/config/BUILD +++ b/pkg/kubelet/config/BUILD @@ -25,10 +25,12 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/pod:go_default_library", "//pkg/api/validation:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/record:go_default_library", "//pkg/fields:go_default_library", "//pkg/kubelet/container:go_default_library", @@ -63,6 +65,7 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/testapi:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/api/validation:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/client/cache:go_default_library", diff --git a/pkg/kubelet/config/apiserver.go b/pkg/kubelet/config/apiserver.go index 4061d9c7330..ae59ecb434c 100644 --- a/pkg/kubelet/config/apiserver.go +++ b/pkg/kubelet/config/apiserver.go @@ -18,9 +18,12 @@ limitations under the License. package config import ( + "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" + podutil "k8s.io/kubernetes/pkg/api/v1/pod" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/fields" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/types" @@ -28,18 +31,22 @@ import ( // NewSourceApiserver creates a config source that watches and pulls from the apiserver. func NewSourceApiserver(c *clientset.Clientset, nodeName types.NodeName, updates chan<- interface{}) { - lw := cache.NewListWatchFromClient(c.Core().RESTClient(), "pods", api.NamespaceAll, fields.OneTermEqualSelector(api.PodHostField, string(nodeName))) + lw := cache.NewListWatchFromClient(c.Core().RESTClient(), "pods", v1.NamespaceAll, fields.OneTermEqualSelector(api.PodHostField, string(nodeName))) newSourceApiserverFromLW(lw, updates) } // newSourceApiserverFromLW holds creates a config source that watches and pulls from the apiserver. func newSourceApiserverFromLW(lw cache.ListerWatcher, updates chan<- interface{}) { send := func(objs []interface{}) { - var pods []*api.Pod + var pods []*v1.Pod for _, o := range objs { - pods = append(pods, o.(*api.Pod)) + pod := o.(*v1.Pod) + if err := podutil.SetInitContainersAndStatuses(pod); err != nil { + glog.Error(err) + } + pods = append(pods, pod) } updates <- kubetypes.PodUpdate{Pods: pods, Op: kubetypes.SET, Source: kubetypes.ApiserverSource} } - cache.NewReflector(lw, &api.Pod{}, cache.NewUndeltaStore(send, cache.MetaNamespaceKeyFunc), 0).Run() + cache.NewReflector(lw, &v1.Pod{}, cache.NewUndeltaStore(send, cache.MetaNamespaceKeyFunc), 0).Run() } diff --git a/pkg/kubelet/config/apiserver_test.go b/pkg/kubelet/config/apiserver_test.go index f05ebd5c3a0..3f2e24dc39f 100644 --- a/pkg/kubelet/config/apiserver_test.go +++ b/pkg/kubelet/config/apiserver_test.go @@ -20,6 +20,7 @@ import ( "testing" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/runtime" @@ -31,31 +32,31 @@ type fakePodLW struct { watchResp watch.Interface } -func (lw fakePodLW) List(options api.ListOptions) (runtime.Object, error) { +func (lw fakePodLW) List(options v1.ListOptions) (runtime.Object, error) { return lw.listResp, nil } -func (lw fakePodLW) Watch(options api.ListOptions) (watch.Interface, error) { +func (lw fakePodLW) Watch(options v1.ListOptions) (watch.Interface, error) { return lw.watchResp, nil } var _ cache.ListerWatcher = fakePodLW{} func TestNewSourceApiserver_UpdatesAndMultiplePods(t *testing.T) { - pod1v1 := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "p"}, - Spec: api.PodSpec{Containers: []api.Container{{Image: "image/one"}}}} - pod1v2 := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "p"}, - Spec: api.PodSpec{Containers: []api.Container{{Image: "image/two"}}}} - pod2 := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "q"}, - Spec: api.PodSpec{Containers: []api.Container{{Image: "image/blah"}}}} + pod1v1 := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "p"}, + Spec: v1.PodSpec{Containers: []v1.Container{{Image: "image/one"}}}} + pod1v2 := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "p"}, + Spec: v1.PodSpec{Containers: []v1.Container{{Image: "image/two"}}}} + pod2 := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "q"}, + Spec: v1.PodSpec{Containers: []v1.Container{{Image: "image/blah"}}}} // Setup fake api client. fakeWatch := watch.NewFake() lw := fakePodLW{ - listResp: &api.PodList{Items: []api.Pod{*pod1v1}}, + listResp: &v1.PodList{Items: []v1.Pod{*pod1v1}}, watchResp: fakeWatch, } @@ -128,17 +129,17 @@ func TestNewSourceApiserver_UpdatesAndMultiplePods(t *testing.T) { } func TestNewSourceApiserver_TwoNamespacesSameName(t *testing.T) { - pod1 := api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "p", Namespace: "one"}, - Spec: api.PodSpec{Containers: []api.Container{{Image: "image/one"}}}} - pod2 := api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "p", Namespace: "two"}, - Spec: api.PodSpec{Containers: []api.Container{{Image: "image/blah"}}}} + pod1 := v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "p", Namespace: "one"}, + Spec: v1.PodSpec{Containers: []v1.Container{{Image: "image/one"}}}} + pod2 := v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "p", Namespace: "two"}, + Spec: v1.PodSpec{Containers: []v1.Container{{Image: "image/blah"}}}} // Setup fake api client. fakeWatch := watch.NewFake() lw := fakePodLW{ - listResp: &api.PodList{Items: []api.Pod{pod1, pod2}}, + listResp: &v1.PodList{Items: []v1.Pod{pod1, pod2}}, watchResp: fakeWatch, } @@ -172,7 +173,7 @@ func TestNewSourceApiserverInitialEmptySendsEmptyPodUpdate(t *testing.T) { // Setup fake api client. fakeWatch := watch.NewFake() lw := fakePodLW{ - listResp: &api.PodList{Items: []api.Pod{}}, + listResp: &v1.PodList{Items: []v1.Pod{}}, watchResp: fakeWatch, } diff --git a/pkg/kubelet/config/common.go b/pkg/kubelet/config/common.go index 7d9861bbfd2..652cd7a8cfc 100644 --- a/pkg/kubelet/config/common.go +++ b/pkg/kubelet/config/common.go @@ -23,6 +23,7 @@ import ( "fmt" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/apimachinery/registered" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" @@ -88,7 +89,7 @@ func getSelfLink(name, namespace string) string { type defaultFunc func(pod *api.Pod) error -func tryDecodeSinglePod(data []byte, defaultFn defaultFunc) (parsed bool, pod *api.Pod, err error) { +func tryDecodeSinglePod(data []byte, defaultFn defaultFunc) (parsed bool, pod *v1.Pod, err error) { // JSON is valid YAML, so this should work for everything. json, err := utilyaml.ToJSON(data) if err != nil { @@ -112,10 +113,14 @@ func tryDecodeSinglePod(data []byte, defaultFn defaultFunc) (parsed bool, pod *a err = fmt.Errorf("invalid pod: %v", errs) return true, pod, err } - return true, newPod, nil + v1Pod := &v1.Pod{} + if err := v1.Convert_api_Pod_To_v1_Pod(newPod, v1Pod, nil); err != nil { + return true, nil, err + } + return true, v1Pod, nil } -func tryDecodePodList(data []byte, defaultFn defaultFunc) (parsed bool, pods api.PodList, err error) { +func tryDecodePodList(data []byte, defaultFn defaultFunc) (parsed bool, pods v1.PodList, err error) { obj, err := runtime.Decode(api.Codecs.UniversalDecoder(), data) if err != nil { return false, pods, err @@ -137,5 +142,9 @@ func tryDecodePodList(data []byte, defaultFn defaultFunc) (parsed bool, pods api return true, pods, err } } - return true, *newPods, err + v1Pods := &v1.PodList{} + if err := v1.Convert_api_PodList_To_v1_PodList(newPods, v1Pods, nil); err != nil { + return true, pods, err + } + return true, *v1Pods, err } diff --git a/pkg/kubelet/config/common_test.go b/pkg/kubelet/config/common_test.go index f1ee4ede87d..f611cbec093 100644 --- a/pkg/kubelet/config/common_test.go +++ b/pkg/kubelet/config/common_test.go @@ -23,6 +23,7 @@ import ( "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/apimachinery/registered" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/securitycontext" @@ -32,27 +33,27 @@ func noDefault(*api.Pod) error { return nil } func TestDecodeSinglePod(t *testing.T) { grace := int64(30) - pod := &api.Pod{ + pod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ APIVersion: "", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "test", UID: "12345", Namespace: "mynamespace", }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyAlways, + DNSPolicy: v1.DNSClusterFirst, TerminationGracePeriodSeconds: &grace, - Containers: []api.Container{{ + Containers: []v1.Container{{ Name: "image", Image: "test/image", ImagePullPolicy: "IfNotPresent", TerminationMessagePath: "/dev/termination-log", SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), }}, - SecurityContext: &api.PodSecurityContext{}, + SecurityContext: &v1.PodSecurityContext{}, }, } json, err := runtime.Encode(testapi.Default.Codec(), pod) @@ -70,7 +71,7 @@ func TestDecodeSinglePod(t *testing.T) { t.Errorf("expected:\n%#v\ngot:\n%#v\n%s", pod, podOut, string(json)) } - for _, gv := range registered.EnabledVersionsForGroup(api.GroupName) { + for _, gv := range registered.EnabledVersionsForGroup(v1.GroupName) { info, _ := runtime.SerializerInfoForMediaType(api.Codecs.SupportedMediaTypes(), "application/yaml") encoder := api.Codecs.EncoderForVersion(info.Serializer, gv) yaml, err := runtime.Encode(encoder, pod) @@ -92,31 +93,31 @@ func TestDecodeSinglePod(t *testing.T) { func TestDecodePodList(t *testing.T) { grace := int64(30) - pod := &api.Pod{ + pod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ APIVersion: "", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "test", UID: "12345", Namespace: "mynamespace", }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyAlways, + DNSPolicy: v1.DNSClusterFirst, TerminationGracePeriodSeconds: &grace, - Containers: []api.Container{{ + Containers: []v1.Container{{ Name: "image", Image: "test/image", ImagePullPolicy: "IfNotPresent", TerminationMessagePath: "/dev/termination-log", SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), }}, - SecurityContext: &api.PodSecurityContext{}, + SecurityContext: &v1.PodSecurityContext{}, }, } - podList := &api.PodList{ - Items: []api.Pod{*pod}, + podList := &v1.PodList{ + Items: []v1.Pod{*pod}, } json, err := runtime.Encode(testapi.Default.Codec(), podList) if err != nil { @@ -133,7 +134,7 @@ func TestDecodePodList(t *testing.T) { t.Errorf("expected:\n%#v\ngot:\n%#v\n%s", podList, &podListOut, string(json)) } - for _, gv := range registered.EnabledVersionsForGroup(api.GroupName) { + for _, gv := range registered.EnabledVersionsForGroup(v1.GroupName) { info, _ := runtime.SerializerInfoForMediaType(api.Codecs.SupportedMediaTypes(), "application/yaml") encoder := api.Codecs.EncoderForVersion(info.Serializer, gv) yaml, err := runtime.Encode(encoder, podList) diff --git a/pkg/kubelet/config/config.go b/pkg/kubelet/config/config.go index 795fec62aa0..1266878ed91 100644 --- a/pkg/kubelet/config/config.go +++ b/pkg/kubelet/config/config.go @@ -23,6 +23,7 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" @@ -116,7 +117,7 @@ func (c *PodConfig) Sync() { type podStorage struct { podLock sync.RWMutex // map of source name to pod name to pod reference - pods map[string]map[string]*api.Pod + pods map[string]map[string]*v1.Pod mode PodConfigNotificationMode // ensures that updates are delivered in strict order @@ -137,7 +138,7 @@ type podStorage struct { // TODO: allow initialization of the current state of the store with snapshotted version. func newPodStorage(updates chan<- kubetypes.PodUpdate, mode PodConfigNotificationMode, recorder record.EventRecorder) *podStorage { return &podStorage{ - pods: make(map[string]map[string]*api.Pod), + pods: make(map[string]map[string]*v1.Pod), mode: mode, updates: updates, sourcesSeen: sets.String{}, @@ -184,7 +185,7 @@ func (s *podStorage) Merge(source string, change interface{}) error { case PodConfigNotificationSnapshotAndUpdates: if len(removes.Pods) > 0 || len(adds.Pods) > 0 || firstSet { - s.updates <- kubetypes.PodUpdate{Pods: s.MergedState().([]*api.Pod), Op: kubetypes.SET, Source: source} + s.updates <- kubetypes.PodUpdate{Pods: s.MergedState().([]*v1.Pod), Op: kubetypes.SET, Source: source} } if len(updates.Pods) > 0 { s.updates <- *updates @@ -195,7 +196,7 @@ func (s *podStorage) Merge(source string, change interface{}) error { case PodConfigNotificationSnapshot: if len(updates.Pods) > 0 || len(deletes.Pods) > 0 || len(adds.Pods) > 0 || len(removes.Pods) > 0 || firstSet { - s.updates <- kubetypes.PodUpdate{Pods: s.MergedState().([]*api.Pod), Op: kubetypes.SET, Source: source} + s.updates <- kubetypes.PodUpdate{Pods: s.MergedState().([]*v1.Pod), Op: kubetypes.SET, Source: source} } case PodConfigNotificationUnknown: @@ -211,21 +212,21 @@ func (s *podStorage) merge(source string, change interface{}) (adds, updates, de s.podLock.Lock() defer s.podLock.Unlock() - addPods := []*api.Pod{} - updatePods := []*api.Pod{} - deletePods := []*api.Pod{} - removePods := []*api.Pod{} - reconcilePods := []*api.Pod{} + addPods := []*v1.Pod{} + updatePods := []*v1.Pod{} + deletePods := []*v1.Pod{} + removePods := []*v1.Pod{} + reconcilePods := []*v1.Pod{} pods := s.pods[source] if pods == nil { - pods = make(map[string]*api.Pod) + pods = make(map[string]*v1.Pod) } // updatePodFunc is the local function which updates the pod cache *oldPods* with new pods *newPods*. // After updated, new pod will be stored in the pod cache *pods*. // Notice that *pods* and *oldPods* could be the same cache. - updatePodsFunc := func(newPods []*api.Pod, oldPods, pods map[string]*api.Pod) { + updatePodsFunc := func(newPods []*v1.Pod, oldPods, pods map[string]*v1.Pod) { filtered := filterInvalidPods(newPods, source, s.recorder) for _, ref := range filtered { name := kubecontainer.GetPodFullName(ref) @@ -282,7 +283,7 @@ func (s *podStorage) merge(source string, change interface{}) (adds, updates, de s.markSourceSet(source) // Clear the old map entries by just creating a new map oldPods := pods - pods = make(map[string]*api.Pod) + pods = make(map[string]*v1.Pod) updatePodsFunc(update.Pods, oldPods, pods) for name, existing := range oldPods { if _, found := pods[name]; !found { @@ -319,11 +320,19 @@ func (s *podStorage) seenSources(sources ...string) bool { return s.sourcesSeen.HasAll(sources...) } -func filterInvalidPods(pods []*api.Pod, source string, recorder record.EventRecorder) (filtered []*api.Pod) { +func filterInvalidPods(pods []*v1.Pod, source string, recorder record.EventRecorder) (filtered []*v1.Pod) { names := sets.String{} for i, pod := range pods { var errlist field.ErrorList - if errs := validation.ValidatePod(pod); len(errs) != 0 { + // TODO: remove the conversion when validation is performed on versioned objects. + internalPod := &api.Pod{} + if err := v1.Convert_v1_Pod_To_api_Pod(pod, internalPod, nil); err != nil { + name := kubecontainer.GetPodFullName(pod) + glog.Warningf("Pod[%d] (%s) from %s failed to convert to v1, ignoring: %v", i+1, name, source, err) + recorder.Eventf(pod, v1.EventTypeWarning, "FailedConversion", "Error converting pod %s from %s, ignoring: %v", name, source, err) + continue + } + if errs := validation.ValidatePod(internalPod); len(errs) != 0 { errlist = append(errlist, errs...) // If validation fails, don't trust it any further - // even Name could be bad. @@ -341,7 +350,7 @@ func filterInvalidPods(pods []*api.Pod, source string, recorder record.EventReco name := bestPodIdentString(pod) err := errlist.ToAggregate() glog.Warningf("Pod[%d] (%s) from %s failed validation, ignoring: %v", i+1, name, source, err) - recorder.Eventf(pod, api.EventTypeWarning, events.FailedValidation, "Error validating pod %s from %s, ignoring: %v", name, source, err) + recorder.Eventf(pod, v1.EventTypeWarning, events.FailedValidation, "Error validating pod %s from %s, ignoring: %v", name, source, err) continue } filtered = append(filtered, pod) @@ -393,14 +402,14 @@ func isAnnotationMapEqual(existingMap, candidateMap map[string]string) bool { } // recordFirstSeenTime records the first seen time of this pod. -func recordFirstSeenTime(pod *api.Pod) { +func recordFirstSeenTime(pod *v1.Pod) { glog.V(4).Infof("Receiving a new pod %q", format.Pod(pod)) pod.Annotations[kubetypes.ConfigFirstSeenAnnotationKey] = kubetypes.NewTimestamp().GetString() } // updateAnnotations returns an Annotation map containing the api annotation map plus // locally managed annotations -func updateAnnotations(existing, ref *api.Pod) { +func updateAnnotations(existing, ref *v1.Pod) { annotations := make(map[string]string, len(ref.Annotations)+len(localAnnotations)) for k, v := range ref.Annotations { annotations[k] = v @@ -413,7 +422,7 @@ func updateAnnotations(existing, ref *api.Pod) { existing.Annotations = annotations } -func podsDifferSemantically(existing, ref *api.Pod) bool { +func podsDifferSemantically(existing, ref *v1.Pod) bool { if reflect.DeepEqual(existing.Spec, ref.Spec) && reflect.DeepEqual(existing.Labels, ref.Labels) && reflect.DeepEqual(existing.DeletionTimestamp, ref.DeletionTimestamp) && @@ -430,7 +439,7 @@ func podsDifferSemantically(existing, ref *api.Pod) bool { // * if ref makes no meaningful change, but changes the pod status, returns needReconcile=true // * else return all false // Now, needUpdate, needGracefulDelete and needReconcile should never be both true -func checkAndUpdatePod(existing, ref *api.Pod) (needUpdate, needReconcile, needGracefulDelete bool) { +func checkAndUpdatePod(existing, ref *v1.Pod) (needUpdate, needReconcile, needGracefulDelete bool) { // 1. this is a reconcile // TODO: it would be better to update the whole object and only preserve certain things @@ -474,27 +483,27 @@ func checkAndUpdatePod(existing, ref *api.Pod) (needUpdate, needReconcile, needG func (s *podStorage) Sync() { s.updateLock.Lock() defer s.updateLock.Unlock() - s.updates <- kubetypes.PodUpdate{Pods: s.MergedState().([]*api.Pod), Op: kubetypes.SET, Source: kubetypes.AllSource} + s.updates <- kubetypes.PodUpdate{Pods: s.MergedState().([]*v1.Pod), Op: kubetypes.SET, Source: kubetypes.AllSource} } // Object implements config.Accessor func (s *podStorage) MergedState() interface{} { s.podLock.RLock() defer s.podLock.RUnlock() - pods := make([]*api.Pod, 0) + pods := make([]*v1.Pod, 0) for _, sourcePods := range s.pods { for _, podRef := range sourcePods { pod, err := api.Scheme.Copy(podRef) if err != nil { glog.Errorf("unable to copy pod: %v", err) } - pods = append(pods, pod.(*api.Pod)) + pods = append(pods, pod.(*v1.Pod)) } } return pods } -func bestPodIdentString(pod *api.Pod) string { +func bestPodIdentString(pod *v1.Pod) string { namespace := pod.Namespace if namespace == "" { namespace = "" @@ -506,15 +515,15 @@ func bestPodIdentString(pod *api.Pod) string { return fmt.Sprintf("%s.%s", name, namespace) } -func copyPods(sourcePods []*api.Pod) []*api.Pod { - pods := []*api.Pod{} +func copyPods(sourcePods []*v1.Pod) []*v1.Pod { + pods := []*v1.Pod{} for _, source := range sourcePods { // Use a deep copy here just in case pod, err := api.Scheme.Copy(source) if err != nil { glog.Errorf("unable to copy pod: %v", err) } - pods = append(pods, pod.(*api.Pod)) + pods = append(pods, pod.(*v1.Pod)) } return pods } diff --git a/pkg/kubelet/config/config_test.go b/pkg/kubelet/config/config_test.go index 4b4b06f4f49..9fd305006ea 100644 --- a/pkg/kubelet/config/config_test.go +++ b/pkg/kubelet/config/config_test.go @@ -26,6 +26,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/conversion" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" @@ -45,7 +46,7 @@ func expectEmptyChannel(t *testing.T, ch <-chan interface{}) { } } -type sortedPods []*api.Pod +type sortedPods []*v1.Pod func (s sortedPods) Len() int { return len(s) @@ -57,17 +58,17 @@ func (s sortedPods) Less(i, j int) bool { return s[i].Namespace < s[j].Namespace } -func CreateValidPod(name, namespace string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func CreateValidPod(name, namespace string) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: types.UID(name), // for the purpose of testing, this is unique enough Name: name, Namespace: namespace, }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyAlways, + DNSPolicy: v1.DNSClusterFirst, + Containers: []v1.Container{ { Name: "ctr", Image: "image", @@ -79,13 +80,13 @@ func CreateValidPod(name, namespace string) *api.Pod { } } -func CreatePodUpdate(op kubetypes.PodOperation, source string, pods ...*api.Pod) kubetypes.PodUpdate { +func CreatePodUpdate(op kubetypes.PodOperation, source string, pods ...*v1.Pod) kubetypes.PodUpdate { return kubetypes.PodUpdate{Pods: pods, Op: op, Source: source} } func createPodConfigTester(mode PodConfigNotificationMode) (chan<- interface{}, <-chan kubetypes.PodUpdate, *PodConfig) { eventBroadcaster := record.NewBroadcaster() - config := NewPodConfig(mode, eventBroadcaster.NewRecorder(api.EventSource{Component: "kubelet"})) + config := NewPodConfig(mode, eventBroadcaster.NewRecorder(v1.EventSource{Component: "kubelet"})) channel := config.Channel(TestSource) ch := config.Updates() return channel, ch, config @@ -186,7 +187,7 @@ func TestInvalidPodFiltered(t *testing.T) { expectPodUpdate(t, ch, CreatePodUpdate(kubetypes.ADD, TestSource, CreateValidPod("foo", "new"))) // add an invalid update - podUpdate = CreatePodUpdate(kubetypes.UPDATE, TestSource, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}) + podUpdate = CreatePodUpdate(kubetypes.UPDATE, TestSource, &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo"}}) channel <- podUpdate expectNoPodUpdate(t, ch) } @@ -204,7 +205,7 @@ func TestNewPodAddedSnapshotAndUpdates(t *testing.T) { // container updates are separated as UPDATE pod := *podUpdate.Pods[0] - pod.Spec.Containers = []api.Container{{Name: "bar", Image: "test", ImagePullPolicy: api.PullIfNotPresent}} + pod.Spec.Containers = []v1.Container{{Name: "bar", Image: "test", ImagePullPolicy: v1.PullIfNotPresent}} channel <- CreatePodUpdate(kubetypes.ADD, TestSource, &pod) expectPodUpdate(t, ch, CreatePodUpdate(kubetypes.UPDATE, TestSource, &pod)) } @@ -222,7 +223,7 @@ func TestNewPodAddedSnapshot(t *testing.T) { // container updates are separated as UPDATE pod := *podUpdate.Pods[0] - pod.Spec.Containers = []api.Container{{Name: "bar", Image: "test", ImagePullPolicy: api.PullIfNotPresent}} + pod.Spec.Containers = []v1.Container{{Name: "bar", Image: "test", ImagePullPolicy: v1.PullIfNotPresent}} channel <- CreatePodUpdate(kubetypes.ADD, TestSource, &pod) expectPodUpdate(t, ch, CreatePodUpdate(kubetypes.SET, TestSource, &pod)) } @@ -240,12 +241,12 @@ func TestNewPodAddedUpdatedRemoved(t *testing.T) { // an kubetypes.ADD should be converted to kubetypes.UPDATE pod := CreateValidPod("foo", "new") - pod.Spec.Containers = []api.Container{{Name: "bar", Image: "test", ImagePullPolicy: api.PullIfNotPresent}} + pod.Spec.Containers = []v1.Container{{Name: "bar", Image: "test", ImagePullPolicy: v1.PullIfNotPresent}} podUpdate = CreatePodUpdate(kubetypes.ADD, TestSource, pod) channel <- podUpdate expectPodUpdate(t, ch, CreatePodUpdate(kubetypes.UPDATE, TestSource, pod)) - podUpdate = CreatePodUpdate(kubetypes.REMOVE, TestSource, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "new"}}) + podUpdate = CreatePodUpdate(kubetypes.REMOVE, TestSource, &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: "new"}}) channel <- podUpdate expectPodUpdate(t, ch, CreatePodUpdate(kubetypes.REMOVE, TestSource, pod)) } @@ -282,7 +283,7 @@ func TestNewPodAddedUpdatedSet(t *testing.T) { // should be converted to an kubetypes.ADD, kubetypes.REMOVE, and kubetypes.UPDATE pod := CreateValidPod("foo2", "new") - pod.Spec.Containers = []api.Container{{Name: "bar", Image: "test", ImagePullPolicy: api.PullIfNotPresent}} + pod.Spec.Containers = []v1.Container{{Name: "bar", Image: "test", ImagePullPolicy: v1.PullIfNotPresent}} podUpdate = CreatePodUpdate(kubetypes.SET, TestSource, pod, CreateValidPod("foo3", "new"), CreateValidPod("foo4", "new")) channel <- podUpdate expectPodUpdate(t, ch, @@ -294,14 +295,14 @@ func TestNewPodAddedUpdatedSet(t *testing.T) { func TestNewPodAddedSetReconciled(t *testing.T) { // Create and touch new test pods, return the new pods and touched pod. We should create new pod list // before touching to avoid data race. - newTestPods := func(touchStatus, touchSpec bool) ([]*api.Pod, *api.Pod) { - pods := []*api.Pod{ + newTestPods := func(touchStatus, touchSpec bool) ([]*v1.Pod, *v1.Pod) { + pods := []*v1.Pod{ CreateValidPod("changeable-pod-0", "new"), CreateValidPod("constant-pod-1", "new"), CreateValidPod("constant-pod-2", "new"), } if touchStatus { - pods[0].Status = api.PodStatus{Message: strconv.Itoa(rand.Int())} + pods[0].Status = v1.PodStatus{Message: strconv.Itoa(rand.Int())} } if touchSpec { pods[0].Spec.Containers[0].Name = strconv.Itoa(rand.Int()) @@ -312,7 +313,7 @@ func TestNewPodAddedSetReconciled(t *testing.T) { kubetypes.ADD, kubetypes.SET, } { - var podWithStatusChange *api.Pod + var podWithStatusChange *v1.Pod pods, _ := newTestPods(false, false) channel, ch, _ := createPodConfigTester(PodConfigNotificationIncremental) @@ -373,7 +374,7 @@ func TestPodUpdateAnnotations(t *testing.T) { t.Fatalf("%v", err) } - podUpdate := CreatePodUpdate(kubetypes.SET, TestSource, CreateValidPod("foo1", "new"), clone.(*api.Pod), CreateValidPod("foo3", "new")) + podUpdate := CreatePodUpdate(kubetypes.SET, TestSource, CreateValidPod("foo1", "new"), clone.(*v1.Pod), CreateValidPod("foo3", "new")) channel <- podUpdate expectPodUpdate(t, ch, CreatePodUpdate(kubetypes.ADD, TestSource, CreateValidPod("foo1", "new"), pod, CreateValidPod("foo3", "new"))) @@ -405,7 +406,7 @@ func TestPodUpdateLabels(t *testing.T) { t.Fatalf("%v", err) } - podUpdate := CreatePodUpdate(kubetypes.SET, TestSource, clone.(*api.Pod)) + podUpdate := CreatePodUpdate(kubetypes.SET, TestSource, clone.(*v1.Pod)) channel <- podUpdate expectPodUpdate(t, ch, CreatePodUpdate(kubetypes.ADD, TestSource, pod)) diff --git a/pkg/kubelet/config/file.go b/pkg/kubelet/config/file.go index 262f360e636..d0af119976b 100644 --- a/pkg/kubelet/config/file.go +++ b/pkg/kubelet/config/file.go @@ -28,6 +28,7 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/types" @@ -50,9 +51,9 @@ func NewSourceFile(path string, nodeName types.NodeName, period time.Duration, u func new(path string, nodeName types.NodeName, period time.Duration, updates chan<- interface{}) *sourceFile { send := func(objs []interface{}) { - var pods []*api.Pod + var pods []*v1.Pod for _, o := range objs { - pods = append(pods, o.(*api.Pod)) + pods = append(pods, o.(*v1.Pod)) } updates <- kubetypes.PodUpdate{Pods: pods, Op: kubetypes.SET, Source: kubetypes.FileSource} } @@ -84,7 +85,7 @@ func (s *sourceFile) resetStoreFromPath() error { return err } // Emit an update with an empty PodList to allow FileSource to be marked as seen - s.updates <- kubetypes.PodUpdate{Pods: []*api.Pod{}, Op: kubetypes.SET, Source: kubetypes.FileSource} + s.updates <- kubetypes.PodUpdate{Pods: []*v1.Pod{}, Op: kubetypes.SET, Source: kubetypes.FileSource} return fmt.Errorf("path does not exist, ignoring") } @@ -116,13 +117,13 @@ func (s *sourceFile) resetStoreFromPath() error { // Get as many pod configs as we can from a directory. Return an error if and only if something // prevented us from reading anything at all. Do not return an error if only some files // were problematic. -func (s *sourceFile) extractFromDir(name string) ([]*api.Pod, error) { +func (s *sourceFile) extractFromDir(name string) ([]*v1.Pod, error) { dirents, err := filepath.Glob(filepath.Join(name, "[^.]*")) if err != nil { return nil, fmt.Errorf("glob failed: %v", err) } - pods := make([]*api.Pod, 0) + pods := make([]*v1.Pod, 0) if len(dirents) == 0 { return pods, nil } @@ -152,7 +153,7 @@ func (s *sourceFile) extractFromDir(name string) ([]*api.Pod, error) { return pods, nil } -func (s *sourceFile) extractFromFile(filename string) (pod *api.Pod, err error) { +func (s *sourceFile) extractFromFile(filename string) (pod *v1.Pod, err error) { glog.V(3).Infof("Reading config file %q", filename) defer func() { if err == nil && pod != nil { @@ -192,7 +193,7 @@ func (s *sourceFile) extractFromFile(filename string) (pod *api.Pod, err error) filename, string(data), podErr) } -func (s *sourceFile) replaceStore(pods ...*api.Pod) (err error) { +func (s *sourceFile) replaceStore(pods ...*v1.Pod) (err error) { objs := []interface{}{} for _, pod := range pods { objs = append(objs, pod) diff --git a/pkg/kubelet/config/file_linux.go b/pkg/kubelet/config/file_linux.go index 0b936d66850..b13de49cce9 100644 --- a/pkg/kubelet/config/file_linux.go +++ b/pkg/kubelet/config/file_linux.go @@ -26,7 +26,7 @@ import ( "github.com/golang/glog" "golang.org/x/exp/inotify" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" ) @@ -45,7 +45,7 @@ func (s *sourceFile) watch() error { return err } // Emit an update with an empty PodList to allow FileSource to be marked as seen - s.updates <- kubetypes.PodUpdate{Pods: []*api.Pod{}, Op: kubetypes.SET, Source: kubetypes.FileSource} + s.updates <- kubetypes.PodUpdate{Pods: []*v1.Pod{}, Op: kubetypes.SET, Source: kubetypes.FileSource} return fmt.Errorf("path does not exist, ignoring") } diff --git a/pkg/kubelet/config/file_linux_test.go b/pkg/kubelet/config/file_linux_test.go index 381eb120b0b..f2af6c5bcb8 100644 --- a/pkg/kubelet/config/file_linux_test.go +++ b/pkg/kubelet/config/file_linux_test.go @@ -32,6 +32,7 @@ import ( "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/api/validation" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/runtime" @@ -85,8 +86,13 @@ func TestReadPodsFromFileExistAlready(t *testing.T) { case got := <-ch: update := got.(kubetypes.PodUpdate) for _, pod := range update.Pods { - if errs := validation.ValidatePod(pod); len(errs) > 0 { - t.Fatalf("%s: Invalid pod %#v, %#v", testCase.desc, pod, errs) + // TODO: remove the conversion when validation is performed on versioned objects. + internalPod := &api.Pod{} + if err := v1.Convert_v1_Pod_To_api_Pod(pod, internalPod, nil); err != nil { + t.Fatalf("%s: Cannot convert pod %#v, %#v", testCase.desc, pod, err) + } + if errs := validation.ValidatePod(internalPod); len(errs) > 0 { + t.Fatalf("%s: Invalid pod %#v, %#v", testCase.desc, internalPod, errs) } } if !api.Semantic.DeepEqual(testCase.expected, update) { @@ -169,47 +175,47 @@ func getTestCases(hostname types.NodeName) []*testCase { return []*testCase{ { desc: "Simple pod", - pod: &api.Pod{ + pod: &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", APIVersion: "", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "test", UID: "12345", Namespace: "mynamespace", }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "image", Image: "test/image", SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults()}}, - SecurityContext: &api.PodSecurityContext{}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Name: "image", Image: "test/image", SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults()}}, + SecurityContext: &v1.PodSecurityContext{}, }, - Status: api.PodStatus{ - Phase: api.PodPending, + Status: v1.PodStatus{ + Phase: v1.PodPending, }, }, - expected: CreatePodUpdate(kubetypes.SET, kubetypes.FileSource, &api.Pod{ - ObjectMeta: api.ObjectMeta{ + expected: CreatePodUpdate(kubetypes.SET, kubetypes.FileSource, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "test-" + string(hostname), UID: "12345", Namespace: "mynamespace", Annotations: map[string]string{kubetypes.ConfigHashAnnotationKey: "12345"}, SelfLink: getSelfLink("test-"+string(hostname), "mynamespace"), }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: string(hostname), - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, + RestartPolicy: v1.RestartPolicyAlways, + DNSPolicy: v1.DNSClusterFirst, TerminationGracePeriodSeconds: &grace, - Containers: []api.Container{{ + Containers: []v1.Container{{ Name: "image", Image: "test/image", TerminationMessagePath: "/dev/termination-log", ImagePullPolicy: "Always", SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults()}}, - SecurityContext: &api.PodSecurityContext{}, + SecurityContext: &v1.PodSecurityContext{}, }, - Status: api.PodStatus{ - Phase: api.PodPending, + Status: v1.PodStatus{ + Phase: v1.PodPending, }, }), }, @@ -312,7 +318,7 @@ func watchFileChanged(watchDir bool, t *testing.T) { lock.Lock() defer lock.Unlock() - pod := testCase.pod.(*api.Pod) + pod := testCase.pod.(*v1.Pod) pod.Spec.Containers[0].Name = "image2" testCase.expected.Pods[0].Spec.Containers[0].Name = "image2" @@ -355,8 +361,13 @@ func expectUpdate(t *testing.T, ch chan interface{}, testCase *testCase) { case got := <-ch: update := got.(kubetypes.PodUpdate) for _, pod := range update.Pods { - if errs := validation.ValidatePod(pod); len(errs) > 0 { - t.Fatalf("%s: Invalid pod %#v, %#v", testCase.desc, pod, errs) + // TODO: remove the conversion when validation is performed on versioned objects. + internalPod := &api.Pod{} + if err := v1.Convert_v1_Pod_To_api_Pod(pod, internalPod, nil); err != nil { + t.Fatalf("%s: Cannot convert pod %#v, %#v", testCase.desc, pod, err) + } + if errs := validation.ValidatePod(internalPod); len(errs) > 0 { + t.Fatalf("%s: Invalid pod %#v, %#v", testCase.desc, internalPod, errs) } } diff --git a/pkg/kubelet/config/http.go b/pkg/kubelet/config/http.go index 41ee92c6e31..0a00607cc05 100644 --- a/pkg/kubelet/config/http.go +++ b/pkg/kubelet/config/http.go @@ -25,6 +25,7 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/util/wait" @@ -101,7 +102,7 @@ func (s *sourceURL) extractFromURL() error { } if len(data) == 0 { // Emit an update with an empty PodList to allow HTTPSource to be marked as seen - s.updates <- kubetypes.PodUpdate{Pods: []*api.Pod{}, Op: kubetypes.SET, Source: kubetypes.HTTPSource} + s.updates <- kubetypes.PodUpdate{Pods: []*v1.Pod{}, Op: kubetypes.SET, Source: kubetypes.HTTPSource} return fmt.Errorf("zero-length data received from %v", s.url) } // Short circuit if the data has not changed since the last time it was read. @@ -117,7 +118,7 @@ func (s *sourceURL) extractFromURL() error { // It parsed but could not be used. return singlePodErr } - s.updates <- kubetypes.PodUpdate{Pods: []*api.Pod{pod}, Op: kubetypes.SET, Source: kubetypes.HTTPSource} + s.updates <- kubetypes.PodUpdate{Pods: []*v1.Pod{pod}, Op: kubetypes.SET, Source: kubetypes.HTTPSource} return nil } @@ -128,7 +129,7 @@ func (s *sourceURL) extractFromURL() error { // It parsed but could not be used. return multiPodErr } - pods := make([]*api.Pod, 0) + pods := make([]*v1.Pod, 0) for i := range podList.Items { pods = append(pods, &podList.Items[i]) } diff --git a/pkg/kubelet/config/http_test.go b/pkg/kubelet/config/http_test.go index c40fc236c0f..01b36862e95 100644 --- a/pkg/kubelet/config/http_test.go +++ b/pkg/kubelet/config/http_test.go @@ -26,6 +26,7 @@ import ( "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/api/validation" "k8s.io/kubernetes/pkg/apimachinery/registered" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" @@ -56,49 +57,49 @@ func TestExtractFromHttpBadness(t *testing.T) { func TestExtractInvalidPods(t *testing.T) { var testCases = []struct { desc string - pod *api.Pod + pod *v1.Pod }{ { desc: "No version", - pod: &api.Pod{TypeMeta: unversioned.TypeMeta{APIVersion: ""}}, + pod: &v1.Pod{TypeMeta: unversioned.TypeMeta{APIVersion: ""}}, }, { desc: "Invalid version", - pod: &api.Pod{TypeMeta: unversioned.TypeMeta{APIVersion: "v1betta2"}}, + pod: &v1.Pod{TypeMeta: unversioned.TypeMeta{APIVersion: "v1betta2"}}, }, { desc: "Invalid volume name", - pod: &api.Pod{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - Spec: api.PodSpec{ - Volumes: []api.Volume{{Name: "_INVALID_"}}, + pod: &v1.Pod{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + Spec: v1.PodSpec{ + Volumes: []v1.Volume{{Name: "_INVALID_"}}, }, }, }, { desc: "Duplicate volume names", - pod: &api.Pod{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - Spec: api.PodSpec{ - Volumes: []api.Volume{{Name: "repeated"}, {Name: "repeated"}}, + pod: &v1.Pod{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + Spec: v1.PodSpec{ + Volumes: []v1.Volume{{Name: "repeated"}, {Name: "repeated"}}, }, }, }, { desc: "Unspecified container name", - pod: &api.Pod{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: ""}}, + pod: &v1.Pod{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Name: ""}}, }, }, }, { desc: "Invalid container name", - pod: &api.Pod{ - TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String()}, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "_INVALID_"}}, + pod: &v1.Pod{ + TypeMeta: unversioned.TypeMeta{APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String()}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Name: "_INVALID_"}}, }, }, }, @@ -133,144 +134,144 @@ func TestExtractPodsFromHTTP(t *testing.T) { }{ { desc: "Single pod", - pods: &api.Pod{ + pods: &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", APIVersion: "", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", UID: "111", Namespace: "mynamespace", }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: string(nodeName), - Containers: []api.Container{{Name: "1", Image: "foo", ImagePullPolicy: api.PullAlways}}, - SecurityContext: &api.PodSecurityContext{}, + Containers: []v1.Container{{Name: "1", Image: "foo", ImagePullPolicy: v1.PullAlways}}, + SecurityContext: &v1.PodSecurityContext{}, }, - Status: api.PodStatus{ - Phase: api.PodPending, + Status: v1.PodStatus{ + Phase: v1.PodPending, }, }, expected: CreatePodUpdate(kubetypes.SET, kubetypes.HTTPSource, - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "111", Name: "foo" + "-" + nodeName, Namespace: "mynamespace", Annotations: map[string]string{kubetypes.ConfigHashAnnotationKey: "111"}, SelfLink: getSelfLink("foo-"+nodeName, "mynamespace"), }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: nodeName, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - SecurityContext: &api.PodSecurityContext{}, + RestartPolicy: v1.RestartPolicyAlways, + DNSPolicy: v1.DNSClusterFirst, + SecurityContext: &v1.PodSecurityContext{}, TerminationGracePeriodSeconds: &grace, - Containers: []api.Container{{ + Containers: []v1.Container{{ Name: "1", Image: "foo", TerminationMessagePath: "/dev/termination-log", ImagePullPolicy: "Always", }}, }, - Status: api.PodStatus{ - Phase: api.PodPending, + Status: v1.PodStatus{ + Phase: v1.PodPending, }, }), }, { desc: "Multiple pods", - pods: &api.PodList{ + pods: &v1.PodList{ TypeMeta: unversioned.TypeMeta{ Kind: "PodList", APIVersion: "", }, - Items: []api.Pod{ + Items: []v1.Pod{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", UID: "111", }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: nodeName, - Containers: []api.Container{{Name: "1", Image: "foo", ImagePullPolicy: api.PullAlways}}, - SecurityContext: &api.PodSecurityContext{}, + Containers: []v1.Container{{Name: "1", Image: "foo", ImagePullPolicy: v1.PullAlways}}, + SecurityContext: &v1.PodSecurityContext{}, }, - Status: api.PodStatus{ - Phase: api.PodPending, + Status: v1.PodStatus{ + Phase: v1.PodPending, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "bar", UID: "222", }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: nodeName, - Containers: []api.Container{{Name: "2", Image: "bar:bartag", ImagePullPolicy: ""}}, - SecurityContext: &api.PodSecurityContext{}, + Containers: []v1.Container{{Name: "2", Image: "bar:bartag", ImagePullPolicy: ""}}, + SecurityContext: &v1.PodSecurityContext{}, }, - Status: api.PodStatus{ - Phase: api.PodPending, + Status: v1.PodStatus{ + Phase: v1.PodPending, }, }, }, }, expected: CreatePodUpdate(kubetypes.SET, kubetypes.HTTPSource, - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "111", Name: "foo" + "-" + nodeName, Namespace: "default", Annotations: map[string]string{kubetypes.ConfigHashAnnotationKey: "111"}, SelfLink: getSelfLink("foo-"+nodeName, kubetypes.NamespaceDefault), }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: nodeName, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, + RestartPolicy: v1.RestartPolicyAlways, + DNSPolicy: v1.DNSClusterFirst, TerminationGracePeriodSeconds: &grace, - SecurityContext: &api.PodSecurityContext{}, + SecurityContext: &v1.PodSecurityContext{}, - Containers: []api.Container{{ + Containers: []v1.Container{{ Name: "1", Image: "foo", TerminationMessagePath: "/dev/termination-log", ImagePullPolicy: "Always", }}, }, - Status: api.PodStatus{ - Phase: api.PodPending, + Status: v1.PodStatus{ + Phase: v1.PodPending, }, }, - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "222", Name: "bar" + "-" + nodeName, Namespace: "default", Annotations: map[string]string{kubetypes.ConfigHashAnnotationKey: "222"}, SelfLink: getSelfLink("bar-"+nodeName, kubetypes.NamespaceDefault), }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: nodeName, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, + RestartPolicy: v1.RestartPolicyAlways, + DNSPolicy: v1.DNSClusterFirst, TerminationGracePeriodSeconds: &grace, - SecurityContext: &api.PodSecurityContext{}, + SecurityContext: &v1.PodSecurityContext{}, - Containers: []api.Container{{ + Containers: []v1.Container{{ Name: "2", Image: "bar:bartag", TerminationMessagePath: "/dev/termination-log", ImagePullPolicy: "IfNotPresent", }}, }, - Status: api.PodStatus{ - Phase: api.PodPending, + Status: v1.PodStatus{ + Phase: v1.PodPending, }, }), }, @@ -304,7 +305,12 @@ func TestExtractPodsFromHTTP(t *testing.T) { t.Errorf("%s: Expected: %#v, Got: %#v", testCase.desc, testCase.expected, update) } for _, pod := range update.Pods { - if errs := validation.ValidatePod(pod); len(errs) != 0 { + // TODO: remove the conversion when validation is performed on versioned objects. + internalPod := &api.Pod{} + if err := v1.Convert_v1_Pod_To_api_Pod(pod, internalPod, nil); err != nil { + t.Fatalf("%s: Cannot convert pod %#v, %#v", testCase.desc, pod, err) + } + if errs := validation.ValidatePod(internalPod); len(errs) != 0 { t.Errorf("%s: Expected no validation errors on %#v, Got %v", testCase.desc, pod, errs.ToAggregate()) } } @@ -312,19 +318,19 @@ func TestExtractPodsFromHTTP(t *testing.T) { } func TestURLWithHeader(t *testing.T) { - pod := &api.Pod{ + pod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), Kind: "Pod", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", UID: "111", Namespace: "mynamespace", }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: "localhost", - Containers: []api.Container{{Name: "1", Image: "foo", ImagePullPolicy: api.PullAlways}}, + Containers: []v1.Container{{Name: "1", Image: "foo", ImagePullPolicy: v1.PullAlways}}, }, } data, err := json.Marshal(pod) diff --git a/pkg/kubelet/container/BUILD b/pkg/kubelet/container/BUILD index 5d03b4ba505..23fdb3d7096 100644 --- a/pkg/kubelet/container/BUILD +++ b/pkg/kubelet/container/BUILD @@ -28,8 +28,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/kubelet/api/v1alpha1/runtime:go_default_library", "//pkg/kubelet/util/format:go_default_library", @@ -59,8 +59,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/types:go_default_library", "//vendor:github.com/stretchr/testify/assert", diff --git a/pkg/kubelet/container/container_reference_manager.go b/pkg/kubelet/container/container_reference_manager.go index f37a7103ab2..1b6710688fd 100644 --- a/pkg/kubelet/container/container_reference_manager.go +++ b/pkg/kubelet/container/container_reference_manager.go @@ -19,7 +19,7 @@ package container import ( "sync" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) // RefManager manages the references for the containers. @@ -28,17 +28,17 @@ import ( // for the caller. type RefManager struct { sync.RWMutex - containerIDToRef map[ContainerID]*api.ObjectReference + containerIDToRef map[ContainerID]*v1.ObjectReference } // NewRefManager creates and returns a container reference manager // with empty contents. func NewRefManager() *RefManager { - return &RefManager{containerIDToRef: make(map[ContainerID]*api.ObjectReference)} + return &RefManager{containerIDToRef: make(map[ContainerID]*v1.ObjectReference)} } // SetRef stores a reference to a pod's container, associating it with the given container ID. -func (c *RefManager) SetRef(id ContainerID, ref *api.ObjectReference) { +func (c *RefManager) SetRef(id ContainerID, ref *v1.ObjectReference) { c.Lock() defer c.Unlock() c.containerIDToRef[id] = ref @@ -52,7 +52,7 @@ func (c *RefManager) ClearRef(id ContainerID) { } // GetRef returns the container reference of the given ID, or (nil, false) if none is stored. -func (c *RefManager) GetRef(id ContainerID) (ref *api.ObjectReference, ok bool) { +func (c *RefManager) GetRef(id ContainerID) (ref *v1.ObjectReference, ok bool) { c.RLock() defer c.RUnlock() ref, ok = c.containerIDToRef[id] diff --git a/pkg/kubelet/container/helpers.go b/pkg/kubelet/container/helpers.go index f60a5419d9a..f88e6c8a5cd 100644 --- a/pkg/kubelet/container/helpers.go +++ b/pkg/kubelet/container/helpers.go @@ -25,8 +25,8 @@ import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" "k8s.io/kubernetes/pkg/kubelet/util/format" @@ -39,25 +39,25 @@ import ( // HandlerRunner runs a lifecycle handler for a container. type HandlerRunner interface { - Run(containerID ContainerID, pod *api.Pod, container *api.Container, handler *api.Handler) (string, error) + Run(containerID ContainerID, pod *v1.Pod, container *v1.Container, handler *v1.Handler) (string, error) } // RuntimeHelper wraps kubelet to make container runtime // able to get necessary informations like the RunContainerOptions, DNS settings. type RuntimeHelper interface { - GenerateRunContainerOptions(pod *api.Pod, container *api.Container, podIP string) (*RunContainerOptions, error) - GetClusterDNS(pod *api.Pod) (dnsServers []string, dnsSearches []string, err error) + GenerateRunContainerOptions(pod *v1.Pod, container *v1.Container, podIP string) (*RunContainerOptions, error) + GetClusterDNS(pod *v1.Pod) (dnsServers []string, dnsSearches []string, err error) GetPodDir(podUID types.UID) string - GeneratePodHostNameAndDomain(pod *api.Pod) (hostname string, hostDomain string, err error) + GeneratePodHostNameAndDomain(pod *v1.Pod) (hostname string, hostDomain string, err error) // GetExtraSupplementalGroupsForPod returns a list of the extra // supplemental groups for the Pod. These extra supplemental groups come // from annotations on persistent volumes that the pod depends on. - GetExtraSupplementalGroupsForPod(pod *api.Pod) []int64 + GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64 } // ShouldContainerBeRestarted checks whether a container needs to be restarted. // TODO(yifan): Think about how to refactor this. -func ShouldContainerBeRestarted(container *api.Container, pod *api.Pod, podStatus *PodStatus) bool { +func ShouldContainerBeRestarted(container *v1.Container, pod *v1.Pod, podStatus *PodStatus) bool { // Get latest container status. status := podStatus.FindContainerStatusByName(container.Name) // If the container was never started before, we should start it. @@ -74,11 +74,11 @@ func ShouldContainerBeRestarted(container *api.Container, pod *api.Pod, podStatu return true } // Check RestartPolicy for dead container - if pod.Spec.RestartPolicy == api.RestartPolicyNever { + if pod.Spec.RestartPolicy == v1.RestartPolicyNever { glog.V(4).Infof("Already ran container %q of pod %q, do nothing", container.Name, format.Pod(pod)) return false } - if pod.Spec.RestartPolicy == api.RestartPolicyOnFailure { + if pod.Spec.RestartPolicy == v1.RestartPolicyOnFailure { // Check the exit code. if status.ExitCode == 0 { glog.V(4).Infof("Already successfully ran container %q of pod %q, do nothing", container.Name, format.Pod(pod)) @@ -90,7 +90,7 @@ func ShouldContainerBeRestarted(container *api.Container, pod *api.Pod, podStatu // HashContainer returns the hash of the container. It is used to compare // the running container with its desired spec. -func HashContainer(container *api.Container) uint64 { +func HashContainer(container *v1.Container) uint64 { hash := adler32.New() hashutil.DeepHashObject(hash, *container) return uint64(hash.Sum32()) @@ -107,7 +107,7 @@ func EnvVarsToMap(envs []EnvVar) map[string]string { return result } -func ExpandContainerCommandAndArgs(container *api.Container, envs []EnvVar) (command []string, args []string) { +func ExpandContainerCommandAndArgs(container *v1.Container, envs []EnvVar) (command []string, args []string) { mapping := expansion.MappingFuncFor(EnvVarsToMap(envs)) if len(container.Command) != 0 { @@ -136,11 +136,11 @@ type innerEventRecorder struct { recorder record.EventRecorder } -func (irecorder *innerEventRecorder) shouldRecordEvent(object runtime.Object) (*api.ObjectReference, bool) { +func (irecorder *innerEventRecorder) shouldRecordEvent(object runtime.Object) (*v1.ObjectReference, bool) { if object == nil { return nil, false } - if ref, ok := object.(*api.ObjectReference); ok { + if ref, ok := object.(*v1.ObjectReference); ok { if !strings.HasPrefix(ref.FieldPath, ImplicitContainerPrefix) { return ref, true } @@ -168,8 +168,8 @@ func (irecorder *innerEventRecorder) PastEventf(object runtime.Object, timestamp } // Pod must not be nil. -func IsHostNetworkPod(pod *api.Pod) bool { - return pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostNetwork +func IsHostNetworkPod(pod *v1.Pod) bool { + return pod.Spec.HostNetwork } // TODO(random-liu): Convert PodStatus to running Pod, should be deprecated soon diff --git a/pkg/kubelet/container/helpers_test.go b/pkg/kubelet/container/helpers_test.go index 4856d79af22..23669158269 100644 --- a/pkg/kubelet/container/helpers_test.go +++ b/pkg/kubelet/container/helpers_test.go @@ -20,7 +20,7 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) func TestEnvVarsToMap(t *testing.T) { @@ -53,18 +53,18 @@ func TestEnvVarsToMap(t *testing.T) { func TestExpandCommandAndArgs(t *testing.T) { cases := []struct { name string - container *api.Container + container *v1.Container envs []EnvVar expectedCommand []string expectedArgs []string }{ { name: "none", - container: &api.Container{}, + container: &v1.Container{}, }, { name: "command expanded", - container: &api.Container{ + container: &v1.Container{ Command: []string{"foo", "$(VAR_TEST)", "$(VAR_TEST2)"}, }, envs: []EnvVar{ @@ -81,7 +81,7 @@ func TestExpandCommandAndArgs(t *testing.T) { }, { name: "args expanded", - container: &api.Container{ + container: &v1.Container{ Args: []string{"zap", "$(VAR_TEST)", "$(VAR_TEST2)"}, }, envs: []EnvVar{ @@ -98,7 +98,7 @@ func TestExpandCommandAndArgs(t *testing.T) { }, { name: "both expanded", - container: &api.Container{ + container: &v1.Container{ Command: []string{"$(VAR_TEST2)--$(VAR_TEST)", "foo", "$(VAR_TEST3)"}, Args: []string{"foo", "$(VAR_TEST)", "$(VAR_TEST2)"}, }, @@ -136,14 +136,14 @@ func TestExpandCommandAndArgs(t *testing.T) { } func TestShouldContainerBeRestarted(t *testing.T) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Name: "no-history"}, {Name: "alive"}, {Name: "succeed"}, @@ -187,10 +187,10 @@ func TestShouldContainerBeRestarted(t *testing.T) { }, }, } - policies := []api.RestartPolicy{ - api.RestartPolicyNever, - api.RestartPolicyOnFailure, - api.RestartPolicyAlways, + policies := []v1.RestartPolicy{ + v1.RestartPolicyNever, + v1.RestartPolicyOnFailure, + v1.RestartPolicyAlways, } expected := map[string][]bool{ "no-history": {true, true, true}, diff --git a/pkg/kubelet/container/ref.go b/pkg/kubelet/container/ref.go index 8fcdc95ad21..04d896dcb53 100644 --- a/pkg/kubelet/container/ref.go +++ b/pkg/kubelet/container/ref.go @@ -19,25 +19,25 @@ package container import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) var ImplicitContainerPrefix string = "implicitly required container " -// GenerateContainerRef returns an *api.ObjectReference which references the given container +// GenerateContainerRef returns an *v1.ObjectReference which references the given container // within the given pod. Returns an error if the reference can't be constructed or the // container doesn't actually belong to the pod. // // This function will return an error if the provided Pod does not have a selfLink, // but we expect selfLink to be populated at all call sites for the function. -func GenerateContainerRef(pod *api.Pod, container *api.Container) (*api.ObjectReference, error) { +func GenerateContainerRef(pod *v1.Pod, container *v1.Container) (*v1.ObjectReference, error) { fieldPath, err := fieldPath(pod, container) if err != nil { // TODO: figure out intelligent way to refer to containers that we implicitly // start (like the pod infra container). This is not a good way, ugh. fieldPath = ImplicitContainerPrefix + container.Name } - ref, err := api.GetPartialReference(pod, fieldPath) + ref, err := v1.GetPartialReference(pod, fieldPath) if err != nil { return nil, err } @@ -46,7 +46,7 @@ func GenerateContainerRef(pod *api.Pod, container *api.Container) (*api.ObjectRe // fieldPath returns a fieldPath locating container within pod. // Returns an error if the container isn't part of the pod. -func fieldPath(pod *api.Pod, container *api.Container) (string, error) { +func fieldPath(pod *v1.Pod, container *v1.Container) (string, error) { for i := range pod.Spec.Containers { here := &pod.Spec.Containers[i] if here.Name == container.Name { diff --git a/pkg/kubelet/container/ref_test.go b/pkg/kubelet/container/ref_test.go index be1cd31bd0d..acb4fb6c855 100644 --- a/pkg/kubelet/container/ref_test.go +++ b/pkg/kubelet/container/ref_test.go @@ -19,29 +19,29 @@ package container import ( "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" ) func TestFieldPath(t *testing.T) { - pod := &api.Pod{Spec: api.PodSpec{Containers: []api.Container{ + pod := &v1.Pod{Spec: v1.PodSpec{Containers: []v1.Container{ {Name: "foo"}, {Name: "bar"}, {Name: ""}, {Name: "baz"}, }}} table := map[string]struct { - pod *api.Pod - container *api.Container + pod *v1.Pod + container *v1.Container path string success bool }{ - "basic": {pod, &api.Container{Name: "foo"}, "spec.containers{foo}", true}, - "basic2": {pod, &api.Container{Name: "baz"}, "spec.containers{baz}", true}, - "emptyName": {pod, &api.Container{Name: ""}, "spec.containers[2]", true}, + "basic": {pod, &v1.Container{Name: "foo"}, "spec.containers{foo}", true}, + "basic2": {pod, &v1.Container{Name: "baz"}, "spec.containers{baz}", true}, + "emptyName": {pod, &v1.Container{Name: ""}, "spec.containers[2]", true}, "basicSamePointer": {pod, &pod.Spec.Containers[0], "spec.containers{foo}", true}, - "missing": {pod, &api.Container{Name: "qux"}, "", false}, + "missing": {pod, &v1.Container{Name: "qux"}, "", false}, } for name, item := range table { @@ -64,20 +64,20 @@ func TestFieldPath(t *testing.T) { func TestGenerateContainerRef(t *testing.T) { var ( - okPod = api.Pod{ + okPod = v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "ok", Namespace: "test-ns", UID: "bar", ResourceVersion: "42", - SelfLink: "/api/" + registered.GroupOrDie(api.GroupName).GroupVersion.String() + "/pods/foo", + SelfLink: "/api/" + registered.GroupOrDie(v1.GroupName).GroupVersion.String() + "/pods/foo", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "by-name", }, @@ -91,24 +91,24 @@ func TestGenerateContainerRef(t *testing.T) { noSelfLinkPod.Kind = "" noSelfLinkPod.APIVersion = "" noSelfLinkPod.ObjectMeta.SelfLink = "" - defaultedSelfLinkPod.ObjectMeta.SelfLink = "/api/" + registered.GroupOrDie(api.GroupName).GroupVersion.String() + "/pods/ok" + defaultedSelfLinkPod.ObjectMeta.SelfLink = "/api/" + registered.GroupOrDie(v1.GroupName).GroupVersion.String() + "/pods/ok" cases := []struct { name string - pod *api.Pod - container *api.Container - expected *api.ObjectReference + pod *v1.Pod + container *v1.Container + expected *v1.ObjectReference success bool }{ { name: "by-name", pod: &okPod, - container: &api.Container{ + container: &v1.Container{ Name: "by-name", }, - expected: &api.ObjectReference{ + expected: &v1.ObjectReference{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), Name: "ok", Namespace: "test-ns", UID: "bar", @@ -120,10 +120,10 @@ func TestGenerateContainerRef(t *testing.T) { { name: "no-name", pod: &okPod, - container: &api.Container{}, - expected: &api.ObjectReference{ + container: &v1.Container{}, + expected: &v1.ObjectReference{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), Name: "ok", Namespace: "test-ns", UID: "bar", @@ -135,19 +135,19 @@ func TestGenerateContainerRef(t *testing.T) { { name: "no-selflink", pod: &noSelfLinkPod, - container: &api.Container{}, + container: &v1.Container{}, expected: nil, success: false, }, { name: "defaulted-selflink", pod: &defaultedSelfLinkPod, - container: &api.Container{ + container: &v1.Container{ Name: "by-name", }, - expected: &api.ObjectReference{ + expected: &v1.ObjectReference{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), Name: "ok", Namespace: "test-ns", UID: "bar", @@ -159,12 +159,12 @@ func TestGenerateContainerRef(t *testing.T) { { name: "implicitly-required", pod: &okPod, - container: &api.Container{ + container: &v1.Container{ Name: "net", }, - expected: &api.ObjectReference{ + expected: &v1.ObjectReference{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), Name: "ok", Namespace: "test-ns", UID: "bar", diff --git a/pkg/kubelet/container/runtime.go b/pkg/kubelet/container/runtime.go index 94001216a17..7242d1d68b2 100644 --- a/pkg/kubelet/container/runtime.go +++ b/pkg/kubelet/container/runtime.go @@ -25,7 +25,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/flowcontrol" @@ -85,13 +85,13 @@ type Runtime interface { // TODO: Revisit this method and make it cleaner. GarbageCollect(gcPolicy ContainerGCPolicy, allSourcesReady bool) error // Syncs the running pod into the desired pod. - SyncPod(pod *api.Pod, apiPodStatus api.PodStatus, podStatus *PodStatus, pullSecrets []api.Secret, backOff *flowcontrol.Backoff) PodSyncResult + SyncPod(pod *v1.Pod, apiPodStatus v1.PodStatus, podStatus *PodStatus, pullSecrets []v1.Secret, backOff *flowcontrol.Backoff) PodSyncResult // KillPod kills all the containers of a pod. Pod may be nil, running pod must not be. // TODO(random-liu): Return PodSyncResult in KillPod. // gracePeriodOverride if specified allows the caller to override the pod default grace period. // only hard kill paths are allowed to specify a gracePeriodOverride in the kubelet in order to not corrupt user data. // it is useful when doing SIGKILL for hard eviction scenarios, or max grace period during soft eviction scenarios. - KillPod(pod *api.Pod, runningPod Pod, gracePeriodOverride *int64) error + KillPod(pod *v1.Pod, runningPod Pod, gracePeriodOverride *int64) error // GetPodStatus retrieves the status of the pod, including the // information of all containers in the pod that are visble in Runtime. GetPodStatus(uid types.UID, name, namespace string) (*PodStatus, error) @@ -111,7 +111,7 @@ type Runtime interface { // default, it returns a snapshot of the container log. Set 'follow' to true to // stream the log. Set 'follow' to false and specify the number of lines (e.g. // "100" or "all") to tail the log. - GetContainerLogs(pod *api.Pod, containerID ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) (err error) + GetContainerLogs(pod *v1.Pod, containerID ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) (err error) // Delete a container. If the container is still running, an error is returned. DeleteContainer(containerID ContainerID) error // ImageService provides methods to image-related methods. @@ -147,7 +147,7 @@ type IndirectStreamingRuntime interface { type ImageService interface { // PullImage pulls an image from the network to local storage using the supplied // secrets if necessary. - PullImage(image ImageSpec, pullSecrets []api.Secret) error + PullImage(image ImageSpec, pullSecrets []v1.Secret) error // IsImagePresent checks whether the container image is already in the local storage. IsImagePresent(image ImageSpec) (bool, error) // Gets all images currently on the machine. @@ -188,8 +188,8 @@ type Pod struct { // PodPair contains both runtime#Pod and api#Pod type PodPair struct { - // APIPod is the api.Pod - APIPod *api.Pod + // APIPod is the v1.Pod + APIPod *v1.Pod // RunningPod is the pod defined defined in pkg/kubelet/container/runtime#Pod RunningPod *Pod } @@ -270,7 +270,7 @@ type Container struct { // a container. ID ContainerID // The name of the container, which should be the same as specified by - // api.Container. + // v1.Container. Name string // The image name of the container, this also includes the tag of the image, // the expected form is "NAME:TAG". @@ -285,7 +285,7 @@ type Container struct { } // PodStatus represents the status of the pod and its containers. -// api.PodStatus can be derived from examining PodStatus and api.Pod. +// v1.PodStatus can be derived from examining PodStatus and v1.Pod. type PodStatus struct { // ID of the pod. ID types.UID @@ -392,7 +392,7 @@ type PortMapping struct { // Name of the port mapping Name string // Protocol of the port mapping. - Protocol api.Protocol + Protocol v1.Protocol // The port number within the container. ContainerPort int // The port number on the host. @@ -570,16 +570,16 @@ func (p *Pod) FindSandboxByID(id ContainerID) *Container { return nil } -// ToAPIPod converts Pod to api.Pod. Note that if a field in api.Pod has no +// ToAPIPod converts Pod to v1.Pod. Note that if a field in v1.Pod has no // corresponding field in Pod, the field would not be populated. -func (p *Pod) ToAPIPod() *api.Pod { - var pod api.Pod +func (p *Pod) ToAPIPod() *v1.Pod { + var pod v1.Pod pod.UID = p.ID pod.Name = p.Name pod.Namespace = p.Namespace for _, c := range p.Containers { - var container api.Container + var container v1.Container container.Name = c.Name container.Image = c.Image pod.Spec.Containers = append(pod.Spec.Containers, container) @@ -593,7 +593,7 @@ func (p *Pod) IsEmpty() bool { } // GetPodFullName returns a name that uniquely identifies a pod. -func GetPodFullName(pod *api.Pod) string { +func GetPodFullName(pod *v1.Pod) string { // Use underscore as the delimiter because it is not allowed in pod name // (DNS subdomain format), while allowed in the container name format. return pod.Name + "_" + pod.Namespace diff --git a/pkg/kubelet/container/testing/BUILD b/pkg/kubelet/container/testing/BUILD index 31c54cd39e5..f59a3c0fd15 100644 --- a/pkg/kubelet/container/testing/BUILD +++ b/pkg/kubelet/container/testing/BUILD @@ -21,7 +21,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/types:go_default_library", "//pkg/util/flowcontrol:go_default_library", diff --git a/pkg/kubelet/container/testing/fake_runtime.go b/pkg/kubelet/container/testing/fake_runtime.go index 6ff792a551c..3b996ea77ca 100644 --- a/pkg/kubelet/container/testing/fake_runtime.go +++ b/pkg/kubelet/container/testing/fake_runtime.go @@ -24,7 +24,7 @@ import ( "sync" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" . "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/flowcontrol" @@ -44,7 +44,7 @@ type FakeRuntime struct { PodList []*FakePod AllPodList []*FakePod ImageList []Image - APIPodStatus api.PodStatus + APIPodStatus v1.PodStatus PodStatus PodStatus StartedPods []string KilledPods []string @@ -133,7 +133,7 @@ func (f *FakeRuntime) ClearCalls() { f.CalledFunctions = []string{} f.PodList = []*FakePod{} f.AllPodList = []*FakePod{} - f.APIPodStatus = api.PodStatus{} + f.APIPodStatus = v1.PodStatus{} f.StartedPods = []string{} f.KilledPods = []string{} f.StartedContainers = []string{} @@ -236,7 +236,7 @@ func (f *FakeRuntime) GetPods(all bool) ([]*Pod, error) { return pods, f.Err } -func (f *FakeRuntime) SyncPod(pod *api.Pod, _ api.PodStatus, _ *PodStatus, _ []api.Secret, backOff *flowcontrol.Backoff) (result PodSyncResult) { +func (f *FakeRuntime) SyncPod(pod *v1.Pod, _ v1.PodStatus, _ *PodStatus, _ []v1.Secret, backOff *flowcontrol.Backoff) (result PodSyncResult) { f.Lock() defer f.Unlock() @@ -252,7 +252,7 @@ func (f *FakeRuntime) SyncPod(pod *api.Pod, _ api.PodStatus, _ *PodStatus, _ []a return } -func (f *FakeRuntime) KillPod(pod *api.Pod, runningPod Pod, gracePeriodOverride *int64) error { +func (f *FakeRuntime) KillPod(pod *v1.Pod, runningPod Pod, gracePeriodOverride *int64) error { f.Lock() defer f.Unlock() @@ -264,7 +264,7 @@ func (f *FakeRuntime) KillPod(pod *api.Pod, runningPod Pod, gracePeriodOverride return f.Err } -func (f *FakeRuntime) RunContainerInPod(container api.Container, pod *api.Pod, volumeMap map[string]volume.VolumePlugin) error { +func (f *FakeRuntime) RunContainerInPod(container v1.Container, pod *v1.Pod, volumeMap map[string]volume.VolumePlugin) error { f.Lock() defer f.Unlock() @@ -281,14 +281,14 @@ func (f *FakeRuntime) RunContainerInPod(container api.Container, pod *api.Pod, v return f.Err } -func (f *FakeRuntime) KillContainerInPod(container api.Container, pod *api.Pod) error { +func (f *FakeRuntime) KillContainerInPod(container v1.Container, pod *v1.Pod) error { f.Lock() defer f.Unlock() f.CalledFunctions = append(f.CalledFunctions, "KillContainerInPod") f.KilledContainers = append(f.KilledContainers, container.Name) - var containers []api.Container + var containers []v1.Container for _, c := range pod.Spec.Containers { if c.Name == container.Name { continue @@ -336,7 +336,7 @@ func (f *FakeDirectStreamingRuntime) AttachContainer(containerID ContainerID, st return f.Err } -func (f *FakeRuntime) GetContainerLogs(pod *api.Pod, containerID ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) (err error) { +func (f *FakeRuntime) GetContainerLogs(pod *v1.Pod, containerID ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) (err error) { f.Lock() defer f.Unlock() @@ -344,7 +344,7 @@ func (f *FakeRuntime) GetContainerLogs(pod *api.Pod, containerID ContainerID, lo return f.Err } -func (f *FakeRuntime) PullImage(image ImageSpec, pullSecrets []api.Secret) error { +func (f *FakeRuntime) PullImage(image ImageSpec, pullSecrets []v1.Secret) error { f.Lock() defer f.Unlock() diff --git a/pkg/kubelet/container/testing/runtime_mock.go b/pkg/kubelet/container/testing/runtime_mock.go index b3edc2c6c06..6fb4acea64c 100644 --- a/pkg/kubelet/container/testing/runtime_mock.go +++ b/pkg/kubelet/container/testing/runtime_mock.go @@ -21,7 +21,7 @@ import ( "time" "github.com/stretchr/testify/mock" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" . "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/flowcontrol" @@ -65,22 +65,22 @@ func (r *Mock) GetPods(all bool) ([]*Pod, error) { return args.Get(0).([]*Pod), args.Error(1) } -func (r *Mock) SyncPod(pod *api.Pod, apiStatus api.PodStatus, status *PodStatus, secrets []api.Secret, backOff *flowcontrol.Backoff) PodSyncResult { +func (r *Mock) SyncPod(pod *v1.Pod, apiStatus v1.PodStatus, status *PodStatus, secrets []v1.Secret, backOff *flowcontrol.Backoff) PodSyncResult { args := r.Called(pod, apiStatus, status, secrets, backOff) return args.Get(0).(PodSyncResult) } -func (r *Mock) KillPod(pod *api.Pod, runningPod Pod, gracePeriodOverride *int64) error { +func (r *Mock) KillPod(pod *v1.Pod, runningPod Pod, gracePeriodOverride *int64) error { args := r.Called(pod, runningPod, gracePeriodOverride) return args.Error(0) } -func (r *Mock) RunContainerInPod(container api.Container, pod *api.Pod, volumeMap map[string]volume.VolumePlugin) error { +func (r *Mock) RunContainerInPod(container v1.Container, pod *v1.Pod, volumeMap map[string]volume.VolumePlugin) error { args := r.Called(pod, pod, volumeMap) return args.Error(0) } -func (r *Mock) KillContainerInPod(container api.Container, pod *api.Pod) error { +func (r *Mock) KillContainerInPod(container v1.Container, pod *v1.Pod) error { args := r.Called(pod, pod) return args.Error(0) } @@ -100,12 +100,12 @@ func (r *Mock) AttachContainer(containerID ContainerID, stdin io.Reader, stdout, return args.Error(0) } -func (r *Mock) GetContainerLogs(pod *api.Pod, containerID ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) (err error) { +func (r *Mock) GetContainerLogs(pod *v1.Pod, containerID ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) (err error) { args := r.Called(pod, containerID, logOptions, stdout, stderr) return args.Error(0) } -func (r *Mock) PullImage(image ImageSpec, pullSecrets []api.Secret) error { +func (r *Mock) PullImage(image ImageSpec, pullSecrets []v1.Secret) error { args := r.Called(image, pullSecrets) return args.Error(0) } diff --git a/pkg/kubelet/custommetrics/BUILD b/pkg/kubelet/custommetrics/BUILD index 976e763f160..ab559c2c085 100644 --- a/pkg/kubelet/custommetrics/BUILD +++ b/pkg/kubelet/custommetrics/BUILD @@ -14,7 +14,7 @@ go_library( name = "go_default_library", srcs = ["custom_metrics.go"], tags = ["automanaged"], - deps = ["//pkg/api:go_default_library"], + deps = ["//pkg/api/v1:go_default_library"], ) go_test( @@ -23,7 +23,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//vendor:github.com/stretchr/testify/assert", ], ) diff --git a/pkg/kubelet/custommetrics/custom_metrics.go b/pkg/kubelet/custommetrics/custom_metrics.go index 314a3b5df00..1df5ff2a391 100644 --- a/pkg/kubelet/custommetrics/custom_metrics.go +++ b/pkg/kubelet/custommetrics/custom_metrics.go @@ -20,7 +20,7 @@ package custommetrics import ( "path" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) const ( @@ -31,7 +31,7 @@ const ( // Alpha implementation. // Returns a path to a cAdvisor-specific custom metrics configuration. -func GetCAdvisorCustomMetricsDefinitionPath(container *api.Container) (*string, error) { +func GetCAdvisorCustomMetricsDefinitionPath(container *v1.Container) (*string, error) { // Assuemes that the container has Custom Metrics enabled if it has "/etc/custom-metrics" directory // mounted as a volume. Custom Metrics definition is expected to be in "definition.json". if container.VolumeMounts != nil { diff --git a/pkg/kubelet/custommetrics/custom_metrics_test.go b/pkg/kubelet/custommetrics/custom_metrics_test.go index bcda7b056c9..49aa236b32a 100644 --- a/pkg/kubelet/custommetrics/custom_metrics_test.go +++ b/pkg/kubelet/custommetrics/custom_metrics_test.go @@ -20,18 +20,18 @@ import ( "testing" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) func TestGetCAdvisorCustomMetricsDefinitionPath(t *testing.T) { - regularContainer := &api.Container{ + regularContainer := &v1.Container{ Name: "test_container", } - cmContainer := &api.Container{ + cmContainer := &v1.Container{ Name: "test_container", - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "cm", MountPath: CustomMetricsDefinitionDir, diff --git a/pkg/kubelet/dockershim/BUILD b/pkg/kubelet/dockershim/BUILD index 9b73ad4b990..18896419ed2 100644 --- a/pkg/kubelet/dockershim/BUILD +++ b/pkg/kubelet/dockershim/BUILD @@ -26,7 +26,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/componentconfig:go_default_library", "//pkg/kubelet/api:go_default_library", "//pkg/kubelet/api/v1alpha1/runtime:go_default_library", @@ -69,7 +69,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/api/v1alpha1/runtime:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/container/testing:go_default_library", diff --git a/pkg/kubelet/dockershim/cm/container_manager_unsupported.go b/pkg/kubelet/dockershim/cm/container_manager_unsupported.go index 5a78017d076..ad0e5b80bfc 100644 --- a/pkg/kubelet/dockershim/cm/container_manager_unsupported.go +++ b/pkg/kubelet/dockershim/cm/container_manager_unsupported.go @@ -20,6 +20,7 @@ package cm import ( "fmt" + "k8s.io/kubernetes/pkg/kubelet/dockertools" ) diff --git a/pkg/kubelet/dockershim/doc.go b/pkg/kubelet/dockershim/doc.go index 619271d3467..5bc3318d5bb 100644 --- a/pkg/kubelet/dockershim/doc.go +++ b/pkg/kubelet/dockershim/doc.go @@ -14,5 +14,5 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Docker integration using pkg/kubelet/api/v1alpha1/runtime/api.pb.go. +// Docker integration using pkg/kubelet/api/v1alpha1/runtime/v1.pb.go. package dockershim diff --git a/pkg/kubelet/dockershim/docker_sandbox.go b/pkg/kubelet/dockershim/docker_sandbox.go index 88fcb4716cd..0504fdb160c 100644 --- a/pkg/kubelet/dockershim/docker_sandbox.go +++ b/pkg/kubelet/dockershim/docker_sandbox.go @@ -305,7 +305,7 @@ func (ds *dockerService) makeSandboxDockerConfig(c *runtimeApi.PodSandboxConfig, labels := makeLabels(c.GetLabels(), c.GetAnnotations()) // Apply a label to distinguish sandboxes from regular containers. labels[containerTypeLabelKey] = containerTypeLabelSandbox - // Apply a container name label for infra container. This is used in summary api. + // Apply a container name label for infra container. This is used in summary v1. // TODO(random-liu): Deprecate this label once container metrics is directly got from CRI. labels[types.KubernetesContainerNameLabel] = sandboxContainerName diff --git a/pkg/kubelet/dockershim/helpers.go b/pkg/kubelet/dockershim/helpers.go index ee2440dbfa5..dd649e80d06 100644 --- a/pkg/kubelet/dockershim/helpers.go +++ b/pkg/kubelet/dockershim/helpers.go @@ -28,7 +28,7 @@ import ( dockernat "github.com/docker/go-connections/nat" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" "k8s.io/kubernetes/pkg/kubelet/dockertools" "k8s.io/kubernetes/pkg/kubelet/types" @@ -235,7 +235,7 @@ func getNetworkNamespace(c *dockertypes.ContainerJSON) string { func getSysctlsFromAnnotations(annotations map[string]string) (map[string]string, error) { var results map[string]string - sysctls, unsafeSysctls, err := api.SysctlsFromPodAnnotations(annotations) + sysctls, unsafeSysctls, err := v1.SysctlsFromPodAnnotations(annotations) if err != nil { return nil, err } diff --git a/pkg/kubelet/dockershim/helpers_test.go b/pkg/kubelet/dockershim/helpers_test.go index 9fb0daebc37..6c2710b63f5 100644 --- a/pkg/kubelet/dockershim/helpers_test.go +++ b/pkg/kubelet/dockershim/helpers_test.go @@ -22,7 +22,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" "k8s.io/kubernetes/pkg/security/apparmor" ) @@ -58,19 +58,19 @@ func TestGetContainerSecurityOpts(t *testing.T) { }, { msg: "Seccomp unconfined", config: makeConfig(map[string]string{ - api.SeccompContainerAnnotationKeyPrefix + containerName: "unconfined", + v1.SeccompContainerAnnotationKeyPrefix + containerName: "unconfined", }), expectedOpts: []string{"seccomp=unconfined"}, }, { msg: "Seccomp default", config: makeConfig(map[string]string{ - api.SeccompContainerAnnotationKeyPrefix + containerName: "docker/default", + v1.SeccompContainerAnnotationKeyPrefix + containerName: "docker/default", }), expectedOpts: nil, }, { msg: "Seccomp pod default", config: makeConfig(map[string]string{ - api.SeccompPodAnnotationKey: "docker/default", + v1.SeccompPodAnnotationKey: "docker/default", }), expectedOpts: nil, }, { @@ -88,8 +88,8 @@ func TestGetContainerSecurityOpts(t *testing.T) { }, { msg: "AppArmor and seccomp profile", config: makeConfig(map[string]string{ - api.SeccompContainerAnnotationKeyPrefix + containerName: "docker/default", - apparmor.ContainerAnnotationKeyPrefix + containerName: apparmor.ProfileNamePrefix + "foo", + v1.SeccompContainerAnnotationKeyPrefix + containerName: "docker/default", + apparmor.ContainerAnnotationKeyPrefix + containerName: apparmor.ProfileNamePrefix + "foo", }), expectedOpts: []string{"apparmor=foo"}, }} @@ -121,20 +121,20 @@ func TestGetSandboxSecurityOpts(t *testing.T) { }, { msg: "Seccomp default", config: makeConfig(map[string]string{ - api.SeccompPodAnnotationKey: "docker/default", + v1.SeccompPodAnnotationKey: "docker/default", }), expectedOpts: nil, }, { msg: "Seccomp unconfined", config: makeConfig(map[string]string{ - api.SeccompPodAnnotationKey: "unconfined", + v1.SeccompPodAnnotationKey: "unconfined", }), expectedOpts: []string{"seccomp=unconfined"}, }, { msg: "Seccomp pod and container profile", config: makeConfig(map[string]string{ - api.SeccompContainerAnnotationKeyPrefix + "test-container": "unconfined", - api.SeccompPodAnnotationKey: "docker/default", + v1.SeccompContainerAnnotationKeyPrefix + "test-container": "unconfined", + v1.SeccompPodAnnotationKey: "docker/default", }), expectedOpts: nil, }} @@ -156,8 +156,8 @@ func TestGetSystclsFromAnnotations(t *testing.T) { expectedSysctls map[string]string }{{ annotations: map[string]string{ - api.SysctlsPodAnnotationKey: "kernel.shmmni=32768,kernel.shmmax=1000000000", - api.UnsafeSysctlsPodAnnotationKey: "knet.ipv4.route.min_pmtu=1000", + v1.SysctlsPodAnnotationKey: "kernel.shmmni=32768,kernel.shmmax=1000000000", + v1.UnsafeSysctlsPodAnnotationKey: "knet.ipv4.route.min_pmtu=1000", }, expectedSysctls: map[string]string{ "kernel.shmmni": "32768", @@ -166,7 +166,7 @@ func TestGetSystclsFromAnnotations(t *testing.T) { }, }, { annotations: map[string]string{ - api.SysctlsPodAnnotationKey: "kernel.shmmni=32768,kernel.shmmax=1000000000", + v1.SysctlsPodAnnotationKey: "kernel.shmmni=32768,kernel.shmmax=1000000000", }, expectedSysctls: map[string]string{ "kernel.shmmni": "32768", @@ -174,7 +174,7 @@ func TestGetSystclsFromAnnotations(t *testing.T) { }, }, { annotations: map[string]string{ - api.UnsafeSysctlsPodAnnotationKey: "knet.ipv4.route.min_pmtu=1000", + v1.UnsafeSysctlsPodAnnotationKey: "knet.ipv4.route.min_pmtu=1000", }, expectedSysctls: map[string]string{ "knet.ipv4.route.min_pmtu": "1000", diff --git a/pkg/kubelet/dockershim/security_context.go b/pkg/kubelet/dockershim/security_context.go index b323db8e9f8..e1b74698d92 100644 --- a/pkg/kubelet/dockershim/security_context.go +++ b/pkg/kubelet/dockershim/security_context.go @@ -22,7 +22,7 @@ import ( dockercontainer "github.com/docker/engine-api/types/container" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" runtimeapi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" "k8s.io/kubernetes/pkg/securitycontext" ) @@ -100,7 +100,7 @@ func modifyHostConfig(sc *runtimeapi.LinuxContainerSecurityContext, sandboxID st if sc.SelinuxOptions != nil { hostConfig.SecurityOpt = securitycontext.ModifySecurityOptions( hostConfig.SecurityOpt, - &api.SELinuxOptions{ + &v1.SELinuxOptions{ User: sc.SelinuxOptions.GetUser(), Role: sc.SelinuxOptions.GetRole(), Type: sc.SelinuxOptions.GetType(), diff --git a/pkg/kubelet/dockertools/BUILD b/pkg/kubelet/dockertools/BUILD index 5a1d3fbd9c5..ec7b287f4a1 100644 --- a/pkg/kubelet/dockertools/BUILD +++ b/pkg/kubelet/dockertools/BUILD @@ -30,6 +30,7 @@ go_library( deps = [ "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/credentialprovider:go_default_library", "//pkg/kubelet/cm:go_default_library", @@ -101,6 +102,7 @@ go_test( deps = [ "//pkg/api:go_default_library", "//pkg/api/testapi:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/componentconfig:go_default_library", "//pkg/client/record:go_default_library", "//pkg/credentialprovider:go_default_library", diff --git a/pkg/kubelet/dockertools/container_gc_test.go b/pkg/kubelet/dockertools/container_gc_test.go index f654b263a21..f46dc05bfb6 100644 --- a/pkg/kubelet/dockertools/container_gc_test.go +++ b/pkg/kubelet/dockertools/container_gc_test.go @@ -24,7 +24,7 @@ import ( "time" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/types" ) @@ -65,8 +65,8 @@ func makeUndefinedContainer(id string, running bool, created time.Time) *FakeCon func addPods(podGetter podGetter, podUIDs ...types.UID) { fakePodGetter := podGetter.(*fakePodGetter) for _, uid := range podUIDs { - fakePodGetter.pods[uid] = &api.Pod{ - ObjectMeta: api.ObjectMeta{ + fakePodGetter.pods[uid] = &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod" + string(uid), Namespace: "test", UID: uid, diff --git a/pkg/kubelet/dockertools/docker.go b/pkg/kubelet/dockertools/docker.go index e38b56e390f..5a8e9b9c2b8 100644 --- a/pkg/kubelet/dockertools/docker.go +++ b/pkg/kubelet/dockertools/docker.go @@ -31,7 +31,7 @@ import ( dockerapi "github.com/docker/engine-api/client" dockertypes "github.com/docker/engine-api/types" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/credentialprovider" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/images" @@ -93,7 +93,7 @@ func SetContainerNamePrefix(prefix string) { // DockerPuller is an abstract interface for testability. It abstracts image pull operations. type DockerPuller interface { - Pull(image string, secrets []api.Secret) error + Pull(image string, secrets []v1.Secret) error IsImagePresent(image string) (bool, error) } @@ -225,7 +225,7 @@ func matchImageIDOnly(inspected dockertypes.ImageInspect, image string) bool { return false } -func (p dockerPuller) Pull(image string, secrets []api.Secret) error { +func (p dockerPuller) Pull(image string, secrets []v1.Secret) error { keyring, err := credentialprovider.MakeDockerKeyring(secrets, p.keyring) if err != nil { return err @@ -293,7 +293,7 @@ func (p dockerPuller) IsImagePresent(image string) (bool, error) { // Although rand.Uint32() is not really unique, but it's enough for us because error will // only occur when instances of the same container in the same pod have the same UID. The // chance is really slim. -func BuildDockerName(dockerName KubeletContainerName, container *api.Container) (string, string, string) { +func BuildDockerName(dockerName KubeletContainerName, container *v1.Container) (string, string, string) { containerName := dockerName.ContainerName + "." + strconv.FormatUint(kubecontainer.HashContainer(container), 16) stableName := fmt.Sprintf("%s_%s_%s_%s", containerNamePrefix, diff --git a/pkg/kubelet/dockertools/docker_manager.go b/pkg/kubelet/dockertools/docker_manager.go index 423b18cb8ea..46a0ac283f1 100644 --- a/pkg/kubelet/dockertools/docker_manager.go +++ b/pkg/kubelet/dockertools/docker_manager.go @@ -45,6 +45,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/kubelet/cm" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" @@ -113,7 +114,7 @@ var ( _ kubecontainer.DirectStreamingRuntime = &DockerManager{} // TODO: make this a TTL based pull (if image older than X policy, pull) - podInfraContainerImagePullPolicy = api.PullIfNotPresent + podInfraContainerImagePullPolicy = v1.PullIfNotPresent // Default set of seccomp security options. defaultSeccompOpt = []dockerOpt{{"seccomp", "unconfined", ""}} @@ -129,7 +130,7 @@ type DockerManager struct { // The image name of the pod infra container. podInfraContainerImage string // (Optional) Additional environment variables to be set for the pod infra container. - podInfraContainerEnv []api.EnvVar + podInfraContainerEnv []v1.EnvVar // TODO(yifan): Record the pull failure so we can eliminate the image checking? // Lower level docker image puller. @@ -194,14 +195,14 @@ type DockerManager struct { // A subset of the pod.Manager interface extracted for testing purposes. type podGetter interface { - GetPodByUID(kubetypes.UID) (*api.Pod, bool) + GetPodByUID(kubetypes.UID) (*v1.Pod, bool) } func PodInfraContainerEnv(env map[string]string) kubecontainer.Option { return func(rt kubecontainer.Runtime) { dm := rt.(*DockerManager) for k, v := range env { - dm.podInfraContainerEnv = append(dm.podInfraContainerEnv, api.EnvVar{ + dm.podInfraContainerEnv = append(dm.podInfraContainerEnv, v1.EnvVar{ Name: k, Value: v, }) @@ -308,7 +309,7 @@ func NewDockerManager( // stream the log. Set 'follow' to false and specify the number of lines (e.g. // "100" or "all") to tail the log. // TODO: Make 'RawTerminal' option flagable. -func (dm *DockerManager) GetContainerLogs(pod *api.Pod, containerID kubecontainer.ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error { +func (dm *DockerManager) GetContainerLogs(pod *v1.Pod, containerID kubecontainer.ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) error { container, err := dm.client.InspectContainer(containerID.ID) if err != nil { return err @@ -318,7 +319,7 @@ func (dm *DockerManager) GetContainerLogs(pod *api.Pod, containerID kubecontaine // Temporarily export this function to share with dockershim. // TODO: clean this up. -func GetContainerLogs(client DockerInterface, pod *api.Pod, containerID kubecontainer.ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer, rawTerm bool) error { +func GetContainerLogs(client DockerInterface, pod *v1.Pod, containerID kubecontainer.ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer, rawTerm bool) error { var since int64 if logOptions.SinceSeconds != nil { t := unversioned.Now().Add(-time.Duration(*logOptions.SinceSeconds) * time.Second) @@ -584,10 +585,10 @@ func makePortsAndBindings(portMappings []kubecontainer.PortMapping) (map[dockern } func (dm *DockerManager) runContainer( - pod *api.Pod, - container *api.Container, + pod *v1.Pod, + container *v1.Container, opts *kubecontainer.RunContainerOptions, - ref *api.ObjectReference, + ref *v1.ObjectReference, netMode string, ipcMode string, utsMode string, @@ -620,7 +621,7 @@ func (dm *DockerManager) runContainer( // TODO: This is kind of hacky, we should really just encode the bits we need. // TODO: This is hacky because the Kubelet should be parameterized to encode a specific version // and needs to be able to migrate this whenever we deprecate v1. Should be a member of DockerManager. - if data, err := kruntime.Encode(api.Codecs.LegacyCodec(unversioned.GroupVersion{Group: api.GroupName, Version: "v1"}), pod); err == nil { + if data, err := kruntime.Encode(api.Codecs.LegacyCodec(unversioned.GroupVersion{Group: v1.GroupName, Version: "v1"}), pod); err == nil { labels[kubernetesPodLabel] = string(data) } else { glog.Errorf("Failed to encode pod: %s for prestop hook", pod.Name) @@ -711,9 +712,9 @@ func (dm *DockerManager) runContainer( // Set sysctls if requested if container.Name == PodInfraContainerName { - sysctls, unsafeSysctls, err := api.SysctlsFromPodAnnotations(pod.Annotations) + sysctls, unsafeSysctls, err := v1.SysctlsFromPodAnnotations(pod.Annotations) if err != nil { - dm.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToCreateContainer, "Failed to create docker container %q of pod %q with error: %v", container.Name, format.Pod(pod), err) + dm.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedToCreateContainer, "Failed to create docker container %q of pod %q with error: %v", container.Name, format.Pod(pod), err) return kubecontainer.ContainerID{}, err } if len(sysctls)+len(unsafeSysctls) > 0 { @@ -789,7 +790,7 @@ func (dm *DockerManager) runContainer( securityContextProvider.ModifyHostConfig(pod, container, dockerOpts.HostConfig, supplementalGids) createResp, err := dm.client.CreateContainer(dockerOpts) if err != nil { - dm.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToCreateContainer, "Failed to create docker container %q of pod %q with error: %v", container.Name, format.Pod(pod), err) + dm.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedToCreateContainer, "Failed to create docker container %q of pod %q with error: %v", container.Name, format.Pod(pod), err) return kubecontainer.ContainerID{}, err } if len(createResp.Warnings) != 0 { @@ -808,21 +809,21 @@ func (dm *DockerManager) runContainer( } createdEventMsg = fmt.Sprintf("%s; Security:[%s]", createdEventMsg, strings.Join(msgs, " ")) } - dm.recorder.Eventf(ref, api.EventTypeNormal, events.CreatedContainer, createdEventMsg) + dm.recorder.Eventf(ref, v1.EventTypeNormal, events.CreatedContainer, createdEventMsg) if err = dm.client.StartContainer(createResp.ID); err != nil { - dm.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToStartContainer, + dm.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedToStartContainer, "Failed to start container with docker id %v with error: %v", utilstrings.ShortenString(createResp.ID, 12), err) return kubecontainer.ContainerID{}, err } - dm.recorder.Eventf(ref, api.EventTypeNormal, events.StartedContainer, "Started container with docker id %v", utilstrings.ShortenString(createResp.ID, 12)) + dm.recorder.Eventf(ref, v1.EventTypeNormal, events.StartedContainer, "Started container with docker id %v", utilstrings.ShortenString(createResp.ID, 12)) return kubecontainer.DockerID(createResp.ID).ContainerID(), nil } // setInfraContainerNetworkConfig sets the network configuration for the infra-container. We only set network configuration for infra-container, all // the user containers will share the same network namespace with infra-container. -func setInfraContainerNetworkConfig(pod *api.Pod, netMode string, opts *kubecontainer.RunContainerOptions, dockerOpts *dockertypes.ContainerCreateConfig) { +func setInfraContainerNetworkConfig(pod *v1.Pod, netMode string, opts *kubecontainer.RunContainerOptions, dockerOpts *dockertypes.ContainerCreateConfig) { exposedPorts, portBindings := makePortsAndBindings(opts.PortMappings) dockerOpts.Config.ExposedPorts = exposedPorts dockerOpts.HostConfig.PortBindings = dockernat.PortMap(portBindings) @@ -838,7 +839,7 @@ func setInfraContainerNetworkConfig(pod *api.Pod, netMode string, opts *kubecont } } -func setEntrypointAndCommand(container *api.Container, opts *kubecontainer.RunContainerOptions, dockerOpts dockertypes.ContainerCreateConfig) { +func setEntrypointAndCommand(container *v1.Container, opts *kubecontainer.RunContainerOptions, dockerOpts dockertypes.ContainerCreateConfig) { command, args := kubecontainer.ExpandContainerCommandAndArgs(container, opts.Envs) dockerOpts.Config.Entrypoint = dockerstrslice.StrSlice(command) @@ -957,7 +958,7 @@ func (dm *DockerManager) ListImages() ([]kubecontainer.Image, error) { } // PullImage pulls an image from network to local storage. -func (dm *DockerManager) PullImage(image kubecontainer.ImageSpec, secrets []api.Secret) error { +func (dm *DockerManager) PullImage(image kubecontainer.ImageSpec, secrets []v1.Secret) error { return dm.dockerPuller.Pull(image.Image, secrets) } @@ -983,8 +984,8 @@ func (dm *DockerManager) RemoveImage(image kubecontainer.ImageSpec) error { } // podInfraContainerChanged returns true if the pod infra container has changed. -func (dm *DockerManager) podInfraContainerChanged(pod *api.Pod, podInfraContainerStatus *kubecontainer.ContainerStatus) (bool, error) { - var ports []api.ContainerPort +func (dm *DockerManager) podInfraContainerChanged(pod *v1.Pod, podInfraContainerStatus *kubecontainer.ContainerStatus) (bool, error) { + var ports []v1.ContainerPort // Check network mode. if kubecontainer.IsHostNetworkPod(pod) { @@ -995,7 +996,7 @@ func (dm *DockerManager) podInfraContainerChanged(pod *api.Pod, podInfraContaine networkMode := getDockerNetworkMode(dockerPodInfraContainer) if networkMode != namespaceModeHost { - glog.V(4).Infof("host: %v, %v", pod.Spec.SecurityContext.HostNetwork, networkMode) + glog.V(4).Infof("host: %v, %v", pod.Spec.HostNetwork, networkMode) return true, nil } } else if dm.networkPlugin.Name() != "cni" && dm.networkPlugin.Name() != "kubenet" { @@ -1008,7 +1009,7 @@ func (dm *DockerManager) podInfraContainerChanged(pod *api.Pod, podInfraContaine ports = append(ports, container.Ports...) } } - expectedPodInfraContainer := &api.Container{ + expectedPodInfraContainer := &v1.Container{ Name: PodInfraContainerName, Image: dm.podInfraContainerImage, Ports: ports, @@ -1019,7 +1020,7 @@ func (dm *DockerManager) podInfraContainerChanged(pod *api.Pod, podInfraContaine } // determine if the container root should be a read only filesystem. -func readOnlyRootFilesystem(container *api.Container) bool { +func readOnlyRootFilesystem(container *v1.Container) bool { return container.SecurityContext != nil && container.SecurityContext.ReadOnlyRootFilesystem != nil && *container.SecurityContext.ReadOnlyRootFilesystem } @@ -1171,7 +1172,7 @@ func (d dockerOpt) GetKV() (string, string) { } // Get the docker security options for seccomp. -func (dm *DockerManager) getSeccompOpts(pod *api.Pod, ctrName string) ([]dockerOpt, error) { +func (dm *DockerManager) getSeccompOpts(pod *v1.Pod, ctrName string) ([]dockerOpt, error) { version, err := dm.APIVersion() if err != nil { return nil, err @@ -1190,10 +1191,10 @@ func (dm *DockerManager) getSeccompOpts(pod *api.Pod, ctrName string) ([]dockerO // Temporarily export this function to share with dockershim. // TODO: clean this up. func GetSeccompOpts(annotations map[string]string, ctrName, profileRoot string) ([]dockerOpt, error) { - profile, profileOK := annotations[api.SeccompContainerAnnotationKeyPrefix+ctrName] + profile, profileOK := annotations[v1.SeccompContainerAnnotationKeyPrefix+ctrName] if !profileOK { // try the pod profile - profile, profileOK = annotations[api.SeccompPodAnnotationKey] + profile, profileOK = annotations[v1.SeccompPodAnnotationKey] if !profileOK { // return early the default return defaultSeccompOpt, nil @@ -1232,7 +1233,7 @@ func GetSeccompOpts(annotations map[string]string, ctrName, profileRoot string) } // Get the docker security options for AppArmor. -func (dm *DockerManager) getAppArmorOpts(pod *api.Pod, ctrName string) ([]dockerOpt, error) { +func (dm *DockerManager) getAppArmorOpts(pod *v1.Pod, ctrName string) ([]dockerOpt, error) { return GetAppArmorOpts(pod.Annotations, ctrName) } @@ -1406,13 +1407,13 @@ func PortForward(client DockerInterface, podInfraContainerID string, port uint16 // TODO(random-liu): After using pod status for KillPod(), we can also remove the kubernetesPodLabel, because all the needed information should have // been extract from new labels and stored in pod status. // only hard eviction scenarios should provide a grace period override, all other code paths must pass nil. -func (dm *DockerManager) KillPod(pod *api.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) error { +func (dm *DockerManager) KillPod(pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) error { result := dm.killPodWithSyncResult(pod, runningPod, gracePeriodOverride) return result.Error() } // NOTE(random-liu): The pod passed in could be *nil* when kubelet restarted. -func (dm *DockerManager) killPodWithSyncResult(pod *api.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) (result kubecontainer.PodSyncResult) { +func (dm *DockerManager) killPodWithSyncResult(pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) (result kubecontainer.PodSyncResult) { // Short circuit if there's nothing to kill. if len(runningPod.Containers) == 0 { return @@ -1423,7 +1424,7 @@ func (dm *DockerManager) killPodWithSyncResult(pod *api.Pod, runningPod kubecont wg := sync.WaitGroup{} var ( networkContainer *kubecontainer.Container - networkSpec *api.Container + networkSpec *v1.Container ) wg.Add(len(runningPod.Containers)) for _, container := range runningPod.Containers { @@ -1431,7 +1432,7 @@ func (dm *DockerManager) killPodWithSyncResult(pod *api.Pod, runningPod kubecont defer utilruntime.HandleCrash() defer wg.Done() - var containerSpec *api.Container + var containerSpec *v1.Container if pod != nil { for i, c := range pod.Spec.Containers { if c.Name == container.Name { @@ -1503,7 +1504,7 @@ func (dm *DockerManager) killPodWithSyncResult(pod *api.Pod, runningPod kubecont // KillContainerInPod kills a container in the pod. It must be passed either a container ID or a container and pod, // and will attempt to lookup the other information if missing. -func (dm *DockerManager) KillContainerInPod(containerID kubecontainer.ContainerID, container *api.Container, pod *api.Pod, message string, gracePeriodOverride *int64) error { +func (dm *DockerManager) KillContainerInPod(containerID kubecontainer.ContainerID, container *v1.Container, pod *v1.Pod, message string, gracePeriodOverride *int64) error { switch { case containerID.IsEmpty(): // Locate the container. @@ -1542,7 +1543,7 @@ func (dm *DockerManager) KillContainerInPod(containerID kubecontainer.ContainerI // KillContainerInPod if information must be retrieved first. It is only valid to provide a grace period override // during hard eviction scenarios. All other code paths in kubelet must never provide a grace period override otherwise // data corruption could occur in the end-user application. -func (dm *DockerManager) killContainer(containerID kubecontainer.ContainerID, container *api.Container, pod *api.Pod, reason string, gracePeriodOverride *int64) error { +func (dm *DockerManager) killContainer(containerID kubecontainer.ContainerID, container *v1.Container, pod *v1.Pod, reason string, gracePeriodOverride *int64) error { ID := containerID.ID name := ID if container != nil { @@ -1614,7 +1615,7 @@ func (dm *DockerManager) killContainer(containerID kubecontainer.ContainerID, co if reason != "" { message = fmt.Sprint(message, ": ", reason) } - dm.recorder.Event(ref, api.EventTypeNormal, events.KillingContainer, message) + dm.recorder.Event(ref, v1.EventTypeNormal, events.KillingContainer, message) dm.containerRefManager.ClearRef(containerID) } return err @@ -1626,13 +1627,13 @@ func (dm *DockerManager) generateFailedContainerEvent(containerID kubecontainer. glog.Warningf("No ref for pod '%q'", podName) return } - dm.recorder.Event(ref, api.EventTypeWarning, reason, message) + dm.recorder.Event(ref, v1.EventTypeWarning, reason, message) } var errNoPodOnContainer = fmt.Errorf("no pod information labels on Docker container") // containerAndPodFromLabels tries to load the appropriate container info off of a Docker container's labels -func containerAndPodFromLabels(inspect *dockertypes.ContainerJSON) (pod *api.Pod, container *api.Container, err error) { +func containerAndPodFromLabels(inspect *dockertypes.ContainerJSON) (pod *v1.Pod, container *v1.Container, err error) { if inspect == nil || inspect.Config == nil || inspect.Config.Labels == nil { return nil, nil, errNoPodOnContainer } @@ -1640,7 +1641,7 @@ func containerAndPodFromLabels(inspect *dockertypes.ContainerJSON) (pod *api.Pod // the pod data may not be set if body, found := labels[kubernetesPodLabel]; found { - pod = &api.Pod{} + pod = &v1.Pod{} if err = kruntime.DecodeInto(api.Codecs.UniversalDecoder(), []byte(body), pod); err == nil { name := labels[types.KubernetesContainerNameLabel] for ix := range pod.Spec.Containers { @@ -1670,7 +1671,7 @@ func containerAndPodFromLabels(inspect *dockertypes.ContainerJSON) (pod *api.Pod if pod == nil { if period, ok := labels[kubernetesPodTerminationGracePeriodLabel]; ok { if seconds, err := strconv.ParseInt(period, 10, 64); err == nil { - pod = &api.Pod{} + pod = &v1.Pod{} pod.DeletionGracePeriodSeconds = &seconds } } @@ -1679,7 +1680,7 @@ func containerAndPodFromLabels(inspect *dockertypes.ContainerJSON) (pod *api.Pod return } -func (dm *DockerManager) applyOOMScoreAdj(pod *api.Pod, container *api.Container, containerInfo *dockertypes.ContainerJSON) error { +func (dm *DockerManager) applyOOMScoreAdj(pod *v1.Pod, container *v1.Container, containerInfo *dockertypes.ContainerJSON) error { if containerInfo.State.Pid == 0 { // Container exited. We cannot do anything about it. Ignore this error. glog.V(2).Infof("Failed to apply OOM score adj on container %q with ID %q. Init process does not exist.", containerInfo.Name, containerInfo.ID) @@ -1709,7 +1710,7 @@ func (dm *DockerManager) applyOOMScoreAdj(pod *api.Pod, container *api.Container // Run a single container from a pod. Returns the docker container ID // If do not need to pass labels, just pass nil. -func (dm *DockerManager) runContainerInPod(pod *api.Pod, container *api.Container, netMode, ipcMode, pidMode, podIP string, restartCount int) (kubecontainer.ContainerID, error) { +func (dm *DockerManager) runContainerInPod(pod *v1.Pod, container *v1.Container, netMode, ipcMode, pidMode, podIP string, restartCount int) (kubecontainer.ContainerID, error) { start := time.Now() defer func() { metrics.ContainerManagerLatency.WithLabelValues("runContainerInPod").Observe(metrics.SinceInMicroseconds(start)) @@ -1790,7 +1791,7 @@ func (dm *DockerManager) runContainerInPod(pod *api.Pod, container *api.Containe return id, err } -func (dm *DockerManager) applyOOMScoreAdjIfNeeded(pod *api.Pod, container *api.Container, containerInfo *dockertypes.ContainerJSON) error { +func (dm *DockerManager) applyOOMScoreAdjIfNeeded(pod *v1.Pod, container *v1.Container, containerInfo *dockertypes.ContainerJSON) error { // Compare current API version with expected api version. result, err := dm.checkDockerAPIVersion(dockerV110APIVersion) if err != nil { @@ -1806,7 +1807,7 @@ func (dm *DockerManager) applyOOMScoreAdjIfNeeded(pod *api.Pod, container *api.C return nil } -func (dm *DockerManager) calculateOomScoreAdj(pod *api.Pod, container *api.Container) int { +func (dm *DockerManager) calculateOomScoreAdj(pod *v1.Pod, container *v1.Container) int { // Set OOM score of the container based on the priority of the container. // Processes in lower-priority pods should be killed first if the system runs out of memory. // The main pod infrastructure container is considered high priority, since if it is killed the @@ -1880,14 +1881,14 @@ func appendToFile(filePath, stringToAppend string) error { // createPodInfraContainer starts the pod infra container for a pod. Returns the docker container ID of the newly created container. // If any error occurs in this function, it will return a brief error and a detailed error message. -func (dm *DockerManager) createPodInfraContainer(pod *api.Pod) (kubecontainer.DockerID, error, string) { +func (dm *DockerManager) createPodInfraContainer(pod *v1.Pod) (kubecontainer.DockerID, error, string) { start := time.Now() defer func() { metrics.ContainerManagerLatency.WithLabelValues("createPodInfraContainer").Observe(metrics.SinceInMicroseconds(start)) }() // Use host networking if specified. netNamespace := "" - var ports []api.ContainerPort + var ports []v1.ContainerPort if kubecontainer.IsHostNetworkPod(pod) { netNamespace = namespaceModeHost @@ -1904,7 +1905,7 @@ func (dm *DockerManager) createPodInfraContainer(pod *api.Pod) (kubecontainer.Do } } - container := &api.Container{ + container := &v1.Container{ Name: PodInfraContainerName, Image: dm.podInfraContainerImage, Ports: ports, @@ -1948,7 +1949,7 @@ type podContainerChangesSpec struct { ContainersToKeep map[kubecontainer.DockerID]int } -func (dm *DockerManager) computePodContainerChanges(pod *api.Pod, podStatus *kubecontainer.PodStatus) (podContainerChangesSpec, error) { +func (dm *DockerManager) computePodContainerChanges(pod *v1.Pod, podStatus *kubecontainer.PodStatus) (podContainerChangesSpec, error) { start := time.Now() defer func() { metrics.ContainerManagerLatency.WithLabelValues("computePodContainerChanges").Observe(metrics.SinceInMicroseconds(start)) @@ -2031,7 +2032,7 @@ func (dm *DockerManager) computePodContainerChanges(pod *api.Pod, podStatus *kub // If we're creating infra container everything will be killed anyway // If RestartPolicy is Always or OnFailure we restart containers that were running before we // killed them when restarting Infra Container. - if pod.Spec.RestartPolicy != api.RestartPolicyNever { + if pod.Spec.RestartPolicy != v1.RestartPolicyNever { message := fmt.Sprintf("Infra Container is being recreated. %q will be restarted.", container.Name) glog.V(1).Info(message) containersToStart[index] = message @@ -2044,7 +2045,7 @@ func (dm *DockerManager) computePodContainerChanges(pod *api.Pod, podStatus *kub // If we have an initialization failure everything will be killed anyway // If RestartPolicy is Always or OnFailure we restart containers that were running before we // killed them when re-running initialization - if pod.Spec.RestartPolicy != api.RestartPolicyNever { + if pod.Spec.RestartPolicy != v1.RestartPolicyNever { message := fmt.Sprintf("Failed to initialize pod. %q will be restarted.", container.Name) glog.V(1).Info(message) containersToStart[index] = message @@ -2069,7 +2070,7 @@ func (dm *DockerManager) computePodContainerChanges(pod *api.Pod, podStatus *kub containersToKeep[containerID] = index continue } - if pod.Spec.RestartPolicy != api.RestartPolicyNever { + if pod.Spec.RestartPolicy != v1.RestartPolicyNever { message := fmt.Sprintf("pod %q container %q is unhealthy, it will be killed and re-created.", format.Pod(pod), container.Name) glog.Info(message) containersToStart[index] = message @@ -2100,7 +2101,7 @@ func (dm *DockerManager) computePodContainerChanges(pod *api.Pod, podStatus *kub } // Sync the running pod to match the specified desired pod. -func (dm *DockerManager) SyncPod(pod *api.Pod, _ api.PodStatus, podStatus *kubecontainer.PodStatus, pullSecrets []api.Secret, backOff *flowcontrol.Backoff) (result kubecontainer.PodSyncResult) { +func (dm *DockerManager) SyncPod(pod *v1.Pod, _ v1.PodStatus, podStatus *kubecontainer.PodStatus, pullSecrets []v1.Secret, backOff *flowcontrol.Backoff) (result kubecontainer.PodSyncResult) { start := time.Now() defer func() { metrics.ContainerManagerLatency.WithLabelValues("SyncPod").Observe(metrics.SinceInMicroseconds(start)) @@ -2114,7 +2115,7 @@ func (dm *DockerManager) SyncPod(pod *api.Pod, _ api.PodStatus, podStatus *kubec glog.V(3).Infof("Got container changes for pod %q: %+v", format.Pod(pod), containerChanges) if containerChanges.InfraChanged { - dm.recorder.Eventf(pod, api.EventTypeNormal, "InfraChanged", "Pod infrastructure changed, it will be killed and re-created.") + dm.recorder.Eventf(pod, v1.EventTypeNormal, "InfraChanged", "Pod infrastructure changed, it will be killed and re-created.") } if containerChanges.StartInfraContainer || (len(containerChanges.ContainersToKeep) == 0 && len(containerChanges.ContainersToStart) == 0) { if len(containerChanges.ContainersToKeep) == 0 && len(containerChanges.ContainersToStart) == 0 { @@ -2139,7 +2140,7 @@ func (dm *DockerManager) SyncPod(pod *api.Pod, _ api.PodStatus, podStatus *kubec if !keep && !keepInit { glog.V(3).Infof("Killing unwanted container %q(id=%q) for pod %q", containerStatus.Name, containerStatus.ID, format.Pod(pod)) // attempt to find the appropriate container policy - var podContainer *api.Container + var podContainer *v1.Container var killMessage string for i, c := range pod.Spec.Containers { if c.Name == containerStatus.Name { @@ -2244,7 +2245,7 @@ func (dm *DockerManager) SyncPod(pod *api.Pod, _ api.PodStatus, podStatus *kubec initContainerResult := kubecontainer.NewSyncResult(kubecontainer.InitContainer, status.Name) initContainerResult.Fail(kubecontainer.ErrRunInitContainer, fmt.Sprintf("init container %q exited with %d", status.Name, status.ExitCode)) result.AddSyncResult(initContainerResult) - if pod.Spec.RestartPolicy == api.RestartPolicyNever { + if pod.Spec.RestartPolicy == v1.RestartPolicyNever { utilruntime.HandleError(fmt.Errorf("error running pod %q init container %q, restart=Never: %#v", format.Pod(pod), status.Name, status)) return } @@ -2330,7 +2331,7 @@ func (dm *DockerManager) SyncPod(pod *api.Pod, _ api.PodStatus, podStatus *kubec // tryContainerStart attempts to pull and start the container, returning an error and a reason string if the start // was not successful. -func (dm *DockerManager) tryContainerStart(container *api.Container, pod *api.Pod, podStatus *kubecontainer.PodStatus, pullSecrets []api.Secret, namespaceMode, pidMode, podIP string) (err error, reason string) { +func (dm *DockerManager) tryContainerStart(container *v1.Container, pod *v1.Pod, podStatus *kubecontainer.PodStatus, pullSecrets []v1.Secret, namespaceMode, pidMode, podIP string) (err error, reason string) { err, msg := dm.imagePuller.EnsureImageExists(pod, container, pullSecrets) if err != nil { return err, msg @@ -2368,7 +2369,7 @@ func (dm *DockerManager) tryContainerStart(container *api.Container, pod *api.Po // pruneInitContainers ensures that before we begin creating init containers, we have reduced the number // of outstanding init containers still present. This reduces load on the container garbage collector // by only preserving the most recent terminated init container. -func (dm *DockerManager) pruneInitContainersBeforeStart(pod *api.Pod, podStatus *kubecontainer.PodStatus, initContainersToKeep map[kubecontainer.DockerID]int) { +func (dm *DockerManager) pruneInitContainersBeforeStart(pod *v1.Pod, podStatus *kubecontainer.PodStatus, initContainersToKeep map[kubecontainer.DockerID]int) { // only the last execution of each init container should be preserved, and only preserve it if it is in the // list of init containers to keep. initContainerNames := sets.NewString() @@ -2417,7 +2418,7 @@ func (dm *DockerManager) pruneInitContainersBeforeStart(pod *api.Pod, podStatus // findActiveInitContainer returns the status of the last failed container, the next init container to // start, or done if there are no further init containers. Status is only returned if an init container // failed, in which case next will point to the current container. -func findActiveInitContainer(pod *api.Pod, podStatus *kubecontainer.PodStatus) (next *api.Container, status *kubecontainer.ContainerStatus, done bool) { +func findActiveInitContainer(pod *v1.Pod, podStatus *kubecontainer.PodStatus) (next *v1.Container, status *kubecontainer.ContainerStatus, done bool) { if len(pod.Spec.InitContainers) == 0 { return nil, nil, true } @@ -2449,7 +2450,7 @@ func findActiveInitContainer(pod *api.Pod, podStatus *kubecontainer.PodStatus) ( } // verifyNonRoot returns an error if the container or image will run as the root user. -func (dm *DockerManager) verifyNonRoot(container *api.Container) error { +func (dm *DockerManager) verifyNonRoot(container *v1.Container) error { if securitycontext.HasRunAsUser(container) { if securitycontext.HasRootRunAsUser(container) { return fmt.Errorf("container's runAsUser breaks non-root policy") @@ -2510,7 +2511,7 @@ func GetUserFromImageUser(id string) string { // If all instances of a container are garbage collected, doBackOff will also return false, which means the container may be restarted before the // backoff deadline. However, because that won't cause error and the chance is really slim, we can just ignore it for now. // If a container is still in backoff, the function will return a brief backoff error and a detailed error message. -func (dm *DockerManager) doBackOff(pod *api.Pod, container *api.Container, podStatus *kubecontainer.PodStatus, backOff *flowcontrol.Backoff) (bool, error, string) { +func (dm *DockerManager) doBackOff(pod *v1.Pod, container *v1.Container, podStatus *kubecontainer.PodStatus, backOff *flowcontrol.Backoff) (bool, error, string) { var cStatus *kubecontainer.ContainerStatus // Use the finished time of the latest exited container as the start point to calculate whether to do back-off. // TODO(random-liu): Better define backoff start point; add unit and e2e test after we finalize this. (See github issue #22240) @@ -2532,7 +2533,7 @@ func (dm *DockerManager) doBackOff(pod *api.Pod, container *api.Container, podSt stableName, _, _ := BuildDockerName(dockerName, container) if backOff.IsInBackOffSince(stableName, ts) { if ref, err := kubecontainer.GenerateContainerRef(pod, container); err == nil { - dm.recorder.Eventf(ref, api.EventTypeWarning, events.BackOffStartContainer, "Back-off restarting failed docker container") + dm.recorder.Eventf(ref, v1.EventTypeWarning, events.BackOffStartContainer, "Back-off restarting failed docker container") } err := fmt.Errorf("Back-off %s restarting failed container=%s pod=%s", backOff.Get(stableName), container.Name, format.Pod(pod)) glog.Infof("%s", err.Error()) @@ -2544,18 +2545,18 @@ func (dm *DockerManager) doBackOff(pod *api.Pod, container *api.Container, podSt } // getPidMode returns the pid mode to use on the docker container based on pod.Spec.HostPID. -func getPidMode(pod *api.Pod) string { +func getPidMode(pod *v1.Pod) string { pidMode := "" - if pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostPID { + if pod.Spec.HostPID { pidMode = namespaceModeHost } return pidMode } // getIPCMode returns the ipc mode to use on the docker container based on pod.Spec.HostIPC. -func getIPCMode(pod *api.Pod) string { +func getIPCMode(pod *v1.Pod) string { ipcMode := "" - if pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostIPC { + if pod.Spec.HostIPC { ipcMode = namespaceModeHost } return ipcMode diff --git a/pkg/kubelet/dockertools/docker_manager_linux.go b/pkg/kubelet/dockertools/docker_manager_linux.go index 2a520468578..c806436c653 100644 --- a/pkg/kubelet/dockertools/docker_manager_linux.go +++ b/pkg/kubelet/dockertools/docker_manager_linux.go @@ -20,7 +20,7 @@ package dockertools import ( dockertypes "github.com/docker/engine-api/types" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) func getContainerIP(container *dockertypes.ContainerJSON) string { @@ -45,7 +45,7 @@ func containerProvidesPodIP(name *KubeletContainerName) bool { } // Returns Seccomp and AppArmor Security options -func (dm *DockerManager) getSecurityOpts(pod *api.Pod, ctrName string) ([]dockerOpt, error) { +func (dm *DockerManager) getSecurityOpts(pod *v1.Pod, ctrName string) ([]dockerOpt, error) { var securityOpts []dockerOpt if seccompOpts, err := dm.getSeccompOpts(pod, ctrName); err != nil { return nil, err diff --git a/pkg/kubelet/dockertools/docker_manager_test.go b/pkg/kubelet/dockertools/docker_manager_test.go index 62263bbb96f..e9ce23115d4 100644 --- a/pkg/kubelet/dockertools/docker_manager_test.go +++ b/pkg/kubelet/dockertools/docker_manager_test.go @@ -40,6 +40,7 @@ import ( "github.com/stretchr/testify/assert" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/testapi" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" @@ -80,7 +81,7 @@ var _ kubecontainer.RuntimeHelper = &fakeRuntimeHelper{} var testPodContainerDir string -func (f *fakeRuntimeHelper) GenerateRunContainerOptions(pod *api.Pod, container *api.Container, podIP string) (*kubecontainer.RunContainerOptions, error) { +func (f *fakeRuntimeHelper) GenerateRunContainerOptions(pod *v1.Pod, container *v1.Container, podIP string) (*kubecontainer.RunContainerOptions, error) { var opts kubecontainer.RunContainerOptions var err error if len(container.TerminationMessagePath) != 0 { @@ -93,12 +94,12 @@ func (f *fakeRuntimeHelper) GenerateRunContainerOptions(pod *api.Pod, container return &opts, nil } -func (f *fakeRuntimeHelper) GetClusterDNS(pod *api.Pod) ([]string, []string, error) { +func (f *fakeRuntimeHelper) GetClusterDNS(pod *v1.Pod) ([]string, []string, error) { return nil, nil, fmt.Errorf("not implemented") } // This is not used by docker runtime. -func (f *fakeRuntimeHelper) GeneratePodHostNameAndDomain(pod *api.Pod) (string, string, error) { +func (f *fakeRuntimeHelper) GeneratePodHostNameAndDomain(pod *v1.Pod) (string, string, error) { return "", "", nil } @@ -106,7 +107,7 @@ func (f *fakeRuntimeHelper) GetPodDir(kubetypes.UID) string { return "" } -func (f *fakeRuntimeHelper) GetExtraSupplementalGroupsForPod(pod *api.Pod) []int64 { +func (f *fakeRuntimeHelper) GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64 { return nil } @@ -116,7 +117,7 @@ func newFakeImageManager() images.ImageManager { return &fakeImageManager{} } -func (m *fakeImageManager) EnsureImageExists(pod *api.Pod, container *api.Container, pullSecrets []api.Secret) (error, string) { +func (m *fakeImageManager) EnsureImageExists(pod *v1.Pod, container *v1.Container, pullSecrets []v1.Secret) (error, string) { return nil, "" } @@ -187,20 +188,20 @@ func matchString(t *testing.T, pattern, str string) bool { func TestSetEntrypointAndCommand(t *testing.T) { cases := []struct { name string - container *api.Container + container *v1.Container envs []kubecontainer.EnvVar expected *dockertypes.ContainerCreateConfig }{ { name: "none", - container: &api.Container{}, + container: &v1.Container{}, expected: &dockertypes.ContainerCreateConfig{ Config: &dockercontainer.Config{}, }, }, { name: "command", - container: &api.Container{ + container: &v1.Container{ Command: []string{"foo", "bar"}, }, expected: &dockertypes.ContainerCreateConfig{ @@ -211,7 +212,7 @@ func TestSetEntrypointAndCommand(t *testing.T) { }, { name: "command expanded", - container: &api.Container{ + container: &v1.Container{ Command: []string{"foo", "$(VAR_TEST)", "$(VAR_TEST2)"}, }, envs: []kubecontainer.EnvVar{ @@ -232,7 +233,7 @@ func TestSetEntrypointAndCommand(t *testing.T) { }, { name: "args", - container: &api.Container{ + container: &v1.Container{ Args: []string{"foo", "bar"}, }, expected: &dockertypes.ContainerCreateConfig{ @@ -243,7 +244,7 @@ func TestSetEntrypointAndCommand(t *testing.T) { }, { name: "args expanded", - container: &api.Container{ + container: &v1.Container{ Args: []string{"zap", "$(VAR_TEST)", "$(VAR_TEST2)"}, }, envs: []kubecontainer.EnvVar{ @@ -264,7 +265,7 @@ func TestSetEntrypointAndCommand(t *testing.T) { }, { name: "both", - container: &api.Container{ + container: &v1.Container{ Command: []string{"foo"}, Args: []string{"bar", "baz"}, }, @@ -277,7 +278,7 @@ func TestSetEntrypointAndCommand(t *testing.T) { }, { name: "both expanded", - container: &api.Container{ + container: &v1.Container{ Command: []string{"$(VAR_TEST2)--$(VAR_TEST)", "foo", "$(VAR_TEST3)"}, Args: []string{"foo", "$(VAR_TEST)", "$(VAR_TEST2)"}, }, @@ -477,13 +478,13 @@ func TestKillContainerInPodWithPreStop(t *testing.T) { ExitCode: 0, } expectedCmd := []string{"foo.sh", "bar"} - pod := makePod("qux", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("qux", &v1.PodSpec{ + Containers: []v1.Container{ { Name: "foo", - Lifecycle: &api.Lifecycle{ - PreStop: &api.Handler{ - Exec: &api.ExecAction{ + Lifecycle: &v1.Lifecycle{ + PreStop: &v1.Handler{ + Exec: &v1.ExecAction{ Command: expectedCmd, }, }, @@ -558,15 +559,15 @@ func TestIsAExitError(t *testing.T) { } } -func generatePodInfraContainerHash(pod *api.Pod) uint64 { - var ports []api.ContainerPort - if pod.Spec.SecurityContext == nil || !pod.Spec.SecurityContext.HostNetwork { +func generatePodInfraContainerHash(pod *v1.Pod) uint64 { + var ports []v1.ContainerPort + if pod.Spec.SecurityContext == nil || !pod.Spec.HostNetwork { for _, container := range pod.Spec.Containers { ports = append(ports, container.Ports...) } } - container := &api.Container{ + container := &v1.Container{ Name: PodInfraContainerName, Image: "", Ports: ports, @@ -577,7 +578,7 @@ func generatePodInfraContainerHash(pod *api.Pod) uint64 { // runSyncPod is a helper function to retrieve the running pods from the fake // docker client and runs SyncPod for the given pod. -func runSyncPod(t *testing.T, dm *DockerManager, fakeDocker *FakeDockerClient, pod *api.Pod, backOff *flowcontrol.Backoff, expectErr bool) kubecontainer.PodSyncResult { +func runSyncPod(t *testing.T, dm *DockerManager, fakeDocker *FakeDockerClient, pod *v1.Pod, backOff *flowcontrol.Backoff, expectErr bool) kubecontainer.PodSyncResult { podStatus, err := dm.GetPodStatus(pod.UID, pod.Name, pod.Namespace) if err != nil { t.Errorf("unexpected error: %v", err) @@ -586,8 +587,8 @@ func runSyncPod(t *testing.T, dm *DockerManager, fakeDocker *FakeDockerClient, p if backOff == nil { backOff = flowcontrol.NewBackOff(time.Second, time.Minute) } - // api.PodStatus is not used in SyncPod now, pass in an empty one. - result := dm.SyncPod(pod, api.PodStatus{}, podStatus, []api.Secret{}, backOff) + // v1.PodStatus is not used in SyncPod now, pass in an empty one. + result := dm.SyncPod(pod, v1.PodStatus{}, podStatus, []v1.Secret{}, backOff) err = result.Error() if err != nil && !expectErr { t.Errorf("unexpected error: %v", err) @@ -601,8 +602,8 @@ func TestSyncPodCreateNetAndContainer(t *testing.T) { dm, fakeDocker := newTestDockerManager() dm.podInfraContainerImage = "pod_infra_image" - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar"}, }, }) @@ -641,8 +642,8 @@ func TestSyncPodCreatesNetAndContainerPullsImage(t *testing.T) { puller := dm.dockerPuller.(*FakeDockerPuller) puller.HasImages = []string{} dm.podInfraContainerImage = "foo/infra_image:v1" - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar", Image: "foo/something:v0", ImagePullPolicy: "IfNotPresent"}, }, }) @@ -672,8 +673,8 @@ func TestSyncPodCreatesNetAndContainerPullsImage(t *testing.T) { func TestSyncPodWithPodInfraCreatesContainer(t *testing.T) { dm, fakeDocker := newTestDockerManager() - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar"}, }, }) @@ -700,8 +701,8 @@ func TestSyncPodWithPodInfraCreatesContainer(t *testing.T) { func TestSyncPodDeletesWithNoPodInfraContainer(t *testing.T) { dm, fakeDocker := newTestDockerManager() - pod := makePod("foo1", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo1", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar1"}, }, }) @@ -735,8 +736,8 @@ func TestSyncPodDeletesWithNoPodInfraContainer(t *testing.T) { func TestSyncPodDeletesDuplicate(t *testing.T) { dm, fakeDocker := newTestDockerManager() - pod := makePod("bar", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("bar", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "foo"}, }, }) @@ -769,8 +770,8 @@ func TestSyncPodDeletesDuplicate(t *testing.T) { func TestSyncPodBadHash(t *testing.T) { dm, fakeDocker := newTestDockerManager() - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar"}, }, }) @@ -802,8 +803,8 @@ func TestSyncPodsUnhealthy(t *testing.T) { infraContainerID = "9876" ) dm, fakeDocker := newTestDockerManager() - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{{Name: "unhealthy"}}, + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{{Name: "unhealthy"}}, }) fakeDocker.SetFakeRunningContainers([]*FakeContainer{ @@ -833,9 +834,9 @@ func TestSyncPodsUnhealthy(t *testing.T) { func TestSyncPodsDoesNothing(t *testing.T) { dm, fakeDocker := newTestDockerManager() - container := api.Container{Name: "bar"} - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + container := v1.Container{Name: "bar"} + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ container, }, }) @@ -856,11 +857,11 @@ func TestSyncPodsDoesNothing(t *testing.T) { func TestSyncPodWithRestartPolicy(t *testing.T) { dm, fakeDocker := newTestDockerManager() - containers := []api.Container{ + containers := []v1.Container{ {Name: "succeeded"}, {Name: "failed"}, } - pod := makePod("foo", &api.PodSpec{ + pod := makePod("foo", &v1.PodSpec{ Containers: containers, }) dockerContainers := []*FakeContainer{ @@ -886,13 +887,13 @@ func TestSyncPodWithRestartPolicy(t *testing.T) { }} tests := []struct { - policy api.RestartPolicy + policy v1.RestartPolicy calls []string created []string stopped []string }{ { - api.RestartPolicyAlways, + v1.RestartPolicyAlways, []string{ // Restart both containers. "create", "start", "inspect_container", "create", "start", "inspect_container", @@ -901,7 +902,7 @@ func TestSyncPodWithRestartPolicy(t *testing.T) { []string{}, }, { - api.RestartPolicyOnFailure, + v1.RestartPolicyOnFailure, []string{ // Restart the failed container. "create", "start", "inspect_container", @@ -910,7 +911,7 @@ func TestSyncPodWithRestartPolicy(t *testing.T) { []string{}, }, { - api.RestartPolicyNever, + v1.RestartPolicyNever, []string{ // Check the pod infra container. "inspect_container", "inspect_container", @@ -943,11 +944,11 @@ func TestSyncPodBackoff(t *testing.T) { startTime := fakeClock.Now() dm, fakeDocker := newTestDockerManager() - containers := []api.Container{ + containers := []v1.Container{ {Name: "good"}, {Name: "bad"}, } - pod := makePod("podfoo", &api.PodSpec{ + pod := makePod("podfoo", &v1.PodSpec{ Containers: containers, }) @@ -1027,14 +1028,14 @@ func TestSyncPodBackoff(t *testing.T) { func TestGetRestartCount(t *testing.T) { dm, fakeDocker := newTestDockerManager() containerName := "bar" - pod := *makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := *makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ {Name: containerName}, }, RestartPolicy: "Always", }) - pod.Status = api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + pod.Status = v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ { Name: containerName, RestartCount: 3, @@ -1043,7 +1044,7 @@ func TestGetRestartCount(t *testing.T) { } // Helper function for verifying the restart count. - verifyRestartCount := func(pod *api.Pod, expectedCount int) { + verifyRestartCount := func(pod *v1.Pod, expectedCount int) { runSyncPod(t, dm, fakeDocker, pod, nil, false) status, err := dm.GetPodStatus(pod.UID, pod.Name, pod.Namespace) if err != nil { @@ -1059,7 +1060,7 @@ func TestGetRestartCount(t *testing.T) { } } - killOneContainer := func(pod *api.Pod) { + killOneContainer := func(pod *v1.Pod) { status, err := dm.GetPodStatus(pod.UID, pod.Name, pod.Namespace) if err != nil { t.Fatalf("unexpected error %v", err) @@ -1108,13 +1109,13 @@ func TestGetRestartCount(t *testing.T) { func TestGetTerminationMessagePath(t *testing.T) { dm, fakeDocker := newTestDockerManager() - containers := []api.Container{ + containers := []v1.Container{ { Name: "bar", TerminationMessagePath: "/dev/somepath", }, } - pod := makePod("foo", &api.PodSpec{ + pod := makePod("foo", &v1.PodSpec{ Containers: containers, }) @@ -1140,13 +1141,13 @@ func TestSyncPodWithPodInfraCreatesContainerCallsHandler(t *testing.T) { fakeHTTPClient := &fakeHTTP{} dm, fakeDocker := newTestDockerManagerWithHTTPClient(fakeHTTPClient) - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ { Name: "bar", - Lifecycle: &api.Lifecycle{ - PostStart: &api.Handler{ - HTTPGet: &api.HTTPGetAction{ + Lifecycle: &v1.Lifecycle{ + PostStart: &v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Host: "foo", Port: intstr.FromInt(8080), Path: "bar", @@ -1183,12 +1184,12 @@ func TestSyncPodEventHandlerFails(t *testing.T) { fakeHTTPClient := &fakeHTTP{err: fmt.Errorf("test error")} dm, fakeDocker := newTestDockerManagerWithHTTPClient(fakeHTTPClient) - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar", - Lifecycle: &api.Lifecycle{ - PostStart: &api.Handler{ - HTTPGet: &api.HTTPGetAction{ + Lifecycle: &v1.Lifecycle{ + PostStart: &v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Host: "does.no.exist", Port: intstr.FromInt(8080), Path: "bar", @@ -1256,12 +1257,12 @@ func TestPortForwardNoSuchContainer(t *testing.T) { func TestSyncPodWithTerminationLog(t *testing.T) { dm, fakeDocker := newTestDockerManager() - container := api.Container{ + container := v1.Container{ Name: "bar", TerminationMessagePath: "/dev/somepath", } - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ container, }, }) @@ -1298,13 +1299,11 @@ func TestSyncPodWithTerminationLog(t *testing.T) { func TestSyncPodWithHostNetwork(t *testing.T) { dm, fakeDocker := newTestDockerManager() - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar"}, }, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, + HostNetwork: true, }) runSyncPod(t, dm, fakeDocker, pod, nil, false) @@ -1342,20 +1341,20 @@ func TestVerifyNonRoot(t *testing.T) { var nonRootUid int64 = 1 tests := map[string]struct { - container *api.Container + container *v1.Container inspectImage *dockertypes.ImageInspect expectedError string }{ // success cases "non-root runAsUser": { - container: &api.Container{ - SecurityContext: &api.SecurityContext{ + container: &v1.Container{ + SecurityContext: &v1.SecurityContext{ RunAsUser: &nonRootUid, }, }, }, "numeric non-root image user": { - container: &api.Container{}, + container: &v1.Container{}, inspectImage: &dockertypes.ImageInspect{ Config: &dockercontainer.Config{ User: "1", @@ -1363,7 +1362,7 @@ func TestVerifyNonRoot(t *testing.T) { }, }, "numeric non-root image user with gid": { - container: &api.Container{}, + container: &v1.Container{}, inspectImage: &dockertypes.ImageInspect{ Config: &dockercontainer.Config{ User: "1:2", @@ -1373,15 +1372,15 @@ func TestVerifyNonRoot(t *testing.T) { // failure cases "root runAsUser": { - container: &api.Container{ - SecurityContext: &api.SecurityContext{ + container: &v1.Container{ + SecurityContext: &v1.SecurityContext{ RunAsUser: &rootUid, }, }, expectedError: "container's runAsUser breaks non-root policy", }, "non-numeric image user": { - container: &api.Container{}, + container: &v1.Container{}, inspectImage: &dockertypes.ImageInspect{ Config: &dockercontainer.Config{ User: "foo", @@ -1390,7 +1389,7 @@ func TestVerifyNonRoot(t *testing.T) { expectedError: "non-numeric user", }, "numeric root image user": { - container: &api.Container{}, + container: &v1.Container{}, inspectImage: &dockertypes.ImageInspect{ Config: &dockercontainer.Config{ User: "0", @@ -1399,7 +1398,7 @@ func TestVerifyNonRoot(t *testing.T) { expectedError: "container has no runAsUser and image will run as root", }, "numeric root image user with gid": { - container: &api.Container{}, + container: &v1.Container{}, inspectImage: &dockertypes.ImageInspect{ Config: &dockercontainer.Config{ User: "0:1", @@ -1408,12 +1407,12 @@ func TestVerifyNonRoot(t *testing.T) { expectedError: "container has no runAsUser and image will run as root", }, "nil image in inspect": { - container: &api.Container{}, + container: &v1.Container{}, inspectImage: nil, expectedError: "unable to inspect image", }, "nil config in image inspect": { - container: &api.Container{}, + container: &v1.Container{}, inspectImage: &dockertypes.ImageInspect{}, expectedError: "unable to inspect image", }, @@ -1471,7 +1470,7 @@ func TestGetUserFromImageUser(t *testing.T) { func TestGetPidMode(t *testing.T) { // test false - pod := &api.Pod{} + pod := &v1.Pod{} pidMode := getPidMode(pod) if pidMode != "" { @@ -1479,8 +1478,8 @@ func TestGetPidMode(t *testing.T) { } // test true - pod.Spec.SecurityContext = &api.PodSecurityContext{} - pod.Spec.SecurityContext.HostPID = true + pod.Spec.SecurityContext = &v1.PodSecurityContext{} + pod.Spec.HostPID = true pidMode = getPidMode(pod) if pidMode != "host" { t.Errorf("expected host pid mode for pod but got %v", pidMode) @@ -1489,7 +1488,7 @@ func TestGetPidMode(t *testing.T) { func TestGetIPCMode(t *testing.T) { // test false - pod := &api.Pod{} + pod := &v1.Pod{} ipcMode := getIPCMode(pod) if ipcMode != "" { @@ -1497,8 +1496,8 @@ func TestGetIPCMode(t *testing.T) { } // test true - pod.Spec.SecurityContext = &api.PodSecurityContext{} - pod.Spec.SecurityContext.HostIPC = true + pod.Spec.SecurityContext = &v1.PodSecurityContext{} + pod.Spec.HostIPC = true ipcMode = getIPCMode(pod) if ipcMode != "host" { t.Errorf("expected host ipc mode for pod but got %v", ipcMode) @@ -1511,13 +1510,13 @@ func TestSyncPodWithPullPolicy(t *testing.T) { puller.HasImages = []string{"foo/existing_one:v1", "foo/want:latest"} dm.podInfraContainerImage = "foo/infra_image:v1" - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ - {Name: "bar", Image: "foo/pull_always_image:v1", ImagePullPolicy: api.PullAlways}, - {Name: "bar2", Image: "foo/pull_if_not_present_image:v1", ImagePullPolicy: api.PullIfNotPresent}, - {Name: "bar3", Image: "foo/existing_one:v1", ImagePullPolicy: api.PullIfNotPresent}, - {Name: "bar4", Image: "foo/want:latest", ImagePullPolicy: api.PullIfNotPresent}, - {Name: "bar5", Image: "foo/pull_never_image:v1", ImagePullPolicy: api.PullNever}, + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ + {Name: "bar", Image: "foo/pull_always_image:v1", ImagePullPolicy: v1.PullAlways}, + {Name: "bar2", Image: "foo/pull_if_not_present_image:v1", ImagePullPolicy: v1.PullIfNotPresent}, + {Name: "bar3", Image: "foo/existing_one:v1", ImagePullPolicy: v1.PullIfNotPresent}, + {Name: "bar4", Image: "foo/want:latest", ImagePullPolicy: v1.PullIfNotPresent}, + {Name: "bar5", Image: "foo/pull_never_image:v1", ImagePullPolicy: v1.PullNever}, }, }) @@ -1555,25 +1554,25 @@ func TestSyncPodWithPullPolicy(t *testing.T) { func TestSyncPodWithFailure(t *testing.T) { pod := makePod("foo", nil) tests := map[string]struct { - container api.Container + container v1.Container dockerError map[string]error pullerError []error expected []*kubecontainer.SyncResult }{ "PullImageFailure": { - api.Container{Name: "bar", Image: "foo/real_image:v1", ImagePullPolicy: api.PullAlways}, + v1.Container{Name: "bar", Image: "foo/real_image:v1", ImagePullPolicy: v1.PullAlways}, map[string]error{}, []error{fmt.Errorf("can't pull image")}, []*kubecontainer.SyncResult{{kubecontainer.StartContainer, "bar", images.ErrImagePull, "can't pull image"}}, }, "CreateContainerFailure": { - api.Container{Name: "bar", Image: "foo/already_present:v2"}, + v1.Container{Name: "bar", Image: "foo/already_present:v2"}, map[string]error{"create": fmt.Errorf("can't create container")}, []error{}, []*kubecontainer.SyncResult{{kubecontainer.StartContainer, "bar", kubecontainer.ErrRunContainer, "can't create container"}}, }, "StartContainerFailure": { - api.Container{Name: "bar", Image: "foo/already_present:v2"}, + v1.Container{Name: "bar", Image: "foo/already_present:v2"}, map[string]error{"start": fmt.Errorf("can't start container")}, []error{}, []*kubecontainer.SyncResult{{kubecontainer.StartContainer, "bar", kubecontainer.ErrRunContainer, "can't start container"}}, @@ -1592,7 +1591,7 @@ func TestSyncPodWithFailure(t *testing.T) { }}) fakeDocker.InjectErrors(test.dockerError) puller.ErrorsToInject = test.pullerError - pod.Spec.Containers = []api.Container{test.container} + pod.Spec.Containers = []v1.Container{test.container} result := runSyncPod(t, dm, fakeDocker, pod, nil, true) verifySyncResults(t, test.expected, result) } @@ -1658,9 +1657,9 @@ func TestSecurityOptsOperator(t *testing.T) { func TestGetSecurityOpts(t *testing.T) { const containerName = "bar" - pod := func(annotations map[string]string) *api.Pod { - p := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := func(annotations map[string]string) *v1.Pod { + p := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ {Name: containerName}, }, }) @@ -1670,7 +1669,7 @@ func TestGetSecurityOpts(t *testing.T) { tests := []struct { msg string - pod *api.Pod + pod *v1.Pod expectedOpts []string }{{ msg: "No security annotations", @@ -1679,7 +1678,7 @@ func TestGetSecurityOpts(t *testing.T) { }, { msg: "Seccomp default", pod: pod(map[string]string{ - api.SeccompContainerAnnotationKeyPrefix + containerName: "docker/default", + v1.SeccompContainerAnnotationKeyPrefix + containerName: "docker/default", }), expectedOpts: nil, }, { @@ -1697,8 +1696,8 @@ func TestGetSecurityOpts(t *testing.T) { }, { msg: "AppArmor and seccomp profile", pod: pod(map[string]string{ - api.SeccompContainerAnnotationKeyPrefix + containerName: "docker/default", - apparmor.ContainerAnnotationKeyPrefix + containerName: apparmor.ProfileNamePrefix + "foo", + v1.SeccompContainerAnnotationKeyPrefix + containerName: "docker/default", + apparmor.ContainerAnnotationKeyPrefix + containerName: apparmor.ProfileNamePrefix + "foo", }), expectedOpts: []string{"apparmor=foo"}, }} @@ -1722,8 +1721,8 @@ func TestSeccompIsUnconfinedByDefaultWithDockerV110(t *testing.T) { recorder := record.NewFakeRecorder(20) dm.recorder = recorder - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar"}, }, }) @@ -1752,19 +1751,19 @@ func TestSeccompIsUnconfinedByDefaultWithDockerV110(t *testing.T) { assert.Contains(t, newContainer.HostConfig.SecurityOpt, "seccomp:unconfined", "Pods with Docker versions >= 1.10 must not have seccomp disabled by default") cid := utilstrings.ShortenString(fakeDocker.Created[1], 12) - assert.NoError(t, expectEvent(recorder, api.EventTypeNormal, events.CreatedContainer, + assert.NoError(t, expectEvent(recorder, v1.EventTypeNormal, events.CreatedContainer, fmt.Sprintf("Created container with docker id %s; Security:[seccomp=unconfined]", cid))) } func TestUnconfinedSeccompProfileWithDockerV110(t *testing.T) { dm, fakeDocker := newTestDockerManagerWithVersion("1.10.1", "1.22") - pod := makePod("foo4", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo4", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar4"}, }, }) pod.Annotations = map[string]string{ - api.SeccompPodAnnotationKey: "unconfined", + v1.SeccompPodAnnotationKey: "unconfined", } runSyncPod(t, dm, fakeDocker, pod, nil, false) @@ -1793,13 +1792,13 @@ func TestUnconfinedSeccompProfileWithDockerV110(t *testing.T) { func TestDefaultSeccompProfileWithDockerV110(t *testing.T) { dm, fakeDocker := newTestDockerManagerWithVersion("1.10.1", "1.22") - pod := makePod("foo1", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo1", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar1"}, }, }) pod.Annotations = map[string]string{ - api.SeccompPodAnnotationKey: "docker/default", + v1.SeccompPodAnnotationKey: "docker/default", } runSyncPod(t, dm, fakeDocker, pod, nil, false) @@ -1828,14 +1827,14 @@ func TestDefaultSeccompProfileWithDockerV110(t *testing.T) { func TestSeccompContainerAnnotationTrumpsPod(t *testing.T) { dm, fakeDocker := newTestDockerManagerWithVersion("1.10.1", "1.22") - pod := makePod("foo2", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo2", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar2"}, }, }) pod.Annotations = map[string]string{ - api.SeccompPodAnnotationKey: "unconfined", - api.SeccompContainerAnnotationKeyPrefix + "bar2": "docker/default", + v1.SeccompPodAnnotationKey: "unconfined", + v1.SeccompContainerAnnotationKeyPrefix + "bar2": "docker/default", } runSyncPod(t, dm, fakeDocker, pod, nil, false) @@ -1871,21 +1870,21 @@ func TestSeccompLocalhostProfileIsLoaded(t *testing.T) { }{ { annotations: map[string]string{ - api.SeccompPodAnnotationKey: "localhost/test", + v1.SeccompPodAnnotationKey: "localhost/test", }, expectedSecOpt: `seccomp={"foo":"bar"}`, expectedSecMsg: "seccomp=test(md5:21aeae45053385adebd25311f9dd9cb1)", }, { annotations: map[string]string{ - api.SeccompPodAnnotationKey: "localhost/sub/subtest", + v1.SeccompPodAnnotationKey: "localhost/sub/subtest", }, expectedSecOpt: `seccomp={"abc":"def"}`, expectedSecMsg: "seccomp=sub/subtest(md5:07c9bcb4db631f7ca191d6e0bca49f76)", }, { annotations: map[string]string{ - api.SeccompPodAnnotationKey: "localhost/not-existing", + v1.SeccompPodAnnotationKey: "localhost/not-existing", }, expectedError: "cannot load seccomp profile", }, @@ -1900,8 +1899,8 @@ func TestSeccompLocalhostProfileIsLoaded(t *testing.T) { _, filename, _, _ := goruntime.Caller(0) dm.seccompProfileRoot = path.Join(path.Dir(filename), "fixtures", "seccomp") - pod := makePod("foo2", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo2", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar2"}, }, }) @@ -1935,7 +1934,7 @@ func TestSeccompLocalhostProfileIsLoaded(t *testing.T) { assert.Contains(t, newContainer.HostConfig.SecurityOpt, test.expectedSecOpt, "The compacted seccomp json profile should be loaded.") cid := utilstrings.ShortenString(fakeDocker.Created[1], 12) - assert.NoError(t, expectEvent(recorder, api.EventTypeNormal, events.CreatedContainer, + assert.NoError(t, expectEvent(recorder, v1.EventTypeNormal, events.CreatedContainer, fmt.Sprintf("Created container with docker id %s; Security:[%s]", cid, test.expectedSecMsg)), "testcase %d", i) } @@ -1943,8 +1942,8 @@ func TestSeccompLocalhostProfileIsLoaded(t *testing.T) { func TestSecurityOptsAreNilWithDockerV19(t *testing.T) { dm, fakeDocker := newTestDockerManagerWithVersion("1.9.1", "1.21") - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar"}, }, }) @@ -2011,8 +2010,8 @@ func TestCreateAppArmorContanier(t *testing.T) { recorder := record.NewFakeRecorder(20) dm.recorder = recorder - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", @@ -2020,8 +2019,8 @@ func TestCreateAppArmorContanier(t *testing.T) { apparmor.ContainerAnnotationKeyPrefix + "test": apparmor.ProfileNamePrefix + "test-profile", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Name: "test"}, }, }, @@ -2053,7 +2052,7 @@ func TestCreateAppArmorContanier(t *testing.T) { assert.Contains(t, securityOpts, "apparmor=test-profile", "Container should have apparmor security opt") cid := utilstrings.ShortenString(fakeDocker.Created[1], 12) - assert.NoError(t, expectEvent(recorder, api.EventTypeNormal, events.CreatedContainer, + assert.NoError(t, expectEvent(recorder, v1.EventTypeNormal, events.CreatedContainer, fmt.Sprintf("Created container with docker id %s; Security:[seccomp=unconfined apparmor=test-profile]", cid))) } @@ -2154,8 +2153,8 @@ func TestGetPodStatusNoSuchContainer(t *testing.T) { infraContainerID = "9876" ) dm, fakeDocker := newTestDockerManager() - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{{Name: "nosuchcontainer"}}, + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{{Name: "nosuchcontainer"}}, }) fakeDocker.SetFakeContainers([]*FakeContainer{ @@ -2191,8 +2190,8 @@ func TestGetPodStatusNoSuchContainer(t *testing.T) { func TestPruneInitContainers(t *testing.T) { dm, fake := newTestDockerManager() - pod := makePod("", &api.PodSpec{ - InitContainers: []api.Container{ + pod := makePod("", &v1.PodSpec{ + InitContainers: []v1.Container{ {Name: "init1"}, {Name: "init2"}, }, @@ -2223,7 +2222,7 @@ func TestPruneInitContainers(t *testing.T) { func TestGetPodStatusFromNetworkPlugin(t *testing.T) { cases := []struct { - pod *api.Pod + pod *v1.Pod fakePodIP string containerID string infraContainerID string @@ -2232,14 +2231,14 @@ func TestGetPodStatusFromNetworkPlugin(t *testing.T) { expectUnknown bool }{ { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "container"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Name: "container"}}, }, }, fakePodIP: "10.10.10.10", @@ -2250,14 +2249,14 @@ func TestGetPodStatusFromNetworkPlugin(t *testing.T) { expectUnknown: false, }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "container"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Name: "container"}}, }, }, fakePodIP: "", @@ -2335,8 +2334,8 @@ func TestSyncPodGetsPodIPFromNetworkPlugin(t *testing.T) { fnp := mock_network.NewMockNetworkPlugin(ctrl) dm.networkPlugin = fnp - pod := makePod("foo", &api.PodSpec{ - Containers: []api.Container{ + pod := makePod("foo", &v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar"}, }, }) @@ -2387,12 +2386,12 @@ func TestContainerAndPodFromLabels(t *testing.T) { } } -func makePod(name string, spec *api.PodSpec) *api.Pod { +func makePod(name string, spec *v1.PodSpec) *v1.Pod { if spec == nil { - spec = &api.PodSpec{Containers: []api.Container{{Name: "foo"}, {Name: "bar"}}} + spec = &v1.PodSpec{Containers: []v1.Container{{Name: "foo"}, {Name: "bar"}}} } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: name, Namespace: "new", diff --git a/pkg/kubelet/dockertools/docker_manager_unsupported.go b/pkg/kubelet/dockertools/docker_manager_unsupported.go index 8182784a161..be8e48f24d7 100644 --- a/pkg/kubelet/dockertools/docker_manager_unsupported.go +++ b/pkg/kubelet/dockertools/docker_manager_unsupported.go @@ -19,7 +19,7 @@ limitations under the License. package dockertools import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" dockertypes "github.com/docker/engine-api/types" ) @@ -37,6 +37,6 @@ func containerProvidesPodIP(name *KubeletContainerName) bool { } // Returns nil as both Seccomp and AppArmor security options are not valid on Windows -func (dm *DockerManager) getSecurityOpts(pod *api.Pod, ctrName string) ([]dockerOpt, error) { +func (dm *DockerManager) getSecurityOpts(pod *v1.Pod, ctrName string) ([]dockerOpt, error) { return nil, nil } diff --git a/pkg/kubelet/dockertools/docker_manager_windows.go b/pkg/kubelet/dockertools/docker_manager_windows.go index cb32cc7aa72..5e1842302af 100644 --- a/pkg/kubelet/dockertools/docker_manager_windows.go +++ b/pkg/kubelet/dockertools/docker_manager_windows.go @@ -21,7 +21,7 @@ package dockertools import ( "os" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" dockertypes "github.com/docker/engine-api/types" ) @@ -53,6 +53,6 @@ func containerProvidesPodIP(name *KubeletContainerName) bool { } // Returns nil as both Seccomp and AppArmor security options are not valid on Windows -func (dm *DockerManager) getSecurityOpts(pod *api.Pod, ctrName string) ([]dockerOpt, error) { +func (dm *DockerManager) getSecurityOpts(pod *v1.Pod, ctrName string) ([]dockerOpt, error) { return nil, nil } diff --git a/pkg/kubelet/dockertools/docker_test.go b/pkg/kubelet/dockertools/docker_test.go index 0a0ba852738..7af13252226 100644 --- a/pkg/kubelet/dockertools/docker_test.go +++ b/pkg/kubelet/dockertools/docker_test.go @@ -33,7 +33,7 @@ import ( dockernat "github.com/docker/go-connections/nat" cadvisorapi "github.com/google/cadvisor/info/v1" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/credentialprovider" @@ -118,7 +118,7 @@ func TestGetContainerID(t *testing.T) { } func verifyPackUnpack(t *testing.T, podNamespace, podUID, podName, containerName string) { - container := &api.Container{Name: containerName} + container := &v1.Container{Name: containerName} hasher := adler32.New() hashutil.DeepHashObject(hasher, *container) computedHash := uint64(hasher.Sum32()) @@ -142,7 +142,7 @@ func TestContainerNaming(t *testing.T) { // No Container name verifyPackUnpack(t, "other", podUID, "name", "") - container := &api.Container{Name: "container"} + container := &v1.Container{Name: "container"} podName := "foo" podNamespace := "test" name := fmt.Sprintf("k8s_%s_%s_%s_%s_42", container.Name, podName, podNamespace, podUID) @@ -416,7 +416,7 @@ func TestPullWithNoSecrets(t *testing.T) { keyring: fakeKeyring, } - err := dp.Pull(test.imageName, []api.Secret{}) + err := dp.Pull(test.imageName, []v1.Secret{}) if err != nil { t.Errorf("unexpected non-nil err: %s", err) continue @@ -459,7 +459,7 @@ func TestPullWithJSONError(t *testing.T) { client: fakeClient, keyring: fakeKeyring, } - err := puller.Pull(test.imageName, []api.Secret{}) + err := puller.Pull(test.imageName, []v1.Secret{}) if err == nil || !strings.Contains(err.Error(), test.expectedError) { t.Errorf("%s: expect error %s, got : %s", i, test.expectedError, err) continue @@ -483,19 +483,19 @@ func TestPullWithSecrets(t *testing.T) { tests := map[string]struct { imageName string - passedSecrets []api.Secret + passedSecrets []v1.Secret builtInDockerConfig credentialprovider.DockerConfig expectedPulls []string }{ "no matching secrets": { "ubuntu", - []api.Secret{}, + []v1.Secret{}, credentialprovider.DockerConfig(map[string]credentialprovider.DockerConfigEntry{}), []string{"ubuntu using {}"}, }, "default keyring secrets": { "ubuntu", - []api.Secret{}, + []v1.Secret{}, credentialprovider.DockerConfig(map[string]credentialprovider.DockerConfigEntry{ "index.docker.io/v1/": {Username: "built-in", Password: "password", Email: "email", Provider: nil}, }), @@ -503,7 +503,7 @@ func TestPullWithSecrets(t *testing.T) { }, "default keyring secrets unused": { "ubuntu", - []api.Secret{}, + []v1.Secret{}, credentialprovider.DockerConfig(map[string]credentialprovider.DockerConfigEntry{ "extraneous": {Username: "built-in", Password: "password", Email: "email", Provider: nil}, }), @@ -511,7 +511,7 @@ func TestPullWithSecrets(t *testing.T) { }, "builtin keyring secrets, but use passed": { "ubuntu", - []api.Secret{{Type: api.SecretTypeDockercfg, Data: map[string][]byte{api.DockerConfigKey: dockercfgContent}}}, + []v1.Secret{{Type: v1.SecretTypeDockercfg, Data: map[string][]byte{v1.DockerConfigKey: dockercfgContent}}}, credentialprovider.DockerConfig(map[string]credentialprovider.DockerConfigEntry{ "index.docker.io/v1/": {Username: "built-in", Password: "password", Email: "email", Provider: nil}, }), @@ -519,7 +519,7 @@ func TestPullWithSecrets(t *testing.T) { }, "builtin keyring secrets, but use passed with new docker config": { "ubuntu", - []api.Secret{{Type: api.SecretTypeDockerConfigJson, Data: map[string][]byte{api.DockerConfigJsonKey: dockerConfigJsonContent}}}, + []v1.Secret{{Type: v1.SecretTypeDockerConfigJson, Data: map[string][]byte{v1.DockerConfigJsonKey: dockerConfigJsonContent}}}, credentialprovider.DockerConfig(map[string]credentialprovider.DockerConfigEntry{ "index.docker.io/v1/": {Username: "built-in", Password: "password", Email: "email", Provider: nil}, }), @@ -564,7 +564,7 @@ func TestDockerKeyringLookupFails(t *testing.T) { keyring: fakeKeyring, } - err := dp.Pull("host/repository/image:version", []api.Secret{}) + err := dp.Pull("host/repository/image:version", []v1.Secret{}) if err == nil { t.Errorf("unexpected non-error") } @@ -908,7 +908,7 @@ func TestFindContainersByPod(t *testing.T) { } func TestMakePortsAndBindings(t *testing.T) { - portMapping := func(container, host int, protocol api.Protocol, ip string) kubecontainer.PortMapping { + portMapping := func(container, host int, protocol v1.Protocol, ip string) kubecontainer.PortMapping { return kubecontainer.PortMapping{ ContainerPort: container, HostPort: host, diff --git a/pkg/kubelet/dockertools/fake_docker_client.go b/pkg/kubelet/dockertools/fake_docker_client.go index 0c538c50e74..e26b4c2a084 100644 --- a/pkg/kubelet/dockertools/fake_docker_client.go +++ b/pkg/kubelet/dockertools/fake_docker_client.go @@ -30,7 +30,7 @@ import ( dockercontainer "github.com/docker/engine-api/types/container" "k8s.io/kubernetes/pkg/util/clock" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) type calledDetail struct { @@ -580,7 +580,7 @@ type FakeDockerPuller struct { } // Pull records the image pull attempt, and optionally injects an error. -func (f *FakeDockerPuller) Pull(image string, secrets []api.Secret) (err error) { +func (f *FakeDockerPuller) Pull(image string, secrets []v1.Secret) (err error) { f.Lock() defer f.Unlock() f.ImagesPulled = append(f.ImagesPulled, image) diff --git a/pkg/kubelet/dockertools/fake_manager.go b/pkg/kubelet/dockertools/fake_manager.go index 1bb5cf59b82..a9538e6abef 100644 --- a/pkg/kubelet/dockertools/fake_manager.go +++ b/pkg/kubelet/dockertools/fake_manager.go @@ -18,7 +18,7 @@ package dockertools import ( cadvisorapi "github.com/google/cadvisor/info/v1" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/network" @@ -65,14 +65,14 @@ func NewFakeDockerManager( } type fakePodGetter struct { - pods map[types.UID]*api.Pod + pods map[types.UID]*v1.Pod } func newFakePodGetter() *fakePodGetter { - return &fakePodGetter{make(map[types.UID]*api.Pod)} + return &fakePodGetter{make(map[types.UID]*v1.Pod)} } -func (f *fakePodGetter) GetPodByUID(uid types.UID) (*api.Pod, bool) { +func (f *fakePodGetter) GetPodByUID(uid types.UID) (*v1.Pod, bool) { pod, found := f.pods[uid] return pod, found } diff --git a/pkg/kubelet/dockertools/kube_docker_client.go b/pkg/kubelet/dockertools/kube_docker_client.go index e6d140cf748..6322148d45f 100644 --- a/pkg/kubelet/dockertools/kube_docker_client.go +++ b/pkg/kubelet/dockertools/kube_docker_client.go @@ -161,7 +161,7 @@ func (d *kubeDockerClient) StartContainer(id string) error { return err } -// Stopping an already stopped container will not cause an error in engine-api. +// Stopping an already stopped container will not cause an error in engine-v1. func (d *kubeDockerClient) StopContainer(id string, timeout int) error { ctx, cancel := d.getCustomTimeoutContext(time.Duration(timeout) * time.Second) defer cancel() diff --git a/pkg/kubelet/dockertools/labels.go b/pkg/kubelet/dockertools/labels.go index 5935e68e0b1..be8cfd9777c 100644 --- a/pkg/kubelet/dockertools/labels.go +++ b/pkg/kubelet/dockertools/labels.go @@ -22,6 +22,7 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/custommetrics" "k8s.io/kubernetes/pkg/kubelet/types" @@ -62,11 +63,11 @@ type labelledContainerInfo struct { Hash string RestartCount int TerminationMessagePath string - PreStopHandler *api.Handler - Ports []api.ContainerPort + PreStopHandler *v1.Handler + Ports []v1.ContainerPort } -func newLabels(container *api.Container, pod *api.Pod, restartCount int, enableCustomMetrics bool) map[string]string { +func newLabels(container *v1.Container, pod *v1.Pod, restartCount int, enableCustomMetrics bool) map[string]string { labels := map[string]string{} labels[types.KubernetesPodNameLabel] = pod.Name labels[types.KubernetesPodNamespaceLabel] = pod.Namespace @@ -128,13 +129,13 @@ func getContainerInfoFromLabel(labels map[string]string) *labelledContainerInfo if containerInfo.PodTerminationGracePeriod, err = getInt64PointerFromLabel(labels, kubernetesPodTerminationGracePeriodLabel); err != nil { logError(containerInfo, kubernetesPodTerminationGracePeriodLabel, err) } - preStopHandler := &api.Handler{} + preStopHandler := &v1.Handler{} if found, err := getJsonObjectFromLabel(labels, kubernetesContainerPreStopHandlerLabel, preStopHandler); err != nil { logError(containerInfo, kubernetesContainerPreStopHandlerLabel, err) } else if found { containerInfo.PreStopHandler = preStopHandler } - containerPorts := []api.ContainerPort{} + containerPorts := []v1.ContainerPort{} if found, err := getJsonObjectFromLabel(labels, kubernetesContainerPortsLabel, &containerPorts); err != nil { logError(containerInfo, kubernetesContainerPortsLabel, err) } else if found { @@ -192,7 +193,7 @@ func getJsonObjectFromLabel(labels map[string]string, label string, value interf return false, nil } -// The label kubernetesPodLabel is added a long time ago (#7421), it serialized the whole api.Pod to a docker label. +// The label kubernetesPodLabel is added a long time ago (#7421), it serialized the whole v1.Pod to a docker label. // We want to remove this label because it serialized too much useless information. However kubelet may still work // with old containers which only have this label for a long time until we completely deprecate the old label. // Before that to ensure correctness we have to supply information with the old labels when newly added labels @@ -200,15 +201,15 @@ func getJsonObjectFromLabel(labels map[string]string, label string, value interf // TODO(random-liu): Remove this function when we can completely remove label kubernetesPodLabel, probably after // dropping support for v1.1. func supplyContainerInfoWithOldLabel(labels map[string]string, containerInfo *labelledContainerInfo) { - // Get api.Pod from old label - var pod *api.Pod + // Get v1.Pod from old label + var pod *v1.Pod data, found := labels[kubernetesPodLabel] if !found { // Don't report any error here, because it's normal that a container has no pod label, especially // when we gradually deprecate the old label return } - pod = &api.Pod{} + pod = &v1.Pod{} if err := runtime.DecodeInto(api.Codecs.UniversalDecoder(), []byte(data), pod); err != nil { // If the pod label can't be parsed, we should report an error logError(containerInfo, kubernetesPodLabel, err) @@ -221,8 +222,8 @@ func supplyContainerInfoWithOldLabel(labels map[string]string, containerInfo *la containerInfo.PodTerminationGracePeriod = pod.Spec.TerminationGracePeriodSeconds } - // Get api.Container from api.Pod - var container *api.Container + // Get v1.Container from v1.Pod + var container *v1.Container for i := range pod.Spec.Containers { if pod.Spec.Containers[i].Name == containerInfo.Name { container = &pod.Spec.Containers[i] diff --git a/pkg/kubelet/dockertools/labels_test.go b/pkg/kubelet/dockertools/labels_test.go index 7b763ed5383..86b97958642 100644 --- a/pkg/kubelet/dockertools/labels_test.go +++ b/pkg/kubelet/dockertools/labels_test.go @@ -21,8 +21,8 @@ import ( "strconv" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/testapi" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/util/format" "k8s.io/kubernetes/pkg/runtime" @@ -33,52 +33,52 @@ func TestLabels(t *testing.T) { restartCount := 5 deletionGracePeriod := int64(10) terminationGracePeriod := int64(10) - lifecycle := &api.Lifecycle{ + lifecycle := &v1.Lifecycle{ // Left PostStart as nil - PreStop: &api.Handler{ - Exec: &api.ExecAction{ + PreStop: &v1.Handler{ + Exec: &v1.ExecAction{ Command: []string{"action1", "action2"}, }, - HTTPGet: &api.HTTPGetAction{ + HTTPGet: &v1.HTTPGetAction{ Path: "path", Host: "host", Port: intstr.FromInt(8080), Scheme: "scheme", }, - TCPSocket: &api.TCPSocketAction{ + TCPSocket: &v1.TCPSocketAction{ Port: intstr.FromString("80"), }, }, } - containerPorts := []api.ContainerPort{ + containerPorts := []v1.ContainerPort{ { Name: "http", HostPort: 80, ContainerPort: 8080, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, { Name: "https", HostPort: 443, ContainerPort: 6443, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, } - container := &api.Container{ + container := &v1.Container{ Name: "test_container", Ports: containerPorts, TerminationMessagePath: "/somepath", Lifecycle: lifecycle, } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "test_pod", Namespace: "test_pod_namespace", UID: "test_pod_uid", DeletionGracePeriodSeconds: &deletionGracePeriod, }, - Spec: api.PodSpec{ - Containers: []api.Container{*container}, + Spec: v1.PodSpec{ + Containers: []v1.Container{*container}, TerminationGracePeriodSeconds: &terminationGracePeriod, }, } diff --git a/pkg/kubelet/envvars/BUILD b/pkg/kubelet/envvars/BUILD index c2065aa7ee8..0dedc5156f6 100644 --- a/pkg/kubelet/envvars/BUILD +++ b/pkg/kubelet/envvars/BUILD @@ -17,7 +17,7 @@ go_library( "envvars.go", ], tags = ["automanaged"], - deps = ["//pkg/api:go_default_library"], + deps = ["//pkg/api/v1:go_default_library"], ) go_test( @@ -25,7 +25,7 @@ go_test( srcs = ["envvars_test.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/envvars:go_default_library", ], ) diff --git a/pkg/kubelet/envvars/envvars.go b/pkg/kubelet/envvars/envvars.go index 883acf61943..713480e162c 100644 --- a/pkg/kubelet/envvars/envvars.go +++ b/pkg/kubelet/envvars/envvars.go @@ -21,36 +21,36 @@ import ( "strconv" "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) // FromServices builds environment variables that a container is started with, // which tell the container where to find the services it may need, which are // provided as an argument. -func FromServices(services []*api.Service) []api.EnvVar { - var result []api.EnvVar +func FromServices(services []*v1.Service) []v1.EnvVar { + var result []v1.EnvVar for i := range services { service := services[i] // ignore services where ClusterIP is "None" or empty // the services passed to this method should be pre-filtered // only services that have the cluster IP set should be included here - if !api.IsServiceIPSet(service) { + if !v1.IsServiceIPSet(service) { continue } // Host name := makeEnvVariableName(service.Name) + "_SERVICE_HOST" - result = append(result, api.EnvVar{Name: name, Value: service.Spec.ClusterIP}) + result = append(result, v1.EnvVar{Name: name, Value: service.Spec.ClusterIP}) // First port - give it the backwards-compatible name name = makeEnvVariableName(service.Name) + "_SERVICE_PORT" - result = append(result, api.EnvVar{Name: name, Value: strconv.Itoa(int(service.Spec.Ports[0].Port))}) + result = append(result, v1.EnvVar{Name: name, Value: strconv.Itoa(int(service.Spec.Ports[0].Port))}) // All named ports (only the first may be unnamed, checked in validation) for i := range service.Spec.Ports { sp := &service.Spec.Ports[i] if sp.Name != "" { pn := name + "_" + makeEnvVariableName(sp.Name) - result = append(result, api.EnvVar{Name: pn, Value: strconv.Itoa(int(sp.Port))}) + result = append(result, v1.EnvVar{Name: pn, Value: strconv.Itoa(int(sp.Port))}) } } // Docker-compatible vars. @@ -67,25 +67,25 @@ func makeEnvVariableName(str string) string { return strings.ToUpper(strings.Replace(str, "-", "_", -1)) } -func makeLinkVariables(service *api.Service) []api.EnvVar { +func makeLinkVariables(service *v1.Service) []v1.EnvVar { prefix := makeEnvVariableName(service.Name) - all := []api.EnvVar{} + all := []v1.EnvVar{} for i := range service.Spec.Ports { sp := &service.Spec.Ports[i] - protocol := string(api.ProtocolTCP) + protocol := string(v1.ProtocolTCP) if sp.Protocol != "" { protocol = string(sp.Protocol) } if i == 0 { // Docker special-cases the first port. - all = append(all, api.EnvVar{ + all = append(all, v1.EnvVar{ Name: prefix + "_PORT", Value: fmt.Sprintf("%s://%s:%d", strings.ToLower(protocol), service.Spec.ClusterIP, sp.Port), }) } portPrefix := fmt.Sprintf("%s_PORT_%d_%s", prefix, sp.Port, strings.ToUpper(protocol)) - all = append(all, []api.EnvVar{ + all = append(all, []v1.EnvVar{ { Name: portPrefix, Value: fmt.Sprintf("%s://%s:%d", strings.ToLower(protocol), service.Spec.ClusterIP, sp.Port), diff --git a/pkg/kubelet/envvars/envvars_test.go b/pkg/kubelet/envvars/envvars_test.go index 9a3876b6f88..1a580136097 100644 --- a/pkg/kubelet/envvars/envvars_test.go +++ b/pkg/kubelet/envvars/envvars_test.go @@ -20,67 +20,67 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/envvars" ) func TestFromServices(t *testing.T) { - sl := []*api.Service{ + sl := []*v1.Service{ { - ObjectMeta: api.ObjectMeta{Name: "foo-bar"}, - Spec: api.ServiceSpec{ + ObjectMeta: v1.ObjectMeta{Name: "foo-bar"}, + Spec: v1.ServiceSpec{ Selector: map[string]string{"bar": "baz"}, ClusterIP: "1.2.3.4", - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ {Port: 8080, Protocol: "TCP"}, }, }, }, { - ObjectMeta: api.ObjectMeta{Name: "abc-123"}, - Spec: api.ServiceSpec{ + ObjectMeta: v1.ObjectMeta{Name: "abc-123"}, + Spec: v1.ServiceSpec{ Selector: map[string]string{"bar": "baz"}, ClusterIP: "5.6.7.8", - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ {Name: "u-d-p", Port: 8081, Protocol: "UDP"}, {Name: "t-c-p", Port: 8081, Protocol: "TCP"}, }, }, }, { - ObjectMeta: api.ObjectMeta{Name: "q-u-u-x"}, - Spec: api.ServiceSpec{ + ObjectMeta: v1.ObjectMeta{Name: "q-u-u-x"}, + Spec: v1.ServiceSpec{ Selector: map[string]string{"bar": "baz"}, ClusterIP: "9.8.7.6", - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ {Port: 8082, Protocol: "TCP"}, {Name: "8083", Port: 8083, Protocol: "TCP"}, }, }, }, { - ObjectMeta: api.ObjectMeta{Name: "svrc-clusterip-none"}, - Spec: api.ServiceSpec{ + ObjectMeta: v1.ObjectMeta{Name: "svrc-clusterip-none"}, + Spec: v1.ServiceSpec{ Selector: map[string]string{"bar": "baz"}, ClusterIP: "None", - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ {Port: 8082, Protocol: "TCP"}, }, }, }, { - ObjectMeta: api.ObjectMeta{Name: "svrc-clusterip-empty"}, - Spec: api.ServiceSpec{ + ObjectMeta: v1.ObjectMeta{Name: "svrc-clusterip-empty"}, + Spec: v1.ServiceSpec{ Selector: map[string]string{"bar": "baz"}, ClusterIP: "", - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ {Port: 8082, Protocol: "TCP"}, }, }, }, } vars := envvars.FromServices(sl) - expected := []api.EnvVar{ + expected := []v1.EnvVar{ {Name: "FOO_BAR_SERVICE_HOST", Value: "1.2.3.4"}, {Name: "FOO_BAR_SERVICE_PORT", Value: "8080"}, {Name: "FOO_BAR_PORT", Value: "tcp://1.2.3.4:8080"}, diff --git a/pkg/kubelet/eviction/BUILD b/pkg/kubelet/eviction/BUILD index 0d3bf2663bf..6fb42fae28f 100644 --- a/pkg/kubelet/eviction/BUILD +++ b/pkg/kubelet/eviction/BUILD @@ -23,6 +23,7 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/kubelet/api/v1alpha1/stats:go_default_library", "//pkg/kubelet/cm:go_default_library", @@ -50,6 +51,7 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/kubelet/api/v1alpha1/stats:go_default_library", "//pkg/kubelet/lifecycle:go_default_library", diff --git a/pkg/kubelet/eviction/eviction_manager.go b/pkg/kubelet/eviction/eviction_manager.go index 0e98156493b..58bf12cb1bb 100644 --- a/pkg/kubelet/eviction/eviction_manager.go +++ b/pkg/kubelet/eviction/eviction_manager.go @@ -23,8 +23,8 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/kubelet/cm" "k8s.io/kubernetes/pkg/kubelet/lifecycle" @@ -48,11 +48,11 @@ type managerImpl struct { // protects access to internal state sync.RWMutex // node conditions are the set of conditions present - nodeConditions []api.NodeConditionType + nodeConditions []v1.NodeConditionType // captures when a node condition was last observed based on a threshold being met nodeConditionsLastObservedAt nodeConditionsObservedAt // nodeRef is a reference to the node - nodeRef *api.ObjectReference + nodeRef *v1.ObjectReference // used to record events about the node recorder record.EventRecorder // used to measure usage stats on system @@ -62,9 +62,9 @@ type managerImpl struct { // records the set of thresholds that have been met (including graceperiod) but not yet resolved thresholdsMet []Threshold // resourceToRankFunc maps a resource to ranking function for that resource. - resourceToRankFunc map[api.ResourceName]rankFunc + resourceToRankFunc map[v1.ResourceName]rankFunc // resourceToNodeReclaimFuncs maps a resource to an ordered list of functions that know how to reclaim that resource. - resourceToNodeReclaimFuncs map[api.ResourceName]nodeReclaimFuncs + resourceToNodeReclaimFuncs map[v1.ResourceName]nodeReclaimFuncs // last observations from synchronize lastObservations signalObservations // notifiersInitialized indicates if the threshold notifiers have been initialized (i.e. synchronize() has been called once) @@ -81,7 +81,7 @@ func NewManager( killPodFunc KillPodFunc, imageGC ImageGC, recorder record.EventRecorder, - nodeRef *api.ObjectReference, + nodeRef *v1.ObjectReference, clock clock.Clock) (Manager, lifecycle.PodAdmitHandler, error) { manager := &managerImpl{ clock: clock, @@ -106,7 +106,7 @@ func (m *managerImpl) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAd } // the node has memory pressure, admit if not best-effort - if hasNodeCondition(m.nodeConditions, api.NodeMemoryPressure) { + if hasNodeCondition(m.nodeConditions, v1.NodeMemoryPressure) { notBestEffort := qos.BestEffort != qos.GetPodQOS(attrs.Pod) if notBestEffort { return lifecycle.PodAdmitResult{Admit: true} @@ -133,14 +133,14 @@ func (m *managerImpl) Start(diskInfoProvider DiskInfoProvider, podFunc ActivePod func (m *managerImpl) IsUnderMemoryPressure() bool { m.RLock() defer m.RUnlock() - return hasNodeCondition(m.nodeConditions, api.NodeMemoryPressure) + return hasNodeCondition(m.nodeConditions, v1.NodeMemoryPressure) } // IsUnderDiskPressure returns true if the node is under disk pressure. func (m *managerImpl) IsUnderDiskPressure() bool { m.RLock() defer m.RUnlock() - return hasNodeCondition(m.nodeConditions, api.NodeDiskPressure) + return hasNodeCondition(m.nodeConditions, v1.NodeDiskPressure) } func startMemoryThresholdNotifier(thresholds []Threshold, observations signalObservations, hard bool, handler thresholdNotifierHandlerFunc) error { @@ -278,7 +278,7 @@ func (m *managerImpl) synchronize(diskInfoProvider DiskInfoProvider, podFunc Act softEviction := isSoftEvictionThresholds(thresholds, resourceToReclaim) // record an event about the resources we are now attempting to reclaim via eviction - m.recorder.Eventf(m.nodeRef, api.EventTypeWarning, "EvictionThresholdMet", "Attempting to reclaim %s", resourceToReclaim) + m.recorder.Eventf(m.nodeRef, v1.EventTypeWarning, "EvictionThresholdMet", "Attempting to reclaim %s", resourceToReclaim) // check if there are node-level resources we can reclaim to reduce pressure before evicting end-user pods. if m.reclaimNodeLevelResources(resourceToReclaim, observations) { @@ -310,13 +310,13 @@ func (m *managerImpl) synchronize(diskInfoProvider DiskInfoProvider, podFunc Act // we kill at most a single pod during each eviction interval for i := range activePods { pod := activePods[i] - status := api.PodStatus{ - Phase: api.PodFailed, + status := v1.PodStatus{ + Phase: v1.PodFailed, Message: fmt.Sprintf(message, resourceToReclaim), Reason: reason, } // record that we are evicting the pod - m.recorder.Eventf(pod, api.EventTypeWarning, reason, fmt.Sprintf(message, resourceToReclaim)) + m.recorder.Eventf(pod, v1.EventTypeWarning, reason, fmt.Sprintf(message, resourceToReclaim)) gracePeriodOverride := int64(0) if softEviction { gracePeriodOverride = m.config.MaxPodGracePeriodSeconds @@ -335,7 +335,7 @@ func (m *managerImpl) synchronize(diskInfoProvider DiskInfoProvider, podFunc Act } // reclaimNodeLevelResources attempts to reclaim node level resources. returns true if thresholds were satisfied and no pod eviction is required. -func (m *managerImpl) reclaimNodeLevelResources(resourceToReclaim api.ResourceName, observations signalObservations) bool { +func (m *managerImpl) reclaimNodeLevelResources(resourceToReclaim v1.ResourceName, observations signalObservations) bool { nodeReclaimFuncs := m.resourceToNodeReclaimFuncs[resourceToReclaim] for _, nodeReclaimFunc := range nodeReclaimFuncs { // attempt to reclaim the pressured resource. diff --git a/pkg/kubelet/eviction/eviction_manager_test.go b/pkg/kubelet/eviction/eviction_manager_test.go index eb40c82c043..a54baaa318f 100644 --- a/pkg/kubelet/eviction/eviction_manager_test.go +++ b/pkg/kubelet/eviction/eviction_manager_test.go @@ -20,8 +20,8 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" statsapi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" "k8s.io/kubernetes/pkg/kubelet/lifecycle" @@ -31,13 +31,13 @@ import ( // mockPodKiller is used to testing which pod is killed type mockPodKiller struct { - pod *api.Pod - status api.PodStatus + pod *v1.Pod + status v1.PodStatus gracePeriodOverride *int64 } // killPodNow records the pod that was killed -func (m *mockPodKiller) killPodNow(pod *api.Pod, status api.PodStatus, gracePeriodOverride *int64) error { +func (m *mockPodKiller) killPodNow(pod *v1.Pod, status v1.PodStatus, gracePeriodOverride *int64) error { m.pod = pod m.status = status m.gracePeriodOverride = gracePeriodOverride @@ -67,23 +67,23 @@ func (m *mockImageGC) DeleteUnusedImages() (int64, error) { return m.freed, m.err } -func makePodWithMemoryStats(name string, requests api.ResourceList, limits api.ResourceList, memoryWorkingSet string) (*api.Pod, statsapi.PodStats) { - pod := newPod(name, []api.Container{ +func makePodWithMemoryStats(name string, requests v1.ResourceList, limits v1.ResourceList, memoryWorkingSet string) (*v1.Pod, statsapi.PodStats) { + pod := newPod(name, []v1.Container{ newContainer(name, requests, limits), }, nil) podStats := newPodMemoryStats(pod, resource.MustParse(memoryWorkingSet)) return pod, podStats } -func makePodWithDiskStats(name string, requests api.ResourceList, limits api.ResourceList, rootFsUsed, logsUsed, perLocalVolumeUsed string) (*api.Pod, statsapi.PodStats) { - pod := newPod(name, []api.Container{ +func makePodWithDiskStats(name string, requests v1.ResourceList, limits v1.ResourceList, rootFsUsed, logsUsed, perLocalVolumeUsed string) (*v1.Pod, statsapi.PodStats) { + pod := newPod(name, []v1.Container{ newContainer(name, requests, limits), }, nil) podStats := newPodDiskStats(pod, parseQuantity(rootFsUsed), parseQuantity(logsUsed), parseQuantity(perLocalVolumeUsed)) return pod, podStats } -func makeMemoryStats(nodeAvailableBytes string, podStats map[*api.Pod]statsapi.PodStats) *statsapi.Summary { +func makeMemoryStats(nodeAvailableBytes string, podStats map[*v1.Pod]statsapi.PodStats) *statsapi.Summary { val := resource.MustParse(nodeAvailableBytes) availableBytes := uint64(val.Value()) WorkingSetBytes := uint64(val.Value()) @@ -102,7 +102,7 @@ func makeMemoryStats(nodeAvailableBytes string, podStats map[*api.Pod]statsapi.P return result } -func makeDiskStats(rootFsAvailableBytes, imageFsAvailableBytes string, podStats map[*api.Pod]statsapi.PodStats) *statsapi.Summary { +func makeDiskStats(rootFsAvailableBytes, imageFsAvailableBytes string, podStats map[*v1.Pod]statsapi.PodStats) *statsapi.Summary { rootFsVal := resource.MustParse(rootFsAvailableBytes) rootFsBytes := uint64(rootFsVal.Value()) rootFsCapacityBytes := uint64(rootFsVal.Value() * 2) @@ -132,8 +132,8 @@ func makeDiskStats(rootFsAvailableBytes, imageFsAvailableBytes string, podStats type podToMake struct { name string - requests api.ResourceList - limits api.ResourceList + requests v1.ResourceList + limits v1.ResourceList memoryWorkingSet string rootFsUsed string logsFsUsed string @@ -155,15 +155,15 @@ func TestMemoryPressure(t *testing.T) { {name: "best-effort-low", requests: newResourceList("", ""), limits: newResourceList("", ""), memoryWorkingSet: "300Mi"}, {name: "best-effort-high", requests: newResourceList("", ""), limits: newResourceList("", ""), memoryWorkingSet: "500Mi"}, } - pods := []*api.Pod{} - podStats := map[*api.Pod]statsapi.PodStats{} + pods := []*v1.Pod{} + podStats := map[*v1.Pod]statsapi.PodStats{} for _, podToMake := range podsToMake { pod, podStat := podMaker(podToMake.name, podToMake.requests, podToMake.limits, podToMake.memoryWorkingSet) pods = append(pods, pod) podStats[pod] = podStat } podToEvict := pods[5] - activePodsFunc := func() []*api.Pod { + activePodsFunc := func() []*v1.Pod { return pods } @@ -171,7 +171,7 @@ func TestMemoryPressure(t *testing.T) { podKiller := &mockPodKiller{} diskInfoProvider := &mockDiskInfoProvider{dedicatedImageFs: false} imageGC := &mockImageGC{freed: int64(0), err: nil} - nodeRef := &api.ObjectReference{Kind: "Node", Name: "test", UID: types.UID("test"), Namespace: ""} + nodeRef := &v1.ObjectReference{Kind: "Node", Name: "test", UID: types.UID("test"), Namespace: ""} config := Config{ MaxPodGracePeriodSeconds: 5, @@ -221,7 +221,7 @@ func TestMemoryPressure(t *testing.T) { // try to admit our pods (they should succeed) expected := []bool{true, true} - for i, pod := range []*api.Pod{bestEffortPodToAdmit, burstablePodToAdmit} { + for i, pod := range []*v1.Pod{bestEffortPodToAdmit, burstablePodToAdmit} { if result := manager.Admit(&lifecycle.PodAdmitAttributes{Pod: pod}); expected[i] != result.Admit { t.Errorf("Admit pod: %v, expected: %v, actual: %v", pod, expected[i], result.Admit) } @@ -298,7 +298,7 @@ func TestMemoryPressure(t *testing.T) { // the best-effort pod should not admit, burstable should expected = []bool{false, true} - for i, pod := range []*api.Pod{bestEffortPodToAdmit, burstablePodToAdmit} { + for i, pod := range []*v1.Pod{bestEffortPodToAdmit, burstablePodToAdmit} { if result := manager.Admit(&lifecycle.PodAdmitAttributes{Pod: pod}); expected[i] != result.Admit { t.Errorf("Admit pod: %v, expected: %v, actual: %v", pod, expected[i], result.Admit) } @@ -322,7 +322,7 @@ func TestMemoryPressure(t *testing.T) { // the best-effort pod should not admit, burstable should expected = []bool{false, true} - for i, pod := range []*api.Pod{bestEffortPodToAdmit, burstablePodToAdmit} { + for i, pod := range []*v1.Pod{bestEffortPodToAdmit, burstablePodToAdmit} { if result := manager.Admit(&lifecycle.PodAdmitAttributes{Pod: pod}); expected[i] != result.Admit { t.Errorf("Admit pod: %v, expected: %v, actual: %v", pod, expected[i], result.Admit) } @@ -346,7 +346,7 @@ func TestMemoryPressure(t *testing.T) { // all pods should admit now expected = []bool{true, true} - for i, pod := range []*api.Pod{bestEffortPodToAdmit, burstablePodToAdmit} { + for i, pod := range []*v1.Pod{bestEffortPodToAdmit, burstablePodToAdmit} { if result := manager.Admit(&lifecycle.PodAdmitAttributes{Pod: pod}); expected[i] != result.Admit { t.Errorf("Admit pod: %v, expected: %v, actual: %v", pod, expected[i], result.Admit) } @@ -372,15 +372,15 @@ func TestDiskPressureNodeFs(t *testing.T) { {name: "best-effort-low", requests: newResourceList("", ""), limits: newResourceList("", ""), perLocalVolumeUsed: "300Mi"}, {name: "best-effort-high", requests: newResourceList("", ""), limits: newResourceList("", ""), rootFsUsed: "500Mi"}, } - pods := []*api.Pod{} - podStats := map[*api.Pod]statsapi.PodStats{} + pods := []*v1.Pod{} + podStats := map[*v1.Pod]statsapi.PodStats{} for _, podToMake := range podsToMake { pod, podStat := podMaker(podToMake.name, podToMake.requests, podToMake.limits, podToMake.rootFsUsed, podToMake.logsFsUsed, podToMake.perLocalVolumeUsed) pods = append(pods, pod) podStats[pod] = podStat } podToEvict := pods[5] - activePodsFunc := func() []*api.Pod { + activePodsFunc := func() []*v1.Pod { return pods } @@ -388,7 +388,7 @@ func TestDiskPressureNodeFs(t *testing.T) { podKiller := &mockPodKiller{} diskInfoProvider := &mockDiskInfoProvider{dedicatedImageFs: false} imageGC := &mockImageGC{freed: int64(0), err: nil} - nodeRef := &api.ObjectReference{Kind: "Node", Name: "test", UID: types.UID("test"), Namespace: ""} + nodeRef := &v1.ObjectReference{Kind: "Node", Name: "test", UID: types.UID("test"), Namespace: ""} config := Config{ MaxPodGracePeriodSeconds: 5, @@ -569,15 +569,15 @@ func TestMinReclaim(t *testing.T) { {name: "best-effort-low", requests: newResourceList("", ""), limits: newResourceList("", ""), memoryWorkingSet: "300Mi"}, {name: "best-effort-high", requests: newResourceList("", ""), limits: newResourceList("", ""), memoryWorkingSet: "500Mi"}, } - pods := []*api.Pod{} - podStats := map[*api.Pod]statsapi.PodStats{} + pods := []*v1.Pod{} + podStats := map[*v1.Pod]statsapi.PodStats{} for _, podToMake := range podsToMake { pod, podStat := podMaker(podToMake.name, podToMake.requests, podToMake.limits, podToMake.memoryWorkingSet) pods = append(pods, pod) podStats[pod] = podStat } podToEvict := pods[5] - activePodsFunc := func() []*api.Pod { + activePodsFunc := func() []*v1.Pod { return pods } @@ -585,7 +585,7 @@ func TestMinReclaim(t *testing.T) { podKiller := &mockPodKiller{} diskInfoProvider := &mockDiskInfoProvider{dedicatedImageFs: false} imageGC := &mockImageGC{freed: int64(0), err: nil} - nodeRef := &api.ObjectReference{Kind: "Node", Name: "test", UID: types.UID("test"), Namespace: ""} + nodeRef := &v1.ObjectReference{Kind: "Node", Name: "test", UID: types.UID("test"), Namespace: ""} config := Config{ MaxPodGracePeriodSeconds: 5, @@ -707,15 +707,15 @@ func TestNodeReclaimFuncs(t *testing.T) { {name: "best-effort-low", requests: newResourceList("", ""), limits: newResourceList("", ""), rootFsUsed: "300Mi"}, {name: "best-effort-high", requests: newResourceList("", ""), limits: newResourceList("", ""), rootFsUsed: "500Mi"}, } - pods := []*api.Pod{} - podStats := map[*api.Pod]statsapi.PodStats{} + pods := []*v1.Pod{} + podStats := map[*v1.Pod]statsapi.PodStats{} for _, podToMake := range podsToMake { pod, podStat := podMaker(podToMake.name, podToMake.requests, podToMake.limits, podToMake.rootFsUsed, podToMake.logsFsUsed, podToMake.perLocalVolumeUsed) pods = append(pods, pod) podStats[pod] = podStat } podToEvict := pods[5] - activePodsFunc := func() []*api.Pod { + activePodsFunc := func() []*v1.Pod { return pods } @@ -724,7 +724,7 @@ func TestNodeReclaimFuncs(t *testing.T) { diskInfoProvider := &mockDiskInfoProvider{dedicatedImageFs: false} imageGcFree := resource.MustParse("700Mi") imageGC := &mockImageGC{freed: imageGcFree.Value(), err: nil} - nodeRef := &api.ObjectReference{Kind: "Node", Name: "test", UID: types.UID("test"), Namespace: ""} + nodeRef := &v1.ObjectReference{Kind: "Node", Name: "test", UID: types.UID("test"), Namespace: ""} config := Config{ MaxPodGracePeriodSeconds: 5, @@ -866,14 +866,14 @@ func TestNodeReclaimFuncs(t *testing.T) { } func TestInodePressureNodeFsInodes(t *testing.T) { - podMaker := func(name string, requests api.ResourceList, limits api.ResourceList, rootInodes, logInodes, volumeInodes string) (*api.Pod, statsapi.PodStats) { - pod := newPod(name, []api.Container{ + podMaker := func(name string, requests v1.ResourceList, limits v1.ResourceList, rootInodes, logInodes, volumeInodes string) (*v1.Pod, statsapi.PodStats) { + pod := newPod(name, []v1.Container{ newContainer(name, requests, limits), }, nil) podStats := newPodInodeStats(pod, parseQuantity(rootInodes), parseQuantity(logInodes), parseQuantity(volumeInodes)) return pod, podStats } - summaryStatsMaker := func(rootFsInodesFree, rootFsInodes string, podStats map[*api.Pod]statsapi.PodStats) *statsapi.Summary { + summaryStatsMaker := func(rootFsInodesFree, rootFsInodes string, podStats map[*v1.Pod]statsapi.PodStats) *statsapi.Summary { rootFsInodesFreeVal := resource.MustParse(rootFsInodesFree) internalRootFsInodesFree := uint64(rootFsInodesFreeVal.Value()) rootFsInodesVal := resource.MustParse(rootFsInodes) @@ -900,15 +900,15 @@ func TestInodePressureNodeFsInodes(t *testing.T) { {name: "best-effort-low", requests: newResourceList("", ""), limits: newResourceList("", ""), rootFsInodesUsed: "300Mi"}, {name: "best-effort-high", requests: newResourceList("", ""), limits: newResourceList("", ""), rootFsInodesUsed: "800Mi"}, } - pods := []*api.Pod{} - podStats := map[*api.Pod]statsapi.PodStats{} + pods := []*v1.Pod{} + podStats := map[*v1.Pod]statsapi.PodStats{} for _, podToMake := range podsToMake { pod, podStat := podMaker(podToMake.name, podToMake.requests, podToMake.limits, podToMake.rootFsInodesUsed, podToMake.logsFsInodesUsed, podToMake.perLocalVolumeInodesUsed) pods = append(pods, pod) podStats[pod] = podStat } podToEvict := pods[5] - activePodsFunc := func() []*api.Pod { + activePodsFunc := func() []*v1.Pod { return pods } @@ -916,7 +916,7 @@ func TestInodePressureNodeFsInodes(t *testing.T) { podKiller := &mockPodKiller{} diskInfoProvider := &mockDiskInfoProvider{dedicatedImageFs: false} imageGC := &mockImageGC{freed: int64(0), err: nil} - nodeRef := &api.ObjectReference{Kind: "Node", Name: "test", UID: types.UID("test"), Namespace: ""} + nodeRef := &v1.ObjectReference{Kind: "Node", Name: "test", UID: types.UID("test"), Namespace: ""} config := Config{ MaxPodGracePeriodSeconds: 5, diff --git a/pkg/kubelet/eviction/helpers.go b/pkg/kubelet/eviction/helpers.go index b6bb414241a..b98a3ef29c4 100644 --- a/pkg/kubelet/eviction/helpers.go +++ b/pkg/kubelet/eviction/helpers.go @@ -26,6 +26,7 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" statsapi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" "k8s.io/kubernetes/pkg/kubelet/qos" "k8s.io/kubernetes/pkg/kubelet/server/stats" @@ -40,45 +41,45 @@ const ( // the message associated with the reason. message = "The node was low on resource: %v." // disk, in bytes. internal to this module, used to account for local disk usage. - resourceDisk api.ResourceName = "disk" + resourceDisk v1.ResourceName = "disk" // inodes, number. internal to this module, used to account for local disk inode consumption. - resourceInodes api.ResourceName = "inodes" + resourceInodes v1.ResourceName = "inodes" // imagefs, in bytes. internal to this module, used to account for local image filesystem usage. - resourceImageFs api.ResourceName = "imagefs" + resourceImageFs v1.ResourceName = "imagefs" // imagefs inodes, number. internal to this module, used to account for local image filesystem inodes. - resourceImageFsInodes api.ResourceName = "imagefsInodes" + resourceImageFsInodes v1.ResourceName = "imagefsInodes" // nodefs, in bytes. internal to this module, used to account for local node root filesystem usage. - resourceNodeFs api.ResourceName = "nodefs" + resourceNodeFs v1.ResourceName = "nodefs" // nodefs inodes, number. internal to this module, used to account for local node root filesystem inodes. - resourceNodeFsInodes api.ResourceName = "nodefsInodes" + resourceNodeFsInodes v1.ResourceName = "nodefsInodes" ) var ( // signalToNodeCondition maps a signal to the node condition to report if threshold is met. - signalToNodeCondition map[Signal]api.NodeConditionType + signalToNodeCondition map[Signal]v1.NodeConditionType // signalToResource maps a Signal to its associated Resource. - signalToResource map[Signal]api.ResourceName + signalToResource map[Signal]v1.ResourceName // resourceToSignal maps a Resource to its associated Signal - resourceToSignal map[api.ResourceName]Signal + resourceToSignal map[v1.ResourceName]Signal ) func init() { // map eviction signals to node conditions - signalToNodeCondition = map[Signal]api.NodeConditionType{} - signalToNodeCondition[SignalMemoryAvailable] = api.NodeMemoryPressure - signalToNodeCondition[SignalImageFsAvailable] = api.NodeDiskPressure - signalToNodeCondition[SignalNodeFsAvailable] = api.NodeDiskPressure - signalToNodeCondition[SignalImageFsInodesFree] = api.NodeDiskPressure - signalToNodeCondition[SignalNodeFsInodesFree] = api.NodeDiskPressure + signalToNodeCondition = map[Signal]v1.NodeConditionType{} + signalToNodeCondition[SignalMemoryAvailable] = v1.NodeMemoryPressure + signalToNodeCondition[SignalImageFsAvailable] = v1.NodeDiskPressure + signalToNodeCondition[SignalNodeFsAvailable] = v1.NodeDiskPressure + signalToNodeCondition[SignalImageFsInodesFree] = v1.NodeDiskPressure + signalToNodeCondition[SignalNodeFsInodesFree] = v1.NodeDiskPressure // map signals to resources (and vice-versa) - signalToResource = map[Signal]api.ResourceName{} - signalToResource[SignalMemoryAvailable] = api.ResourceMemory + signalToResource = map[Signal]v1.ResourceName{} + signalToResource[SignalMemoryAvailable] = v1.ResourceMemory signalToResource[SignalImageFsAvailable] = resourceImageFs signalToResource[SignalImageFsInodesFree] = resourceImageFsInodes signalToResource[SignalNodeFsAvailable] = resourceNodeFs signalToResource[SignalNodeFsInodesFree] = resourceNodeFsInodes - resourceToSignal = map[api.ResourceName]Signal{} + resourceToSignal = map[v1.ResourceName]Signal{} for key, value := range signalToResource { resourceToSignal[value] = key } @@ -337,11 +338,11 @@ func memoryUsage(memStats *statsapi.MemoryStats) *resource.Quantity { // localVolumeNames returns the set of volumes for the pod that are local // TODO: sumamry API should report what volumes consume local storage rather than hard-code here. -func localVolumeNames(pod *api.Pod) []string { +func localVolumeNames(pod *v1.Pod) []string { result := []string{} for _, volume := range pod.Spec.Volumes { if volume.HostPath != nil || - (volume.EmptyDir != nil && volume.EmptyDir.Medium != api.StorageMediumMemory) || + (volume.EmptyDir != nil && volume.EmptyDir.Medium != v1.StorageMediumMemory) || volume.ConfigMap != nil || volume.GitRepo != nil { result = append(result, volume.Name) @@ -351,7 +352,7 @@ func localVolumeNames(pod *api.Pod) []string { } // podDiskUsage aggregates pod disk usage and inode consumption for the specified stats to measure. -func podDiskUsage(podStats statsapi.PodStats, pod *api.Pod, statsToMeasure []fsStatsType) (api.ResourceList, error) { +func podDiskUsage(podStats statsapi.PodStats, pod *v1.Pod, statsToMeasure []fsStatsType) (v1.ResourceList, error) { disk := resource.Quantity{Format: resource.BinarySI} inodes := resource.Quantity{Format: resource.BinarySI} for _, container := range podStats.Containers { @@ -376,14 +377,14 @@ func podDiskUsage(podStats statsapi.PodStats, pod *api.Pod, statsToMeasure []fsS } } } - return api.ResourceList{ + return v1.ResourceList{ resourceDisk: disk, resourceInodes: inodes, }, nil } // podMemoryUsage aggregates pod memory usage. -func podMemoryUsage(podStats statsapi.PodStats) (api.ResourceList, error) { +func podMemoryUsage(podStats statsapi.PodStats) (v1.ResourceList, error) { disk := resource.Quantity{Format: resource.BinarySI} memory := resource.Quantity{Format: resource.BinarySI} for _, container := range podStats.Containers { @@ -394,9 +395,9 @@ func podMemoryUsage(podStats statsapi.PodStats) (api.ResourceList, error) { // memory usage (if known) memory.Add(*memoryUsage(container.Memory)) } - return api.ResourceList{ - api.ResourceMemory: memory, - resourceDisk: disk, + return v1.ResourceList{ + v1.ResourceMemory: memory, + resourceDisk: disk, }, nil } @@ -419,7 +420,7 @@ func cachedStatsFunc(podStats []statsapi.PodStats) statsFunc { for i := range podStats { uid2PodStats[podStats[i].PodRef.UID] = podStats[i] } - return func(pod *api.Pod) (statsapi.PodStats, bool) { + return func(pod *v1.Pod) (statsapi.PodStats, bool) { stats, found := uid2PodStats[string(pod.UID)] return stats, found } @@ -431,16 +432,16 @@ func cachedStatsFunc(podStats []statsapi.PodStats) statsFunc { // 0 if p1 == p2 // +1 if p1 > p2 // -type cmpFunc func(p1, p2 *api.Pod) int +type cmpFunc func(p1, p2 *v1.Pod) int // multiSorter implements the Sort interface, sorting changes within. type multiSorter struct { - pods []*api.Pod + pods []*v1.Pod cmp []cmpFunc } // Sort sorts the argument slice according to the less functions passed to OrderedBy. -func (ms *multiSorter) Sort(pods []*api.Pod) { +func (ms *multiSorter) Sort(pods []*v1.Pod) { ms.pods = pods sort.Sort(ms) } @@ -484,7 +485,7 @@ func (ms *multiSorter) Less(i, j int) bool { } // qosComparator compares pods by QoS (BestEffort < Burstable < Guaranteed) -func qosComparator(p1, p2 *api.Pod) int { +func qosComparator(p1, p2 *v1.Pod) int { qosP1 := qos.GetPodQOS(p1) qosP2 := qos.GetPodQOS(p2) // its a tie @@ -508,7 +509,7 @@ func qosComparator(p1, p2 *api.Pod) int { // memory compares pods by largest consumer of memory relative to request. func memory(stats statsFunc) cmpFunc { - return func(p1, p2 *api.Pod) int { + return func(p1, p2 *v1.Pod) int { p1Stats, found := stats(p1) // if we have no usage stats for p1, we want p2 first if !found { @@ -531,12 +532,12 @@ func memory(stats statsFunc) cmpFunc { } // adjust p1, p2 usage relative to the request (if any) - p1Memory := p1Usage[api.ResourceMemory] + p1Memory := p1Usage[v1.ResourceMemory] p1Spec := core.PodUsageFunc(p1) p1Request := p1Spec[api.ResourceRequestsMemory] p1Memory.Sub(p1Request) - p2Memory := p2Usage[api.ResourceMemory] + p2Memory := p2Usage[v1.ResourceMemory] p2Spec := core.PodUsageFunc(p2) p2Request := p2Spec[api.ResourceRequestsMemory] p2Memory.Sub(p2Request) @@ -547,8 +548,8 @@ func memory(stats statsFunc) cmpFunc { } // disk compares pods by largest consumer of disk relative to request for the specified disk resource. -func disk(stats statsFunc, fsStatsToMeasure []fsStatsType, diskResource api.ResourceName) cmpFunc { - return func(p1, p2 *api.Pod) int { +func disk(stats statsFunc, fsStatsToMeasure []fsStatsType, diskResource v1.ResourceName) cmpFunc { + return func(p1, p2 *v1.Pod) int { p1Stats, found := stats(p1) // if we have no usage stats for p1, we want p2 first if !found { @@ -580,26 +581,26 @@ func disk(stats statsFunc, fsStatsToMeasure []fsStatsType, diskResource api.Reso } // rankMemoryPressure orders the input pods for eviction in response to memory pressure. -func rankMemoryPressure(pods []*api.Pod, stats statsFunc) { +func rankMemoryPressure(pods []*v1.Pod, stats statsFunc) { orderedBy(qosComparator, memory(stats)).Sort(pods) } // rankDiskPressureFunc returns a rankFunc that measures the specified fs stats. -func rankDiskPressureFunc(fsStatsToMeasure []fsStatsType, diskResource api.ResourceName) rankFunc { - return func(pods []*api.Pod, stats statsFunc) { +func rankDiskPressureFunc(fsStatsToMeasure []fsStatsType, diskResource v1.ResourceName) rankFunc { + return func(pods []*v1.Pod, stats statsFunc) { orderedBy(qosComparator, disk(stats, fsStatsToMeasure, diskResource)).Sort(pods) } } -// byEvictionPriority implements sort.Interface for []api.ResourceName. -type byEvictionPriority []api.ResourceName +// byEvictionPriority implements sort.Interface for []v1.ResourceName. +type byEvictionPriority []v1.ResourceName func (a byEvictionPriority) Len() int { return len(a) } func (a byEvictionPriority) Swap(i, j int) { a[i], a[j] = a[j], a[i] } // Less ranks memory before all other resources. func (a byEvictionPriority) Less(i, j int) bool { - return a[i] == api.ResourceMemory + return a[i] == v1.ResourceMemory } // makeSignalObservations derives observations using the specified summary provider. @@ -740,8 +741,8 @@ func thresholdsMetGracePeriod(observedAt thresholdsObservedAt, now time.Time) [] } // nodeConditions returns the set of node conditions associated with a threshold -func nodeConditions(thresholds []Threshold) []api.NodeConditionType { - results := []api.NodeConditionType{} +func nodeConditions(thresholds []Threshold) []v1.NodeConditionType { + results := []v1.NodeConditionType{} for _, threshold := range thresholds { if nodeCondition, found := signalToNodeCondition[threshold.Signal]; found { if !hasNodeCondition(results, nodeCondition) { @@ -753,7 +754,7 @@ func nodeConditions(thresholds []Threshold) []api.NodeConditionType { } // nodeConditionsLastObservedAt merges the input with the previous observation to determine when a condition was most recently met. -func nodeConditionsLastObservedAt(nodeConditions []api.NodeConditionType, lastObservedAt nodeConditionsObservedAt, now time.Time) nodeConditionsObservedAt { +func nodeConditionsLastObservedAt(nodeConditions []v1.NodeConditionType, lastObservedAt nodeConditionsObservedAt, now time.Time) nodeConditionsObservedAt { results := nodeConditionsObservedAt{} // the input conditions were observed "now" for i := range nodeConditions { @@ -770,8 +771,8 @@ func nodeConditionsLastObservedAt(nodeConditions []api.NodeConditionType, lastOb } // nodeConditionsObservedSince returns the set of conditions that have been observed within the specified period -func nodeConditionsObservedSince(observedAt nodeConditionsObservedAt, period time.Duration, now time.Time) []api.NodeConditionType { - results := []api.NodeConditionType{} +func nodeConditionsObservedSince(observedAt nodeConditionsObservedAt, period time.Duration, now time.Time) []v1.NodeConditionType { + results := []v1.NodeConditionType{} for nodeCondition, at := range observedAt { duration := now.Sub(at) if duration < period { @@ -792,7 +793,7 @@ func hasFsStatsType(inputs []fsStatsType, item fsStatsType) bool { } // hasNodeCondition returns true if the node condition is in the input list -func hasNodeCondition(inputs []api.NodeConditionType, item api.NodeConditionType) bool { +func hasNodeCondition(inputs []v1.NodeConditionType, item v1.NodeConditionType) bool { for _, input := range inputs { if input == item { return true @@ -837,8 +838,8 @@ func compareThresholdValue(a ThresholdValue, b ThresholdValue) bool { } // getStarvedResources returns the set of resources that are starved based on thresholds met. -func getStarvedResources(thresholds []Threshold) []api.ResourceName { - results := []api.ResourceName{} +func getStarvedResources(thresholds []Threshold) []v1.ResourceName { + results := []v1.ResourceName{} for _, threshold := range thresholds { if starvedResource, found := signalToResource[threshold.Signal]; found { results = append(results, starvedResource) @@ -848,7 +849,7 @@ func getStarvedResources(thresholds []Threshold) []api.ResourceName { } // isSoftEviction returns true if the thresholds met for the starved resource are only soft thresholds -func isSoftEvictionThresholds(thresholds []Threshold, starvedResource api.ResourceName) bool { +func isSoftEvictionThresholds(thresholds []Threshold, starvedResource v1.ResourceName) bool { for _, threshold := range thresholds { if resourceToCheck := signalToResource[threshold.Signal]; resourceToCheck != starvedResource { continue @@ -866,9 +867,9 @@ func isHardEvictionThreshold(threshold Threshold) bool { } // buildResourceToRankFunc returns ranking functions associated with resources -func buildResourceToRankFunc(withImageFs bool) map[api.ResourceName]rankFunc { - resourceToRankFunc := map[api.ResourceName]rankFunc{ - api.ResourceMemory: rankMemoryPressure, +func buildResourceToRankFunc(withImageFs bool) map[v1.ResourceName]rankFunc { + resourceToRankFunc := map[v1.ResourceName]rankFunc{ + v1.ResourceMemory: rankMemoryPressure, } // usage of an imagefs is optional if withImageFs { @@ -890,13 +891,13 @@ func buildResourceToRankFunc(withImageFs bool) map[api.ResourceName]rankFunc { } // PodIsEvicted returns true if the reported pod status is due to an eviction. -func PodIsEvicted(podStatus api.PodStatus) bool { - return podStatus.Phase == api.PodFailed && podStatus.Reason == reason +func PodIsEvicted(podStatus v1.PodStatus) bool { + return podStatus.Phase == v1.PodFailed && podStatus.Reason == reason } // buildResourceToNodeReclaimFuncs returns reclaim functions associated with resources. -func buildResourceToNodeReclaimFuncs(imageGC ImageGC, withImageFs bool) map[api.ResourceName]nodeReclaimFuncs { - resourceToReclaimFunc := map[api.ResourceName]nodeReclaimFuncs{} +func buildResourceToNodeReclaimFuncs(imageGC ImageGC, withImageFs bool) map[v1.ResourceName]nodeReclaimFuncs { + resourceToReclaimFunc := map[v1.ResourceName]nodeReclaimFuncs{} // usage of an imagefs is optional if withImageFs { // with an imagefs, nodefs pressure should just delete logs diff --git a/pkg/kubelet/eviction/helpers_test.go b/pkg/kubelet/eviction/helpers_test.go index b53a5008baa..bff42bcc903 100644 --- a/pkg/kubelet/eviction/helpers_test.go +++ b/pkg/kubelet/eviction/helpers_test.go @@ -25,6 +25,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" statsapi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/types" @@ -397,20 +398,20 @@ func thresholdEqual(a Threshold, b Threshold) bool { // TestOrderedByQoS ensures we order BestEffort < Burstable < Guaranteed func TestOrderedByQoS(t *testing.T) { - bestEffort := newPod("best-effort", []api.Container{ + bestEffort := newPod("best-effort", []v1.Container{ newContainer("best-effort", newResourceList("", ""), newResourceList("", "")), }, nil) - burstable := newPod("burstable", []api.Container{ + burstable := newPod("burstable", []v1.Container{ newContainer("burstable", newResourceList("100m", "100Mi"), newResourceList("200m", "200Mi")), }, nil) - guaranteed := newPod("guaranteed", []api.Container{ + guaranteed := newPod("guaranteed", []v1.Container{ newContainer("guaranteed", newResourceList("200m", "200Mi"), newResourceList("200m", "200Mi")), }, nil) - pods := []*api.Pod{guaranteed, burstable, bestEffort} + pods := []*v1.Pod{guaranteed, burstable, bestEffort} orderedBy(qosComparator).Sort(pods) - expected := []*api.Pod{bestEffort, burstable, guaranteed} + expected := []*v1.Pod{bestEffort, burstable, guaranteed} for i := range expected { if pods[i] != expected[i] { t.Errorf("Expected pod: %s, but got: %s", expected[i].Name, pods[i].Name) @@ -427,51 +428,51 @@ func TestOrderedbyInodes(t *testing.T) { } // testOrderedByDisk ensures we order pods by greediest resource consumer -func testOrderedByResource(t *testing.T, orderedByResource api.ResourceName, - newPodStatsFunc func(pod *api.Pod, rootFsUsed, logsUsed, perLocalVolumeUsed resource.Quantity) statsapi.PodStats) { - pod1 := newPod("best-effort-high", []api.Container{ +func testOrderedByResource(t *testing.T, orderedByResource v1.ResourceName, + newPodStatsFunc func(pod *v1.Pod, rootFsUsed, logsUsed, perLocalVolumeUsed resource.Quantity) statsapi.PodStats) { + pod1 := newPod("best-effort-high", []v1.Container{ newContainer("best-effort-high", newResourceList("", ""), newResourceList("", "")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - pod2 := newPod("best-effort-low", []api.Container{ + pod2 := newPod("best-effort-low", []v1.Container{ newContainer("best-effort-low", newResourceList("", ""), newResourceList("", "")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - pod3 := newPod("burstable-high", []api.Container{ + pod3 := newPod("burstable-high", []v1.Container{ newContainer("burstable-high", newResourceList("100m", "100Mi"), newResourceList("200m", "1Gi")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - pod4 := newPod("burstable-low", []api.Container{ + pod4 := newPod("burstable-low", []v1.Container{ newContainer("burstable-low", newResourceList("100m", "100Mi"), newResourceList("200m", "1Gi")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - pod5 := newPod("guaranteed-high", []api.Container{ + pod5 := newPod("guaranteed-high", []v1.Container{ newContainer("guaranteed-high", newResourceList("100m", "1Gi"), newResourceList("100m", "1Gi")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - pod6 := newPod("guaranteed-low", []api.Container{ + pod6 := newPod("guaranteed-low", []v1.Container{ newContainer("guaranteed-low", newResourceList("100m", "1Gi"), newResourceList("100m", "1Gi")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - stats := map[*api.Pod]statsapi.PodStats{ + stats := map[*v1.Pod]statsapi.PodStats{ pod1: newPodStatsFunc(pod1, resource.MustParse("50Mi"), resource.MustParse("100Mi"), resource.MustParse("50Mi")), // 200Mi pod2: newPodStatsFunc(pod2, resource.MustParse("100Mi"), resource.MustParse("150Mi"), resource.MustParse("50Mi")), // 300Mi pod3: newPodStatsFunc(pod3, resource.MustParse("200Mi"), resource.MustParse("150Mi"), resource.MustParse("50Mi")), // 400Mi @@ -479,13 +480,13 @@ func testOrderedByResource(t *testing.T, orderedByResource api.ResourceName, pod5: newPodStatsFunc(pod5, resource.MustParse("400Mi"), resource.MustParse("100Mi"), resource.MustParse("50Mi")), // 550Mi pod6: newPodStatsFunc(pod6, resource.MustParse("500Mi"), resource.MustParse("100Mi"), resource.MustParse("50Mi")), // 650Mi } - statsFn := func(pod *api.Pod) (statsapi.PodStats, bool) { + statsFn := func(pod *v1.Pod) (statsapi.PodStats, bool) { result, found := stats[pod] return result, found } - pods := []*api.Pod{pod1, pod2, pod3, pod4, pod5, pod6} + pods := []*v1.Pod{pod1, pod2, pod3, pod4, pod5, pod6} orderedBy(disk(statsFn, []fsStatsType{fsStatsRoot, fsStatsLogs, fsStatsLocalVolumeSource}, orderedByResource)).Sort(pods) - expected := []*api.Pod{pod6, pod5, pod4, pod3, pod2, pod1} + expected := []*v1.Pod{pod6, pod5, pod4, pod3, pod2, pod1} for i := range expected { if pods[i] != expected[i] { t.Errorf("Expected pod[%d]: %s, but got: %s", i, expected[i].Name, pods[i].Name) @@ -502,51 +503,51 @@ func TestOrderedbyQoSInodes(t *testing.T) { } // testOrderedByQoSDisk ensures we order pods by qos and then greediest resource consumer -func testOrderedByQoSResource(t *testing.T, orderedByResource api.ResourceName, - newPodStatsFunc func(pod *api.Pod, rootFsUsed, logsUsed, perLocalVolumeUsed resource.Quantity) statsapi.PodStats) { - pod1 := newPod("best-effort-high", []api.Container{ +func testOrderedByQoSResource(t *testing.T, orderedByResource v1.ResourceName, + newPodStatsFunc func(pod *v1.Pod, rootFsUsed, logsUsed, perLocalVolumeUsed resource.Quantity) statsapi.PodStats) { + pod1 := newPod("best-effort-high", []v1.Container{ newContainer("best-effort-high", newResourceList("", ""), newResourceList("", "")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - pod2 := newPod("best-effort-low", []api.Container{ + pod2 := newPod("best-effort-low", []v1.Container{ newContainer("best-effort-low", newResourceList("", ""), newResourceList("", "")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - pod3 := newPod("burstable-high", []api.Container{ + pod3 := newPod("burstable-high", []v1.Container{ newContainer("burstable-high", newResourceList("100m", "100Mi"), newResourceList("200m", "1Gi")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - pod4 := newPod("burstable-low", []api.Container{ + pod4 := newPod("burstable-low", []v1.Container{ newContainer("burstable-low", newResourceList("100m", "100Mi"), newResourceList("200m", "1Gi")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - pod5 := newPod("guaranteed-high", []api.Container{ + pod5 := newPod("guaranteed-high", []v1.Container{ newContainer("guaranteed-high", newResourceList("100m", "1Gi"), newResourceList("100m", "1Gi")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - pod6 := newPod("guaranteed-low", []api.Container{ + pod6 := newPod("guaranteed-low", []v1.Container{ newContainer("guaranteed-low", newResourceList("100m", "1Gi"), newResourceList("100m", "1Gi")), - }, []api.Volume{ - newVolume("local-volume", api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + }, []v1.Volume{ + newVolume("local-volume", v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }), }) - stats := map[*api.Pod]statsapi.PodStats{ + stats := map[*v1.Pod]statsapi.PodStats{ pod1: newPodStatsFunc(pod1, resource.MustParse("50Mi"), resource.MustParse("100Mi"), resource.MustParse("50Mi")), // 200Mi pod2: newPodStatsFunc(pod2, resource.MustParse("100Mi"), resource.MustParse("150Mi"), resource.MustParse("50Mi")), // 300Mi pod3: newPodStatsFunc(pod3, resource.MustParse("200Mi"), resource.MustParse("150Mi"), resource.MustParse("50Mi")), // 400Mi @@ -554,13 +555,13 @@ func testOrderedByQoSResource(t *testing.T, orderedByResource api.ResourceName, pod5: newPodStatsFunc(pod5, resource.MustParse("400Mi"), resource.MustParse("100Mi"), resource.MustParse("50Mi")), // 550Mi pod6: newPodStatsFunc(pod6, resource.MustParse("500Mi"), resource.MustParse("100Mi"), resource.MustParse("50Mi")), // 650Mi } - statsFn := func(pod *api.Pod) (statsapi.PodStats, bool) { + statsFn := func(pod *v1.Pod) (statsapi.PodStats, bool) { result, found := stats[pod] return result, found } - pods := []*api.Pod{pod1, pod2, pod3, pod4, pod5, pod6} + pods := []*v1.Pod{pod1, pod2, pod3, pod4, pod5, pod6} orderedBy(qosComparator, disk(statsFn, []fsStatsType{fsStatsRoot, fsStatsLogs, fsStatsLocalVolumeSource}, orderedByResource)).Sort(pods) - expected := []*api.Pod{pod2, pod1, pod4, pod3, pod6, pod5} + expected := []*v1.Pod{pod2, pod1, pod4, pod3, pod6, pod5} for i := range expected { if pods[i] != expected[i] { t.Errorf("Expected pod[%d]: %s, but got: %s", i, expected[i].Name, pods[i].Name) @@ -570,25 +571,25 @@ func testOrderedByQoSResource(t *testing.T, orderedByResource api.ResourceName, // TestOrderedByMemory ensures we order pods by greediest memory consumer relative to request. func TestOrderedByMemory(t *testing.T) { - pod1 := newPod("best-effort-high", []api.Container{ + pod1 := newPod("best-effort-high", []v1.Container{ newContainer("best-effort-high", newResourceList("", ""), newResourceList("", "")), }, nil) - pod2 := newPod("best-effort-low", []api.Container{ + pod2 := newPod("best-effort-low", []v1.Container{ newContainer("best-effort-low", newResourceList("", ""), newResourceList("", "")), }, nil) - pod3 := newPod("burstable-high", []api.Container{ + pod3 := newPod("burstable-high", []v1.Container{ newContainer("burstable-high", newResourceList("100m", "100Mi"), newResourceList("200m", "1Gi")), }, nil) - pod4 := newPod("burstable-low", []api.Container{ + pod4 := newPod("burstable-low", []v1.Container{ newContainer("burstable-low", newResourceList("100m", "100Mi"), newResourceList("200m", "1Gi")), }, nil) - pod5 := newPod("guaranteed-high", []api.Container{ + pod5 := newPod("guaranteed-high", []v1.Container{ newContainer("guaranteed-high", newResourceList("100m", "1Gi"), newResourceList("100m", "1Gi")), }, nil) - pod6 := newPod("guaranteed-low", []api.Container{ + pod6 := newPod("guaranteed-low", []v1.Container{ newContainer("guaranteed-low", newResourceList("100m", "1Gi"), newResourceList("100m", "1Gi")), }, nil) - stats := map[*api.Pod]statsapi.PodStats{ + stats := map[*v1.Pod]statsapi.PodStats{ pod1: newPodMemoryStats(pod1, resource.MustParse("500Mi")), // 500 relative to request pod2: newPodMemoryStats(pod2, resource.MustParse("300Mi")), // 300 relative to request pod3: newPodMemoryStats(pod3, resource.MustParse("800Mi")), // 700 relative to request @@ -596,13 +597,13 @@ func TestOrderedByMemory(t *testing.T) { pod5: newPodMemoryStats(pod5, resource.MustParse("800Mi")), // -200 relative to request pod6: newPodMemoryStats(pod6, resource.MustParse("200Mi")), // -800 relative to request } - statsFn := func(pod *api.Pod) (statsapi.PodStats, bool) { + statsFn := func(pod *v1.Pod) (statsapi.PodStats, bool) { result, found := stats[pod] return result, found } - pods := []*api.Pod{pod1, pod2, pod3, pod4, pod5, pod6} + pods := []*v1.Pod{pod1, pod2, pod3, pod4, pod5, pod6} orderedBy(memory(statsFn)).Sort(pods) - expected := []*api.Pod{pod3, pod1, pod2, pod4, pod5, pod6} + expected := []*v1.Pod{pod3, pod1, pod2, pod4, pod5, pod6} for i := range expected { if pods[i] != expected[i] { t.Errorf("Expected pod[%d]: %s, but got: %s", i, expected[i].Name, pods[i].Name) @@ -612,25 +613,25 @@ func TestOrderedByMemory(t *testing.T) { // TestOrderedByQoSMemory ensures we order by qosComparator and then memory consumption relative to request. func TestOrderedByQoSMemory(t *testing.T) { - pod1 := newPod("best-effort-high", []api.Container{ + pod1 := newPod("best-effort-high", []v1.Container{ newContainer("best-effort-high", newResourceList("", ""), newResourceList("", "")), }, nil) - pod2 := newPod("best-effort-low", []api.Container{ + pod2 := newPod("best-effort-low", []v1.Container{ newContainer("best-effort-low", newResourceList("", ""), newResourceList("", "")), }, nil) - pod3 := newPod("burstable-high", []api.Container{ + pod3 := newPod("burstable-high", []v1.Container{ newContainer("burstable-high", newResourceList("100m", "100Mi"), newResourceList("200m", "1Gi")), }, nil) - pod4 := newPod("burstable-low", []api.Container{ + pod4 := newPod("burstable-low", []v1.Container{ newContainer("burstable-low", newResourceList("100m", "100Mi"), newResourceList("200m", "1Gi")), }, nil) - pod5 := newPod("guaranteed-high", []api.Container{ + pod5 := newPod("guaranteed-high", []v1.Container{ newContainer("guaranteed-high", newResourceList("100m", "1Gi"), newResourceList("100m", "1Gi")), }, nil) - pod6 := newPod("guaranteed-low", []api.Container{ + pod6 := newPod("guaranteed-low", []v1.Container{ newContainer("guaranteed-low", newResourceList("100m", "1Gi"), newResourceList("100m", "1Gi")), }, nil) - stats := map[*api.Pod]statsapi.PodStats{ + stats := map[*v1.Pod]statsapi.PodStats{ pod1: newPodMemoryStats(pod1, resource.MustParse("500Mi")), // 500 relative to request pod2: newPodMemoryStats(pod2, resource.MustParse("50Mi")), // 50 relative to request pod3: newPodMemoryStats(pod3, resource.MustParse("50Mi")), // -50 relative to request @@ -638,12 +639,12 @@ func TestOrderedByQoSMemory(t *testing.T) { pod5: newPodMemoryStats(pod5, resource.MustParse("800Mi")), // -200 relative to request pod6: newPodMemoryStats(pod6, resource.MustParse("200Mi")), // -800 relative to request } - statsFn := func(pod *api.Pod) (statsapi.PodStats, bool) { + statsFn := func(pod *v1.Pod) (statsapi.PodStats, bool) { result, found := stats[pod] return result, found } - pods := []*api.Pod{pod1, pod2, pod3, pod4, pod5, pod6} - expected := []*api.Pod{pod1, pod2, pod4, pod3, pod5, pod6} + pods := []*v1.Pod{pod1, pod2, pod3, pod4, pod5, pod6} + expected := []*v1.Pod{pod1, pod2, pod4, pod3, pod5, pod6} orderedBy(qosComparator, memory(statsFn)).Sort(pods) for i := range expected { if pods[i] != expected[i] { @@ -662,7 +663,7 @@ func (f *fakeSummaryProvider) Get() (*statsapi.Summary, error) { // newPodStats returns a pod stat where each container is using the specified working set // each pod must have a Name, UID, Namespace -func newPodStats(pod *api.Pod, containerWorkingSetBytes int64) statsapi.PodStats { +func newPodStats(pod *v1.Pod, containerWorkingSetBytes int64) statsapi.PodStats { result := statsapi.PodStats{ PodRef: statsapi.PodReference{ Name: pod.Name, @@ -682,14 +683,14 @@ func newPodStats(pod *api.Pod, containerWorkingSetBytes int64) statsapi.PodStats } func TestMakeSignalObservations(t *testing.T) { - podMaker := func(name, namespace, uid string, numContainers int) *api.Pod { - pod := &api.Pod{} + podMaker := func(name, namespace, uid string, numContainers int) *v1.Pod { + pod := &v1.Pod{} pod.Name = name pod.Namespace = namespace pod.UID = types.UID(uid) - pod.Spec = api.PodSpec{} + pod.Spec = v1.PodSpec{} for i := 0; i < numContainers; i++ { - pod.Spec.Containers = append(pod.Spec.Containers, api.Container{ + pod.Spec.Containers = append(pod.Spec.Containers, v1.Container{ Name: fmt.Sprintf("ctr%v", i), }) } @@ -731,7 +732,7 @@ func TestMakeSignalObservations(t *testing.T) { provider := &fakeSummaryProvider{ result: fakeStats, } - pods := []*api.Pod{ + pods := []*v1.Pod{ podMaker("pod1", "ns1", "uuid1", 1), podMaker("pod1", "ns2", "uuid2", 1), podMaker("pod3", "ns3", "uuid3", 1), @@ -1199,17 +1200,17 @@ func TestThresholdsMetGracePeriod(t *testing.T) { func TestNodeConditions(t *testing.T) { testCases := map[string]struct { inputs []Threshold - result []api.NodeConditionType + result []v1.NodeConditionType }{ "empty-list": { inputs: []Threshold{}, - result: []api.NodeConditionType{}, + result: []v1.NodeConditionType{}, }, "memory.available": { inputs: []Threshold{ {Signal: SignalMemoryAvailable}, }, - result: []api.NodeConditionType{api.NodeMemoryPressure}, + result: []v1.NodeConditionType{v1.NodeMemoryPressure}, }, } for testName, testCase := range testCases { @@ -1224,37 +1225,37 @@ func TestNodeConditionsLastObservedAt(t *testing.T) { now := unversioned.Now() oldTime := unversioned.NewTime(now.Time.Add(-1 * time.Minute)) testCases := map[string]struct { - nodeConditions []api.NodeConditionType + nodeConditions []v1.NodeConditionType lastObservedAt nodeConditionsObservedAt now time.Time result nodeConditionsObservedAt }{ "no-previous-observation": { - nodeConditions: []api.NodeConditionType{api.NodeMemoryPressure}, + nodeConditions: []v1.NodeConditionType{v1.NodeMemoryPressure}, lastObservedAt: nodeConditionsObservedAt{}, now: now.Time, result: nodeConditionsObservedAt{ - api.NodeMemoryPressure: now.Time, + v1.NodeMemoryPressure: now.Time, }, }, "previous-observation": { - nodeConditions: []api.NodeConditionType{api.NodeMemoryPressure}, + nodeConditions: []v1.NodeConditionType{v1.NodeMemoryPressure}, lastObservedAt: nodeConditionsObservedAt{ - api.NodeMemoryPressure: oldTime.Time, + v1.NodeMemoryPressure: oldTime.Time, }, now: now.Time, result: nodeConditionsObservedAt{ - api.NodeMemoryPressure: now.Time, + v1.NodeMemoryPressure: now.Time, }, }, "old-observation": { - nodeConditions: []api.NodeConditionType{}, + nodeConditions: []v1.NodeConditionType{}, lastObservedAt: nodeConditionsObservedAt{ - api.NodeMemoryPressure: oldTime.Time, + v1.NodeMemoryPressure: oldTime.Time, }, now: now.Time, result: nodeConditionsObservedAt{ - api.NodeMemoryPressure: oldTime.Time, + v1.NodeMemoryPressure: oldTime.Time, }, }, } @@ -1273,23 +1274,23 @@ func TestNodeConditionsObservedSince(t *testing.T) { observedAt nodeConditionsObservedAt period time.Duration now time.Time - result []api.NodeConditionType + result []v1.NodeConditionType }{ "in-period": { observedAt: nodeConditionsObservedAt{ - api.NodeMemoryPressure: observedTime.Time, + v1.NodeMemoryPressure: observedTime.Time, }, period: 2 * time.Minute, now: now.Time, - result: []api.NodeConditionType{api.NodeMemoryPressure}, + result: []v1.NodeConditionType{v1.NodeMemoryPressure}, }, "out-of-period": { observedAt: nodeConditionsObservedAt{ - api.NodeMemoryPressure: observedTime.Time, + v1.NodeMemoryPressure: observedTime.Time, }, period: 30 * time.Second, now: now.Time, - result: []api.NodeConditionType{}, + result: []v1.NodeConditionType{}, }, } for testName, testCase := range testCases { @@ -1302,18 +1303,18 @@ func TestNodeConditionsObservedSince(t *testing.T) { func TestHasNodeConditions(t *testing.T) { testCases := map[string]struct { - inputs []api.NodeConditionType - item api.NodeConditionType + inputs []v1.NodeConditionType + item v1.NodeConditionType result bool }{ "has-condition": { - inputs: []api.NodeConditionType{api.NodeReady, api.NodeOutOfDisk, api.NodeMemoryPressure}, - item: api.NodeMemoryPressure, + inputs: []v1.NodeConditionType{v1.NodeReady, v1.NodeOutOfDisk, v1.NodeMemoryPressure}, + item: v1.NodeMemoryPressure, result: true, }, "does-not-have-condition": { - inputs: []api.NodeConditionType{api.NodeReady, api.NodeOutOfDisk}, - item: api.NodeMemoryPressure, + inputs: []v1.NodeConditionType{v1.NodeReady, v1.NodeOutOfDisk}, + item: v1.NodeMemoryPressure, result: false, }, } @@ -1327,31 +1328,38 @@ func TestHasNodeConditions(t *testing.T) { func TestGetStarvedResources(t *testing.T) { testCases := map[string]struct { inputs []Threshold - result []api.ResourceName + result []v1.ResourceName }{ "memory.available": { inputs: []Threshold{ {Signal: SignalMemoryAvailable}, }, - result: []api.ResourceName{api.ResourceMemory}, + result: []v1.ResourceName{v1.ResourceMemory}, }, "imagefs.available": { inputs: []Threshold{ {Signal: SignalImageFsAvailable}, }, - result: []api.ResourceName{resourceImageFs}, + result: []v1.ResourceName{resourceImageFs}, }, "nodefs.available": { inputs: []Threshold{ {Signal: SignalNodeFsAvailable}, }, - result: []api.ResourceName{resourceNodeFs}, + result: []v1.ResourceName{resourceNodeFs}, }, } + var internalResourceNames = func(in []v1.ResourceName) []api.ResourceName { + var out []api.ResourceName + for _, name := range in { + out = append(out, api.ResourceName(name)) + } + return out + } for testName, testCase := range testCases { actual := getStarvedResources(testCase.inputs) - actualSet := quota.ToSet(actual) - expectedSet := quota.ToSet(testCase.result) + actualSet := quota.ToSet(internalResourceNames(actual)) + expectedSet := quota.ToSet(internalResourceNames(testCase.result)) if !actualSet.Equal(expectedSet) { t.Errorf("Test case: %s, expected: %v, actual: %v", testName, expectedSet, actualSet) } @@ -1448,7 +1456,7 @@ func testCompareThresholdValue(t *testing.T) { } // newPodInodeStats returns stats with specified usage amounts. -func newPodInodeStats(pod *api.Pod, rootFsInodesUsed, logsInodesUsed, perLocalVolumeInodesUsed resource.Quantity) statsapi.PodStats { +func newPodInodeStats(pod *v1.Pod, rootFsInodesUsed, logsInodesUsed, perLocalVolumeInodesUsed resource.Quantity) statsapi.PodStats { result := statsapi.PodStats{ PodRef: statsapi.PodReference{ Name: pod.Name, Namespace: pod.Namespace, UID: string(pod.UID), @@ -1480,7 +1488,7 @@ func newPodInodeStats(pod *api.Pod, rootFsInodesUsed, logsInodesUsed, perLocalVo } // newPodDiskStats returns stats with specified usage amounts. -func newPodDiskStats(pod *api.Pod, rootFsUsed, logsUsed, perLocalVolumeUsed resource.Quantity) statsapi.PodStats { +func newPodDiskStats(pod *v1.Pod, rootFsUsed, logsUsed, perLocalVolumeUsed resource.Quantity) statsapi.PodStats { result := statsapi.PodStats{ PodRef: statsapi.PodReference{ Name: pod.Name, Namespace: pod.Namespace, UID: string(pod.UID), @@ -1513,7 +1521,7 @@ func newPodDiskStats(pod *api.Pod, rootFsUsed, logsUsed, perLocalVolumeUsed reso return result } -func newPodMemoryStats(pod *api.Pod, workingSet resource.Quantity) statsapi.PodStats { +func newPodMemoryStats(pod *v1.Pod, workingSet resource.Quantity) statsapi.PodStats { result := statsapi.PodStats{ PodRef: statsapi.PodReference{ Name: pod.Name, Namespace: pod.Namespace, UID: string(pod.UID), @@ -1530,46 +1538,46 @@ func newPodMemoryStats(pod *api.Pod, workingSet resource.Quantity) statsapi.PodS return result } -func newResourceList(cpu, memory string) api.ResourceList { - res := api.ResourceList{} +func newResourceList(cpu, memory string) v1.ResourceList { + res := v1.ResourceList{} if cpu != "" { - res[api.ResourceCPU] = resource.MustParse(cpu) + res[v1.ResourceCPU] = resource.MustParse(cpu) } if memory != "" { - res[api.ResourceMemory] = resource.MustParse(memory) + res[v1.ResourceMemory] = resource.MustParse(memory) } return res } -func newResourceRequirements(requests, limits api.ResourceList) api.ResourceRequirements { - res := api.ResourceRequirements{} +func newResourceRequirements(requests, limits v1.ResourceList) v1.ResourceRequirements { + res := v1.ResourceRequirements{} res.Requests = requests res.Limits = limits return res } -func newContainer(name string, requests api.ResourceList, limits api.ResourceList) api.Container { - return api.Container{ +func newContainer(name string, requests v1.ResourceList, limits v1.ResourceList) v1.Container { + return v1.Container{ Name: name, Resources: newResourceRequirements(requests, limits), } } -func newVolume(name string, volumeSource api.VolumeSource) api.Volume { - return api.Volume{ +func newVolume(name string, volumeSource v1.VolumeSource) v1.Volume { + return v1.Volume{ Name: name, VolumeSource: volumeSource, } } // newPod uses the name as the uid. Make names unique for testing. -func newPod(name string, containers []api.Container, volumes []api.Volume) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func newPod(name string, containers []v1.Container, volumes []v1.Volume) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, UID: types.UID(name), }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ Containers: containers, Volumes: volumes, }, @@ -1577,7 +1585,7 @@ func newPod(name string, containers []api.Container, volumes []api.Volume) *api. } // nodeConditionList is a simple alias to support equality checking independent of order -type nodeConditionList []api.NodeConditionType +type nodeConditionList []v1.NodeConditionType // Equal adds the ability to check equality between two lists of node conditions. func (s1 nodeConditionList) Equal(s2 nodeConditionList) bool { diff --git a/pkg/kubelet/eviction/types.go b/pkg/kubelet/eviction/types.go index 7cbfff7f9a3..e7e2a7d3b73 100644 --- a/pkg/kubelet/eviction/types.go +++ b/pkg/kubelet/eviction/types.go @@ -19,9 +19,9 @@ package eviction import ( "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" statsapi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" ) @@ -126,16 +126,16 @@ type ImageGC interface { // pod - the pod to kill // status - the desired status to associate with the pod (i.e. why its killed) // gracePeriodOverride - the grace period override to use instead of what is on the pod spec -type KillPodFunc func(pod *api.Pod, status api.PodStatus, gracePeriodOverride *int64) error +type KillPodFunc func(pod *v1.Pod, status v1.PodStatus, gracePeriodOverride *int64) error // ActivePodsFunc returns pods bound to the kubelet that are active (i.e. non-terminal state) -type ActivePodsFunc func() []*api.Pod +type ActivePodsFunc func() []*v1.Pod // statsFunc returns the usage stats if known for an input pod. -type statsFunc func(pod *api.Pod) (statsapi.PodStats, bool) +type statsFunc func(pod *v1.Pod) (statsapi.PodStats, bool) // rankFunc sorts the pods in eviction order -type rankFunc func(pods []*api.Pod, stats statsFunc) +type rankFunc func(pods []*v1.Pod, stats statsFunc) // signalObservation is the observed resource usage type signalObservation struct { @@ -154,7 +154,7 @@ type signalObservations map[Signal]signalObservation type thresholdsObservedAt map[Threshold]time.Time // nodeConditionsObservedAt maps a node condition to a time that it was observed -type nodeConditionsObservedAt map[api.NodeConditionType]time.Time +type nodeConditionsObservedAt map[v1.NodeConditionType]time.Time // nodeReclaimFunc is a function that knows how to reclaim a resource from the node without impacting pods. type nodeReclaimFunc func() (*resource.Quantity, error) diff --git a/pkg/kubelet/images/BUILD b/pkg/kubelet/images/BUILD index 44bfd0284b4..5898bf725a4 100644 --- a/pkg/kubelet/images/BUILD +++ b/pkg/kubelet/images/BUILD @@ -22,7 +22,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/kubelet/cadvisor:go_default_library", "//pkg/kubelet/container:go_default_library", @@ -46,7 +46,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/kubelet/cadvisor/testing:go_default_library", "//pkg/kubelet/container:go_default_library", diff --git a/pkg/kubelet/images/helpers.go b/pkg/kubelet/images/helpers.go index f8fd5f1537e..67a8da94ff3 100644 --- a/pkg/kubelet/images/helpers.go +++ b/pkg/kubelet/images/helpers.go @@ -19,7 +19,7 @@ package images import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/util/flowcontrol" ) @@ -42,7 +42,7 @@ type throttledImageService struct { limiter flowcontrol.RateLimiter } -func (ts throttledImageService) PullImage(image kubecontainer.ImageSpec, secrets []api.Secret) error { +func (ts throttledImageService) PullImage(image kubecontainer.ImageSpec, secrets []v1.Secret) error { if ts.limiter.TryAccept() { return ts.ImageService.PullImage(image, secrets) } diff --git a/pkg/kubelet/images/image_gc_manager.go b/pkg/kubelet/images/image_gc_manager.go index c17c8741275..131b5685e87 100644 --- a/pkg/kubelet/images/image_gc_manager.go +++ b/pkg/kubelet/images/image_gc_manager.go @@ -24,7 +24,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/kubelet/cadvisor" "k8s.io/kubernetes/pkg/kubelet/container" @@ -85,7 +85,7 @@ type realImageGCManager struct { recorder record.EventRecorder // Reference to this node. - nodeRef *api.ObjectReference + nodeRef *v1.ObjectReference // Track initialization initialized bool @@ -103,7 +103,7 @@ type imageRecord struct { size int64 } -func NewImageGCManager(runtime container.Runtime, cadvisorInterface cadvisor.Interface, recorder record.EventRecorder, nodeRef *api.ObjectReference, policy ImageGCPolicy) (ImageGCManager, error) { +func NewImageGCManager(runtime container.Runtime, cadvisorInterface cadvisor.Interface, recorder record.EventRecorder, nodeRef *v1.ObjectReference, policy ImageGCPolicy) (ImageGCManager, error) { // Validate policy. if policy.HighThresholdPercent < 0 || policy.HighThresholdPercent > 100 { return nil, fmt.Errorf("invalid HighThresholdPercent %d, must be in range [0-100]", policy.HighThresholdPercent) @@ -227,7 +227,7 @@ func (im *realImageGCManager) GarbageCollect() error { // Check valid capacity. if capacity == 0 { err := fmt.Errorf("invalid capacity %d on device %q at mount point %q", capacity, fsInfo.Device, fsInfo.Mountpoint) - im.recorder.Eventf(im.nodeRef, api.EventTypeWarning, events.InvalidDiskCapacity, err.Error()) + im.recorder.Eventf(im.nodeRef, v1.EventTypeWarning, events.InvalidDiskCapacity, err.Error()) return err } @@ -243,7 +243,7 @@ func (im *realImageGCManager) GarbageCollect() error { if freed < amountToFree { err := fmt.Errorf("failed to garbage collect required amount of images. Wanted to free %d, but freed %d", amountToFree, freed) - im.recorder.Eventf(im.nodeRef, api.EventTypeWarning, events.FreeDiskSpaceFailed, err.Error()) + im.recorder.Eventf(im.nodeRef, v1.EventTypeWarning, events.FreeDiskSpaceFailed, err.Error()) return err } } diff --git a/pkg/kubelet/images/image_manager.go b/pkg/kubelet/images/image_manager.go index 02ea5b4267a..b2809f1353a 100644 --- a/pkg/kubelet/images/image_manager.go +++ b/pkg/kubelet/images/image_manager.go @@ -21,7 +21,7 @@ import ( dockerref "github.com/docker/distribution/reference" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/events" @@ -59,13 +59,13 @@ func NewImageManager(recorder record.EventRecorder, imageService kubecontainer.I // shouldPullImage returns whether we should pull an image according to // the presence and pull policy of the image. -func shouldPullImage(container *api.Container, imagePresent bool) bool { - if container.ImagePullPolicy == api.PullNever { +func shouldPullImage(container *v1.Container, imagePresent bool) bool { + if container.ImagePullPolicy == v1.PullNever { return false } - if container.ImagePullPolicy == api.PullAlways || - (container.ImagePullPolicy == api.PullIfNotPresent && (!imagePresent)) { + if container.ImagePullPolicy == v1.PullAlways || + (container.ImagePullPolicy == v1.PullIfNotPresent && (!imagePresent)) { return true } @@ -73,7 +73,7 @@ func shouldPullImage(container *api.Container, imagePresent bool) bool { } // records an event using ref, event msg. log to glog using prefix, msg, logFn -func (m *imageManager) logIt(ref *api.ObjectReference, eventtype, event, prefix, msg string, logFn func(args ...interface{})) { +func (m *imageManager) logIt(ref *v1.ObjectReference, eventtype, event, prefix, msg string, logFn func(args ...interface{})) { if ref != nil { m.recorder.Event(ref, eventtype, event, msg) } else { @@ -82,7 +82,7 @@ func (m *imageManager) logIt(ref *api.ObjectReference, eventtype, event, prefix, } // EnsureImageExists pulls the image for the specified pod and container. -func (m *imageManager) EnsureImageExists(pod *api.Pod, container *api.Container, pullSecrets []api.Secret) (error, string) { +func (m *imageManager) EnsureImageExists(pod *v1.Pod, container *v1.Container, pullSecrets []v1.Secret) (error, string) { logPrefix := fmt.Sprintf("%s/%s", pod.Name, container.Image) ref, err := kubecontainer.GenerateContainerRef(pod, container) if err != nil { @@ -93,7 +93,7 @@ func (m *imageManager) EnsureImageExists(pod *api.Pod, container *api.Container, image, err := applyDefaultImageTag(container.Image) if err != nil { msg := fmt.Sprintf("Failed to apply default image tag %q: %v", container.Image, err) - m.logIt(ref, api.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, glog.Warning) + m.logIt(ref, v1.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, glog.Warning) return ErrInvalidImageName, msg } @@ -101,18 +101,18 @@ func (m *imageManager) EnsureImageExists(pod *api.Pod, container *api.Container, present, err := m.imageService.IsImagePresent(spec) if err != nil { msg := fmt.Sprintf("Failed to inspect image %q: %v", container.Image, err) - m.logIt(ref, api.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, glog.Warning) + m.logIt(ref, v1.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, glog.Warning) return ErrImageInspect, msg } if !shouldPullImage(container, present) { if present { msg := fmt.Sprintf("Container image %q already present on machine", container.Image) - m.logIt(ref, api.EventTypeNormal, events.PulledImage, logPrefix, msg, glog.Info) + m.logIt(ref, v1.EventTypeNormal, events.PulledImage, logPrefix, msg, glog.Info) return nil, "" } else { msg := fmt.Sprintf("Container image %q is not present with pull policy of Never", container.Image) - m.logIt(ref, api.EventTypeWarning, events.ErrImageNeverPullPolicy, logPrefix, msg, glog.Warning) + m.logIt(ref, v1.EventTypeWarning, events.ErrImageNeverPullPolicy, logPrefix, msg, glog.Warning) return ErrImageNeverPull, msg } } @@ -120,14 +120,14 @@ func (m *imageManager) EnsureImageExists(pod *api.Pod, container *api.Container, backOffKey := fmt.Sprintf("%s_%s", pod.UID, container.Image) if m.backOff.IsInBackOffSinceUpdate(backOffKey, m.backOff.Clock.Now()) { msg := fmt.Sprintf("Back-off pulling image %q", container.Image) - m.logIt(ref, api.EventTypeNormal, events.BackOffPullImage, logPrefix, msg, glog.Info) + m.logIt(ref, v1.EventTypeNormal, events.BackOffPullImage, logPrefix, msg, glog.Info) return ErrImagePullBackOff, msg } - m.logIt(ref, api.EventTypeNormal, events.PullingImage, logPrefix, fmt.Sprintf("pulling image %q", container.Image), glog.Info) + m.logIt(ref, v1.EventTypeNormal, events.PullingImage, logPrefix, fmt.Sprintf("pulling image %q", container.Image), glog.Info) errChan := make(chan error) m.puller.pullImage(spec, pullSecrets, errChan) if err := <-errChan; err != nil { - m.logIt(ref, api.EventTypeWarning, events.FailedToPullImage, logPrefix, fmt.Sprintf("Failed to pull image %q: %v", container.Image, err), glog.Warning) + m.logIt(ref, v1.EventTypeWarning, events.FailedToPullImage, logPrefix, fmt.Sprintf("Failed to pull image %q: %v", container.Image, err), glog.Warning) m.backOff.Next(backOffKey, m.backOff.Clock.Now()) if err == RegistryUnavailable { msg := fmt.Sprintf("image pull failed for %s because the registry is unavailable.", container.Image) @@ -136,7 +136,7 @@ func (m *imageManager) EnsureImageExists(pod *api.Pod, container *api.Container, return ErrImagePull, err.Error() } } - m.logIt(ref, api.EventTypeNormal, events.PulledImage, logPrefix, fmt.Sprintf("Successfully pulled image %q", container.Image), glog.Info) + m.logIt(ref, v1.EventTypeNormal, events.PulledImage, logPrefix, fmt.Sprintf("Successfully pulled image %q", container.Image), glog.Info) m.backOff.GC() return nil, "" } diff --git a/pkg/kubelet/images/image_manager_test.go b/pkg/kubelet/images/image_manager_test.go index 7ff7137a627..e8284932ed6 100644 --- a/pkg/kubelet/images/image_manager_test.go +++ b/pkg/kubelet/images/image_manager_test.go @@ -22,7 +22,7 @@ import ( "time" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" . "k8s.io/kubernetes/pkg/kubelet/container" ctest "k8s.io/kubernetes/pkg/kubelet/container/testing" @@ -31,8 +31,8 @@ import ( ) func TestParallelPuller(t *testing.T) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "test_pod", Namespace: "test-ns", UID: "bar", @@ -42,7 +42,7 @@ func TestParallelPuller(t *testing.T) { cases := []struct { containerImage string - policy api.PullPolicy + policy v1.PullPolicy calledFunctions []string inspectErr error pullerErr error @@ -50,7 +50,7 @@ func TestParallelPuller(t *testing.T) { }{ { // pull missing image containerImage: "missing_image", - policy: api.PullIfNotPresent, + policy: v1.PullIfNotPresent, calledFunctions: []string{"IsImagePresent", "PullImage"}, inspectErr: nil, pullerErr: nil, @@ -58,35 +58,35 @@ func TestParallelPuller(t *testing.T) { { // image present, don't pull containerImage: "present_image", - policy: api.PullIfNotPresent, + policy: v1.PullIfNotPresent, calledFunctions: []string{"IsImagePresent"}, inspectErr: nil, pullerErr: nil, expectedErr: []error{nil, nil, nil}}, // image present, pull it {containerImage: "present_image", - policy: api.PullAlways, + policy: v1.PullAlways, calledFunctions: []string{"IsImagePresent", "PullImage"}, inspectErr: nil, pullerErr: nil, expectedErr: []error{nil, nil, nil}}, // missing image, error PullNever {containerImage: "missing_image", - policy: api.PullNever, + policy: v1.PullNever, calledFunctions: []string{"IsImagePresent"}, inspectErr: nil, pullerErr: nil, expectedErr: []error{ErrImageNeverPull, ErrImageNeverPull, ErrImageNeverPull}}, // missing image, unable to inspect {containerImage: "missing_image", - policy: api.PullIfNotPresent, + policy: v1.PullIfNotPresent, calledFunctions: []string{"IsImagePresent"}, inspectErr: errors.New("unknown inspectError"), pullerErr: nil, expectedErr: []error{ErrImageInspect, ErrImageInspect, ErrImageInspect}}, // missing image, unable to fetch {containerImage: "typo_image", - policy: api.PullIfNotPresent, + policy: v1.PullIfNotPresent, calledFunctions: []string{"IsImagePresent", "PullImage"}, inspectErr: nil, pullerErr: errors.New("404"), @@ -94,7 +94,7 @@ func TestParallelPuller(t *testing.T) { } for i, c := range cases { - container := &api.Container{ + container := &v1.Container{ Name: "container_name", Image: c.containerImage, ImagePullPolicy: c.policy, @@ -122,8 +122,8 @@ func TestParallelPuller(t *testing.T) { } func TestSerializedPuller(t *testing.T) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "test_pod", Namespace: "test-ns", UID: "bar", @@ -133,7 +133,7 @@ func TestSerializedPuller(t *testing.T) { cases := []struct { containerImage string - policy api.PullPolicy + policy v1.PullPolicy calledFunctions []string inspectErr error pullerErr error @@ -141,7 +141,7 @@ func TestSerializedPuller(t *testing.T) { }{ { // pull missing image containerImage: "missing_image", - policy: api.PullIfNotPresent, + policy: v1.PullIfNotPresent, calledFunctions: []string{"IsImagePresent", "PullImage"}, inspectErr: nil, pullerErr: nil, @@ -149,35 +149,35 @@ func TestSerializedPuller(t *testing.T) { { // image present, don't pull containerImage: "present_image", - policy: api.PullIfNotPresent, + policy: v1.PullIfNotPresent, calledFunctions: []string{"IsImagePresent"}, inspectErr: nil, pullerErr: nil, expectedErr: []error{nil, nil, nil}}, // image present, pull it {containerImage: "present_image", - policy: api.PullAlways, + policy: v1.PullAlways, calledFunctions: []string{"IsImagePresent", "PullImage"}, inspectErr: nil, pullerErr: nil, expectedErr: []error{nil, nil, nil}}, // missing image, error PullNever {containerImage: "missing_image", - policy: api.PullNever, + policy: v1.PullNever, calledFunctions: []string{"IsImagePresent"}, inspectErr: nil, pullerErr: nil, expectedErr: []error{ErrImageNeverPull, ErrImageNeverPull, ErrImageNeverPull}}, // missing image, unable to inspect {containerImage: "missing_image", - policy: api.PullIfNotPresent, + policy: v1.PullIfNotPresent, calledFunctions: []string{"IsImagePresent"}, inspectErr: errors.New("unknown inspectError"), pullerErr: nil, expectedErr: []error{ErrImageInspect, ErrImageInspect, ErrImageInspect}}, // missing image, unable to fetch {containerImage: "typo_image", - policy: api.PullIfNotPresent, + policy: v1.PullIfNotPresent, calledFunctions: []string{"IsImagePresent", "PullImage"}, inspectErr: nil, pullerErr: errors.New("404"), @@ -185,7 +185,7 @@ func TestSerializedPuller(t *testing.T) { } for i, c := range cases { - container := &api.Container{ + container := &v1.Container{ Name: "container_name", Image: c.containerImage, ImagePullPolicy: c.policy, diff --git a/pkg/kubelet/images/puller.go b/pkg/kubelet/images/puller.go index 7bcbd0bf9f5..5698e4c2664 100644 --- a/pkg/kubelet/images/puller.go +++ b/pkg/kubelet/images/puller.go @@ -19,13 +19,13 @@ package images import ( "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/util/wait" ) type imagePuller interface { - pullImage(kubecontainer.ImageSpec, []api.Secret, chan<- error) + pullImage(kubecontainer.ImageSpec, []v1.Secret, chan<- error) } var _, _ imagePuller = ¶llelImagePuller{}, &serialImagePuller{} @@ -38,7 +38,7 @@ func newParallelImagePuller(imageService kubecontainer.ImageService) imagePuller return ¶llelImagePuller{imageService} } -func (pip *parallelImagePuller) pullImage(spec kubecontainer.ImageSpec, pullSecrets []api.Secret, errChan chan<- error) { +func (pip *parallelImagePuller) pullImage(spec kubecontainer.ImageSpec, pullSecrets []v1.Secret, errChan chan<- error) { go func() { errChan <- pip.imageService.PullImage(spec, pullSecrets) }() @@ -60,11 +60,11 @@ func newSerialImagePuller(imageService kubecontainer.ImageService) imagePuller { type imagePullRequest struct { spec kubecontainer.ImageSpec - pullSecrets []api.Secret + pullSecrets []v1.Secret errChan chan<- error } -func (sip *serialImagePuller) pullImage(spec kubecontainer.ImageSpec, pullSecrets []api.Secret, errChan chan<- error) { +func (sip *serialImagePuller) pullImage(spec kubecontainer.ImageSpec, pullSecrets []v1.Secret, errChan chan<- error) { sip.pullRequests <- &imagePullRequest{ spec: spec, pullSecrets: pullSecrets, diff --git a/pkg/kubelet/images/types.go b/pkg/kubelet/images/types.go index 1f81d947e17..9870088f948 100644 --- a/pkg/kubelet/images/types.go +++ b/pkg/kubelet/images/types.go @@ -19,7 +19,7 @@ package images import ( "errors" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) var ( @@ -49,7 +49,7 @@ var ( // Implementations are expected to be thread safe. type ImageManager interface { // EnsureImageExists ensures that image specified in `container` exists. - EnsureImageExists(pod *api.Pod, container *api.Container, pullSecrets []api.Secret) (error, string) + EnsureImageExists(pod *v1.Pod, container *v1.Container, pullSecrets []v1.Secret) (error, string) // TODO(ronl): consolidating image managing and deleting operation in this interface } diff --git a/pkg/kubelet/kubelet.go b/pkg/kubelet/kubelet.go index a563f1dd572..67cb8f9c0ff 100644 --- a/pkg/kubelet/kubelet.go +++ b/pkg/kubelet/kubelet.go @@ -33,10 +33,11 @@ import ( cadvisorapi "github.com/google/cadvisor/info/v1" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" componentconfigv1alpha1 "k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/fields" @@ -152,11 +153,11 @@ const ( // SyncHandler is an interface implemented by Kubelet, for testability type SyncHandler interface { - HandlePodAdditions(pods []*api.Pod) - HandlePodUpdates(pods []*api.Pod) - HandlePodRemoves(pods []*api.Pod) - HandlePodReconcile(pods []*api.Pod) - HandlePodSyncs(pods []*api.Pod) + HandlePodAdditions(pods []*v1.Pod) + HandlePodUpdates(pods []*v1.Pod) + HandlePodRemoves(pods []*v1.Pod) + HandlePodReconcile(pods []*v1.Pod) + HandlePodSyncs(pods []*v1.Pod) HandlePodCleanups() error } @@ -330,8 +331,8 @@ func NewMainKubelet(kubeCfg *componentconfig.KubeletConfiguration, kubeDeps *Kub MaxContainers: int(kubeCfg.MaxContainerCount), } - daemonEndpoints := &api.NodeDaemonEndpoints{ - KubeletEndpoint: api.DaemonEndpoint{Port: kubeCfg.Port}, + daemonEndpoints := &v1.NodeDaemonEndpoints{ + KubeletEndpoint: v1.DaemonEndpoint{Port: kubeCfg.Port}, } imageGCPolicy := images.ImageGCPolicy{ @@ -373,16 +374,16 @@ func NewMainKubelet(kubeCfg *componentconfig.KubeletConfiguration, kubeDeps *Kub serviceStore := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}) if kubeClient != nil { - serviceLW := cache.NewListWatchFromClient(kubeClient.Core().RESTClient(), "services", api.NamespaceAll, fields.Everything()) - cache.NewReflector(serviceLW, &api.Service{}, serviceStore, 0).Run() + serviceLW := cache.NewListWatchFromClient(kubeClient.Core().RESTClient(), "services", v1.NamespaceAll, fields.Everything()) + cache.NewReflector(serviceLW, &v1.Service{}, serviceStore, 0).Run() } serviceLister := &cache.StoreToServiceLister{Indexer: serviceStore} nodeStore := cache.NewStore(cache.MetaNamespaceKeyFunc) if kubeClient != nil { fieldSelector := fields.Set{api.ObjectNameField: string(nodeName)}.AsSelector() - nodeLW := cache.NewListWatchFromClient(kubeClient.Core().RESTClient(), "nodes", api.NamespaceAll, fieldSelector) - cache.NewReflector(nodeLW, &api.Node{}, nodeStore, 0).Run() + nodeLW := cache.NewListWatchFromClient(kubeClient.Core().RESTClient(), "nodes", v1.NamespaceAll, fieldSelector) + cache.NewReflector(nodeLW, &v1.Node{}, nodeStore, 0).Run() } nodeLister := &cache.StoreToNodeLister{Store: nodeStore} nodeInfo := &predicates.CachedNodeInfo{StoreToNodeLister: nodeLister} @@ -390,7 +391,7 @@ func NewMainKubelet(kubeCfg *componentconfig.KubeletConfiguration, kubeDeps *Kub // TODO: get the real node object of ourself, // and use the real node name and UID. // TODO: what is namespace for node? - nodeRef := &api.ObjectReference{ + nodeRef := &v1.ObjectReference{ Kind: "Node", Name: string(nodeName), UID: types.UID(nodeName), @@ -764,14 +765,14 @@ func NewMainKubelet(kubeCfg *componentconfig.KubeletConfiguration, kubeDeps *Kub if err != nil { return nil, err } - safeWhitelist, err := sysctl.NewWhitelist(sysctl.SafeSysctlWhitelist(), api.SysctlsPodAnnotationKey) + safeWhitelist, err := sysctl.NewWhitelist(sysctl.SafeSysctlWhitelist(), v1.SysctlsPodAnnotationKey) if err != nil { return nil, err } // Safe, whitelisted sysctls can always be used as unsafe sysctls in the spec // Hence, we concatenate those two lists. safeAndUnsafeSysctls := append(sysctl.SafeSysctlWhitelist(), kubeCfg.AllowedUnsafeSysctls...) - unsafeWhitelist, err := sysctl.NewWhitelist(safeAndUnsafeSysctls, api.UnsafeSysctlsPodAnnotationKey) + unsafeWhitelist, err := sysctl.NewWhitelist(safeAndUnsafeSysctls, v1.UnsafeSysctlsPodAnnotationKey) if err != nil { return nil, err } @@ -803,11 +804,11 @@ func NewMainKubelet(kubeCfg *componentconfig.KubeletConfiguration, kubeDeps *Kub } type serviceLister interface { - List(labels.Selector) ([]*api.Service, error) + List(labels.Selector) ([]*v1.Service, error) } type nodeLister interface { - List() (machines api.NodeList, err error) + List() (machines v1.NodeList, err error) } // Kubelet is the main kubelet implementation. @@ -928,7 +929,7 @@ type Kubelet struct { autoDetectCloudProvider bool // Reference to this node. - nodeRef *api.ObjectReference + nodeRef *v1.ObjectReference // Container runtime. containerRuntime kubecontainer.Runtime @@ -1012,7 +1013,7 @@ type Kubelet struct { cpuCFSQuota bool // Information about the ports which are opened by daemons on Node running this Kubelet server. - daemonEndpoints *api.NodeDaemonEndpoints + daemonEndpoints *v1.NodeDaemonEndpoints // A queue used to trigger pod workers. workQueue queue.WorkQueue @@ -1049,7 +1050,7 @@ type Kubelet struct { babysitDaemons bool // handlers called during the tryUpdateNodeStatus cycle - setNodeStatusFuncs []func(*api.Node) error + setNodeStatusFuncs []func(*v1.Node) error // TODO: think about moving this to be centralized in PodWorkers in follow-on. // the list of handlers to call during pod admission. @@ -1125,7 +1126,7 @@ func (kl *Kubelet) StartGarbageCollection() { go wait.Until(func() { if err := kl.containerGC.GarbageCollect(kl.sourcesReady.AllReady()); err != nil { glog.Errorf("Container garbage collection failed: %v", err) - kl.recorder.Eventf(kl.nodeRef, api.EventTypeWarning, events.ContainerGCFailed, err.Error()) + kl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, events.ContainerGCFailed, err.Error()) loggedContainerGCFailure = true } else { var vLevel glog.Level = 4 @@ -1142,7 +1143,7 @@ func (kl *Kubelet) StartGarbageCollection() { go wait.Until(func() { if err := kl.imageManager.GarbageCollect(); err != nil { glog.Errorf("Image garbage collection failed: %v", err) - kl.recorder.Eventf(kl.nodeRef, api.EventTypeWarning, events.ImageGCFailed, err.Error()) + kl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, events.ImageGCFailed, err.Error()) loggedImageGCFailure = true } else { var vLevel glog.Level = 4 @@ -1223,7 +1224,7 @@ func (kl *Kubelet) Run(updates <-chan kubetypes.PodUpdate) { glog.Warning("No api server defined - no node status update will be sent.") } if err := kl.initializeModules(); err != nil { - kl.recorder.Eventf(kl.nodeRef, api.EventTypeWarning, events.KubeletSetupFailed, err.Error()) + kl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, events.KubeletSetupFailed, err.Error()) glog.Error(err) kl.runtimeState.setInitError(err) } @@ -1265,7 +1266,7 @@ func (kl *Kubelet) GetKubeClient() clientset.Interface { // GetClusterDNS returns a list of the DNS servers and a list of the DNS search // domains of the cluster. -func (kl *Kubelet) GetClusterDNS(pod *api.Pod) ([]string, []string, error) { +func (kl *Kubelet) GetClusterDNS(pod *v1.Pod) ([]string, []string, error) { var hostDNS, hostSearch []string // Get host DNS settings if kl.resolverConfig != "" { @@ -1280,13 +1281,13 @@ func (kl *Kubelet) GetClusterDNS(pod *api.Pod) ([]string, []string, error) { return nil, nil, err } } - useClusterFirstPolicy := pod.Spec.DNSPolicy == api.DNSClusterFirst + useClusterFirstPolicy := pod.Spec.DNSPolicy == v1.DNSClusterFirst if useClusterFirstPolicy && kl.clusterDNS == nil { // clusterDNS is not known. // pod with ClusterDNSFirst Policy cannot be created - kl.recorder.Eventf(pod, api.EventTypeWarning, "MissingClusterDNS", "kubelet does not have ClusterDNS IP configured and cannot create Pod using %q policy. Falling back to DNSDefault policy.", pod.Spec.DNSPolicy) + kl.recorder.Eventf(pod, v1.EventTypeWarning, "MissingClusterDNS", "kubelet does not have ClusterDNS IP configured and cannot create Pod using %q policy. Falling back to DNSDefault policy.", pod.Spec.DNSPolicy) log := fmt.Sprintf("kubelet does not have ClusterDNS IP configured and cannot create Pod using %q policy. pod: %q. Falling back to DNSDefault policy.", pod.Spec.DNSPolicy, format.Pod(pod)) - kl.recorder.Eventf(kl.nodeRef, api.EventTypeWarning, "MissingClusterDNS", log) + kl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, "MissingClusterDNS", log) // fallback to DNSDefault useClusterFirstPolicy = false @@ -1331,7 +1332,7 @@ func (kl *Kubelet) GetClusterDNS(pod *api.Pod) ([]string, []string, error) { // // The workflow is: // * If the pod is being created, record pod worker start latency -// * Call generateAPIPodStatus to prepare an api.PodStatus for the pod +// * Call generateAPIPodStatus to prepare an v1.PodStatus for the pod // * If the pod is being seen as running for the first time, record pod // start latency // * Update the status of the pod in the status manager @@ -1398,7 +1399,7 @@ func (kl *Kubelet) syncPod(o syncPodOptions) error { // Record the time it takes for the pod to become running. existingStatus, ok := kl.statusManager.GetPodStatus(pod.UID) - if !ok || existingStatus.Phase == api.PodPending && apiPodStatus.Phase == api.PodRunning && + if !ok || existingStatus.Phase == v1.PodPending && apiPodStatus.Phase == v1.PodRunning && !firstSeenTime.IsZero() { metrics.PodStartLatency.Observe(metrics.SinceInMicroseconds(firstSeenTime)) } @@ -1426,7 +1427,7 @@ func (kl *Kubelet) syncPod(o syncPodOptions) error { kl.statusManager.SetPodStatus(pod, apiPodStatus) // Kill pod if it should not be running - if !runnable.Admit || pod.DeletionTimestamp != nil || apiPodStatus.Phase == api.PodFailed { + if !runnable.Admit || pod.DeletionTimestamp != nil || apiPodStatus.Phase == v1.PodFailed { var syncErr error if err := kl.killPod(pod, nil, podStatus, nil); err != nil { syncErr = fmt.Errorf("error killing pod: %v", err) @@ -1478,7 +1479,7 @@ func (kl *Kubelet) syncPod(o syncPodOptions) error { // expected to run only once and if the kubelet is restarted then // they are not expected to run again. // We don't create and apply updates to cgroup if its a run once pod and was killed above - if !(podKilled && pod.Spec.RestartPolicy == api.RestartPolicyNever) { + if !(podKilled && pod.Spec.RestartPolicy == v1.RestartPolicyNever) { if err := pcm.EnsureExists(pod); err != nil { return fmt.Errorf("failed to ensure that the pod: %v cgroups exist and are correctly applied: %v", pod.UID, err) } @@ -1517,7 +1518,7 @@ func (kl *Kubelet) syncPod(o syncPodOptions) error { // Wait for volumes to attach/mount if err := kl.volumeManager.WaitForAttachAndMount(pod); err != nil { - kl.recorder.Eventf(pod, api.EventTypeWarning, events.FailedMountVolume, "Unable to mount volumes for pod %q: %v", format.Pod(pod), err) + kl.recorder.Eventf(pod, v1.EventTypeWarning, events.FailedMountVolume, "Unable to mount volumes for pod %q: %v", format.Pod(pod), err) glog.Errorf("Unable to mount volumes for pod %q: %v; skipping pod", format.Pod(pod), err) return err } @@ -1548,13 +1549,13 @@ func (kl *Kubelet) syncPod(o syncPodOptions) error { } if egress != nil || ingress != nil { if podUsesHostNetwork(pod) { - kl.recorder.Event(pod, api.EventTypeWarning, events.HostNetworkNotSupported, "Bandwidth shaping is not currently supported on the host network") + kl.recorder.Event(pod, v1.EventTypeWarning, events.HostNetworkNotSupported, "Bandwidth shaping is not currently supported on the host network") } else if kl.shaper != nil { if len(apiPodStatus.PodIP) > 0 { err = kl.shaper.ReconcileCIDR(fmt.Sprintf("%s/32", apiPodStatus.PodIP), egress, ingress) } } else { - kl.recorder.Event(pod, api.EventTypeWarning, events.UndefinedShaper, "Pod requests bandwidth shaping, but the shaper is undefined") + kl.recorder.Event(pod, v1.EventTypeWarning, events.UndefinedShaper, "Pod requests bandwidth shaping, but the shaper is undefined") } } @@ -1564,14 +1565,14 @@ func (kl *Kubelet) syncPod(o syncPodOptions) error { // Get pods which should be resynchronized. Currently, the following pod should be resynchronized: // * pod whose work is ready. // * internal modules that request sync of a pod. -func (kl *Kubelet) getPodsToSync() []*api.Pod { +func (kl *Kubelet) getPodsToSync() []*v1.Pod { allPods := kl.podManager.GetPods() podUIDs := kl.workQueue.GetWork() podUIDSet := sets.NewString() for _, podUID := range podUIDs { podUIDSet.Insert(string(podUID)) } - var podsToSync []*api.Pod + var podsToSync []*v1.Pod for _, pod := range allPods { if podUIDSet.Has(string(pod.UID)) { // The work of the pod is ready @@ -1594,7 +1595,7 @@ func (kl *Kubelet) getPodsToSync() []*api.Pod { // // deletePod returns an error if not all sources are ready or the pod is not // found in the runtime cache. -func (kl *Kubelet) deletePod(pod *api.Pod) error { +func (kl *Kubelet) deletePod(pod *v1.Pod) error { if pod == nil { return fmt.Errorf("deletePod does not allow nil pod") } @@ -1647,10 +1648,10 @@ func (kl *Kubelet) isOutOfDisk() bool { // rejectPod records an event about the pod with the given reason and message, // and updates the pod to the failed phase in the status manage. -func (kl *Kubelet) rejectPod(pod *api.Pod, reason, message string) { - kl.recorder.Eventf(pod, api.EventTypeWarning, reason, message) - kl.statusManager.SetPodStatus(pod, api.PodStatus{ - Phase: api.PodFailed, +func (kl *Kubelet) rejectPod(pod *v1.Pod, reason, message string) { + kl.recorder.Eventf(pod, v1.EventTypeWarning, reason, message) + kl.statusManager.SetPodStatus(pod, v1.PodStatus{ + Phase: v1.PodFailed, Reason: reason, Message: "Pod " + message}) } @@ -1660,7 +1661,7 @@ func (kl *Kubelet) rejectPod(pod *api.Pod, reason, message string) { // The function returns a boolean value indicating whether the pod // can be admitted, a brief single-word reason and a message explaining why // the pod cannot be admitted. -func (kl *Kubelet) canAdmitPod(pods []*api.Pod, pod *api.Pod) (bool, string, string) { +func (kl *Kubelet) canAdmitPod(pods []*v1.Pod, pod *v1.Pod) (bool, string, string) { // the kubelet will invoke each pod admit handler in sequence // if any handler rejects, the pod is rejected. // TODO: move out of disk check into a pod admitter @@ -1681,7 +1682,7 @@ func (kl *Kubelet) canAdmitPod(pods []*api.Pod, pod *api.Pod) (bool, string, str return true, "", "" } -func (kl *Kubelet) canRunPod(pod *api.Pod) lifecycle.PodAdmitResult { +func (kl *Kubelet) canRunPod(pod *v1.Pod) lifecycle.PodAdmitResult { attrs := &lifecycle.PodAdmitAttributes{Pod: pod} // Get "OtherPods". Rejected pods are failed, so only include admitted pods that are alive. attrs.OtherPods = kl.filterOutTerminatedPods(kl.podManager.GetPods()) @@ -1813,7 +1814,7 @@ func (kl *Kubelet) syncLoopIteration(configCh <-chan kubetypes.PodUpdate, handle // PLEG event for a pod; sync it. if pod, ok := kl.podManager.GetPodByUID(e.ID); ok { glog.V(2).Infof("SyncLoop (PLEG): %q, event: %#v", format.Pod(pod), e) - handler.HandlePodSyncs([]*api.Pod{pod}) + handler.HandlePodSyncs([]*v1.Pod{pod}) } else { // If the pod no longer exists, ignore the event. glog.V(4).Infof("SyncLoop (PLEG): ignore irrelevant event: %#v", e) @@ -1846,7 +1847,7 @@ func (kl *Kubelet) syncLoopIteration(configCh <-chan kubetypes.PodUpdate, handle break } glog.V(1).Infof("SyncLoop (container unhealthy): %q", format.Pod(pod)) - handler.HandlePodSyncs([]*api.Pod{pod}) + handler.HandlePodSyncs([]*v1.Pod{pod}) } case <-housekeepingCh: if !kl.sourcesReady.AllReady() { @@ -1866,7 +1867,7 @@ func (kl *Kubelet) syncLoopIteration(configCh <-chan kubetypes.PodUpdate, handle // dispatchWork starts the asynchronous sync of the pod in a pod worker. // If the pod is terminated, dispatchWork -func (kl *Kubelet) dispatchWork(pod *api.Pod, syncType kubetypes.SyncPodType, mirrorPod *api.Pod, start time.Time) { +func (kl *Kubelet) dispatchWork(pod *v1.Pod, syncType kubetypes.SyncPodType, mirrorPod *v1.Pod, start time.Time) { if kl.podIsTerminated(pod) { if pod.DeletionTimestamp != nil { // If the pod is in a terminated state, there is no pod worker to @@ -1895,7 +1896,7 @@ func (kl *Kubelet) dispatchWork(pod *api.Pod, syncType kubetypes.SyncPodType, mi } // TODO: handle mirror pods in a separate component (issue #17251) -func (kl *Kubelet) handleMirrorPod(mirrorPod *api.Pod, start time.Time) { +func (kl *Kubelet) handleMirrorPod(mirrorPod *v1.Pod, start time.Time) { // Mirror pod ADD/UPDATE/DELETE operations are considered an UPDATE to the // corresponding static pod. Send update to the pod worker if the static // pod exists. @@ -1906,7 +1907,7 @@ func (kl *Kubelet) handleMirrorPod(mirrorPod *api.Pod, start time.Time) { // HandlePodAdditions is the callback in SyncHandler for pods being added from // a config source. -func (kl *Kubelet) HandlePodAdditions(pods []*api.Pod) { +func (kl *Kubelet) HandlePodAdditions(pods []*v1.Pod) { start := kl.clock.Now() sort.Sort(sliceutils.PodsByCreationTime(pods)) for _, pod := range pods { @@ -1934,7 +1935,7 @@ func (kl *Kubelet) HandlePodAdditions(pods []*api.Pod) { // HandlePodUpdates is the callback in the SyncHandler interface for pods // being updated from a config source. -func (kl *Kubelet) HandlePodUpdates(pods []*api.Pod) { +func (kl *Kubelet) HandlePodUpdates(pods []*v1.Pod) { start := kl.clock.Now() for _, pod := range pods { kl.podManager.UpdatePod(pod) @@ -1951,7 +1952,7 @@ func (kl *Kubelet) HandlePodUpdates(pods []*api.Pod) { // HandlePodRemoves is the callback in the SyncHandler interface for pods // being removed from a config source. -func (kl *Kubelet) HandlePodRemoves(pods []*api.Pod) { +func (kl *Kubelet) HandlePodRemoves(pods []*v1.Pod) { start := kl.clock.Now() for _, pod := range pods { kl.podManager.DeletePod(pod) @@ -1970,7 +1971,7 @@ func (kl *Kubelet) HandlePodRemoves(pods []*api.Pod) { // HandlePodReconcile is the callback in the SyncHandler interface for pods // that should be reconciled. -func (kl *Kubelet) HandlePodReconcile(pods []*api.Pod) { +func (kl *Kubelet) HandlePodReconcile(pods []*v1.Pod) { for _, pod := range pods { // Update the pod in pod manager, status manager will do periodically reconcile according // to the pod manager. @@ -1987,7 +1988,7 @@ func (kl *Kubelet) HandlePodReconcile(pods []*api.Pod) { // HandlePodSyncs is the callback in the syncHandler interface for pods // that should be dispatched to pod workers for sync. -func (kl *Kubelet) HandlePodSyncs(pods []*api.Pod) { +func (kl *Kubelet) HandlePodSyncs(pods []*v1.Pod) { start := kl.clock.Now() for _, pod := range pods { mirrorPod, _ := kl.podManager.GetMirrorPodByPod(pod) @@ -2054,7 +2055,7 @@ func (kl *Kubelet) updateRuntimeUp() { // updateCloudProviderFromMachineInfo updates the node's provider ID field // from the given cadvisor machine info. -func (kl *Kubelet) updateCloudProviderFromMachineInfo(node *api.Node, info *cadvisorapi.MachineInfo) { +func (kl *Kubelet) updateCloudProviderFromMachineInfo(node *v1.Node, info *cadvisorapi.MachineInfo) { if info.CloudProvider != cadvisorapi.UnknownProvider && info.CloudProvider != cadvisorapi.Baremetal { // The cloud providers from pkg/cloudprovider/providers/* that update ProviderID @@ -2074,7 +2075,7 @@ func (kl *Kubelet) GetConfiguration() componentconfig.KubeletConfiguration { // BirthCry sends an event that the kubelet has started up. func (kl *Kubelet) BirthCry() { // Make an event that kubelet restarted. - kl.recorder.Eventf(kl.nodeRef, api.EventTypeNormal, events.StartingKubelet, "Starting kubelet.") + kl.recorder.Eventf(kl.nodeRef, v1.EventTypeNormal, events.StartingKubelet, "Starting kubelet.") } // StreamingConnectionIdleTimeout returns the timeout for streaming connections to the HTTP server. @@ -2117,12 +2118,12 @@ func isSyncPodWorthy(event *pleg.PodLifecycleEvent) bool { // parseResourceList parses the given configuration map into an API // ResourceList or returns an error. -func parseResourceList(m utilconfig.ConfigurationMap) (api.ResourceList, error) { - rl := make(api.ResourceList) +func parseResourceList(m utilconfig.ConfigurationMap) (v1.ResourceList, error) { + rl := make(v1.ResourceList) for k, v := range m { - switch api.ResourceName(k) { + switch v1.ResourceName(k) { // Only CPU and memory resources are supported. - case api.ResourceCPU, api.ResourceMemory: + case v1.ResourceCPU, v1.ResourceMemory: q, err := resource.ParseQuantity(v) if err != nil { return nil, err @@ -2130,7 +2131,7 @@ func parseResourceList(m utilconfig.ConfigurationMap) (api.ResourceList, error) if q.Sign() == -1 { return nil, fmt.Errorf("resource quantity for %q cannot be negative: %v", k, v) } - rl[api.ResourceName(k)] = q + rl[v1.ResourceName(k)] = q default: return nil, fmt.Errorf("cannot reserve %q resource", k) } diff --git a/pkg/kubelet/kubelet_getters.go b/pkg/kubelet/kubelet_getters.go index 0eb55d826ca..df0a44fca93 100644 --- a/pkg/kubelet/kubelet_getters.go +++ b/pkg/kubelet/kubelet_getters.go @@ -24,7 +24,7 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/cmd/kubelet/app/options" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/cm" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/types" @@ -142,21 +142,21 @@ func (kl *Kubelet) getPodContainerDir(podUID types.UID, ctrName string) string { // GetPods returns all pods bound to the kubelet and their spec, and the mirror // pods. -func (kl *Kubelet) GetPods() []*api.Pod { +func (kl *Kubelet) GetPods() []*v1.Pod { return kl.podManager.GetPods() } // GetRunningPods returns all pods running on kubelet from looking at the // container runtime cache. This function converts kubecontainer.Pod to -// api.Pod, so only the fields that exist in both kubecontainer.Pod and -// api.Pod are considered meaningful. -func (kl *Kubelet) GetRunningPods() ([]*api.Pod, error) { +// v1.Pod, so only the fields that exist in both kubecontainer.Pod and +// v1.Pod are considered meaningful. +func (kl *Kubelet) GetRunningPods() ([]*v1.Pod, error) { pods, err := kl.runtimeCache.GetPods() if err != nil { return nil, err } - apiPods := make([]*api.Pod, 0, len(pods)) + apiPods := make([]*v1.Pod, 0, len(pods)) for _, pod := range pods { apiPods = append(apiPods, pod.ToAPIPod()) } @@ -165,13 +165,13 @@ func (kl *Kubelet) GetRunningPods() ([]*api.Pod, error) { // GetPodByFullName gets the pod with the given 'full' name, which // incorporates the namespace as well as whether the pod was found. -func (kl *Kubelet) GetPodByFullName(podFullName string) (*api.Pod, bool) { +func (kl *Kubelet) GetPodByFullName(podFullName string) (*v1.Pod, bool) { return kl.podManager.GetPodByFullName(podFullName) } // GetPodByName provides the first pod that matches namespace and name, as well // as whether the pod was found. -func (kl *Kubelet) GetPodByName(namespace, name string) (*api.Pod, bool) { +func (kl *Kubelet) GetPodByName(namespace, name string) (*v1.Pod, bool) { return kl.podManager.GetPodByName(namespace, name) } @@ -187,19 +187,19 @@ func (kl *Kubelet) GetRuntime() kubecontainer.Runtime { } // GetNode returns the node info for the configured node name of this Kubelet. -func (kl *Kubelet) GetNode() (*api.Node, error) { +func (kl *Kubelet) GetNode() (*v1.Node, error) { if kl.standaloneMode { return kl.initialNode() } return kl.nodeInfo.GetNodeInfo(string(kl.nodeName)) } -// getNodeAnyWay() must return a *api.Node which is required by RunGeneralPredicates(). -// The *api.Node is obtained as follows: +// getNodeAnyWay() must return a *v1.Node which is required by RunGeneralPredicates(). +// The *v1.Node is obtained as follows: // Return kubelet's nodeInfo for this node, except on error or if in standalone mode, // in which case return a manufactured nodeInfo representing a node with no pods, // zero capacity, and the default labels. -func (kl *Kubelet) getNodeAnyWay() (*api.Node, error) { +func (kl *Kubelet) getNodeAnyWay() (*v1.Node, error) { if !kl.standaloneMode { if n, err := kl.nodeInfo.GetNodeInfo(string(kl.nodeName)); err == nil { return n, nil @@ -235,7 +235,7 @@ func (kl *Kubelet) getHostIPAnyWay() (net.IP, error) { // GetExtraSupplementalGroupsForPod returns a list of the extra // supplemental groups for the Pod. These extra supplemental groups come // from annotations on persistent volumes that the pod depends on. -func (kl *Kubelet) GetExtraSupplementalGroupsForPod(pod *api.Pod) []int64 { +func (kl *Kubelet) GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64 { return kl.volumeManager.GetExtraSupplementalGroupsForPod(pod) } diff --git a/pkg/kubelet/kubelet_network.go b/pkg/kubelet/kubelet_network.go index 8267560841b..db1538969d8 100644 --- a/pkg/kubelet/kubelet_network.go +++ b/pkg/kubelet/kubelet_network.go @@ -23,7 +23,7 @@ import ( "strings" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" "k8s.io/kubernetes/pkg/kubelet/network" "k8s.io/kubernetes/pkg/util/bandwidth" @@ -146,7 +146,7 @@ func parseResolvConf(reader io.Reader, dnsScrubber dnsScrubber) (nameservers []s // cleanupBandwidthLimits updates the status of bandwidth-limited containers // and ensures that only the appropriate CIDRs are active on the node. -func (kl *Kubelet) cleanupBandwidthLimits(allPods []*api.Pod) error { +func (kl *Kubelet) cleanupBandwidthLimits(allPods []*v1.Pod) error { if kl.shaper == nil { return nil } @@ -174,7 +174,7 @@ func (kl *Kubelet) cleanupBandwidthLimits(allPods []*api.Pod) error { } status = kl.generateAPIPodStatus(pod, s) } - if status.Phase == api.PodRunning { + if status.Phase == v1.PodRunning { possibleCIDRs.Insert(fmt.Sprintf("%s/32", status.PodIP)) } } diff --git a/pkg/kubelet/kubelet_network_test.go b/pkg/kubelet/kubelet_network_test.go index dbb3fa1cba8..6c36d2d7dd3 100644 --- a/pkg/kubelet/kubelet_network_test.go +++ b/pkg/kubelet/kubelet_network_test.go @@ -22,7 +22,7 @@ import ( "strings" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/bandwidth" ) @@ -137,7 +137,7 @@ func TestParseResolvConf(t *testing.T) { } func TestCleanupBandwidthLimits(t *testing.T) { - testPod := func(name, ingress string) *api.Pod { + testPod := func(name, ingress string) *v1.Pod { pod := podWithUidNameNs("", name, "") if len(ingress) != 0 { @@ -150,18 +150,18 @@ func TestCleanupBandwidthLimits(t *testing.T) { // TODO(random-liu): We removed the test case for pod status not cached here. We should add a higher // layer status getter function and test that function instead. tests := []struct { - status *api.PodStatus - pods []*api.Pod + status *v1.PodStatus + pods []*v1.Pod inputCIDRs []string expectResetCIDRs []string name string }{ { - status: &api.PodStatus{ + status: &v1.PodStatus{ PodIP: "1.2.3.4", - Phase: api.PodRunning, + Phase: v1.PodRunning, }, - pods: []*api.Pod{ + pods: []*v1.Pod{ testPod("foo", "10M"), testPod("bar", ""), }, @@ -170,11 +170,11 @@ func TestCleanupBandwidthLimits(t *testing.T) { name: "pod running", }, { - status: &api.PodStatus{ + status: &v1.PodStatus{ PodIP: "1.2.3.4", - Phase: api.PodFailed, + Phase: v1.PodFailed, }, - pods: []*api.Pod{ + pods: []*v1.Pod{ testPod("foo", "10M"), testPod("bar", ""), }, @@ -183,11 +183,11 @@ func TestCleanupBandwidthLimits(t *testing.T) { name: "pod not running", }, { - status: &api.PodStatus{ + status: &v1.PodStatus{ PodIP: "1.2.3.4", - Phase: api.PodFailed, + Phase: v1.PodFailed, }, - pods: []*api.Pod{ + pods: []*v1.Pod{ testPod("foo", ""), testPod("bar", ""), }, diff --git a/pkg/kubelet/kubelet_node_status.go b/pkg/kubelet/kubelet_node_status.go index ec8f52f6ddf..0b353d005c0 100644 --- a/pkg/kubelet/kubelet_node_status.go +++ b/pkg/kubelet/kubelet_node_status.go @@ -26,10 +26,10 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/kubelet/cadvisor" @@ -67,7 +67,7 @@ func (kl *Kubelet) registerWithApiServer() { node, err := kl.initialNode() if err != nil { - glog.Errorf("Unable to construct api.Node object for kubelet: %v", err) + glog.Errorf("Unable to construct v1.Node object for kubelet: %v", err) continue } @@ -88,7 +88,7 @@ func (kl *Kubelet) registerWithApiServer() { // persistent volumes for the node. If a node of the same name exists but has // a different externalID value, it attempts to delete that node so that a // later attempt can recreate it. -func (kl *Kubelet) tryRegisterWithApiServer(node *api.Node) bool { +func (kl *Kubelet) tryRegisterWithApiServer(node *v1.Node) bool { _, err := kl.kubeClient.Core().Nodes().Create(node) if err == nil { return true @@ -142,7 +142,7 @@ func (kl *Kubelet) tryRegisterWithApiServer(node *api.Node) bool { // reconcileCMADAnnotationWithExistingNode reconciles the controller-managed // attach-detach annotation on a new node and the existing node, returning // whether the existing node must be updated. -func (kl *Kubelet) reconcileCMADAnnotationWithExistingNode(node, existingNode *api.Node) bool { +func (kl *Kubelet) reconcileCMADAnnotationWithExistingNode(node, existingNode *v1.Node) bool { var ( existingCMAAnnotation = existingNode.Annotations[volumehelper.ControllerManagedAttachAnnotation] newCMAAnnotation, newSet = node.Annotations[volumehelper.ControllerManagedAttachAnnotation] @@ -169,11 +169,11 @@ func (kl *Kubelet) reconcileCMADAnnotationWithExistingNode(node, existingNode *a return true } -// initialNode constructs the initial api.Node for this Kubelet, incorporating node +// initialNode constructs the initial v1.Node for this Kubelet, incorporating node // labels, information from the cloud provider, and Kubelet configuration. -func (kl *Kubelet) initialNode() (*api.Node, error) { - node := &api.Node{ - ObjectMeta: api.ObjectMeta{ +func (kl *Kubelet) initialNode() (*v1.Node, error) { + node := &v1.Node{ + ObjectMeta: v1.ObjectMeta{ Name: string(kl.nodeName), Labels: map[string]string{ unversioned.LabelHostname: kl.hostname, @@ -181,15 +181,15 @@ func (kl *Kubelet) initialNode() (*api.Node, error) { unversioned.LabelArch: goRuntime.GOARCH, }, }, - Spec: api.NodeSpec{ + Spec: v1.NodeSpec{ Unschedulable: !kl.registerSchedulable, }, } // Initially, set NodeNetworkUnavailable to true. if kl.providerRequiresNetworkingConfiguration() { - node.Status.Conditions = append(node.Status.Conditions, api.NodeCondition{ - Type: api.NodeNetworkUnavailable, - Status: api.ConditionTrue, + node.Status.Conditions = append(node.Status.Conditions, v1.NodeCondition{ + Type: v1.NodeNetworkUnavailable, + Status: v1.ConditionTrue, Reason: "NoRouteCreated", Message: "Node created without a route", LastTransitionTime: unversioned.NewTime(kl.clock.Now()), @@ -320,8 +320,8 @@ func (kl *Kubelet) tryUpdateNodeStatus() error { // field selector for the name of the node (field selectors with // specified name are handled efficiently by apiserver). Once // apiserver supports GET from cache, change it here. - opts := api.ListOptions{ - FieldSelector: fields.Set{"metadata.name": string(kl.nodeName)}.AsSelector(), + opts := v1.ListOptions{ + FieldSelector: fields.Set{"metadata.name": string(kl.nodeName)}.AsSelector().String(), ResourceVersion: "0", } nodes, err := kl.kubeClient.Core().Nodes().List(opts) @@ -359,7 +359,7 @@ func (kl *Kubelet) recordNodeStatusEvent(eventtype, event string) { } // Set IP and hostname addresses for the node. -func (kl *Kubelet) setNodeAddress(node *api.Node) error { +func (kl *Kubelet) setNodeAddress(node *v1.Node) error { if kl.nodeIP != nil { if err := kl.validateNodeIP(); err != nil { return fmt.Errorf("failed to validate nodeIP: %v", err) @@ -383,9 +383,9 @@ func (kl *Kubelet) setNodeAddress(node *api.Node) error { if kl.nodeIP != nil { for _, nodeAddress := range nodeAddresses { if nodeAddress.Address == kl.nodeIP.String() { - node.Status.Addresses = []api.NodeAddress{ + node.Status.Addresses = []v1.NodeAddress{ {Type: nodeAddress.Type, Address: nodeAddress.Address}, - {Type: api.NodeHostName, Address: kl.GetHostname()}, + {Type: v1.NodeHostName, Address: kl.GetHostname()}, } return nil } @@ -395,15 +395,15 @@ func (kl *Kubelet) setNodeAddress(node *api.Node) error { // Only add a NodeHostName address if the cloudprovider did not specify one // (we assume the cloudprovider knows best) - var addressNodeHostName *api.NodeAddress + var addressNodeHostName *v1.NodeAddress for i := range nodeAddresses { - if nodeAddresses[i].Type == api.NodeHostName { + if nodeAddresses[i].Type == v1.NodeHostName { addressNodeHostName = &nodeAddresses[i] break } } if addressNodeHostName == nil { - hostnameAddress := api.NodeAddress{Type: api.NodeHostName, Address: kl.GetHostname()} + hostnameAddress := v1.NodeAddress{Type: v1.NodeHostName, Address: kl.GetHostname()} nodeAddresses = append(nodeAddresses, hostnameAddress) } else { glog.V(2).Infof("Using Node Hostname from cloudprovider: %q", addressNodeHostName.Address) @@ -440,21 +440,21 @@ func (kl *Kubelet) setNodeAddress(node *api.Node) error { // We tried everything we could, but the IP address wasn't fetchable; error out return fmt.Errorf("can't get ip address of node %s. error: %v", node.Name, err) } else { - node.Status.Addresses = []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: ipAddr.String()}, - {Type: api.NodeInternalIP, Address: ipAddr.String()}, - {Type: api.NodeHostName, Address: kl.GetHostname()}, + node.Status.Addresses = []v1.NodeAddress{ + {Type: v1.NodeLegacyHostIP, Address: ipAddr.String()}, + {Type: v1.NodeInternalIP, Address: ipAddr.String()}, + {Type: v1.NodeHostName, Address: kl.GetHostname()}, } } } return nil } -func (kl *Kubelet) setNodeStatusMachineInfo(node *api.Node) { +func (kl *Kubelet) setNodeStatusMachineInfo(node *v1.Node) { // Note: avoid blindly overwriting the capacity in case opaque // resources are being advertised. if node.Status.Capacity == nil { - node.Status.Capacity = api.ResourceList{} + node.Status.Capacity = v1.ResourceList{} } // TODO: Post NotReady if we cannot get MachineInfo from cAdvisor. This needs to start @@ -463,10 +463,10 @@ func (kl *Kubelet) setNodeStatusMachineInfo(node *api.Node) { if err != nil { // TODO(roberthbailey): This is required for test-cmd.sh to pass. // See if the test should be updated instead. - node.Status.Capacity[api.ResourceCPU] = *resource.NewMilliQuantity(0, resource.DecimalSI) - node.Status.Capacity[api.ResourceMemory] = resource.MustParse("0Gi") - node.Status.Capacity[api.ResourcePods] = *resource.NewQuantity(int64(kl.maxPods), resource.DecimalSI) - node.Status.Capacity[api.ResourceNvidiaGPU] = *resource.NewQuantity(int64(kl.nvidiaGPUs), resource.DecimalSI) + node.Status.Capacity[v1.ResourceCPU] = *resource.NewMilliQuantity(0, resource.DecimalSI) + node.Status.Capacity[v1.ResourceMemory] = resource.MustParse("0Gi") + node.Status.Capacity[v1.ResourcePods] = *resource.NewQuantity(int64(kl.maxPods), resource.DecimalSI) + node.Status.Capacity[v1.ResourceNvidiaGPU] = *resource.NewQuantity(int64(kl.nvidiaGPUs), resource.DecimalSI) glog.Errorf("Error getting machine info: %v", err) } else { @@ -478,26 +478,26 @@ func (kl *Kubelet) setNodeStatusMachineInfo(node *api.Node) { } if kl.podsPerCore > 0 { - node.Status.Capacity[api.ResourcePods] = *resource.NewQuantity( + node.Status.Capacity[v1.ResourcePods] = *resource.NewQuantity( int64(math.Min(float64(info.NumCores*kl.podsPerCore), float64(kl.maxPods))), resource.DecimalSI) } else { - node.Status.Capacity[api.ResourcePods] = *resource.NewQuantity( + node.Status.Capacity[v1.ResourcePods] = *resource.NewQuantity( int64(kl.maxPods), resource.DecimalSI) } - node.Status.Capacity[api.ResourceNvidiaGPU] = *resource.NewQuantity( + node.Status.Capacity[v1.ResourceNvidiaGPU] = *resource.NewQuantity( int64(kl.nvidiaGPUs), resource.DecimalSI) if node.Status.NodeInfo.BootID != "" && node.Status.NodeInfo.BootID != info.BootID { // TODO: This requires a transaction, either both node status is updated // and event is recorded or neither should happen, see issue #6055. - kl.recorder.Eventf(kl.nodeRef, api.EventTypeWarning, events.NodeRebooted, + kl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, events.NodeRebooted, "Node %s has been rebooted, boot id: %s", kl.nodeName, info.BootID) } node.Status.NodeInfo.BootID = info.BootID } // Set Allocatable. - node.Status.Allocatable = make(api.ResourceList) + node.Status.Allocatable = make(v1.ResourceList) for k, v := range node.Status.Capacity { value := *(v.Copy()) if kl.reservation.System != nil { @@ -515,7 +515,7 @@ func (kl *Kubelet) setNodeStatusMachineInfo(node *api.Node) { } // Set versioninfo for the node. -func (kl *Kubelet) setNodeStatusVersionInfo(node *api.Node) { +func (kl *Kubelet) setNodeStatusVersionInfo(node *v1.Node) { verinfo, err := kl.cadvisor.VersionInfo() if err != nil { glog.Errorf("Error getting version info: %v", err) @@ -537,14 +537,14 @@ func (kl *Kubelet) setNodeStatusVersionInfo(node *api.Node) { } // Set daemonEndpoints for the node. -func (kl *Kubelet) setNodeStatusDaemonEndpoints(node *api.Node) { +func (kl *Kubelet) setNodeStatusDaemonEndpoints(node *v1.Node) { node.Status.DaemonEndpoints = *kl.daemonEndpoints } // Set images list for the node -func (kl *Kubelet) setNodeStatusImages(node *api.Node) { +func (kl *Kubelet) setNodeStatusImages(node *v1.Node) { // Update image list of this node - var imagesOnNode []api.ContainerImage + var imagesOnNode []v1.ContainerImage containerImages, err := kl.imageManager.GetImageList() if err != nil { glog.Errorf("Error getting image list: %v", err) @@ -561,7 +561,7 @@ func (kl *Kubelet) setNodeStatusImages(node *api.Node) { if len(names) > maxNamesPerImageInNodeStatus { names = names[0:maxNamesPerImageInNodeStatus] } - imagesOnNode = append(imagesOnNode, api.ContainerImage{ + imagesOnNode = append(imagesOnNode, v1.ContainerImage{ Names: names, SizeBytes: image.Size, }) @@ -571,13 +571,13 @@ func (kl *Kubelet) setNodeStatusImages(node *api.Node) { } // Set the GOOS and GOARCH for this node -func (kl *Kubelet) setNodeStatusGoRuntime(node *api.Node) { +func (kl *Kubelet) setNodeStatusGoRuntime(node *v1.Node) { node.Status.NodeInfo.OperatingSystem = goRuntime.GOOS node.Status.NodeInfo.Architecture = goRuntime.GOARCH } // Set status for the node. -func (kl *Kubelet) setNodeStatusInfo(node *api.Node) { +func (kl *Kubelet) setNodeStatusInfo(node *v1.Node) { kl.setNodeStatusMachineInfo(node) kl.setNodeStatusVersionInfo(node) kl.setNodeStatusDaemonEndpoints(node) @@ -586,25 +586,25 @@ func (kl *Kubelet) setNodeStatusInfo(node *api.Node) { } // Set Ready condition for the node. -func (kl *Kubelet) setNodeReadyCondition(node *api.Node) { +func (kl *Kubelet) setNodeReadyCondition(node *v1.Node) { // NOTE(aaronlevy): NodeReady condition needs to be the last in the list of node conditions. // This is due to an issue with version skewed kubelet and master components. // ref: https://github.com/kubernetes/kubernetes/issues/16961 currentTime := unversioned.NewTime(kl.clock.Now()) - var newNodeReadyCondition api.NodeCondition + var newNodeReadyCondition v1.NodeCondition rs := append(kl.runtimeState.runtimeErrors(), kl.runtimeState.networkErrors()...) if len(rs) == 0 { - newNodeReadyCondition = api.NodeCondition{ - Type: api.NodeReady, - Status: api.ConditionTrue, + newNodeReadyCondition = v1.NodeCondition{ + Type: v1.NodeReady, + Status: v1.ConditionTrue, Reason: "KubeletReady", Message: "kubelet is posting ready status", LastHeartbeatTime: currentTime, } } else { - newNodeReadyCondition = api.NodeCondition{ - Type: api.NodeReady, - Status: api.ConditionFalse, + newNodeReadyCondition = v1.NodeCondition{ + Type: v1.NodeReady, + Status: v1.ConditionFalse, Reason: "KubeletNotReady", Message: strings.Join(rs, ","), LastHeartbeatTime: currentTime, @@ -613,7 +613,7 @@ func (kl *Kubelet) setNodeReadyCondition(node *api.Node) { // Append AppArmor status if it's enabled. // TODO(timstclair): This is a temporary message until node feature reporting is added. - if newNodeReadyCondition.Status == api.ConditionTrue && + if newNodeReadyCondition.Status == v1.ConditionTrue && kl.appArmorValidator != nil && kl.appArmorValidator.ValidateHost() == nil { newNodeReadyCondition.Message = fmt.Sprintf("%s. AppArmor enabled", newNodeReadyCondition.Message) } @@ -627,7 +627,7 @@ func (kl *Kubelet) setNodeReadyCondition(node *api.Node) { readyConditionUpdated := false needToRecordEvent := false for i := range node.Status.Conditions { - if node.Status.Conditions[i].Type == api.NodeReady { + if node.Status.Conditions[i].Type == v1.NodeReady { if node.Status.Conditions[i].Status == newNodeReadyCondition.Status { newNodeReadyCondition.LastTransitionTime = node.Status.Conditions[i].LastTransitionTime } else { @@ -644,23 +644,23 @@ func (kl *Kubelet) setNodeReadyCondition(node *api.Node) { node.Status.Conditions = append(node.Status.Conditions, newNodeReadyCondition) } if needToRecordEvent { - if newNodeReadyCondition.Status == api.ConditionTrue { - kl.recordNodeStatusEvent(api.EventTypeNormal, events.NodeReady) + if newNodeReadyCondition.Status == v1.ConditionTrue { + kl.recordNodeStatusEvent(v1.EventTypeNormal, events.NodeReady) } else { - kl.recordNodeStatusEvent(api.EventTypeNormal, events.NodeNotReady) + kl.recordNodeStatusEvent(v1.EventTypeNormal, events.NodeNotReady) } } } // setNodeMemoryPressureCondition for the node. // TODO: this needs to move somewhere centralized... -func (kl *Kubelet) setNodeMemoryPressureCondition(node *api.Node) { +func (kl *Kubelet) setNodeMemoryPressureCondition(node *v1.Node) { currentTime := unversioned.NewTime(kl.clock.Now()) - var condition *api.NodeCondition + var condition *v1.NodeCondition // Check if NodeMemoryPressure condition already exists and if it does, just pick it up for update. for i := range node.Status.Conditions { - if node.Status.Conditions[i].Type == api.NodeMemoryPressure { + if node.Status.Conditions[i].Type == v1.NodeMemoryPressure { condition = &node.Status.Conditions[i] } } @@ -668,9 +668,9 @@ func (kl *Kubelet) setNodeMemoryPressureCondition(node *api.Node) { newCondition := false // If the NodeMemoryPressure condition doesn't exist, create one if condition == nil { - condition = &api.NodeCondition{ - Type: api.NodeMemoryPressure, - Status: api.ConditionUnknown, + condition = &v1.NodeCondition{ + Type: v1.NodeMemoryPressure, + Status: v1.ConditionUnknown, } // cannot be appended to node.Status.Conditions here because it gets // copied to the slice. So if we append to the slice here none of the @@ -683,25 +683,25 @@ func (kl *Kubelet) setNodeMemoryPressureCondition(node *api.Node) { // Note: The conditions below take care of the case when a new NodeMemoryPressure condition is // created and as well as the case when the condition already exists. When a new condition - // is created its status is set to api.ConditionUnknown which matches either - // condition.Status != api.ConditionTrue or - // condition.Status != api.ConditionFalse in the conditions below depending on whether + // is created its status is set to v1.ConditionUnknown which matches either + // condition.Status != v1.ConditionTrue or + // condition.Status != v1.ConditionFalse in the conditions below depending on whether // the kubelet is under memory pressure or not. if kl.evictionManager.IsUnderMemoryPressure() { - if condition.Status != api.ConditionTrue { - condition.Status = api.ConditionTrue + if condition.Status != v1.ConditionTrue { + condition.Status = v1.ConditionTrue condition.Reason = "KubeletHasInsufficientMemory" condition.Message = "kubelet has insufficient memory available" condition.LastTransitionTime = currentTime - kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasInsufficientMemory") + kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasInsufficientMemory") } } else { - if condition.Status != api.ConditionFalse { - condition.Status = api.ConditionFalse + if condition.Status != v1.ConditionFalse { + condition.Status = v1.ConditionFalse condition.Reason = "KubeletHasSufficientMemory" condition.Message = "kubelet has sufficient memory available" condition.LastTransitionTime = currentTime - kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasSufficientMemory") + kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasSufficientMemory") } } @@ -712,13 +712,13 @@ func (kl *Kubelet) setNodeMemoryPressureCondition(node *api.Node) { // setNodeDiskPressureCondition for the node. // TODO: this needs to move somewhere centralized... -func (kl *Kubelet) setNodeDiskPressureCondition(node *api.Node) { +func (kl *Kubelet) setNodeDiskPressureCondition(node *v1.Node) { currentTime := unversioned.NewTime(kl.clock.Now()) - var condition *api.NodeCondition + var condition *v1.NodeCondition // Check if NodeDiskPressure condition already exists and if it does, just pick it up for update. for i := range node.Status.Conditions { - if node.Status.Conditions[i].Type == api.NodeDiskPressure { + if node.Status.Conditions[i].Type == v1.NodeDiskPressure { condition = &node.Status.Conditions[i] } } @@ -726,9 +726,9 @@ func (kl *Kubelet) setNodeDiskPressureCondition(node *api.Node) { newCondition := false // If the NodeDiskPressure condition doesn't exist, create one if condition == nil { - condition = &api.NodeCondition{ - Type: api.NodeDiskPressure, - Status: api.ConditionUnknown, + condition = &v1.NodeCondition{ + Type: v1.NodeDiskPressure, + Status: v1.ConditionUnknown, } // cannot be appended to node.Status.Conditions here because it gets // copied to the slice. So if we append to the slice here none of the @@ -741,25 +741,25 @@ func (kl *Kubelet) setNodeDiskPressureCondition(node *api.Node) { // Note: The conditions below take care of the case when a new NodeDiskressure condition is // created and as well as the case when the condition already exists. When a new condition - // is created its status is set to api.ConditionUnknown which matches either - // condition.Status != api.ConditionTrue or - // condition.Status != api.ConditionFalse in the conditions below depending on whether + // is created its status is set to v1.ConditionUnknown which matches either + // condition.Status != v1.ConditionTrue or + // condition.Status != v1.ConditionFalse in the conditions below depending on whether // the kubelet is under disk pressure or not. if kl.evictionManager.IsUnderDiskPressure() { - if condition.Status != api.ConditionTrue { - condition.Status = api.ConditionTrue + if condition.Status != v1.ConditionTrue { + condition.Status = v1.ConditionTrue condition.Reason = "KubeletHasDiskPressure" condition.Message = "kubelet has disk pressure" condition.LastTransitionTime = currentTime - kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasDiskPressure") + kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasDiskPressure") } } else { - if condition.Status != api.ConditionFalse { - condition.Status = api.ConditionFalse + if condition.Status != v1.ConditionFalse { + condition.Status = v1.ConditionFalse condition.Reason = "KubeletHasNoDiskPressure" condition.Message = "kubelet has no disk pressure" condition.LastTransitionTime = currentTime - kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasNoDiskPressure") + kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasNoDiskPressure") } } @@ -769,13 +769,13 @@ func (kl *Kubelet) setNodeDiskPressureCondition(node *api.Node) { } // Set OODcondition for the node. -func (kl *Kubelet) setNodeOODCondition(node *api.Node) { +func (kl *Kubelet) setNodeOODCondition(node *v1.Node) { currentTime := unversioned.NewTime(kl.clock.Now()) - var nodeOODCondition *api.NodeCondition + var nodeOODCondition *v1.NodeCondition // Check if NodeOutOfDisk condition already exists and if it does, just pick it up for update. for i := range node.Status.Conditions { - if node.Status.Conditions[i].Type == api.NodeOutOfDisk { + if node.Status.Conditions[i].Type == v1.NodeOutOfDisk { nodeOODCondition = &node.Status.Conditions[i] } } @@ -783,9 +783,9 @@ func (kl *Kubelet) setNodeOODCondition(node *api.Node) { newOODCondition := false // If the NodeOutOfDisk condition doesn't exist, create one. if nodeOODCondition == nil { - nodeOODCondition = &api.NodeCondition{ - Type: api.NodeOutOfDisk, - Status: api.ConditionUnknown, + nodeOODCondition = &v1.NodeCondition{ + Type: v1.NodeOutOfDisk, + Status: v1.ConditionUnknown, } // nodeOODCondition cannot be appended to node.Status.Conditions here because it gets // copied to the slice. So if we append nodeOODCondition to the slice here none of the @@ -798,29 +798,29 @@ func (kl *Kubelet) setNodeOODCondition(node *api.Node) { // Note: The conditions below take care of the case when a new NodeOutOfDisk condition is // created and as well as the case when the condition already exists. When a new condition - // is created its status is set to api.ConditionUnknown which matches either - // nodeOODCondition.Status != api.ConditionTrue or - // nodeOODCondition.Status != api.ConditionFalse in the conditions below depending on whether + // is created its status is set to v1.ConditionUnknown which matches either + // nodeOODCondition.Status != v1.ConditionTrue or + // nodeOODCondition.Status != v1.ConditionFalse in the conditions below depending on whether // the kubelet is out of disk or not. if kl.isOutOfDisk() { - if nodeOODCondition.Status != api.ConditionTrue { - nodeOODCondition.Status = api.ConditionTrue + if nodeOODCondition.Status != v1.ConditionTrue { + nodeOODCondition.Status = v1.ConditionTrue nodeOODCondition.Reason = "KubeletOutOfDisk" nodeOODCondition.Message = "out of disk space" nodeOODCondition.LastTransitionTime = currentTime - kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeOutOfDisk") + kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeOutOfDisk") } } else { - if nodeOODCondition.Status != api.ConditionFalse { + if nodeOODCondition.Status != v1.ConditionFalse { // Update the out of disk condition when the condition status is unknown even if we // are within the outOfDiskTransitionFrequency duration. We do this to set the // condition status correctly at kubelet startup. - if nodeOODCondition.Status == api.ConditionUnknown || kl.clock.Since(nodeOODCondition.LastTransitionTime.Time) >= kl.outOfDiskTransitionFrequency { - nodeOODCondition.Status = api.ConditionFalse + if nodeOODCondition.Status == v1.ConditionUnknown || kl.clock.Since(nodeOODCondition.LastTransitionTime.Time) >= kl.outOfDiskTransitionFrequency { + nodeOODCondition.Status = v1.ConditionFalse nodeOODCondition.Reason = "KubeletHasSufficientDisk" nodeOODCondition.Message = "kubelet has sufficient disk space available" nodeOODCondition.LastTransitionTime = currentTime - kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasSufficientDisk") + kl.recordNodeStatusEvent(v1.EventTypeNormal, "NodeHasSufficientDisk") } else { glog.Infof("Node condition status for OutOfDisk is false, but last transition time is less than %s", kl.outOfDiskTransitionFrequency) } @@ -837,12 +837,12 @@ func (kl *Kubelet) setNodeOODCondition(node *api.Node) { var oldNodeUnschedulable bool // record if node schedulable change. -func (kl *Kubelet) recordNodeSchedulableEvent(node *api.Node) { +func (kl *Kubelet) recordNodeSchedulableEvent(node *v1.Node) { if oldNodeUnschedulable != node.Spec.Unschedulable { if node.Spec.Unschedulable { - kl.recordNodeStatusEvent(api.EventTypeNormal, events.NodeNotSchedulable) + kl.recordNodeStatusEvent(v1.EventTypeNormal, events.NodeNotSchedulable) } else { - kl.recordNodeStatusEvent(api.EventTypeNormal, events.NodeSchedulable) + kl.recordNodeStatusEvent(v1.EventTypeNormal, events.NodeSchedulable) } oldNodeUnschedulable = node.Spec.Unschedulable } @@ -850,7 +850,7 @@ func (kl *Kubelet) recordNodeSchedulableEvent(node *api.Node) { // Update VolumesInUse field in Node Status only after states are synced up at least once // in volume reconciler. -func (kl *Kubelet) setNodeVolumesInUseStatus(node *api.Node) { +func (kl *Kubelet) setNodeVolumesInUseStatus(node *v1.Node) { // Make sure to only update node status after reconciler starts syncing up states if kl.volumeManager.ReconcilerStatesHasBeenSynced() { node.Status.VolumesInUse = kl.volumeManager.GetVolumesInUse() @@ -861,7 +861,7 @@ func (kl *Kubelet) setNodeVolumesInUseStatus(node *api.Node) { // any fields that are currently set. // TODO(madhusudancs): Simplify the logic for setting node conditions and // refactor the node status condition code out to a different file. -func (kl *Kubelet) setNodeStatus(node *api.Node) error { +func (kl *Kubelet) setNodeStatus(node *v1.Node) error { for _, f := range kl.setNodeStatusFuncs { if err := f(node); err != nil { return err @@ -872,15 +872,15 @@ func (kl *Kubelet) setNodeStatus(node *api.Node) error { // defaultNodeStatusFuncs is a factory that generates the default set of // setNodeStatus funcs -func (kl *Kubelet) defaultNodeStatusFuncs() []func(*api.Node) error { +func (kl *Kubelet) defaultNodeStatusFuncs() []func(*v1.Node) error { // initial set of node status update handlers, can be modified by Option's - withoutError := func(f func(*api.Node)) func(*api.Node) error { - return func(n *api.Node) error { + withoutError := func(f func(*v1.Node)) func(*v1.Node) error { + return func(n *v1.Node) error { f(n) return nil } } - return []func(*api.Node) error{ + return []func(*v1.Node) error{ kl.setNodeAddress, withoutError(kl.setNodeStatusInfo), withoutError(kl.setNodeOODCondition), @@ -894,7 +894,7 @@ func (kl *Kubelet) defaultNodeStatusFuncs() []func(*api.Node) error { // SetNodeStatus returns a functional Option that adds the given node status // update handler to the Kubelet -func SetNodeStatus(f func(*api.Node) error) Option { +func SetNodeStatus(f func(*v1.Node) error) Option { return func(k *Kubelet) { k.setNodeStatusFuncs = append(k.setNodeStatusFuncs, f) } diff --git a/pkg/kubelet/kubelet_node_status_test.go b/pkg/kubelet/kubelet_node_status_test.go index 16124ce3650..5f862fc43d1 100644 --- a/pkg/kubelet/kubelet_node_status_test.go +++ b/pkg/kubelet/kubelet_node_status_test.go @@ -31,7 +31,8 @@ import ( apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/testing/core" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/util/sliceutils" @@ -49,7 +50,7 @@ const ( ) // generateTestingImageList generate randomly generated image list and corresponding expectedImageList. -func generateTestingImageList(count int) ([]kubecontainer.Image, []api.ContainerImage) { +func generateTestingImageList(count int) ([]kubecontainer.Image, []v1.ContainerImage) { // imageList is randomly generated image list var imageList []kubecontainer.Image for ; count > 0; count-- { @@ -64,10 +65,10 @@ func generateTestingImageList(count int) ([]kubecontainer.Image, []api.Container // expectedImageList is generated by imageList according to size and maxImagesInNodeStatus // 1. sort the imageList by size sort.Sort(sliceutils.ByImageSize(imageList)) - // 2. convert sorted imageList to api.ContainerImage list - var expectedImageList []api.ContainerImage + // 2. convert sorted imageList to v1.ContainerImage list + var expectedImageList []v1.ContainerImage for _, kubeImage := range imageList { - apiImage := api.ContainerImage{ + apiImage := v1.ContainerImage{ Names: kubeImage.RepoTags[0:maxNamesPerImageInNodeStatus], SizeBytes: kubeImage.Size, } @@ -96,8 +97,8 @@ func TestUpdateNewNodeStatus(t *testing.T) { t, inputImageList, false /* controllerAttachDetachEnabled */) kubelet := testKubelet.kubelet kubeClient := testKubelet.fakeKubeClient - kubeClient.ReactionChain = fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{ - {ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}}, + kubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}}, }}).ReactionChain machineInfo := &cadvisorapi.MachineInfo{ MachineID: "123", @@ -120,45 +121,45 @@ func TestUpdateNewNodeStatus(t *testing.T) { t.Fatalf("can't update disk space manager: %v", err) } - expectedNode := &api.Node{ - ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, - Spec: api.NodeSpec{}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + expectedNode := &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}, + Spec: v1.NodeSpec{}, + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionFalse, Reason: "KubeletHasSufficientDisk", Message: fmt.Sprintf("kubelet has sufficient disk space available"), LastHeartbeatTime: unversioned.Time{}, LastTransitionTime: unversioned.Time{}, }, { - Type: api.NodeMemoryPressure, - Status: api.ConditionFalse, + Type: v1.NodeMemoryPressure, + Status: v1.ConditionFalse, Reason: "KubeletHasSufficientMemory", Message: fmt.Sprintf("kubelet has sufficient memory available"), LastHeartbeatTime: unversioned.Time{}, LastTransitionTime: unversioned.Time{}, }, { - Type: api.NodeDiskPressure, - Status: api.ConditionFalse, + Type: v1.NodeDiskPressure, + Status: v1.ConditionFalse, Reason: "KubeletHasNoDiskPressure", Message: fmt.Sprintf("kubelet has no disk pressure"), LastHeartbeatTime: unversioned.Time{}, LastTransitionTime: unversioned.Time{}, }, { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, Reason: "KubeletReady", Message: fmt.Sprintf("kubelet is posting ready status"), LastHeartbeatTime: unversioned.Time{}, LastTransitionTime: unversioned.Time{}, }, }, - NodeInfo: api.NodeSystemInfo{ + NodeInfo: v1.NodeSystemInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", @@ -170,22 +171,22 @@ func TestUpdateNewNodeStatus(t *testing.T) { KubeletVersion: version.Get().String(), KubeProxyVersion: version.Get().String(), }, - Capacity: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(10E9, resource.BinarySI), - api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - api.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), + Capacity: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(10E9, resource.BinarySI), + v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), + v1.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), }, - Allocatable: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(1800, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(9900E6, resource.BinarySI), - api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - api.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), + Allocatable: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(1800, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(9900E6, resource.BinarySI), + v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), + v1.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), }, - Addresses: []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: "127.0.0.1"}, - {Type: api.NodeInternalIP, Address: "127.0.0.1"}, - {Type: api.NodeHostName, Address: testKubeletHostname}, + Addresses: []v1.NodeAddress{ + {Type: v1.NodeLegacyHostIP, Address: "127.0.0.1"}, + {Type: v1.NodeInternalIP, Address: "127.0.0.1"}, + {Type: v1.NodeHostName, Address: testKubeletHostname}, }, Images: expectedImageList, }, @@ -202,7 +203,7 @@ func TestUpdateNewNodeStatus(t *testing.T) { if !actions[1].Matches("update", "nodes") || actions[1].GetSubresource() != "status" { t.Fatalf("unexpected actions: %v", actions) } - updatedNode, ok := actions[1].(core.UpdateAction).GetObject().(*api.Node) + updatedNode, ok := actions[1].(core.UpdateAction).GetObject().(*v1.Node) if !ok { t.Errorf("unexpected object type") } @@ -218,7 +219,7 @@ func TestUpdateNewNodeStatus(t *testing.T) { } // Version skew workaround. See: https://github.com/kubernetes/kubernetes/issues/16961 - if updatedNode.Status.Conditions[len(updatedNode.Status.Conditions)-1].Type != api.NodeReady { + if updatedNode.Status.Conditions[len(updatedNode.Status.Conditions)-1].Type != v1.NodeReady { t.Errorf("unexpected node condition order. NodeReady should be last.") } @@ -236,8 +237,8 @@ func TestUpdateNewNodeOutOfDiskStatusWithTransitionFrequency(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kubelet := testKubelet.kubelet kubeClient := testKubelet.fakeKubeClient - kubeClient.ReactionChain = fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{ - {ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}}, + kubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}}, }}).ReactionChain machineInfo := &cadvisorapi.MachineInfo{ MachineID: "123", @@ -262,9 +263,9 @@ func TestUpdateNewNodeOutOfDiskStatusWithTransitionFrequency(t *testing.T) { kubelet.outOfDiskTransitionFrequency = 10 * time.Second - expectedNodeOutOfDiskCondition := api.NodeCondition{ - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, + expectedNodeOutOfDiskCondition := v1.NodeCondition{ + Type: v1.NodeOutOfDisk, + Status: v1.ConditionFalse, Reason: "KubeletHasSufficientDisk", Message: fmt.Sprintf("kubelet has sufficient disk space available"), LastHeartbeatTime: unversioned.Time{}, @@ -282,12 +283,12 @@ func TestUpdateNewNodeOutOfDiskStatusWithTransitionFrequency(t *testing.T) { if !actions[1].Matches("update", "nodes") || actions[1].GetSubresource() != "status" { t.Fatalf("unexpected actions: %v", actions) } - updatedNode, ok := actions[1].(core.UpdateAction).GetObject().(*api.Node) + updatedNode, ok := actions[1].(core.UpdateAction).GetObject().(*v1.Node) if !ok { t.Errorf("unexpected object type") } - var oodCondition api.NodeCondition + var oodCondition v1.NodeCondition for i, cond := range updatedNode.Status.Conditions { if cond.LastHeartbeatTime.IsZero() { t.Errorf("unexpected zero last probe timestamp for %v condition", cond.Type) @@ -297,7 +298,7 @@ func TestUpdateNewNodeOutOfDiskStatusWithTransitionFrequency(t *testing.T) { } updatedNode.Status.Conditions[i].LastHeartbeatTime = unversioned.Time{} updatedNode.Status.Conditions[i].LastTransitionTime = unversioned.Time{} - if cond.Type == api.NodeOutOfDisk { + if cond.Type == v1.NodeOutOfDisk { oodCondition = updatedNode.Status.Conditions[i] } } @@ -311,54 +312,54 @@ func TestUpdateExistingNodeStatus(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kubelet := testKubelet.kubelet kubeClient := testKubelet.fakeKubeClient - kubeClient.ReactionChain = fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{ + kubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, - Spec: api.NodeSpec{}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}, + Spec: v1.NodeSpec{}, + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeOutOfDisk, - Status: api.ConditionTrue, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionTrue, Reason: "KubeletOutOfDisk", Message: "out of disk space", LastHeartbeatTime: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, { - Type: api.NodeMemoryPressure, - Status: api.ConditionFalse, + Type: v1.NodeMemoryPressure, + Status: v1.ConditionFalse, Reason: "KubeletHasSufficientMemory", Message: fmt.Sprintf("kubelet has sufficient memory available"), LastHeartbeatTime: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, { - Type: api.NodeDiskPressure, - Status: api.ConditionFalse, + Type: v1.NodeDiskPressure, + Status: v1.ConditionFalse, Reason: "KubeletHasSufficientDisk", Message: fmt.Sprintf("kubelet has sufficient disk space available"), LastHeartbeatTime: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, Reason: "KubeletReady", Message: fmt.Sprintf("kubelet is posting ready status"), LastHeartbeatTime: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), LastTransitionTime: unversioned.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, }, - Capacity: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(3000, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(20E9, resource.BinarySI), - api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), + Capacity: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(3000, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(20E9, resource.BinarySI), + v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), }, - Allocatable: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(2800, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(19900E6, resource.BinarySI), - api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), + Allocatable: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(2800, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(19900E6, resource.BinarySI), + v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), }, }, }, @@ -384,45 +385,45 @@ func TestUpdateExistingNodeStatus(t *testing.T) { t.Fatalf("can't update disk space manager: %v", err) } - expectedNode := &api.Node{ - ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, - Spec: api.NodeSpec{}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + expectedNode := &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}, + Spec: v1.NodeSpec{}, + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeOutOfDisk, - Status: api.ConditionTrue, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionTrue, Reason: "KubeletOutOfDisk", Message: "out of disk space", LastHeartbeatTime: unversioned.Time{}, // placeholder LastTransitionTime: unversioned.Time{}, // placeholder }, { - Type: api.NodeMemoryPressure, - Status: api.ConditionFalse, + Type: v1.NodeMemoryPressure, + Status: v1.ConditionFalse, Reason: "KubeletHasSufficientMemory", Message: fmt.Sprintf("kubelet has sufficient memory available"), LastHeartbeatTime: unversioned.Time{}, LastTransitionTime: unversioned.Time{}, }, { - Type: api.NodeDiskPressure, - Status: api.ConditionFalse, + Type: v1.NodeDiskPressure, + Status: v1.ConditionFalse, Reason: "KubeletHasSufficientDisk", Message: fmt.Sprintf("kubelet has sufficient disk space available"), LastHeartbeatTime: unversioned.Time{}, LastTransitionTime: unversioned.Time{}, }, { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, Reason: "KubeletReady", Message: fmt.Sprintf("kubelet is posting ready status"), LastHeartbeatTime: unversioned.Time{}, // placeholder LastTransitionTime: unversioned.Time{}, // placeholder }, }, - NodeInfo: api.NodeSystemInfo{ + NodeInfo: v1.NodeSystemInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", @@ -434,25 +435,25 @@ func TestUpdateExistingNodeStatus(t *testing.T) { KubeletVersion: version.Get().String(), KubeProxyVersion: version.Get().String(), }, - Capacity: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(20E9, resource.BinarySI), - api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - api.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), + Capacity: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(20E9, resource.BinarySI), + v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), + v1.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), }, - Allocatable: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(1800, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(19900E6, resource.BinarySI), - api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - api.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), + Allocatable: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(1800, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(19900E6, resource.BinarySI), + v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), + v1.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), }, - Addresses: []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: "127.0.0.1"}, - {Type: api.NodeInternalIP, Address: "127.0.0.1"}, - {Type: api.NodeHostName, Address: testKubeletHostname}, + Addresses: []v1.NodeAddress{ + {Type: v1.NodeLegacyHostIP, Address: "127.0.0.1"}, + {Type: v1.NodeInternalIP, Address: "127.0.0.1"}, + {Type: v1.NodeHostName, Address: testKubeletHostname}, }, // images will be sorted from max to min in node status. - Images: []api.ContainerImage{ + Images: []v1.ContainerImage{ { Names: []string{"gcr.io/google_containers:v3", "gcr.io/google_containers:v4"}, SizeBytes: 456, @@ -477,7 +478,7 @@ func TestUpdateExistingNodeStatus(t *testing.T) { if !ok { t.Errorf("unexpected action type. expected UpdateAction, got %#v", actions[1]) } - updatedNode, ok := updateAction.GetObject().(*api.Node) + updatedNode, ok := updateAction.GetObject().(*v1.Node) if !ok { t.Errorf("unexpected object type") } @@ -494,7 +495,7 @@ func TestUpdateExistingNodeStatus(t *testing.T) { } // Version skew workaround. See: https://github.com/kubernetes/kubernetes/issues/16961 - if updatedNode.Status.Conditions[len(updatedNode.Status.Conditions)-1].Type != api.NodeReady { + if updatedNode.Status.Conditions[len(updatedNode.Status.Conditions)-1].Type != v1.NodeReady { t.Errorf("unexpected node condition order. NodeReady should be last.") } @@ -508,23 +509,23 @@ func TestUpdateExistingNodeOutOfDiskStatusWithTransitionFrequency(t *testing.T) kubelet := testKubelet.kubelet clock := testKubelet.fakeClock kubeClient := testKubelet.fakeKubeClient - kubeClient.ReactionChain = fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{ + kubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, - Spec: api.NodeSpec{}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}, + Spec: v1.NodeSpec{}, + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeReady, - Status: api.ConditionTrue, + Type: v1.NodeReady, + Status: v1.ConditionTrue, Reason: "KubeletReady", Message: fmt.Sprintf("kubelet is posting ready status"), LastHeartbeatTime: unversioned.NewTime(clock.Now()), LastTransitionTime: unversioned.NewTime(clock.Now()), }, { - Type: api.NodeOutOfDisk, - Status: api.ConditionTrue, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionTrue, Reason: "KubeletOutOfDisk", Message: "out of disk space", LastHeartbeatTime: unversioned.NewTime(clock.Now()), @@ -558,17 +559,17 @@ func TestUpdateExistingNodeOutOfDiskStatusWithTransitionFrequency(t *testing.T) kubelet.outOfDiskTransitionFrequency = 5 * time.Second - ood := api.NodeCondition{ - Type: api.NodeOutOfDisk, - Status: api.ConditionTrue, + ood := v1.NodeCondition{ + Type: v1.NodeOutOfDisk, + Status: v1.ConditionTrue, Reason: "KubeletOutOfDisk", Message: "out of disk space", LastHeartbeatTime: unversioned.NewTime(clock.Now()), // placeholder LastTransitionTime: unversioned.NewTime(clock.Now()), // placeholder } - noOod := api.NodeCondition{ - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, + noOod := v1.NodeCondition{ + Type: v1.NodeOutOfDisk, + Status: v1.ConditionFalse, Reason: "KubeletHasSufficientDisk", Message: fmt.Sprintf("kubelet has sufficient disk space available"), LastHeartbeatTime: unversioned.NewTime(clock.Now()), // placeholder @@ -578,7 +579,7 @@ func TestUpdateExistingNodeOutOfDiskStatusWithTransitionFrequency(t *testing.T) testCases := []struct { rootFsAvail uint64 dockerFsAvail uint64 - expected api.NodeCondition + expected v1.NodeCondition }{ { // NodeOutOfDisk==false @@ -640,15 +641,15 @@ func TestUpdateExistingNodeOutOfDiskStatusWithTransitionFrequency(t *testing.T) if !ok { t.Errorf("%d. unexpected action type. expected UpdateAction, got %#v", tcIdx, actions[1]) } - updatedNode, ok := updateAction.GetObject().(*api.Node) + updatedNode, ok := updateAction.GetObject().(*v1.Node) if !ok { t.Errorf("%d. unexpected object type", tcIdx) } kubeClient.ClearActions() - var oodCondition api.NodeCondition + var oodCondition v1.NodeCondition for i, cond := range updatedNode.Status.Conditions { - if cond.Type == api.NodeOutOfDisk { + if cond.Type == v1.NodeOutOfDisk { oodCondition = updatedNode.Status.Conditions[i] } } @@ -665,8 +666,8 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { kubelet := testKubelet.kubelet clock := testKubelet.fakeClock kubeClient := testKubelet.fakeKubeClient - kubeClient.ReactionChain = fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{ - {ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}}, + kubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}}, }}).ReactionChain mockCadvisor := testKubelet.fakeCadvisor mockCadvisor.On("Start").Return(nil) @@ -689,30 +690,30 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { t.Fatalf("can't update disk space manager: %v", err) } - expectedNode := &api.Node{ - ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, - Spec: api.NodeSpec{}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + expectedNode := &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}, + Spec: v1.NodeSpec{}, + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, + Type: v1.NodeOutOfDisk, + Status: v1.ConditionFalse, Reason: "KubeletHasSufficientDisk", Message: "kubelet has sufficient disk space available", LastHeartbeatTime: unversioned.Time{}, LastTransitionTime: unversioned.Time{}, }, { - Type: api.NodeMemoryPressure, - Status: api.ConditionFalse, + Type: v1.NodeMemoryPressure, + Status: v1.ConditionFalse, Reason: "KubeletHasSufficientMemory", Message: fmt.Sprintf("kubelet has sufficient memory available"), LastHeartbeatTime: unversioned.Time{}, LastTransitionTime: unversioned.Time{}, }, { - Type: api.NodeDiskPressure, - Status: api.ConditionFalse, + Type: v1.NodeDiskPressure, + Status: v1.ConditionFalse, Reason: "KubeletHasNoDiskPressure", Message: fmt.Sprintf("kubelet has no disk pressure"), LastHeartbeatTime: unversioned.Time{}, @@ -720,7 +721,7 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { }, {}, //placeholder }, - NodeInfo: api.NodeSystemInfo{ + NodeInfo: v1.NodeSystemInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", @@ -732,24 +733,24 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { KubeletVersion: version.Get().String(), KubeProxyVersion: version.Get().String(), }, - Capacity: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(10E9, resource.BinarySI), - api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - api.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), + Capacity: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(10E9, resource.BinarySI), + v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), + v1.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), }, - Allocatable: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(1800, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(9900E6, resource.BinarySI), - api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - api.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), + Allocatable: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(1800, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(9900E6, resource.BinarySI), + v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), + v1.ResourceNvidiaGPU: *resource.NewQuantity(0, resource.DecimalSI), }, - Addresses: []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: "127.0.0.1"}, - {Type: api.NodeInternalIP, Address: "127.0.0.1"}, - {Type: api.NodeHostName, Address: testKubeletHostname}, + Addresses: []v1.NodeAddress{ + {Type: v1.NodeLegacyHostIP, Address: "127.0.0.1"}, + {Type: v1.NodeInternalIP, Address: "127.0.0.1"}, + {Type: v1.NodeHostName, Address: testKubeletHostname}, }, - Images: []api.ContainerImage{ + Images: []v1.ContainerImage{ { Names: []string{"gcr.io/google_containers:v3", "gcr.io/google_containers:v4"}, SizeBytes: 456, @@ -762,7 +763,7 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { }, } - checkNodeStatus := func(status api.ConditionStatus, reason string) { + checkNodeStatus := func(status v1.ConditionStatus, reason string) { kubeClient.ClearActions() if err := kubelet.updateNodeStatus(); err != nil { t.Errorf("unexpected error: %v", err) @@ -774,7 +775,7 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { if !actions[1].Matches("update", "nodes") || actions[1].GetSubresource() != "status" { t.Fatalf("unexpected actions: %v", actions) } - updatedNode, ok := actions[1].(core.UpdateAction).GetObject().(*api.Node) + updatedNode, ok := actions[1].(core.UpdateAction).GetObject().(*v1.Node) if !ok { t.Errorf("unexpected action type. expected UpdateAction, got %#v", actions[1]) } @@ -792,15 +793,15 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { // Version skew workaround. See: https://github.com/kubernetes/kubernetes/issues/16961 lastIndex := len(updatedNode.Status.Conditions) - 1 - if updatedNode.Status.Conditions[lastIndex].Type != api.NodeReady { + if updatedNode.Status.Conditions[lastIndex].Type != v1.NodeReady { t.Errorf("unexpected node condition order. NodeReady should be last.") } if updatedNode.Status.Conditions[lastIndex].Message == "" { t.Errorf("unexpected empty condition message") } updatedNode.Status.Conditions[lastIndex].Message = "" - expectedNode.Status.Conditions[lastIndex] = api.NodeCondition{ - Type: api.NodeReady, + expectedNode.Status.Conditions[lastIndex] = v1.NodeCondition{ + Type: v1.NodeReady, Status: status, Reason: reason, LastHeartbeatTime: unversioned.Time{}, @@ -815,17 +816,17 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { // Should report kubelet not ready if the runtime check is out of date clock.SetTime(time.Now().Add(-maxWaitForContainerRuntime)) kubelet.updateRuntimeUp() - checkNodeStatus(api.ConditionFalse, "KubeletNotReady") + checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") // Should report kubelet ready if the runtime check is updated clock.SetTime(time.Now()) kubelet.updateRuntimeUp() - checkNodeStatus(api.ConditionTrue, "KubeletReady") + checkNodeStatus(v1.ConditionTrue, "KubeletReady") // Should report kubelet not ready if the runtime check is out of date clock.SetTime(time.Now().Add(-maxWaitForContainerRuntime)) kubelet.updateRuntimeUp() - checkNodeStatus(api.ConditionFalse, "KubeletNotReady") + checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") // Should report kubelet not ready if the runtime check failed fakeRuntime := testKubelet.fakeRuntime @@ -833,7 +834,7 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { fakeRuntime.StatusErr = fmt.Errorf("injected runtime status error") clock.SetTime(time.Now()) kubelet.updateRuntimeUp() - checkNodeStatus(api.ConditionFalse, "KubeletNotReady") + checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") // Test cri integration. kubelet.kubeletConfiguration.EnableCRI = true @@ -842,12 +843,12 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { // Should report node not ready if runtime status is nil. fakeRuntime.RuntimeStatus = nil kubelet.updateRuntimeUp() - checkNodeStatus(api.ConditionFalse, "KubeletNotReady") + checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") // Should report node not ready if runtime status is empty. fakeRuntime.RuntimeStatus = &kubecontainer.RuntimeStatus{} kubelet.updateRuntimeUp() - checkNodeStatus(api.ConditionFalse, "KubeletNotReady") + checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") // Should report node not ready if RuntimeReady is false. fakeRuntime.RuntimeStatus = &kubecontainer.RuntimeStatus{ @@ -857,7 +858,7 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { }, } kubelet.updateRuntimeUp() - checkNodeStatus(api.ConditionFalse, "KubeletNotReady") + checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") // Should report node ready if RuntimeReady is true. fakeRuntime.RuntimeStatus = &kubecontainer.RuntimeStatus{ @@ -867,7 +868,7 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { }, } kubelet.updateRuntimeUp() - checkNodeStatus(api.ConditionTrue, "KubeletReady") + checkNodeStatus(v1.ConditionTrue, "KubeletReady") // Should report node not ready if NetworkReady is false. fakeRuntime.RuntimeStatus = &kubecontainer.RuntimeStatus{ @@ -877,14 +878,14 @@ func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { }, } kubelet.updateRuntimeUp() - checkNodeStatus(api.ConditionFalse, "KubeletNotReady") + checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") } func TestUpdateNodeStatusError(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kubelet := testKubelet.kubelet // No matching node for the kubelet - testKubelet.fakeKubeClient.ReactionChain = fake.NewSimpleClientset(&api.NodeList{Items: []api.Node{}}).ReactionChain + testKubelet.fakeKubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{}}).ReactionChain if err := kubelet.updateNodeStatus(); err == nil { t.Errorf("unexpected non error: %v", err) @@ -900,15 +901,15 @@ func TestRegisterWithApiServer(t *testing.T) { kubeClient := testKubelet.fakeKubeClient kubeClient.AddReactor("create", "nodes", func(action core.Action) (bool, runtime.Object, error) { // Return an error on create. - return true, &api.Node{}, &apierrors.StatusError{ + return true, &v1.Node{}, &apierrors.StatusError{ ErrStatus: unversioned.Status{Reason: unversioned.StatusReasonAlreadyExists}, } }) kubeClient.AddReactor("get", "nodes", func(action core.Action) (bool, runtime.Object, error) { // Return an existing (matching) node on get. - return true, &api.Node{ - ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, - Spec: api.NodeSpec{ExternalID: testKubeletHostname}, + return true, &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}, + Spec: v1.NodeSpec{ExternalID: testKubeletHostname}, }, nil }) kubeClient.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) { @@ -961,10 +962,10 @@ func TestTryRegisterWithApiServer(t *testing.T) { ErrStatus: unversioned.Status{Reason: unversioned.StatusReasonConflict}, } - newNode := func(cmad bool, externalID string) *api.Node { - node := &api.Node{ - ObjectMeta: api.ObjectMeta{}, - Spec: api.NodeSpec{ + newNode := func(cmad bool, externalID string) *v1.Node { + node := &v1.Node{ + ObjectMeta: v1.ObjectMeta{}, + Spec: v1.NodeSpec{ ExternalID: externalID, }, } @@ -979,8 +980,8 @@ func TestTryRegisterWithApiServer(t *testing.T) { cases := []struct { name string - newNode *api.Node - existingNode *api.Node + newNode *v1.Node + existingNode *v1.Node createError error getError error updateError error @@ -993,7 +994,7 @@ func TestTryRegisterWithApiServer(t *testing.T) { }{ { name: "success case - new node", - newNode: &api.Node{}, + newNode: &v1.Node{}, expectedResult: true, expectedActions: 1, }, @@ -1111,23 +1112,23 @@ func TestTryRegisterWithApiServer(t *testing.T) { } if tc.testSavedNode { - var savedNode *api.Node + var savedNode *v1.Node var ok bool t.Logf("actions: %v: %+v", len(actions), actions) action := actions[tc.savedNodeIndex] if action.GetVerb() == "create" { createAction := action.(core.CreateAction) - savedNode, ok = createAction.GetObject().(*api.Node) + savedNode, ok = createAction.GetObject().(*v1.Node) if !ok { - t.Errorf("%v: unexpected type; couldn't convert to *api.Node: %+v", tc.name, createAction.GetObject()) + t.Errorf("%v: unexpected type; couldn't convert to *v1.Node: %+v", tc.name, createAction.GetObject()) continue } } else if action.GetVerb() == "update" { updateAction := action.(core.UpdateAction) - savedNode, ok = updateAction.GetObject().(*api.Node) + savedNode, ok = updateAction.GetObject().(*v1.Node) if !ok { - t.Errorf("%v: unexpected type; couldn't convert to *api.Node: %+v", tc.name, updateAction.GetObject()) + t.Errorf("%v: unexpected type; couldn't convert to *v1.Node: %+v", tc.name, updateAction.GetObject()) continue } } diff --git a/pkg/kubelet/kubelet_pods.go b/pkg/kubelet/kubelet_pods.go index c56f25745ef..d8b1f17012e 100644 --- a/pkg/kubelet/kubelet_pods.go +++ b/pkg/kubelet/kubelet_pods.go @@ -33,9 +33,10 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" - utilpod "k8s.io/kubernetes/pkg/api/pod" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/validation" + "k8s.io/kubernetes/pkg/api/v1" + utilpod "k8s.io/kubernetes/pkg/api/v1/pod" + "k8s.io/kubernetes/pkg/api/v1/validation" "k8s.io/kubernetes/pkg/fieldpath" "k8s.io/kubernetes/pkg/kubelet/cm" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" @@ -72,7 +73,7 @@ func (kl *Kubelet) listPodsFromDisk() ([]types.UID, error) { } // getActivePods returns non-terminal pods -func (kl *Kubelet) getActivePods() []*api.Pod { +func (kl *Kubelet) getActivePods() []*v1.Pod { allPods := kl.podManager.GetPods() activePods := kl.filterOutTerminatedPods(allPods) return activePods @@ -82,7 +83,7 @@ func (kl *Kubelet) getActivePods() []*api.Pod { // Experimental. For now, we hardcode /dev/nvidia0 no matter what the user asks for // (we only support one device per node). // TODO: add support for more than 1 GPU after #28216. -func makeDevices(container *api.Container) []kubecontainer.DeviceInfo { +func makeDevices(container *v1.Container) []kubecontainer.DeviceInfo { nvidiaGPULimit := container.Resources.Limits.NvidiaGPU() if nvidiaGPULimit.Value() != 0 { return []kubecontainer.DeviceInfo{ @@ -96,14 +97,14 @@ func makeDevices(container *api.Container) []kubecontainer.DeviceInfo { } // makeMounts determines the mount points for the given container. -func makeMounts(pod *api.Pod, podDir string, container *api.Container, hostName, hostDomain, podIP string, podVolumes kubecontainer.VolumeMap) ([]kubecontainer.Mount, error) { +func makeMounts(pod *v1.Pod, podDir string, container *v1.Container, hostName, hostDomain, podIP string, podVolumes kubecontainer.VolumeMap) ([]kubecontainer.Mount, error) { // Kubernetes only mounts on /etc/hosts if : // - container does not use hostNetwork and // - container is not an infrastructure(pause) container // - container is not already mounting on /etc/hosts // When the pause container is being created, its IP is still unknown. Hence, PodIP will not have been set. // OS is not Windows - mountEtcHostsFile := (pod.Spec.SecurityContext == nil || !pod.Spec.SecurityContext.HostNetwork) && len(podIP) > 0 && runtime.GOOS != "windows" + mountEtcHostsFile := (pod.Spec.SecurityContext == nil || !pod.Spec.HostNetwork) && len(podIP) > 0 && runtime.GOOS != "windows" glog.V(3).Infof("container: %v/%v/%v podIP: %q creating hosts mount: %v", pod.Namespace, pod.Name, container.Name, podIP, mountEtcHostsFile) mounts := []kubecontainer.Mount{} for _, mount := range container.VolumeMounts { @@ -198,7 +199,7 @@ func ensureHostsFile(fileName, hostIP, hostName, hostDomainName string) error { return ioutil.WriteFile(fileName, buffer.Bytes(), 0644) } -func makePortMappings(container *api.Container) (ports []kubecontainer.PortMapping) { +func makePortMappings(container *v1.Container) (ports []kubecontainer.PortMapping) { names := make(map[string]struct{}) for _, p := range container.Ports { pm := kubecontainer.PortMapping{ @@ -248,7 +249,7 @@ func truncatePodHostnameIfNeeded(podName, hostname string) (string, error) { // GeneratePodHostNameAndDomain creates a hostname and domain name for a pod, // given that pod's spec and annotations or returns an error. -func (kl *Kubelet) GeneratePodHostNameAndDomain(pod *api.Pod) (string, string, error) { +func (kl *Kubelet) GeneratePodHostNameAndDomain(pod *v1.Pod) (string, string, error) { // TODO(vmarmol): Handle better. clusterDomain := kl.clusterDomain podAnnotations := pod.Annotations @@ -290,7 +291,7 @@ func (kl *Kubelet) GeneratePodHostNameAndDomain(pod *api.Pod) (string, string, e // GenerateRunContainerOptions generates the RunContainerOptions, which can be used by // the container runtime to set parameters for launching a container. -func (kl *Kubelet) GenerateRunContainerOptions(pod *api.Pod, container *api.Container, podIP string) (*kubecontainer.RunContainerOptions, error) { +func (kl *Kubelet) GenerateRunContainerOptions(pod *v1.Pod, container *v1.Container, podIP string) (*kubecontainer.RunContainerOptions, error) { var err error pcm := kl.containerManager.NewPodContainerManager() _, podContainerName := pcm.GetPodContainerName(pod) @@ -345,7 +346,7 @@ var masterServices = sets.NewString("kubernetes") // pod in namespace ns should see. func (kl *Kubelet) getServiceEnvVarMap(ns string) (map[string]string, error) { var ( - serviceMap = make(map[string]*api.Service) + serviceMap = make(map[string]*v1.Service) m = make(map[string]string) ) @@ -364,7 +365,7 @@ func (kl *Kubelet) getServiceEnvVarMap(ns string) (map[string]string, error) { for i := range services { service := services[i] // ignore services where ClusterIP is "None" or empty - if !api.IsServiceIPSet(service) { + if !v1.IsServiceIPSet(service) { continue } serviceName := service.Name @@ -385,7 +386,7 @@ func (kl *Kubelet) getServiceEnvVarMap(ns string) (map[string]string, error) { } } - mappedServices := []*api.Service{} + mappedServices := []*v1.Service{} for key := range serviceMap { mappedServices = append(mappedServices, serviceMap[key]) } @@ -397,11 +398,11 @@ func (kl *Kubelet) getServiceEnvVarMap(ns string) (map[string]string, error) { } // Make the environment variables for a pod in the given namespace. -func (kl *Kubelet) makeEnvironmentVariables(pod *api.Pod, container *api.Container, podIP string) ([]kubecontainer.EnvVar, error) { +func (kl *Kubelet) makeEnvironmentVariables(pod *v1.Pod, container *v1.Container, podIP string) ([]kubecontainer.EnvVar, error) { var result []kubecontainer.EnvVar // Note: These are added to the docker Config, but are not included in the checksum computed // by dockertools.BuildDockerName(...). That way, we can still determine whether an - // api.Container is already running by its hash. (We don't want to restart a container just + // v1.Container is already running by its hash. (We don't want to restart a container just // because some service changed.) // // Note that there is a race between Kubelet seeing the pod and kubelet seeing the service. @@ -424,8 +425,8 @@ func (kl *Kubelet) makeEnvironmentVariables(pod *api.Pod, container *api.Contain // 3. Add remaining service environment vars var ( tmpEnv = make(map[string]string) - configMaps = make(map[string]*api.ConfigMap) - secrets = make(map[string]*api.Secret) + configMaps = make(map[string]*v1.ConfigMap) + secrets = make(map[string]*v1.Secret) mappingFunc = expansion.MappingFuncFor(tmpEnv, serviceEnv) ) for _, envVar := range container.Env { @@ -510,7 +511,7 @@ func (kl *Kubelet) makeEnvironmentVariables(pod *api.Pod, container *api.Contain // podFieldSelectorRuntimeValue returns the runtime value of the given // selector for a pod. -func (kl *Kubelet) podFieldSelectorRuntimeValue(fs *api.ObjectFieldSelector, pod *api.Pod, podIP string) (string, error) { +func (kl *Kubelet) podFieldSelectorRuntimeValue(fs *v1.ObjectFieldSelector, pod *v1.Pod, podIP string) (string, error) { internalFieldPath, _, err := api.Scheme.ConvertFieldLabel(fs.APIVersion, "Pod", fs.FieldPath, "") if err != nil { return "", err @@ -527,7 +528,7 @@ func (kl *Kubelet) podFieldSelectorRuntimeValue(fs *api.ObjectFieldSelector, pod } // containerResourceRuntimeValue returns the value of the provided container resource -func containerResourceRuntimeValue(fs *api.ResourceFieldSelector, pod *api.Pod, container *api.Container) (string, error) { +func containerResourceRuntimeValue(fs *v1.ResourceFieldSelector, pod *v1.Pod, container *v1.Container) (string, error) { containerName := fs.ContainerName if len(containerName) == 0 { return fieldpath.ExtractContainerResourceValue(fs, container) @@ -538,7 +539,7 @@ func containerResourceRuntimeValue(fs *api.ResourceFieldSelector, pod *api.Pod, // One of the following arguments must be non-nil: runningPod, status. // TODO: Modify containerRuntime.KillPod() to accept the right arguments. -func (kl *Kubelet) killPod(pod *api.Pod, runningPod *kubecontainer.Pod, status *kubecontainer.PodStatus, gracePeriodOverride *int64) error { +func (kl *Kubelet) killPod(pod *v1.Pod, runningPod *kubecontainer.Pod, status *kubecontainer.PodStatus, gracePeriodOverride *int64) error { var p kubecontainer.Pod if runningPod != nil { p = *runningPod @@ -577,7 +578,7 @@ func (kl *Kubelet) killPod(pod *api.Pod, runningPod *kubecontainer.Pod, status * } // makePodDataDirs creates the dirs for the pod datas. -func (kl *Kubelet) makePodDataDirs(pod *api.Pod) error { +func (kl *Kubelet) makePodDataDirs(pod *v1.Pod) error { uid := pod.UID if err := os.MkdirAll(kl.getPodDir(uid), 0750); err != nil && !os.IsExist(err) { return err @@ -592,8 +593,8 @@ func (kl *Kubelet) makePodDataDirs(pod *api.Pod) error { } // returns whether the pod uses the host network namespace. -func podUsesHostNetwork(pod *api.Pod) bool { - return pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostNetwork +func podUsesHostNetwork(pod *v1.Pod) bool { + return pod.Spec.HostNetwork } // getPullSecretsForPod inspects the Pod and retrieves the referenced pull @@ -601,8 +602,8 @@ func podUsesHostNetwork(pod *api.Pod) bool { // TODO: duplicate secrets are being retrieved multiple times and there // is no cache. Creating and using a secret manager interface will make this // easier to address. -func (kl *Kubelet) getPullSecretsForPod(pod *api.Pod) ([]api.Secret, error) { - pullSecrets := []api.Secret{} +func (kl *Kubelet) getPullSecretsForPod(pod *v1.Pod) ([]v1.Secret, error) { + pullSecrets := []v1.Secret{} for _, secretRef := range pod.Spec.ImagePullSecrets { secret, err := kl.kubeClient.Core().Secrets(pod.Namespace).Get(secretRef.Name) @@ -618,8 +619,8 @@ func (kl *Kubelet) getPullSecretsForPod(pod *api.Pod) ([]api.Secret, error) { } // Returns true if pod is in the terminated state ("Failed" or "Succeeded"). -func (kl *Kubelet) podIsTerminated(pod *api.Pod) bool { - var status api.PodStatus +func (kl *Kubelet) podIsTerminated(pod *v1.Pod) bool { + var status v1.PodStatus // Check the cached pod status which was set after the last sync. status, ok := kl.statusManager.GetPodStatus(pod.UID) if !ok { @@ -628,7 +629,7 @@ func (kl *Kubelet) podIsTerminated(pod *api.Pod) bool { // restarted. status = pod.Status } - if status.Phase == api.PodFailed || status.Phase == api.PodSucceeded { + if status.Phase == v1.PodFailed || status.Phase == v1.PodSucceeded { return true } @@ -637,8 +638,8 @@ func (kl *Kubelet) podIsTerminated(pod *api.Pod) bool { // filterOutTerminatedPods returns the given pods which the status manager // does not consider failed or succeeded. -func (kl *Kubelet) filterOutTerminatedPods(pods []*api.Pod) []*api.Pod { - var filteredPods []*api.Pod +func (kl *Kubelet) filterOutTerminatedPods(pods []*v1.Pod) []*v1.Pod { + var filteredPods []*v1.Pod for _, p := range pods { if kl.podIsTerminated(p) { continue @@ -650,7 +651,7 @@ func (kl *Kubelet) filterOutTerminatedPods(pods []*api.Pod) []*api.Pod { // removeOrphanedPodStatuses removes obsolete entries in podStatus where // the pod is no longer considered bound to this node. -func (kl *Kubelet) removeOrphanedPodStatuses(pods []*api.Pod, mirrorPods []*api.Pod) { +func (kl *Kubelet) removeOrphanedPodStatuses(pods []*v1.Pod, mirrorPods []*v1.Pod) { podUIDs := make(map[types.UID]bool) for _, pod := range pods { podUIDs[pod.UID] = true @@ -778,7 +779,7 @@ func (kl *Kubelet) podKiller() { break } killing.Insert(string(runningPod.ID)) - go func(apiPod *api.Pod, runningPod *kubecontainer.Pod, ch chan types.UID) { + go func(apiPod *v1.Pod, runningPod *kubecontainer.Pod, ch chan types.UID) { defer func() { ch <- runningPod.ID }() @@ -796,7 +797,7 @@ func (kl *Kubelet) podKiller() { } // checkHostPortConflicts detects pods with conflicted host ports. -func hasHostPortConflicts(pods []*api.Pod) bool { +func hasHostPortConflicts(pods []*v1.Pod) bool { ports := sets.String{} for _, pod := range pods { if errs := validation.AccumulateUniqueHostPorts(pod.Spec.Containers, &ports, field.NewPath("spec", "containers")); len(errs) > 0 { @@ -815,13 +816,13 @@ func hasHostPortConflicts(pods []*api.Pod) bool { // of the container. The previous flag will only return the logs for the last terminated container, otherwise, the current // running container is preferred over a previous termination. If info about the container is not available then a specific // error is returned to the end user. -func (kl *Kubelet) validateContainerLogStatus(podName string, podStatus *api.PodStatus, containerName string, previous bool) (containerID kubecontainer.ContainerID, err error) { +func (kl *Kubelet) validateContainerLogStatus(podName string, podStatus *v1.PodStatus, containerName string, previous bool) (containerID kubecontainer.ContainerID, err error) { var cID string - cStatus, found := api.GetContainerStatus(podStatus.ContainerStatuses, containerName) + cStatus, found := v1.GetContainerStatus(podStatus.ContainerStatuses, containerName) // if not found, check the init containers if !found { - cStatus, found = api.GetContainerStatus(podStatus.InitContainerStatuses, containerName) + cStatus, found = v1.GetContainerStatus(podStatus.InitContainerStatuses, containerName) } if !found { return kubecontainer.ContainerID{}, fmt.Errorf("container %q in pod %q is not available", containerName, podName) @@ -866,7 +867,7 @@ func (kl *Kubelet) validateContainerLogStatus(podName string, podStatus *api.Pod // GetKubeletContainerLogs returns logs from the container // TODO: this method is returning logs of random container attempts, when it should be returning the most recent attempt // or all of them. -func (kl *Kubelet) GetKubeletContainerLogs(podFullName, containerName string, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error { +func (kl *Kubelet) GetKubeletContainerLogs(podFullName, containerName string, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) error { // Pod workers periodically write status to statusManager. If status is not // cached there, something is wrong (or kubelet just restarted and hasn't // caught up yet). Just assume the pod is not ready yet. @@ -914,12 +915,12 @@ func (kl *Kubelet) GetKubeletContainerLogs(podFullName, containerName string, lo // GetPhase returns the phase of a pod given its container info. // This func is exported to simplify integration with 3rd party kubelet // integrations like kubernetes-mesos. -func GetPhase(spec *api.PodSpec, info []api.ContainerStatus) api.PodPhase { +func GetPhase(spec *v1.PodSpec, info []v1.ContainerStatus) v1.PodPhase { initialized := 0 pendingInitialization := 0 failedInitialization := 0 for _, container := range spec.InitContainers { - containerStatus, ok := api.GetContainerStatus(info, container.Name) + containerStatus, ok := v1.GetContainerStatus(info, container.Name) if !ok { pendingInitialization++ continue @@ -956,7 +957,7 @@ func GetPhase(spec *api.PodSpec, info []api.ContainerStatus) api.PodPhase { failed := 0 succeeded := 0 for _, container := range spec.Containers { - containerStatus, ok := api.GetContainerStatus(info, container.Name) + containerStatus, ok := v1.GetContainerStatus(info, container.Name) if !ok { unknown++ continue @@ -983,8 +984,8 @@ func GetPhase(spec *api.PodSpec, info []api.ContainerStatus) api.PodPhase { } } - if failedInitialization > 0 && spec.RestartPolicy == api.RestartPolicyNever { - return api.PodFailed + if failedInitialization > 0 && spec.RestartPolicy == v1.RestartPolicyNever { + return v1.PodFailed } switch { @@ -993,46 +994,46 @@ func GetPhase(spec *api.PodSpec, info []api.ContainerStatus) api.PodPhase { case waiting > 0: glog.V(5).Infof("pod waiting > 0, pending") // One or more containers has not been started - return api.PodPending + return v1.PodPending case running > 0 && unknown == 0: // All containers have been started, and at least // one container is running - return api.PodRunning + return v1.PodRunning case running == 0 && stopped > 0 && unknown == 0: // All containers are terminated - if spec.RestartPolicy == api.RestartPolicyAlways { + if spec.RestartPolicy == v1.RestartPolicyAlways { // All containers are in the process of restarting - return api.PodRunning + return v1.PodRunning } if stopped == succeeded { // RestartPolicy is not Always, and all // containers are terminated in success - return api.PodSucceeded + return v1.PodSucceeded } - if spec.RestartPolicy == api.RestartPolicyNever { + if spec.RestartPolicy == v1.RestartPolicyNever { // RestartPolicy is Never, and all containers are // terminated with at least one in failure - return api.PodFailed + return v1.PodFailed } // RestartPolicy is OnFailure, and at least one in failure // and in the process of restarting - return api.PodRunning + return v1.PodRunning default: glog.V(5).Infof("pod default case, pending") - return api.PodPending + return v1.PodPending } } // generateAPIPodStatus creates the final API pod status for a pod, given the // internal pod status. -func (kl *Kubelet) generateAPIPodStatus(pod *api.Pod, podStatus *kubecontainer.PodStatus) api.PodStatus { +func (kl *Kubelet) generateAPIPodStatus(pod *v1.Pod, podStatus *kubecontainer.PodStatus) v1.PodStatus { glog.V(3).Infof("Generating status for %q", format.Pod(pod)) // check if an internal module has requested the pod is evicted. for _, podSyncHandler := range kl.PodSyncHandlers { if result := podSyncHandler.ShouldEvict(pod); result.Evict { - return api.PodStatus{ - Phase: api.PodFailed, + return v1.PodStatus{ + Phase: v1.PodFailed, Reason: result.Reason, Message: result.Message, } @@ -1043,7 +1044,7 @@ func (kl *Kubelet) generateAPIPodStatus(pod *api.Pod, podStatus *kubecontainer.P // Assume info is ready to process spec := &pod.Spec - allStatus := append(append([]api.ContainerStatus{}, s.ContainerStatuses...), s.InitContainerStatuses...) + allStatus := append(append([]v1.ContainerStatus{}, s.ContainerStatuses...), s.InitContainerStatuses...) s.Phase = GetPhase(spec, allStatus) kl.probeManager.UpdatePodStatus(pod.UID, s) s.Conditions = append(s.Conditions, status.GeneratePodInitializedCondition(spec, s.InitContainerStatuses, s.Phase)) @@ -1051,12 +1052,12 @@ func (kl *Kubelet) generateAPIPodStatus(pod *api.Pod, podStatus *kubecontainer.P // s (the PodStatus we are creating) will not have a PodScheduled condition yet, because converStatusToAPIStatus() // does not create one. If the existing PodStatus has a PodScheduled condition, then copy it into s and make sure // it is set to true. If the existing PodStatus does not have a PodScheduled condition, then create one that is set to true. - if _, oldPodScheduled := api.GetPodCondition(&pod.Status, api.PodScheduled); oldPodScheduled != nil { + if _, oldPodScheduled := v1.GetPodCondition(&pod.Status, v1.PodScheduled); oldPodScheduled != nil { s.Conditions = append(s.Conditions, *oldPodScheduled) } - api.UpdatePodCondition(&pod.Status, &api.PodCondition{ - Type: api.PodScheduled, - Status: api.ConditionTrue, + v1.UpdatePodCondition(&pod.Status, &v1.PodCondition{ + Type: v1.PodScheduled, + Status: v1.ConditionTrue, }) if !kl.standaloneMode { @@ -1077,8 +1078,8 @@ func (kl *Kubelet) generateAPIPodStatus(pod *api.Pod, podStatus *kubecontainer.P // convertStatusToAPIStatus creates an api PodStatus for the given pod from // the given internal pod status. It is purely transformative and does not // alter the kubelet state at all. -func (kl *Kubelet) convertStatusToAPIStatus(pod *api.Pod, podStatus *kubecontainer.PodStatus) *api.PodStatus { - var apiPodStatus api.PodStatus +func (kl *Kubelet) convertStatusToAPIStatus(pod *v1.Pod, podStatus *kubecontainer.PodStatus) *v1.PodStatus { + var apiPodStatus v1.PodStatus apiPodStatus.PodIP = podStatus.IP apiPodStatus.ContainerStatuses = kl.convertToAPIContainerStatuses( @@ -1101,10 +1102,10 @@ func (kl *Kubelet) convertStatusToAPIStatus(pod *api.Pod, podStatus *kubecontain // convertToAPIContainerStatuses converts the given internal container // statuses into API container statuses. -func (kl *Kubelet) convertToAPIContainerStatuses(pod *api.Pod, podStatus *kubecontainer.PodStatus, previousStatus []api.ContainerStatus, containers []api.Container, hasInitContainers, isInitContainer bool) []api.ContainerStatus { - convertContainerStatus := func(cs *kubecontainer.ContainerStatus) *api.ContainerStatus { +func (kl *Kubelet) convertToAPIContainerStatuses(pod *v1.Pod, podStatus *kubecontainer.PodStatus, previousStatus []v1.ContainerStatus, containers []v1.Container, hasInitContainers, isInitContainer bool) []v1.ContainerStatus { + convertContainerStatus := func(cs *kubecontainer.ContainerStatus) *v1.ContainerStatus { cid := cs.ID.String() - status := &api.ContainerStatus{ + status := &v1.ContainerStatus{ Name: cs.Name, RestartCount: int32(cs.RestartCount), Image: cs.Image, @@ -1113,9 +1114,9 @@ func (kl *Kubelet) convertToAPIContainerStatuses(pod *api.Pod, podStatus *kubeco } switch cs.State { case kubecontainer.ContainerStateRunning: - status.State.Running = &api.ContainerStateRunning{StartedAt: unversioned.NewTime(cs.StartedAt)} + status.State.Running = &v1.ContainerStateRunning{StartedAt: unversioned.NewTime(cs.StartedAt)} case kubecontainer.ContainerStateExited: - status.State.Terminated = &api.ContainerStateTerminated{ + status.State.Terminated = &v1.ContainerStateTerminated{ ExitCode: int32(cs.ExitCode), Reason: cs.Reason, Message: cs.Message, @@ -1124,26 +1125,26 @@ func (kl *Kubelet) convertToAPIContainerStatuses(pod *api.Pod, podStatus *kubeco ContainerID: cid, } default: - status.State.Waiting = &api.ContainerStateWaiting{} + status.State.Waiting = &v1.ContainerStateWaiting{} } return status } // Fetch old containers statuses from old pod status. - oldStatuses := make(map[string]api.ContainerStatus, len(containers)) + oldStatuses := make(map[string]v1.ContainerStatus, len(containers)) for _, status := range previousStatus { oldStatuses[status.Name] = status } // Set all container statuses to default waiting state - statuses := make(map[string]*api.ContainerStatus, len(containers)) - defaultWaitingState := api.ContainerState{Waiting: &api.ContainerStateWaiting{Reason: "ContainerCreating"}} + statuses := make(map[string]*v1.ContainerStatus, len(containers)) + defaultWaitingState := v1.ContainerState{Waiting: &v1.ContainerStateWaiting{Reason: "ContainerCreating"}} if hasInitContainers { - defaultWaitingState = api.ContainerState{Waiting: &api.ContainerStateWaiting{Reason: "PodInitializing"}} + defaultWaitingState = v1.ContainerState{Waiting: &v1.ContainerStateWaiting{Reason: "PodInitializing"}} } for _, container := range containers { - status := &api.ContainerStatus{ + status := &v1.ContainerStatus{ Name: container.Name, Image: container.Image, State: defaultWaitingState, @@ -1206,8 +1207,8 @@ func (kl *Kubelet) convertToAPIContainerStatuses(pod *api.Pod, podStatus *kubeco if status.State.Terminated != nil { status.LastTerminationState = status.State } - status.State = api.ContainerState{ - Waiting: &api.ContainerStateWaiting{ + status.State = v1.ContainerState{ + Waiting: &v1.ContainerStateWaiting{ Reason: reason.Error(), Message: message, }, @@ -1215,7 +1216,7 @@ func (kl *Kubelet) convertToAPIContainerStatuses(pod *api.Pod, podStatus *kubeco statuses[container.Name] = status } - var containerStatuses []api.ContainerStatus + var containerStatuses []v1.ContainerStatus for _, status := range statuses { containerStatuses = append(containerStatuses, *status) } @@ -1386,7 +1387,7 @@ func (kl *Kubelet) GetPortForward(podName, podNamespace string, podUID types.UID // running and whose volumes have been cleaned up. func (kl *Kubelet) cleanupOrphanedPodCgroups( cgroupPods map[types.UID]cm.CgroupName, - pods []*api.Pod, runningPods []*kubecontainer.Pod) error { + pods []*v1.Pod, runningPods []*kubecontainer.Pod) error { // Add all running and existing terminated pods to a set allPods allPods := sets.NewString() for _, pod := range pods { @@ -1426,7 +1427,7 @@ func (kl *Kubelet) cleanupOrphanedPodCgroups( // NOTE: when if a container shares any namespace with another container it must also share the user namespace // or it will not have the correct capabilities in the namespace. This means that host user namespace // is enabled per pod, not per container. -func (kl *Kubelet) enableHostUserNamespace(pod *api.Pod) bool { +func (kl *Kubelet) enableHostUserNamespace(pod *v1.Pod) bool { if hasPrivilegedContainer(pod) || hasHostNamespace(pod) || hasHostVolume(pod) || hasNonNamespacedCapability(pod) || kl.hasHostMountPVC(pod) { return true @@ -1435,7 +1436,7 @@ func (kl *Kubelet) enableHostUserNamespace(pod *api.Pod) bool { } // hasPrivilegedContainer returns true if any of the containers in the pod are privileged. -func hasPrivilegedContainer(pod *api.Pod) bool { +func hasPrivilegedContainer(pod *v1.Pod) bool { for _, c := range pod.Spec.Containers { if c.SecurityContext != nil && c.SecurityContext.Privileged != nil && @@ -1447,7 +1448,7 @@ func hasPrivilegedContainer(pod *api.Pod) bool { } // hasNonNamespacedCapability returns true if MKNOD, SYS_TIME, or SYS_MODULE is requested for any container. -func hasNonNamespacedCapability(pod *api.Pod) bool { +func hasNonNamespacedCapability(pod *v1.Pod) bool { for _, c := range pod.Spec.Containers { if c.SecurityContext != nil && c.SecurityContext.Capabilities != nil { for _, cap := range c.SecurityContext.Capabilities.Add { @@ -1462,7 +1463,7 @@ func hasNonNamespacedCapability(pod *api.Pod) bool { } // hasHostVolume returns true if the pod spec has a HostPath volume. -func hasHostVolume(pod *api.Pod) bool { +func hasHostVolume(pod *v1.Pod) bool { for _, v := range pod.Spec.Volumes { if v.HostPath != nil { return true @@ -1472,15 +1473,15 @@ func hasHostVolume(pod *api.Pod) bool { } // hasHostNamespace returns true if hostIPC, hostNetwork, or hostPID are set to true. -func hasHostNamespace(pod *api.Pod) bool { +func hasHostNamespace(pod *v1.Pod) bool { if pod.Spec.SecurityContext == nil { return false } - return pod.Spec.SecurityContext.HostIPC || pod.Spec.SecurityContext.HostNetwork || pod.Spec.SecurityContext.HostPID + return pod.Spec.HostIPC || pod.Spec.HostNetwork || pod.Spec.HostPID } // hasHostMountPVC returns true if a PVC is referencing a HostPath volume. -func (kl *Kubelet) hasHostMountPVC(pod *api.Pod) bool { +func (kl *Kubelet) hasHostMountPVC(pod *v1.Pod) bool { for _, volume := range pod.Spec.Volumes { if volume.PersistentVolumeClaim != nil { pvc, err := kl.kubeClient.Core().PersistentVolumeClaims(pod.Namespace).Get(volume.PersistentVolumeClaim.ClaimName) diff --git a/pkg/kubelet/kubelet_pods_test.go b/pkg/kubelet/kubelet_pods_test.go index b38372e4c35..7cac9533835 100644 --- a/pkg/kubelet/kubelet_pods_test.go +++ b/pkg/kubelet/kubelet_pods_test.go @@ -26,8 +26,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/client/testing/core" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" @@ -39,8 +39,8 @@ import ( ) func TestMakeMounts(t *testing.T) { - container := api.Container{ - VolumeMounts: []api.VolumeMount{ + container := v1.Container{ + VolumeMounts: []v1.VolumeMount{ { MountPath: "/etc/hosts", Name: "disk", @@ -70,11 +70,9 @@ func TestMakeMounts(t *testing.T) { "disk5": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/var/lib/kubelet/podID/volumes/empty/disk5"}}, } - pod := api.Pod{ - Spec: api.PodSpec{ - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, + pod := v1.Pod{ + Spec: v1.PodSpec{ + HostNetwork: true, }, } @@ -123,7 +121,7 @@ func TestRunInContainerNoSuchPod(t *testing.T) { podNamespace := "nsFoo" containerName := "containerFoo" output, err := kubelet.RunInContainer( - kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{Name: podName, Namespace: podNamespace}}), + kubecontainer.GetPodFullName(&v1.Pod{ObjectMeta: v1.ObjectMeta{Name: podName, Namespace: podNamespace}}), "", containerName, []string{"ls"}) @@ -174,13 +172,13 @@ func TestGenerateRunContainerOptions_DNSConfigurationParams(t *testing.T) { kubelet.clusterDNS = net.ParseIP(clusterNS) pods := newTestPods(2) - pods[0].Spec.DNSPolicy = api.DNSClusterFirst - pods[1].Spec.DNSPolicy = api.DNSDefault + pods[0].Spec.DNSPolicy = v1.DNSClusterFirst + pods[1].Spec.DNSPolicy = v1.DNSDefault options := make([]*kubecontainer.RunContainerOptions, 2) for i, pod := range pods { var err error - options[i], err = kubelet.GenerateRunContainerOptions(pod, &api.Container{}, "") + options[i], err = kubelet.GenerateRunContainerOptions(pod, &v1.Container{}, "") if err != nil { t.Fatalf("failed to generate container options: %v", err) } @@ -201,7 +199,7 @@ func TestGenerateRunContainerOptions_DNSConfigurationParams(t *testing.T) { kubelet.resolverConfig = "/etc/resolv.conf" for i, pod := range pods { var err error - options[i], err = kubelet.GenerateRunContainerOptions(pod, &api.Container{}, "") + options[i], err = kubelet.GenerateRunContainerOptions(pod, &v1.Container{}, "") if err != nil { t.Fatalf("failed to generate container options: %v", err) } @@ -220,10 +218,10 @@ func TestGenerateRunContainerOptions_DNSConfigurationParams(t *testing.T) { } type testServiceLister struct { - services []*api.Service + services []*v1.Service } -func (ls testServiceLister) List(labels.Selector) ([]*api.Service, error) { +func (ls testServiceLister) List(labels.Selector) ([]*v1.Service, error) { return ls.services, nil } @@ -237,12 +235,12 @@ func (e envs) Swap(i, j int) { e[i], e[j] = e[j], e[i] } func (e envs) Less(i, j int) bool { return e[i].Name < e[j].Name } -func buildService(name, namespace, clusterIP, protocol string, port int) *api.Service { - return &api.Service{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespace}, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{{ - Protocol: api.Protocol(protocol), +func buildService(name, namespace, clusterIP, protocol string, port int) *v1.Service { + return &v1.Service{ + ObjectMeta: v1.ObjectMeta{Name: name, Namespace: namespace}, + Spec: v1.ServiceSpec{ + Ports: []v1.ServicePort{{ + Protocol: v1.Protocol(protocol), Port: int32(port), }}, ClusterIP: clusterIP, @@ -251,8 +249,8 @@ func buildService(name, namespace, clusterIP, protocol string, port int) *api.Se } func TestMakeEnvironmentVariables(t *testing.T) { - services := []*api.Service{ - buildService("kubernetes", api.NamespaceDefault, "1.2.3.1", "TCP", 8081), + services := []*v1.Service{ + buildService("kubernetes", v1.NamespaceDefault, "1.2.3.1", "TCP", 8081), buildService("test", "test1", "1.2.3.3", "TCP", 8083), buildService("kubernetes", "test2", "1.2.3.4", "TCP", 8084), buildService("test", "test2", "1.2.3.5", "TCP", 8085), @@ -267,7 +265,7 @@ func TestMakeEnvironmentVariables(t *testing.T) { testCases := []struct { name string // the name of the test case ns string // the namespace to generate environment for - container *api.Container // the container to use + container *v1.Container // the container to use masterServiceNs string // the namespace to read master service info from nilLister bool // whether the lister should be nil expectedEnvs []kubecontainer.EnvVar // a set of expected environment vars @@ -275,8 +273,8 @@ func TestMakeEnvironmentVariables(t *testing.T) { { name: "api server = Y, kubelet = Y", ns: "test1", - container: &api.Container{ - Env: []api.EnvVar{ + container: &v1.Container{ + Env: []v1.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, @@ -287,7 +285,7 @@ func TestMakeEnvironmentVariables(t *testing.T) { {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, }, }, - masterServiceNs: api.NamespaceDefault, + masterServiceNs: v1.NamespaceDefault, nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAR"}, @@ -310,8 +308,8 @@ func TestMakeEnvironmentVariables(t *testing.T) { { name: "api server = Y, kubelet = N", ns: "test1", - container: &api.Container{ - Env: []api.EnvVar{ + container: &v1.Container{ + Env: []v1.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, @@ -322,7 +320,7 @@ func TestMakeEnvironmentVariables(t *testing.T) { {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, }, }, - masterServiceNs: api.NamespaceDefault, + masterServiceNs: v1.NamespaceDefault, nilLister: true, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAR"}, @@ -338,12 +336,12 @@ func TestMakeEnvironmentVariables(t *testing.T) { { name: "api server = N; kubelet = Y", ns: "test1", - container: &api.Container{ - Env: []api.EnvVar{ + container: &v1.Container{ + Env: []v1.EnvVar{ {Name: "FOO", Value: "BAZ"}, }, }, - masterServiceNs: api.NamespaceDefault, + masterServiceNs: v1.NamespaceDefault, nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAZ"}, @@ -366,8 +364,8 @@ func TestMakeEnvironmentVariables(t *testing.T) { { name: "master service in pod ns", ns: "test2", - container: &api.Container{ - Env: []api.EnvVar{ + container: &v1.Container{ + Env: []v1.EnvVar{ {Name: "FOO", Value: "ZAP"}, }, }, @@ -394,7 +392,7 @@ func TestMakeEnvironmentVariables(t *testing.T) { { name: "pod in master service ns", ns: "kubernetes", - container: &api.Container{}, + container: &v1.Container{}, masterServiceNs: "kubernetes", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ @@ -417,49 +415,49 @@ func TestMakeEnvironmentVariables(t *testing.T) { { name: "downward api pod", ns: "downward-api", - container: &api.Container{ - Env: []api.EnvVar{ + container: &v1.Container{ + Env: []v1.EnvVar{ { Name: "POD_NAME", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + ValueFrom: &v1.EnvVarSource{ + FieldRef: &v1.ObjectFieldSelector{ + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), FieldPath: "metadata.name", }, }, }, { Name: "POD_NAMESPACE", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + ValueFrom: &v1.EnvVarSource{ + FieldRef: &v1.ObjectFieldSelector{ + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), FieldPath: "metadata.namespace", }, }, }, { Name: "POD_NODE_NAME", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + ValueFrom: &v1.EnvVarSource{ + FieldRef: &v1.ObjectFieldSelector{ + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), FieldPath: "spec.nodeName", }, }, }, { Name: "POD_SERVICE_ACCOUNT_NAME", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + ValueFrom: &v1.EnvVarSource{ + FieldRef: &v1.ObjectFieldSelector{ + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), FieldPath: "spec.serviceAccountName", }, }, }, { Name: "POD_IP", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + ValueFrom: &v1.EnvVarSource{ + FieldRef: &v1.ObjectFieldSelector{ + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), FieldPath: "status.podIP", }, }, @@ -479,17 +477,17 @@ func TestMakeEnvironmentVariables(t *testing.T) { { name: "env expansion", ns: "test1", - container: &api.Container{ - Env: []api.EnvVar{ + container: &v1.Container{ + Env: []v1.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "POD_NAME", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + ValueFrom: &v1.EnvVarSource{ + FieldRef: &v1.ObjectFieldSelector{ + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), FieldPath: "metadata.name", }, }, @@ -619,12 +617,12 @@ func TestMakeEnvironmentVariables(t *testing.T) { kl.serviceLister = testServiceLister{services} } - testPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + testPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: tc.ns, Name: "dapi-test-pod-name", }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ ServiceAccountName: "special", NodeName: "node-name", }, @@ -640,58 +638,58 @@ func TestMakeEnvironmentVariables(t *testing.T) { } } -func waitingState(cName string) api.ContainerStatus { - return api.ContainerStatus{ +func waitingState(cName string) v1.ContainerStatus { + return v1.ContainerStatus{ Name: cName, - State: api.ContainerState{ - Waiting: &api.ContainerStateWaiting{}, + State: v1.ContainerState{ + Waiting: &v1.ContainerStateWaiting{}, }, } } -func waitingStateWithLastTermination(cName string) api.ContainerStatus { - return api.ContainerStatus{ +func waitingStateWithLastTermination(cName string) v1.ContainerStatus { + return v1.ContainerStatus{ Name: cName, - State: api.ContainerState{ - Waiting: &api.ContainerStateWaiting{}, + State: v1.ContainerState{ + Waiting: &v1.ContainerStateWaiting{}, }, - LastTerminationState: api.ContainerState{ - Terminated: &api.ContainerStateTerminated{ + LastTerminationState: v1.ContainerState{ + Terminated: &v1.ContainerStateTerminated{ ExitCode: 0, }, }, } } -func runningState(cName string) api.ContainerStatus { - return api.ContainerStatus{ +func runningState(cName string) v1.ContainerStatus { + return v1.ContainerStatus{ Name: cName, - State: api.ContainerState{ - Running: &api.ContainerStateRunning{}, + State: v1.ContainerState{ + Running: &v1.ContainerStateRunning{}, }, } } -func stoppedState(cName string) api.ContainerStatus { - return api.ContainerStatus{ +func stoppedState(cName string) v1.ContainerStatus { + return v1.ContainerStatus{ Name: cName, - State: api.ContainerState{ - Terminated: &api.ContainerStateTerminated{}, + State: v1.ContainerState{ + Terminated: &v1.ContainerStateTerminated{}, }, } } -func succeededState(cName string) api.ContainerStatus { - return api.ContainerStatus{ +func succeededState(cName string) v1.ContainerStatus { + return v1.ContainerStatus{ Name: cName, - State: api.ContainerState{ - Terminated: &api.ContainerStateTerminated{ + State: v1.ContainerState{ + Terminated: &v1.ContainerStateTerminated{ ExitCode: 0, }, }, } } -func failedState(cName string) api.ContainerStatus { - return api.ContainerStatus{ +func failedState(cName string) v1.ContainerStatus { + return v1.ContainerStatus{ Name: cName, - State: api.ContainerState{ - Terminated: &api.ContainerStateTerminated{ + State: v1.ContainerState{ + Terminated: &v1.ContainerStateTerminated{ ExitCode: -1, }, }, @@ -699,96 +697,96 @@ func failedState(cName string) api.ContainerStatus { } func TestPodPhaseWithRestartAlways(t *testing.T) { - desiredState := api.PodSpec{ + desiredState := v1.PodSpec{ NodeName: "machine", - Containers: []api.Container{ + Containers: []v1.Container{ {Name: "containerA"}, {Name: "containerB"}, }, - RestartPolicy: api.RestartPolicyAlways, + RestartPolicy: v1.RestartPolicyAlways, } tests := []struct { - pod *api.Pod - status api.PodPhase + pod *v1.Pod + status v1.PodPhase test string }{ - {&api.Pod{Spec: desiredState, Status: api.PodStatus{}}, api.PodPending, "waiting"}, + {&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"}, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, - api.PodRunning, + v1.PodRunning, "all running", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ stoppedState("containerA"), stoppedState("containerB"), }, }, }, - api.PodRunning, + v1.PodRunning, "all stopped with restart always", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), stoppedState("containerB"), }, }, }, - api.PodRunning, + v1.PodRunning, "mixed state #1 with restart always", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), }, }, }, - api.PodPending, + v1.PodPending, "mixed state #2 with restart always", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), waitingState("containerB"), }, }, }, - api.PodPending, + v1.PodPending, "mixed state #3 with restart always", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), waitingStateWithLastTermination("containerB"), }, }, }, - api.PodRunning, + v1.PodRunning, "backoff crashloop container with restart always", }, } @@ -799,96 +797,96 @@ func TestPodPhaseWithRestartAlways(t *testing.T) { } func TestPodPhaseWithRestartNever(t *testing.T) { - desiredState := api.PodSpec{ + desiredState := v1.PodSpec{ NodeName: "machine", - Containers: []api.Container{ + Containers: []v1.Container{ {Name: "containerA"}, {Name: "containerB"}, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, } tests := []struct { - pod *api.Pod - status api.PodPhase + pod *v1.Pod + status v1.PodPhase test string }{ - {&api.Pod{Spec: desiredState, Status: api.PodStatus{}}, api.PodPending, "waiting"}, + {&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"}, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, - api.PodRunning, + v1.PodRunning, "all running with restart never", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ succeededState("containerA"), succeededState("containerB"), }, }, }, - api.PodSucceeded, + v1.PodSucceeded, "all succeeded with restart never", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ failedState("containerA"), failedState("containerB"), }, }, }, - api.PodFailed, + v1.PodFailed, "all failed with restart never", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), succeededState("containerB"), }, }, }, - api.PodRunning, + v1.PodRunning, "mixed state #1 with restart never", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), }, }, }, - api.PodPending, + v1.PodPending, "mixed state #2 with restart never", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), waitingState("containerB"), }, }, }, - api.PodPending, + v1.PodPending, "mixed state #3 with restart never", }, } @@ -899,109 +897,109 @@ func TestPodPhaseWithRestartNever(t *testing.T) { } func TestPodPhaseWithRestartOnFailure(t *testing.T) { - desiredState := api.PodSpec{ + desiredState := v1.PodSpec{ NodeName: "machine", - Containers: []api.Container{ + Containers: []v1.Container{ {Name: "containerA"}, {Name: "containerB"}, }, - RestartPolicy: api.RestartPolicyOnFailure, + RestartPolicy: v1.RestartPolicyOnFailure, } tests := []struct { - pod *api.Pod - status api.PodPhase + pod *v1.Pod + status v1.PodPhase test string }{ - {&api.Pod{Spec: desiredState, Status: api.PodStatus{}}, api.PodPending, "waiting"}, + {&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"}, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, - api.PodRunning, + v1.PodRunning, "all running with restart onfailure", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ succeededState("containerA"), succeededState("containerB"), }, }, }, - api.PodSucceeded, + v1.PodSucceeded, "all succeeded with restart onfailure", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ failedState("containerA"), failedState("containerB"), }, }, }, - api.PodRunning, + v1.PodRunning, "all failed with restart never", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), succeededState("containerB"), }, }, }, - api.PodRunning, + v1.PodRunning, "mixed state #1 with restart onfailure", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), }, }, }, - api.PodPending, + v1.PodPending, "mixed state #2 with restart onfailure", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), waitingState("containerB"), }, }, }, - api.PodPending, + v1.PodPending, "mixed state #3 with restart onfailure", }, { - &api.Pod{ + &v1.Pod{ Spec: desiredState, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ + Status: v1.PodStatus{ + ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), waitingStateWithLastTermination("containerB"), }, }, }, - api.PodRunning, + v1.PodRunning, "backoff crashloop container with restart onfailure", }, } @@ -1218,17 +1216,17 @@ func TestPortForward(t *testing.T) { // Tests that identify the host port conflicts are detected correctly. func TestGetHostPortConflicts(t *testing.T) { - pods := []*api.Pod{ - {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}}}, - {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 81}}}}}}, - {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 82}}}}}}, - {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 83}}}}}}, + pods := []*v1.Pod{ + {Spec: v1.PodSpec{Containers: []v1.Container{{Ports: []v1.ContainerPort{{HostPort: 80}}}}}}, + {Spec: v1.PodSpec{Containers: []v1.Container{{Ports: []v1.ContainerPort{{HostPort: 81}}}}}}, + {Spec: v1.PodSpec{Containers: []v1.Container{{Ports: []v1.ContainerPort{{HostPort: 82}}}}}}, + {Spec: v1.PodSpec{Containers: []v1.Container{{Ports: []v1.ContainerPort{{HostPort: 83}}}}}}, } // Pods should not cause any conflict. assert.False(t, hasHostPortConflicts(pods), "Should not have port conflicts") - expected := &api.Pod{ - Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 81}}}}}, + expected := &v1.Pod{ + Spec: v1.PodSpec{Containers: []v1.Container{{Ports: []v1.ContainerPort{{HostPort: 81}}}}}, } // The new pod should cause conflict and be reported. pods = append(pods, expected) @@ -1237,21 +1235,21 @@ func TestGetHostPortConflicts(t *testing.T) { func TestMakeDevices(t *testing.T) { testCases := []struct { - container *api.Container + container *v1.Container devices []kubecontainer.DeviceInfo test string }{ { test: "no device", - container: &api.Container{}, + container: &v1.Container{}, devices: nil, }, { test: "gpu", - container: &api.Container{ - Resources: api.ResourceRequirements{ - Limits: map[api.ResourceName]resource.Quantity{ - api.ResourceNvidiaGPU: resource.MustParse("1000"), + container: &v1.Container{ + Resources: v1.ResourceRequirements{ + Limits: map[v1.ResourceName]resource.Quantity{ + v1.ResourceNvidiaGPU: resource.MustParse("1000"), }, }, }, @@ -1273,7 +1271,7 @@ func TestHasPrivilegedContainer(t *testing.T) { return &b } tests := map[string]struct { - securityContext *api.SecurityContext + securityContext *v1.SecurityContext expected bool }{ "nil sc": { @@ -1281,23 +1279,23 @@ func TestHasPrivilegedContainer(t *testing.T) { expected: false, }, "nil privleged": { - securityContext: &api.SecurityContext{}, + securityContext: &v1.SecurityContext{}, expected: false, }, "false privleged": { - securityContext: &api.SecurityContext{Privileged: newBoolPtr(false)}, + securityContext: &v1.SecurityContext{Privileged: newBoolPtr(false)}, expected: false, }, "true privleged": { - securityContext: &api.SecurityContext{Privileged: newBoolPtr(true)}, + securityContext: &v1.SecurityContext{Privileged: newBoolPtr(true)}, expected: true, }, } for k, v := range tests { - pod := &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + pod := &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {SecurityContext: v.securityContext}, }, }, @@ -1342,34 +1340,34 @@ func TestHasHostMountPVC(t *testing.T) { for k, v := range tests { testKubelet := newTestKubelet(t, false) - pod := &api.Pod{ - Spec: api.PodSpec{}, + pod := &v1.Pod{ + Spec: v1.PodSpec{}, } - volumeToReturn := &api.PersistentVolume{ - Spec: api.PersistentVolumeSpec{}, + volumeToReturn := &v1.PersistentVolume{ + Spec: v1.PersistentVolumeSpec{}, } if v.podHasPVC { - pod.Spec.Volumes = []api.Volume{ + pod.Spec.Volumes = []v1.Volume{ { - VolumeSource: api.VolumeSource{ - PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{}, + VolumeSource: v1.VolumeSource{ + PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{}, }, }, } if v.pvcIsHostPath { - volumeToReturn.Spec.PersistentVolumeSource = api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{}, + volumeToReturn.Spec.PersistentVolumeSource = v1.PersistentVolumeSource{ + HostPath: &v1.HostPathVolumeSource{}, } } } testKubelet.fakeKubeClient.AddReactor("get", "persistentvolumeclaims", func(action core.Action) (bool, runtime.Object, error) { - return true, &api.PersistentVolumeClaim{ - Spec: api.PersistentVolumeClaimSpec{ + return true, &v1.PersistentVolumeClaim{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "foo", }, }, v.pvcError @@ -1387,16 +1385,16 @@ func TestHasHostMountPVC(t *testing.T) { } func TestHasNonNamespacedCapability(t *testing.T) { - createPodWithCap := func(caps []api.Capability) *api.Pod { - pod := &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{{}}, + createPodWithCap := func(caps []v1.Capability) *v1.Pod { + pod := &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{}}, }, } if len(caps) > 0 { - pod.Spec.Containers[0].SecurityContext = &api.SecurityContext{ - Capabilities: &api.Capabilities{ + pod.Spec.Containers[0].SecurityContext = &v1.SecurityContext{ + Capabilities: &v1.Capabilities{ Add: caps, }, } @@ -1404,19 +1402,19 @@ func TestHasNonNamespacedCapability(t *testing.T) { return pod } - nilCaps := createPodWithCap([]api.Capability{api.Capability("foo")}) + nilCaps := createPodWithCap([]v1.Capability{v1.Capability("foo")}) nilCaps.Spec.Containers[0].SecurityContext = nil tests := map[string]struct { - pod *api.Pod + pod *v1.Pod expected bool }{ "nil security contxt": {createPodWithCap(nil), false}, "nil caps": {nilCaps, false}, - "namespaced cap": {createPodWithCap([]api.Capability{api.Capability("foo")}), false}, - "non-namespaced cap MKNOD": {createPodWithCap([]api.Capability{api.Capability("MKNOD")}), true}, - "non-namespaced cap SYS_TIME": {createPodWithCap([]api.Capability{api.Capability("SYS_TIME")}), true}, - "non-namespaced cap SYS_MODULE": {createPodWithCap([]api.Capability{api.Capability("SYS_MODULE")}), true}, + "namespaced cap": {createPodWithCap([]v1.Capability{v1.Capability("foo")}), false}, + "non-namespaced cap MKNOD": {createPodWithCap([]v1.Capability{v1.Capability("MKNOD")}), true}, + "non-namespaced cap SYS_TIME": {createPodWithCap([]v1.Capability{v1.Capability("SYS_TIME")}), true}, + "non-namespaced cap SYS_MODULE": {createPodWithCap([]v1.Capability{v1.Capability("SYS_MODULE")}), true}, } for k, v := range tests { @@ -1428,12 +1426,12 @@ func TestHasNonNamespacedCapability(t *testing.T) { } func TestHasHostVolume(t *testing.T) { - pod := &api.Pod{ - Spec: api.PodSpec{ - Volumes: []api.Volume{ + pod := &v1.Pod{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{}, + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{}, }, }, }, @@ -1454,39 +1452,45 @@ func TestHasHostVolume(t *testing.T) { func TestHasHostNamespace(t *testing.T) { tests := map[string]struct { - psc *api.PodSecurityContext + ps v1.PodSpec expected bool }{ - "nil psc": {psc: nil, expected: false}, + "nil psc": { + ps: v1.PodSpec{}, + expected: false}, + "host pid true": { - psc: &api.PodSecurityContext{ - HostPID: true, + ps: v1.PodSpec{ + HostPID: true, + SecurityContext: &v1.PodSecurityContext{}, }, expected: true, }, "host ipc true": { - psc: &api.PodSecurityContext{ - HostIPC: true, + ps: v1.PodSpec{ + HostIPC: true, + SecurityContext: &v1.PodSecurityContext{}, }, expected: true, }, "host net true": { - psc: &api.PodSecurityContext{ - HostNetwork: true, + ps: v1.PodSpec{ + HostNetwork: true, + SecurityContext: &v1.PodSecurityContext{}, }, expected: true, }, "no host ns": { - psc: &api.PodSecurityContext{}, + ps: v1.PodSpec{ + SecurityContext: &v1.PodSecurityContext{}, + }, expected: false, }, } for k, v := range tests { - pod := &api.Pod{ - Spec: api.PodSpec{ - SecurityContext: v.psc, - }, + pod := &v1.Pod{ + Spec: v.ps, } actual := hasHostNamespace(pod) if actual != v.expected { diff --git a/pkg/kubelet/kubelet_resources.go b/pkg/kubelet/kubelet_resources.go index 53a1107ce37..ea2a3033b64 100644 --- a/pkg/kubelet/kubelet_resources.go +++ b/pkg/kubelet/kubelet_resources.go @@ -20,6 +20,7 @@ import ( "fmt" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/fieldpath" ) @@ -30,7 +31,7 @@ import ( // the node allocatable. // TODO: if/when we have pod level resources, we need to update this function // to use those limits instead of node allocatable. -func (kl *Kubelet) defaultPodLimitsForDownwardApi(pod *api.Pod, container *api.Container) (*api.Pod, *api.Container, error) { +func (kl *Kubelet) defaultPodLimitsForDownwardApi(pod *v1.Pod, container *v1.Container) (*v1.Pod, *v1.Container, error) { if pod == nil { return nil, nil, fmt.Errorf("invalid input, pod cannot be nil") } @@ -45,7 +46,7 @@ func (kl *Kubelet) defaultPodLimitsForDownwardApi(pod *api.Pod, container *api.C if err != nil { return nil, nil, fmt.Errorf("failed to perform a deep copy of pod object: %v", err) } - outputPod, ok := podCopy.(*api.Pod) + outputPod, ok := podCopy.(*v1.Pod) if !ok { return nil, nil, fmt.Errorf("unexpected type returned from deep copy of pod object") } @@ -53,13 +54,13 @@ func (kl *Kubelet) defaultPodLimitsForDownwardApi(pod *api.Pod, container *api.C fieldpath.MergeContainerResourceLimits(&outputPod.Spec.Containers[idx], allocatable) } - var outputContainer *api.Container + var outputContainer *v1.Container if container != nil { containerCopy, err := api.Scheme.DeepCopy(container) if err != nil { return nil, nil, fmt.Errorf("failed to perform a deep copy of container object: %v", err) } - outputContainer, ok = containerCopy.(*api.Container) + outputContainer, ok = containerCopy.(*v1.Container) if !ok { return nil, nil, fmt.Errorf("unexpected type returned from deep copy of container object") } diff --git a/pkg/kubelet/kubelet_resources_test.go b/pkg/kubelet/kubelet_resources_test.go index 751df62cd1c..b0a09da9222 100644 --- a/pkg/kubelet/kubelet_resources_test.go +++ b/pkg/kubelet/kubelet_resources_test.go @@ -25,6 +25,7 @@ import ( cadvisorapiv2 "github.com/google/cadvisor/info/v2" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" ) @@ -41,19 +42,19 @@ func TestPodResourceLimitsDefaulting(t *testing.T) { tk.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) tk.kubelet.reservation = kubetypes.Reservation{ - Kubernetes: api.ResourceList{ - api.ResourceCPU: resource.MustParse("3"), - api.ResourceMemory: resource.MustParse("4Gi"), + Kubernetes: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("3"), + v1.ResourceMemory: resource.MustParse("4Gi"), }, - System: api.ResourceList{ - api.ResourceCPU: resource.MustParse("1"), - api.ResourceMemory: resource.MustParse("2Gi"), + System: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("1"), + v1.ResourceMemory: resource.MustParse("2Gi"), }, } cases := []struct { - pod *api.Pod - expected *api.Pod + pod *v1.Pod + expected *v1.Pod }{ { pod: getPod("0", "0"), @@ -82,20 +83,20 @@ func TestPodResourceLimitsDefaulting(t *testing.T) { } } -func getPod(cpuLimit, memoryLimit string) *api.Pod { - resources := api.ResourceRequirements{} +func getPod(cpuLimit, memoryLimit string) *v1.Pod { + resources := v1.ResourceRequirements{} if cpuLimit != "" || memoryLimit != "" { - resources.Limits = make(api.ResourceList) + resources.Limits = make(v1.ResourceList) } if cpuLimit != "" { - resources.Limits[api.ResourceCPU] = resource.MustParse(cpuLimit) + resources.Limits[v1.ResourceCPU] = resource.MustParse(cpuLimit) } if memoryLimit != "" { - resources.Limits[api.ResourceMemory] = resource.MustParse(memoryLimit) + resources.Limits[v1.ResourceMemory] = resource.MustParse(memoryLimit) } - return &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + return &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "foo", Resources: resources, diff --git a/pkg/kubelet/kubelet_test.go b/pkg/kubelet/kubelet_test.go index 0c7ad75ad68..b62d718800b 100644 --- a/pkg/kubelet/kubelet_test.go +++ b/pkg/kubelet/kubelet_test.go @@ -28,12 +28,12 @@ import ( cadvisorapiv2 "github.com/google/cadvisor/info/v2" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" "k8s.io/kubernetes/pkg/capabilities" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/record" cadvisortest "k8s.io/kubernetes/pkg/kubelet/cadvisor/testing" "k8s.io/kubernetes/pkg/kubelet/cm" @@ -141,7 +141,7 @@ func newTestKubeletWithImageList( t.Fatalf("can't mkdir(%q): %v", kubelet.rootDirectory, err) } kubelet.sourcesReady = config.NewSourcesReady(func(_ sets.String) bool { return true }) - kubelet.masterServiceNamespace = api.NamespaceDefault + kubelet.masterServiceNamespace = v1.NamespaceDefault kubelet.serviceLister = testServiceLister{} kubelet.nodeLister = testNodeLister{} kubelet.nodeInfo = testNodeInfo{} @@ -149,7 +149,7 @@ func newTestKubeletWithImageList( if err := kubelet.setupDataDirs(); err != nil { t.Fatalf("can't initialize kubelet data dirs: %v", err) } - kubelet.daemonEndpoints = &api.NodeDaemonEndpoints{} + kubelet.daemonEndpoints = &v1.NodeDaemonEndpoints{} mockCadvisor := &cadvisortest.Mock{} kubelet.cadvisor = mockCadvisor @@ -178,7 +178,7 @@ func newTestKubeletWithImageList( kubelet.livenessManager = proberesults.NewManager() kubelet.containerManager = cm.NewStubContainerManager() - fakeNodeRef := &api.ObjectReference{ + fakeNodeRef := &v1.ObjectReference{ Kind: "Node", Name: testKubeletHostname, UID: types.UID(testKubeletHostname), @@ -195,9 +195,9 @@ func newTestKubeletWithImageList( kubelet.podKillingCh = make(chan *kubecontainer.PodPair, 20) kubelet.resyncInterval = 10 * time.Second kubelet.reservation = kubetypes.Reservation{ - Kubernetes: api.ResourceList{ - api.ResourceCPU: resource.MustParse(testReservationCPU), - api.ResourceMemory: resource.MustParse(testReservationMemory), + Kubernetes: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse(testReservationCPU), + v1.ResourceMemory: resource.MustParse(testReservationMemory), }, } kubelet.workQueue = queue.NewBasicWorkQueue(fakeClock) @@ -209,7 +209,7 @@ func newTestKubeletWithImageList( // TODO: Factor out "StatsProvider" from Kubelet so we don't have a cyclic dependency volumeStatsAggPeriod := time.Second * 10 kubelet.resourceAnalyzer = stats.NewResourceAnalyzer(kubelet, volumeStatsAggPeriod, kubelet.containerRuntime) - nodeRef := &api.ObjectReference{ + nodeRef := &v1.ObjectReference{ Kind: "Node", Name: string(kubelet.nodeName), UID: types.UID(kubelet.nodeName), @@ -253,16 +253,14 @@ func newTestKubeletWithImageList( return &TestKubelet{kubelet, fakeRuntime, mockCadvisor, fakeKubeClient, fakeMirrorClient, fakeClock, nil, plug} } -func newTestPods(count int) []*api.Pod { - pods := make([]*api.Pod, count) +func newTestPods(count int) []*v1.Pod { + pods := make([]*v1.Pod, count) for i := 0; i < count; i++ { - pods[i] = &api.Pod{ - Spec: api.PodSpec{ - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, + pods[i] = &v1.Pod{ + Spec: v1.PodSpec{ + HostNetwork: true, }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: types.UID(10000 + i), Name: fmt.Sprintf("pod%d", i), }, @@ -326,9 +324,9 @@ func TestSyncPodsStartPod(t *testing.T) { testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime - pods := []*api.Pod{ - podWithUidNameNsSpec("12345678", "foo", "new", api.PodSpec{ - Containers: []api.Container{ + pods := []*v1.Pod{ + podWithUidNameNsSpec("12345678", "foo", "new", v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar"}, }, }), @@ -371,14 +369,14 @@ func TestSyncPodsDeletesWhenSourcesAreReady(t *testing.T) { } type testNodeLister struct { - nodes []api.Node + nodes []v1.Node } type testNodeInfo struct { - nodes []api.Node + nodes []v1.Node } -func (ls testNodeInfo) GetNodeInfo(id string) (*api.Node, error) { +func (ls testNodeInfo) GetNodeInfo(id string) (*v1.Node, error) { for _, node := range ls.nodes { if node.Name == id { return &node, nil @@ -387,8 +385,8 @@ func (ls testNodeInfo) GetNodeInfo(id string) (*api.Node, error) { return nil, fmt.Errorf("Node with name: %s does not exist", id) } -func (ls testNodeLister) List() (api.NodeList, error) { - return api.NodeList{ +func (ls testNodeLister) List() (v1.NodeList, error) { + return v1.NodeList{ Items: ls.nodes, }, nil } @@ -401,29 +399,29 @@ func TestHandlePortConflicts(t *testing.T) { testKubelet.fakeCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) - kl.nodeLister = testNodeLister{nodes: []api.Node{ + kl.nodeLister = testNodeLister{nodes: []v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: string(kl.nodeName)}, - Status: api.NodeStatus{ - Allocatable: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), + ObjectMeta: v1.ObjectMeta{Name: string(kl.nodeName)}, + Status: v1.NodeStatus{ + Allocatable: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), }, }, }, }} - kl.nodeInfo = testNodeInfo{nodes: []api.Node{ + kl.nodeInfo = testNodeInfo{nodes: []v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: string(kl.nodeName)}, - Status: api.NodeStatus{ - Allocatable: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), + ObjectMeta: v1.ObjectMeta{Name: string(kl.nodeName)}, + Status: v1.NodeStatus{ + Allocatable: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), }, }, }, }} - spec := api.PodSpec{NodeName: string(kl.nodeName), Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}} - pods := []*api.Pod{ + spec := v1.PodSpec{NodeName: string(kl.nodeName), Containers: []v1.Container{{Ports: []v1.ContainerPort{{HostPort: 80}}}}} + pods := []*v1.Pod{ podWithUidNameNsSpec("123456789", "newpod", "foo", spec), podWithUidNameNsSpec("987654321", "oldpod", "foo", spec), } @@ -439,12 +437,12 @@ func TestHandlePortConflicts(t *testing.T) { // notfittingPod should be Failed status, found := kl.statusManager.GetPodStatus(notfittingPod.UID) require.True(t, found, "Status of pod %q is not found in the status map", notfittingPod.UID) - require.Equal(t, api.PodFailed, status.Phase) + require.Equal(t, v1.PodFailed, status.Phase) // fittingPod should be Pending status, found = kl.statusManager.GetPodStatus(fittingPod.UID) require.True(t, found, "Status of pod %q is not found in the status map", fittingPod.UID) - require.Equal(t, api.PodPending, status.Phase) + require.Equal(t, v1.PodPending, status.Phase) } // Tests that we handle host name conflicts correctly by setting the failed status in status map. @@ -455,31 +453,31 @@ func TestHandleHostNameConflicts(t *testing.T) { testKubelet.fakeCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) - kl.nodeLister = testNodeLister{nodes: []api.Node{ + kl.nodeLister = testNodeLister{nodes: []v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: "127.0.0.1"}, - Status: api.NodeStatus{ - Allocatable: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), + ObjectMeta: v1.ObjectMeta{Name: "127.0.0.1"}, + Status: v1.NodeStatus{ + Allocatable: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), }, }, }, }} - kl.nodeInfo = testNodeInfo{nodes: []api.Node{ + kl.nodeInfo = testNodeInfo{nodes: []v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: "127.0.0.1"}, - Status: api.NodeStatus{ - Allocatable: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), + ObjectMeta: v1.ObjectMeta{Name: "127.0.0.1"}, + Status: v1.NodeStatus{ + Allocatable: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), }, }, }, }} // default NodeName in test is 127.0.0.1 - pods := []*api.Pod{ - podWithUidNameNsSpec("123456789", "notfittingpod", "foo", api.PodSpec{NodeName: "127.0.0.2"}), - podWithUidNameNsSpec("987654321", "fittingpod", "foo", api.PodSpec{NodeName: "127.0.0.1"}), + pods := []*v1.Pod{ + podWithUidNameNsSpec("123456789", "notfittingpod", "foo", v1.PodSpec{NodeName: "127.0.0.2"}), + podWithUidNameNsSpec("987654321", "fittingpod", "foo", v1.PodSpec{NodeName: "127.0.0.1"}), } notfittingPod := pods[0] @@ -490,24 +488,24 @@ func TestHandleHostNameConflicts(t *testing.T) { // notfittingPod should be Failed status, found := kl.statusManager.GetPodStatus(notfittingPod.UID) require.True(t, found, "Status of pod %q is not found in the status map", notfittingPod.UID) - require.Equal(t, api.PodFailed, status.Phase) + require.Equal(t, v1.PodFailed, status.Phase) // fittingPod should be Pending status, found = kl.statusManager.GetPodStatus(fittingPod.UID) require.True(t, found, "Status of pod %q is not found in the status map", fittingPod.UID) - require.Equal(t, api.PodPending, status.Phase) + require.Equal(t, v1.PodPending, status.Phase) } // Tests that we handle not matching labels selector correctly by setting the failed status in status map. func TestHandleNodeSelector(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kl := testKubelet.kubelet - nodes := []api.Node{ + nodes := []v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: testKubeletHostname, Labels: map[string]string{"key": "B"}}, - Status: api.NodeStatus{ - Allocatable: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), + ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname, Labels: map[string]string{"key": "B"}}, + Status: v1.NodeStatus{ + Allocatable: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), }, }, }, @@ -517,9 +515,9 @@ func TestHandleNodeSelector(t *testing.T) { testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorapi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) - pods := []*api.Pod{ - podWithUidNameNsSpec("123456789", "podA", "foo", api.PodSpec{NodeSelector: map[string]string{"key": "A"}}), - podWithUidNameNsSpec("987654321", "podB", "foo", api.PodSpec{NodeSelector: map[string]string{"key": "B"}}), + pods := []*v1.Pod{ + podWithUidNameNsSpec("123456789", "podA", "foo", v1.PodSpec{NodeSelector: map[string]string{"key": "A"}}), + podWithUidNameNsSpec("987654321", "podB", "foo", v1.PodSpec{NodeSelector: map[string]string{"key": "B"}}), } // The first pod should be rejected. notfittingPod := pods[0] @@ -530,24 +528,24 @@ func TestHandleNodeSelector(t *testing.T) { // notfittingPod should be Failed status, found := kl.statusManager.GetPodStatus(notfittingPod.UID) require.True(t, found, "Status of pod %q is not found in the status map", notfittingPod.UID) - require.Equal(t, api.PodFailed, status.Phase) + require.Equal(t, v1.PodFailed, status.Phase) // fittingPod should be Pending status, found = kl.statusManager.GetPodStatus(fittingPod.UID) require.True(t, found, "Status of pod %q is not found in the status map", fittingPod.UID) - require.Equal(t, api.PodPending, status.Phase) + require.Equal(t, v1.PodPending, status.Phase) } // Tests that we handle exceeded resources correctly by setting the failed status in status map. func TestHandleMemExceeded(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kl := testKubelet.kubelet - nodes := []api.Node{ - {ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, - Status: api.NodeStatus{Capacity: api.ResourceList{}, Allocatable: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(10, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(100, resource.BinarySI), - api.ResourcePods: *resource.NewQuantity(40, resource.DecimalSI), + nodes := []v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}, + Status: v1.NodeStatus{Capacity: v1.ResourceList{}, Allocatable: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(10, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(100, resource.BinarySI), + v1.ResourcePods: *resource.NewQuantity(40, resource.DecimalSI), }}}, } kl.nodeLister = testNodeLister{nodes: nodes} @@ -556,13 +554,13 @@ func TestHandleMemExceeded(t *testing.T) { testKubelet.fakeCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) - spec := api.PodSpec{NodeName: string(kl.nodeName), - Containers: []api.Container{{Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + spec := v1.PodSpec{NodeName: string(kl.nodeName), + Containers: []v1.Container{{Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "memory": resource.MustParse("90"), }, }}}} - pods := []*api.Pod{ + pods := []*v1.Pod{ podWithUidNameNsSpec("123456789", "newpod", "foo", spec), podWithUidNameNsSpec("987654321", "oldpod", "foo", spec), } @@ -578,12 +576,12 @@ func TestHandleMemExceeded(t *testing.T) { // notfittingPod should be Failed status, found := kl.statusManager.GetPodStatus(notfittingPod.UID) require.True(t, found, "Status of pod %q is not found in the status map", notfittingPod.UID) - require.Equal(t, api.PodFailed, status.Phase) + require.Equal(t, v1.PodFailed, status.Phase) // fittingPod should be Pending status, found = kl.statusManager.GetPodStatus(fittingPod.UID) require.True(t, found, "Status of pod %q is not found in the status map", fittingPod.UID) - require.Equal(t, api.PodPending, status.Phase) + require.Equal(t, v1.PodPending, status.Phase) } // TODO(filipg): This test should be removed once StatusSyncer can do garbage collection without external signal. @@ -600,9 +598,9 @@ func TestPurgingObsoleteStatusMapEntries(t *testing.T) { testKubelet.fakeCadvisor.On("VersionInfo").Return(versionInfo, nil) kl := testKubelet.kubelet - pods := []*api.Pod{ - {ObjectMeta: api.ObjectMeta{Name: "pod1", UID: "1234"}, Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}}}, - {ObjectMeta: api.ObjectMeta{Name: "pod2", UID: "4567"}, Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}}}, + pods := []*v1.Pod{ + {ObjectMeta: v1.ObjectMeta{Name: "pod1", UID: "1234"}, Spec: v1.PodSpec{Containers: []v1.Container{{Ports: []v1.ContainerPort{{HostPort: 80}}}}}}, + {ObjectMeta: v1.ObjectMeta{Name: "pod2", UID: "4567"}, Spec: v1.PodSpec{Containers: []v1.Container{{Ports: []v1.ContainerPort{{HostPort: 80}}}}}}, } podToTest := pods[1] // Run once to populate the status map. @@ -611,7 +609,7 @@ func TestPurgingObsoleteStatusMapEntries(t *testing.T) { t.Fatalf("expected to have status cached for pod2") } // Sync with empty pods so that the entry in status map will be removed. - kl.podManager.SetPods([]*api.Pod{}) + kl.podManager.SetPods([]*v1.Pod{}) kl.HandlePodCleanups() if _, found := kl.statusManager.GetPodStatus(podToTest.UID); found { t.Fatalf("expected to not have status cached for pod2") @@ -623,19 +621,19 @@ func TestValidateContainerLogStatus(t *testing.T) { kubelet := testKubelet.kubelet containerName := "x" testCases := []struct { - statuses []api.ContainerStatus + statuses []v1.ContainerStatus success bool // whether getting logs for the container should succeed. pSuccess bool // whether getting logs for the previous container should succeed. }{ { - statuses: []api.ContainerStatus{ + statuses: []v1.ContainerStatus{ { Name: containerName, - State: api.ContainerState{ - Running: &api.ContainerStateRunning{}, + State: v1.ContainerState{ + Running: &v1.ContainerStateRunning{}, }, - LastTerminationState: api.ContainerState{ - Terminated: &api.ContainerStateTerminated{}, + LastTerminationState: v1.ContainerState{ + Terminated: &v1.ContainerStateTerminated{}, }, }, }, @@ -643,11 +641,11 @@ func TestValidateContainerLogStatus(t *testing.T) { pSuccess: true, }, { - statuses: []api.ContainerStatus{ + statuses: []v1.ContainerStatus{ { Name: containerName, - State: api.ContainerState{ - Running: &api.ContainerStateRunning{}, + State: v1.ContainerState{ + Running: &v1.ContainerStateRunning{}, }, }, }, @@ -655,11 +653,11 @@ func TestValidateContainerLogStatus(t *testing.T) { pSuccess: false, }, { - statuses: []api.ContainerStatus{ + statuses: []v1.ContainerStatus{ { Name: containerName, - State: api.ContainerState{ - Terminated: &api.ContainerStateTerminated{}, + State: v1.ContainerState{ + Terminated: &v1.ContainerStateTerminated{}, }, }, }, @@ -667,11 +665,11 @@ func TestValidateContainerLogStatus(t *testing.T) { pSuccess: false, }, { - statuses: []api.ContainerStatus{ + statuses: []v1.ContainerStatus{ { Name: containerName, - State: api.ContainerState{ - Waiting: &api.ContainerStateWaiting{}, + State: v1.ContainerState{ + Waiting: &v1.ContainerStateWaiting{}, }, }, }, @@ -679,20 +677,20 @@ func TestValidateContainerLogStatus(t *testing.T) { pSuccess: false, }, { - statuses: []api.ContainerStatus{ + statuses: []v1.ContainerStatus{ { Name: containerName, - State: api.ContainerState{Waiting: &api.ContainerStateWaiting{Reason: "ErrImagePull"}}, + State: v1.ContainerState{Waiting: &v1.ContainerStateWaiting{Reason: "ErrImagePull"}}, }, }, success: false, pSuccess: false, }, { - statuses: []api.ContainerStatus{ + statuses: []v1.ContainerStatus{ { Name: containerName, - State: api.ContainerState{Waiting: &api.ContainerStateWaiting{Reason: "ErrImagePullBackOff"}}, + State: v1.ContainerState{Waiting: &v1.ContainerStateWaiting{Reason: "ErrImagePullBackOff"}}, }, }, success: false, @@ -703,7 +701,7 @@ func TestValidateContainerLogStatus(t *testing.T) { for i, tc := range testCases { // Access the log of the most recent container previous := false - podStatus := &api.PodStatus{ContainerStatuses: tc.statuses} + podStatus := &v1.PodStatus{ContainerStatuses: tc.statuses} _, err := kubelet.validateContainerLogStatus("podName", podStatus, containerName, previous) if !tc.success { assert.Error(t, err, fmt.Sprintf("[case %d] error", i)) @@ -756,7 +754,7 @@ func TestCreateMirrorPod(t *testing.T) { manager := testKubelet.fakeMirrorClient pod := podWithUidNameNs("12345678", "bar", "foo") pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = "file" - pods := []*api.Pod{pod} + pods := []*v1.Pod{pod} kl.podManager.SetPods(pods) err := kl.syncPod(syncPodOptions{ pod: pod, @@ -780,23 +778,23 @@ func TestDeleteOutdatedMirrorPod(t *testing.T) { kl := testKubelet.kubelet manager := testKubelet.fakeMirrorClient - pod := podWithUidNameNsSpec("12345678", "foo", "ns", api.PodSpec{ - Containers: []api.Container{ + pod := podWithUidNameNsSpec("12345678", "foo", "ns", v1.PodSpec{ + Containers: []v1.Container{ {Name: "1234", Image: "foo"}, }, }) pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = "file" // Mirror pod has an outdated spec. - mirrorPod := podWithUidNameNsSpec("11111111", "foo", "ns", api.PodSpec{ - Containers: []api.Container{ + mirrorPod := podWithUidNameNsSpec("11111111", "foo", "ns", v1.PodSpec{ + Containers: []v1.Container{ {Name: "1234", Image: "bar"}, }, }) mirrorPod.Annotations[kubetypes.ConfigSourceAnnotationKey] = "api" mirrorPod.Annotations[kubetypes.ConfigMirrorAnnotationKey] = "mirror" - pods := []*api.Pod{pod, mirrorPod} + pods := []*v1.Pod{pod, mirrorPod} kl.podManager.SetPods(pods) err := kl.syncPod(syncPodOptions{ pod: pod, @@ -821,9 +819,9 @@ func TestDeleteOrphanedMirrorPods(t *testing.T) { kl := testKubelet.kubelet manager := testKubelet.fakeMirrorClient - orphanPods := []*api.Pod{ + orphanPods := []*v1.Pod{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "pod1", Namespace: "ns", @@ -834,7 +832,7 @@ func TestDeleteOrphanedMirrorPods(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "12345679", Name: "pod2", Namespace: "ns", @@ -862,9 +860,9 @@ func TestDeleteOrphanedMirrorPods(t *testing.T) { func TestGetContainerInfoForMirrorPods(t *testing.T) { // pods contain one static and one mirror pod with the same name but // different UIDs. - pods := []*api.Pod{ + pods := []*v1.Pod{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "1234", Name: "qux", Namespace: "ns", @@ -872,14 +870,14 @@ func TestGetContainerInfoForMirrorPods(t *testing.T) { kubetypes.ConfigSourceAnnotationKey: "file", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Name: "foo"}, }, }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "5678", Name: "qux", Namespace: "ns", @@ -888,8 +886,8 @@ func TestGetContainerInfoForMirrorPods(t *testing.T) { kubetypes.ConfigMirrorAnnotationKey: "mirror", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Name: "foo"}, }, }, @@ -948,17 +946,15 @@ func TestHostNetworkAllowed(t *testing.T) { HostNetworkSources: []string{kubetypes.ApiserverSource, kubetypes.FileSource}, }, }) - pod := podWithUidNameNsSpec("12345678", "foo", "new", api.PodSpec{ - Containers: []api.Container{ + pod := podWithUidNameNsSpec("12345678", "foo", "new", v1.PodSpec{ + Containers: []v1.Container{ {Name: "foo"}, }, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, + HostNetwork: true, }) pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = kubetypes.FileSource - kubelet.podManager.SetPods([]*api.Pod{pod}) + kubelet.podManager.SetPods([]*v1.Pod{pod}) err := kubelet.syncPod(syncPodOptions{ pod: pod, podStatus: &kubecontainer.PodStatus{}, @@ -982,13 +978,11 @@ func TestHostNetworkDisallowed(t *testing.T) { HostNetworkSources: []string{}, }, }) - pod := podWithUidNameNsSpec("12345678", "foo", "new", api.PodSpec{ - Containers: []api.Container{ + pod := podWithUidNameNsSpec("12345678", "foo", "new", v1.PodSpec{ + Containers: []v1.Container{ {Name: "foo"}, }, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, + HostNetwork: true, }) pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = kubetypes.FileSource @@ -1014,13 +1008,13 @@ func TestPrivilegeContainerAllowed(t *testing.T) { AllowPrivileged: true, }) privileged := true - pod := podWithUidNameNsSpec("12345678", "foo", "new", api.PodSpec{ - Containers: []api.Container{ - {Name: "foo", SecurityContext: &api.SecurityContext{Privileged: &privileged}}, + pod := podWithUidNameNsSpec("12345678", "foo", "new", v1.PodSpec{ + Containers: []v1.Container{ + {Name: "foo", SecurityContext: &v1.SecurityContext{Privileged: &privileged}}, }, }) - kubelet.podManager.SetPods([]*api.Pod{pod}) + kubelet.podManager.SetPods([]*v1.Pod{pod}) err := kubelet.syncPod(syncPodOptions{ pod: pod, podStatus: &kubecontainer.PodStatus{}, @@ -1041,9 +1035,9 @@ func TestPrivilegedContainerDisallowed(t *testing.T) { AllowPrivileged: false, }) privileged := true - pod := podWithUidNameNsSpec("12345678", "foo", "new", api.PodSpec{ - Containers: []api.Container{ - {Name: "foo", SecurityContext: &api.SecurityContext{Privileged: &privileged}}, + pod := podWithUidNameNsSpec("12345678", "foo", "new", v1.PodSpec{ + Containers: []v1.Container{ + {Name: "foo", SecurityContext: &v1.SecurityContext{Privileged: &privileged}}, }, }) @@ -1070,16 +1064,15 @@ func TestNetworkErrorsWithoutHostNetwork(t *testing.T) { }, }) - pod := podWithUidNameNsSpec("12345678", "hostnetwork", "new", api.PodSpec{ - SecurityContext: &api.PodSecurityContext{ - HostNetwork: false, - }, - Containers: []api.Container{ + pod := podWithUidNameNsSpec("12345678", "hostnetwork", "new", v1.PodSpec{ + HostNetwork: false, + + Containers: []v1.Container{ {Name: "foo"}, }, }) - kubelet.podManager.SetPods([]*api.Pod{pod}) + kubelet.podManager.SetPods([]*v1.Pod{pod}) err := kubelet.syncPod(syncPodOptions{ pod: pod, podStatus: &kubecontainer.PodStatus{}, @@ -1088,7 +1081,7 @@ func TestNetworkErrorsWithoutHostNetwork(t *testing.T) { assert.Error(t, err, "expected pod with hostNetwork=false to fail when network in error") pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = kubetypes.FileSource - pod.Spec.SecurityContext.HostNetwork = true + pod.Spec.HostNetwork = true err = kubelet.syncPod(syncPodOptions{ pod: pod, podStatus: &kubecontainer.PodStatus{}, @@ -1101,20 +1094,20 @@ func TestFilterOutTerminatedPods(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kubelet := testKubelet.kubelet pods := newTestPods(5) - pods[0].Status.Phase = api.PodFailed - pods[1].Status.Phase = api.PodSucceeded - pods[2].Status.Phase = api.PodRunning - pods[3].Status.Phase = api.PodPending + pods[0].Status.Phase = v1.PodFailed + pods[1].Status.Phase = v1.PodSucceeded + pods[2].Status.Phase = v1.PodRunning + pods[3].Status.Phase = v1.PodPending - expected := []*api.Pod{pods[2], pods[3], pods[4]} + expected := []*v1.Pod{pods[2], pods[3], pods[4]} kubelet.podManager.SetPods(pods) actual := kubelet.filterOutTerminatedPods(pods) assert.Equal(t, expected, actual) } func TestMakePortMappings(t *testing.T) { - port := func(name string, protocol api.Protocol, containerPort, hostPort int32, ip string) api.ContainerPort { - return api.ContainerPort{ + port := func(name string, protocol v1.Protocol, containerPort, hostPort int32, ip string) v1.ContainerPort { + return v1.ContainerPort{ Name: name, Protocol: protocol, ContainerPort: containerPort, @@ -1122,7 +1115,7 @@ func TestMakePortMappings(t *testing.T) { HostIP: ip, } } - portMapping := func(name string, protocol api.Protocol, containerPort, hostPort int, ip string) kubecontainer.PortMapping { + portMapping := func(name string, protocol v1.Protocol, containerPort, hostPort int, ip string) kubecontainer.PortMapping { return kubecontainer.PortMapping{ Name: name, Protocol: protocol, @@ -1133,26 +1126,26 @@ func TestMakePortMappings(t *testing.T) { } tests := []struct { - container *api.Container + container *v1.Container expectedPortMappings []kubecontainer.PortMapping }{ { - &api.Container{ + &v1.Container{ Name: "fooContainer", - Ports: []api.ContainerPort{ - port("", api.ProtocolTCP, 80, 8080, "127.0.0.1"), - port("", api.ProtocolTCP, 443, 4343, "192.168.0.1"), - port("foo", api.ProtocolUDP, 555, 5555, ""), + Ports: []v1.ContainerPort{ + port("", v1.ProtocolTCP, 80, 8080, "127.0.0.1"), + port("", v1.ProtocolTCP, 443, 4343, "192.168.0.1"), + port("foo", v1.ProtocolUDP, 555, 5555, ""), // Duplicated, should be ignored. - port("foo", api.ProtocolUDP, 888, 8888, ""), + port("foo", v1.ProtocolUDP, 888, 8888, ""), // Duplicated, should be ignored. - port("", api.ProtocolTCP, 80, 8888, ""), + port("", v1.ProtocolTCP, 80, 8888, ""), }, }, []kubecontainer.PortMapping{ - portMapping("fooContainer-TCP:80", api.ProtocolTCP, 80, 8080, "127.0.0.1"), - portMapping("fooContainer-TCP:443", api.ProtocolTCP, 443, 4343, "192.168.0.1"), - portMapping("fooContainer-foo", api.ProtocolUDP, 555, 5555, ""), + portMapping("fooContainer-TCP:80", v1.ProtocolTCP, 80, 8080, "127.0.0.1"), + portMapping("fooContainer-TCP:443", v1.ProtocolTCP, 443, 4343, "192.168.0.1"), + portMapping("fooContainer-foo", v1.ProtocolUDP, 555, 5555, ""), }, }, } @@ -1173,20 +1166,20 @@ func TestSyncPodsSetStatusToFailedForPodsThatRunTooLong(t *testing.T) { startTime := unversioned.NewTime(now.Time.Add(-1 * time.Minute)) exceededActiveDeadlineSeconds := int64(30) - pods := []*api.Pod{ + pods := []*v1.Pod{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Name: "foo"}, }, ActiveDeadlineSeconds: &exceededActiveDeadlineSeconds, }, - Status: api.PodStatus{ + Status: v1.PodStatus{ StartTime: &startTime, }, }, @@ -1207,7 +1200,7 @@ func TestSyncPodsSetStatusToFailedForPodsThatRunTooLong(t *testing.T) { kubelet.HandlePodUpdates(pods) status, found := kubelet.statusManager.GetPodStatus(pods[0].UID) assert.True(t, found, "expected to found status for pod %q", pods[0].UID) - assert.Equal(t, api.PodFailed, status.Phase) + assert.Equal(t, v1.PodFailed, status.Phase) } func TestSyncPodsDoesNotSetPodsThatDidNotRunTooLongToFailed(t *testing.T) { @@ -1225,20 +1218,20 @@ func TestSyncPodsDoesNotSetPodsThatDidNotRunTooLongToFailed(t *testing.T) { startTime := unversioned.NewTime(now.Time.Add(-1 * time.Minute)) exceededActiveDeadlineSeconds := int64(300) - pods := []*api.Pod{ + pods := []*v1.Pod{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Name: "foo"}, }, ActiveDeadlineSeconds: &exceededActiveDeadlineSeconds, }, - Status: api.PodStatus{ + Status: v1.PodStatus{ StartTime: &startTime, }, }, @@ -1259,12 +1252,12 @@ func TestSyncPodsDoesNotSetPodsThatDidNotRunTooLongToFailed(t *testing.T) { kubelet.HandlePodUpdates(pods) status, found := kubelet.statusManager.GetPodStatus(pods[0].UID) assert.True(t, found, "expected to found status for pod %q", pods[0].UID) - assert.NotEqual(t, api.PodFailed, status.Phase) + assert.NotEqual(t, v1.PodFailed, status.Phase) } -func podWithUidNameNs(uid types.UID, name, namespace string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func podWithUidNameNs(uid types.UID, name, namespace string) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: uid, Name: name, Namespace: namespace, @@ -1273,7 +1266,7 @@ func podWithUidNameNs(uid types.UID, name, namespace string) *api.Pod { } } -func podWithUidNameNsSpec(uid types.UID, name, namespace string, spec api.PodSpec) *api.Pod { +func podWithUidNameNsSpec(uid types.UID, name, namespace string, spec v1.PodSpec) *v1.Pod { pod := podWithUidNameNs(uid, name, namespace) pod.Spec = spec return pod @@ -1287,7 +1280,7 @@ func TestDeletePodDirsForDeletedPods(t *testing.T) { testKubelet.fakeCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) kl := testKubelet.kubelet - pods := []*api.Pod{ + pods := []*v1.Pod{ podWithUidNameNs("12345678", "pod1", "ns"), podWithUidNameNs("12345679", "pod2", "ns"), } @@ -1300,13 +1293,13 @@ func TestDeletePodDirsForDeletedPods(t *testing.T) { } // Pod 1 has been deleted and no longer exists. - kl.podManager.SetPods([]*api.Pod{pods[0]}) + kl.podManager.SetPods([]*v1.Pod{pods[0]}) kl.HandlePodCleanups() assert.True(t, dirExists(kl.getPodDir(pods[0].UID)), "Expected directory to exist for pod 0") assert.False(t, dirExists(kl.getPodDir(pods[1].UID)), "Expected directory to be deleted for pod 1") } -func syncAndVerifyPodDir(t *testing.T, testKubelet *TestKubelet, pods []*api.Pod, podsToCheck []*api.Pod, shouldExist bool) { +func syncAndVerifyPodDir(t *testing.T, testKubelet *TestKubelet, pods []*v1.Pod, podsToCheck []*v1.Pod, shouldExist bool) { kl := testKubelet.kubelet kl.podManager.SetPods(pods) @@ -1326,7 +1319,7 @@ func TestDoesNotDeletePodDirsForTerminatedPods(t *testing.T) { testKubelet.fakeCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) kl := testKubelet.kubelet - pods := []*api.Pod{ + pods := []*v1.Pod{ podWithUidNameNs("12345678", "pod1", "ns"), podWithUidNameNs("12345679", "pod2", "ns"), podWithUidNameNs("12345680", "pod3", "ns"), @@ -1335,8 +1328,8 @@ func TestDoesNotDeletePodDirsForTerminatedPods(t *testing.T) { syncAndVerifyPodDir(t, testKubelet, pods, pods, true) // Pod 1 failed, and pod 2 succeeded. None of the pod directories should be // deleted. - kl.statusManager.SetPodStatus(pods[1], api.PodStatus{Phase: api.PodFailed}) - kl.statusManager.SetPodStatus(pods[2], api.PodStatus{Phase: api.PodSucceeded}) + kl.statusManager.SetPodStatus(pods[1], v1.PodStatus{Phase: v1.PodFailed}) + kl.statusManager.SetPodStatus(pods[2], v1.PodStatus{Phase: v1.PodSucceeded}) syncAndVerifyPodDir(t, testKubelet, pods, pods, true) } @@ -1356,20 +1349,20 @@ func TestDoesNotDeletePodDirsIfContainerIsRunning(t *testing.T) { // Sync once to create pod directory; confirm that the pod directory has // already been created. - pods := []*api.Pod{apiPod} - syncAndVerifyPodDir(t, testKubelet, pods, []*api.Pod{apiPod}, true) + pods := []*v1.Pod{apiPod} + syncAndVerifyPodDir(t, testKubelet, pods, []*v1.Pod{apiPod}, true) // Pretend the pod is deleted from apiserver, but is still active on the node. // The pod directory should not be removed. - pods = []*api.Pod{} + pods = []*v1.Pod{} testKubelet.fakeRuntime.PodList = []*containertest.FakePod{{runningPod, ""}} - syncAndVerifyPodDir(t, testKubelet, pods, []*api.Pod{apiPod}, true) + syncAndVerifyPodDir(t, testKubelet, pods, []*v1.Pod{apiPod}, true) // The pod is deleted and also not active on the node. The pod directory // should be removed. - pods = []*api.Pod{} + pods = []*v1.Pod{} testKubelet.fakeRuntime.PodList = []*containertest.FakePod{} - syncAndVerifyPodDir(t, testKubelet, pods, []*api.Pod{apiPod}, false) + syncAndVerifyPodDir(t, testKubelet, pods, []*v1.Pod{apiPod}, false) } func TestGetPodsToSync(t *testing.T) { @@ -1395,7 +1388,7 @@ func TestGetPodsToSync(t *testing.T) { clock.Step(1 * time.Minute) - expected := []*api.Pod{pods[2], pods[3], pods[0]} + expected := []*v1.Pod{pods[2], pods[3], pods[0]} podsToSync := kubelet.getPodsToSync() sort.Sort(podsByUID(expected)) sort.Sort(podsByUID(podsToSync)) @@ -1412,7 +1405,7 @@ func TestGenerateAPIPodStatusWithSortedContainers(t *testing.T) { numContainers := 10 expectedOrder := []string{} cStatuses := []*kubecontainer.ContainerStatus{} - specContainerList := []api.Container{} + specContainerList := []v1.Container{} for i := 0; i < numContainers; i++ { id := fmt.Sprintf("%v", i) containerName := fmt.Sprintf("%vcontainer", id) @@ -1427,10 +1420,10 @@ func TestGenerateAPIPodStatusWithSortedContainers(t *testing.T) { } else { cStatuses = append([]*kubecontainer.ContainerStatus{cStatus}, cStatuses...) } - specContainerList = append(specContainerList, api.Container{Name: containerName}) + specContainerList = append(specContainerList, v1.Container{Name: containerName}) } pod := podWithUidNameNs("uid1", "foo", "test") - pod.Spec = api.PodSpec{ + pod.Spec = v1.PodSpec{ Containers: specContainerList, } @@ -1450,7 +1443,7 @@ func TestGenerateAPIPodStatusWithSortedContainers(t *testing.T) { } } -func verifyContainerStatuses(t *testing.T, statuses []api.ContainerStatus, state, lastTerminationState map[string]api.ContainerState, message string) { +func verifyContainerStatuses(t *testing.T, statuses []v1.ContainerStatus, state, lastTerminationState map[string]v1.ContainerState, message string) { for _, s := range statuses { assert.Equal(t, s.State, state[s.Name], "%s: state", message) assert.Equal(t, s.LastTerminationState, lastTerminationState[s.Name], "%s: last terminated state", message) @@ -1472,7 +1465,7 @@ func TestGenerateAPIPodStatusWithReasonCache(t *testing.T) { testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) kubelet := testKubelet.kubelet pod := podWithUidNameNs("12345678", "foo", "new") - pod.Spec = api.PodSpec{RestartPolicy: api.RestartPolicyOnFailure} + pod.Spec = v1.PodSpec{RestartPolicy: v1.RestartPolicyOnFailure} podStatus := &kubecontainer.PodStatus{ ID: pod.UID, @@ -1480,48 +1473,48 @@ func TestGenerateAPIPodStatusWithReasonCache(t *testing.T) { Namespace: pod.Namespace, } tests := []struct { - containers []api.Container + containers []v1.Container statuses []*kubecontainer.ContainerStatus reasons map[string]error - oldStatuses []api.ContainerStatus - expectedState map[string]api.ContainerState + oldStatuses []v1.ContainerStatus + expectedState map[string]v1.ContainerState // Only set expectedInitState when it is different from expectedState - expectedInitState map[string]api.ContainerState - expectedLastTerminationState map[string]api.ContainerState + expectedInitState map[string]v1.ContainerState + expectedLastTerminationState map[string]v1.ContainerState }{ // For container with no historical record, State should be Waiting, LastTerminationState should be retrieved from // old status from apiserver. { - containers: []api.Container{{Name: "without-old-record"}, {Name: "with-old-record"}}, + containers: []v1.Container{{Name: "without-old-record"}, {Name: "with-old-record"}}, statuses: []*kubecontainer.ContainerStatus{}, reasons: map[string]error{}, - oldStatuses: []api.ContainerStatus{{ + oldStatuses: []v1.ContainerStatus{{ Name: "with-old-record", - LastTerminationState: api.ContainerState{Terminated: &api.ContainerStateTerminated{}}, + LastTerminationState: v1.ContainerState{Terminated: &v1.ContainerStateTerminated{}}, }}, - expectedState: map[string]api.ContainerState{ - "without-old-record": {Waiting: &api.ContainerStateWaiting{ + expectedState: map[string]v1.ContainerState{ + "without-old-record": {Waiting: &v1.ContainerStateWaiting{ Reason: startWaitingReason, }}, - "with-old-record": {Waiting: &api.ContainerStateWaiting{ + "with-old-record": {Waiting: &v1.ContainerStateWaiting{ Reason: startWaitingReason, }}, }, - expectedInitState: map[string]api.ContainerState{ - "without-old-record": {Waiting: &api.ContainerStateWaiting{ + expectedInitState: map[string]v1.ContainerState{ + "without-old-record": {Waiting: &v1.ContainerStateWaiting{ Reason: initWaitingReason, }}, - "with-old-record": {Waiting: &api.ContainerStateWaiting{ + "with-old-record": {Waiting: &v1.ContainerStateWaiting{ Reason: initWaitingReason, }}, }, - expectedLastTerminationState: map[string]api.ContainerState{ - "with-old-record": {Terminated: &api.ContainerStateTerminated{}}, + expectedLastTerminationState: map[string]v1.ContainerState{ + "with-old-record": {Terminated: &v1.ContainerStateTerminated{}}, }, }, // For running container, State should be Running, LastTerminationState should be retrieved from latest terminated status. { - containers: []api.Container{{Name: "running"}}, + containers: []v1.Container{{Name: "running"}}, statuses: []*kubecontainer.ContainerStatus{ { Name: "running", @@ -1535,14 +1528,14 @@ func TestGenerateAPIPodStatusWithReasonCache(t *testing.T) { }, }, reasons: map[string]error{}, - oldStatuses: []api.ContainerStatus{}, - expectedState: map[string]api.ContainerState{ - "running": {Running: &api.ContainerStateRunning{ + oldStatuses: []v1.ContainerStatus{}, + expectedState: map[string]v1.ContainerState{ + "running": {Running: &v1.ContainerStateRunning{ StartedAt: unversioned.NewTime(testTimestamp), }}, }, - expectedLastTerminationState: map[string]api.ContainerState{ - "running": {Terminated: &api.ContainerStateTerminated{ + expectedLastTerminationState: map[string]v1.ContainerState{ + "running": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 1, ContainerID: emptyContainerID, }}, @@ -1557,7 +1550,7 @@ func TestGenerateAPIPodStatusWithReasonCache(t *testing.T) { // recent start error or not, State should be Terminated, LastTerminationState should be retrieved from second latest // terminated status. { - containers: []api.Container{{Name: "without-reason"}, {Name: "with-reason"}}, + containers: []v1.Container{{Name: "without-reason"}, {Name: "with-reason"}}, statuses: []*kubecontainer.ContainerStatus{ { Name: "without-reason", @@ -1591,28 +1584,28 @@ func TestGenerateAPIPodStatusWithReasonCache(t *testing.T) { }, }, reasons: map[string]error{"with-reason": testErrorReason, "succeed": testErrorReason}, - oldStatuses: []api.ContainerStatus{}, - expectedState: map[string]api.ContainerState{ - "without-reason": {Terminated: &api.ContainerStateTerminated{ + oldStatuses: []v1.ContainerStatus{}, + expectedState: map[string]v1.ContainerState{ + "without-reason": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 1, ContainerID: emptyContainerID, }}, - "with-reason": {Waiting: &api.ContainerStateWaiting{Reason: testErrorReason.Error()}}, - "succeed": {Terminated: &api.ContainerStateTerminated{ + "with-reason": {Waiting: &v1.ContainerStateWaiting{Reason: testErrorReason.Error()}}, + "succeed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 0, ContainerID: emptyContainerID, }}, }, - expectedLastTerminationState: map[string]api.ContainerState{ - "without-reason": {Terminated: &api.ContainerStateTerminated{ + expectedLastTerminationState: map[string]v1.ContainerState{ + "without-reason": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 3, ContainerID: emptyContainerID, }}, - "with-reason": {Terminated: &api.ContainerStateTerminated{ + "with-reason": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 2, ContainerID: emptyContainerID, }}, - "succeed": {Terminated: &api.ContainerStateTerminated{ + "succeed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 5, ContainerID: emptyContainerID, }}, @@ -1661,7 +1654,7 @@ func TestGenerateAPIPodStatusWithDifferentRestartPolicies(t *testing.T) { testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) kubelet := testKubelet.kubelet pod := podWithUidNameNs("12345678", "foo", "new") - containers := []api.Container{{Name: "succeed"}, {Name: "failed"}} + containers := []v1.Container{{Name: "succeed"}, {Name: "failed"}} podStatus := &kubecontainer.PodStatus{ ID: pod.UID, Name: pod.Name, @@ -1692,88 +1685,88 @@ func TestGenerateAPIPodStatusWithDifferentRestartPolicies(t *testing.T) { kubelet.reasonCache.add(pod.UID, "succeed", testErrorReason, "") kubelet.reasonCache.add(pod.UID, "failed", testErrorReason, "") for c, test := range []struct { - restartPolicy api.RestartPolicy - expectedState map[string]api.ContainerState - expectedLastTerminationState map[string]api.ContainerState + restartPolicy v1.RestartPolicy + expectedState map[string]v1.ContainerState + expectedLastTerminationState map[string]v1.ContainerState // Only set expectedInitState when it is different from expectedState - expectedInitState map[string]api.ContainerState + expectedInitState map[string]v1.ContainerState // Only set expectedInitLastTerminationState when it is different from expectedLastTerminationState - expectedInitLastTerminationState map[string]api.ContainerState + expectedInitLastTerminationState map[string]v1.ContainerState }{ { - restartPolicy: api.RestartPolicyNever, - expectedState: map[string]api.ContainerState{ - "succeed": {Terminated: &api.ContainerStateTerminated{ + restartPolicy: v1.RestartPolicyNever, + expectedState: map[string]v1.ContainerState{ + "succeed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 0, ContainerID: emptyContainerID, }}, - "failed": {Terminated: &api.ContainerStateTerminated{ + "failed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 1, ContainerID: emptyContainerID, }}, }, - expectedLastTerminationState: map[string]api.ContainerState{ - "succeed": {Terminated: &api.ContainerStateTerminated{ + expectedLastTerminationState: map[string]v1.ContainerState{ + "succeed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 2, ContainerID: emptyContainerID, }}, - "failed": {Terminated: &api.ContainerStateTerminated{ + "failed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 3, ContainerID: emptyContainerID, }}, }, }, { - restartPolicy: api.RestartPolicyOnFailure, - expectedState: map[string]api.ContainerState{ - "succeed": {Terminated: &api.ContainerStateTerminated{ + restartPolicy: v1.RestartPolicyOnFailure, + expectedState: map[string]v1.ContainerState{ + "succeed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 0, ContainerID: emptyContainerID, }}, - "failed": {Waiting: &api.ContainerStateWaiting{Reason: testErrorReason.Error()}}, + "failed": {Waiting: &v1.ContainerStateWaiting{Reason: testErrorReason.Error()}}, }, - expectedLastTerminationState: map[string]api.ContainerState{ - "succeed": {Terminated: &api.ContainerStateTerminated{ + expectedLastTerminationState: map[string]v1.ContainerState{ + "succeed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 2, ContainerID: emptyContainerID, }}, - "failed": {Terminated: &api.ContainerStateTerminated{ + "failed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 1, ContainerID: emptyContainerID, }}, }, }, { - restartPolicy: api.RestartPolicyAlways, - expectedState: map[string]api.ContainerState{ - "succeed": {Waiting: &api.ContainerStateWaiting{Reason: testErrorReason.Error()}}, - "failed": {Waiting: &api.ContainerStateWaiting{Reason: testErrorReason.Error()}}, + restartPolicy: v1.RestartPolicyAlways, + expectedState: map[string]v1.ContainerState{ + "succeed": {Waiting: &v1.ContainerStateWaiting{Reason: testErrorReason.Error()}}, + "failed": {Waiting: &v1.ContainerStateWaiting{Reason: testErrorReason.Error()}}, }, - expectedLastTerminationState: map[string]api.ContainerState{ - "succeed": {Terminated: &api.ContainerStateTerminated{ + expectedLastTerminationState: map[string]v1.ContainerState{ + "succeed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 0, ContainerID: emptyContainerID, }}, - "failed": {Terminated: &api.ContainerStateTerminated{ + "failed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 1, ContainerID: emptyContainerID, }}, }, // If the init container is terminated with exit code 0, it won't be restarted even when the // restart policy is RestartAlways. - expectedInitState: map[string]api.ContainerState{ - "succeed": {Terminated: &api.ContainerStateTerminated{ + expectedInitState: map[string]v1.ContainerState{ + "succeed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 0, ContainerID: emptyContainerID, }}, - "failed": {Waiting: &api.ContainerStateWaiting{Reason: testErrorReason.Error()}}, + "failed": {Waiting: &v1.ContainerStateWaiting{Reason: testErrorReason.Error()}}, }, - expectedInitLastTerminationState: map[string]api.ContainerState{ - "succeed": {Terminated: &api.ContainerStateTerminated{ + expectedInitLastTerminationState: map[string]v1.ContainerState{ + "succeed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 2, ContainerID: emptyContainerID, }}, - "failed": {Terminated: &api.ContainerStateTerminated{ + "failed": {Terminated: &v1.ContainerStateTerminated{ ExitCode: 1, ContainerID: emptyContainerID, }}, @@ -1805,7 +1798,7 @@ func TestGenerateAPIPodStatusWithDifferentRestartPolicies(t *testing.T) { // testPodAdmitHandler is a lifecycle.PodAdmitHandler for testing. type testPodAdmitHandler struct { // list of pods to reject. - podsToReject []*api.Pod + podsToReject []*v1.Pod } // Admit rejects all pods in the podsToReject list with a matching UID. @@ -1822,22 +1815,22 @@ func (a *testPodAdmitHandler) Admit(attrs *lifecycle.PodAdmitAttributes) lifecyc func TestHandlePodAdditionsInvokesPodAdmitHandlers(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kl := testKubelet.kubelet - kl.nodeLister = testNodeLister{nodes: []api.Node{ + kl.nodeLister = testNodeLister{nodes: []v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: string(kl.nodeName)}, - Status: api.NodeStatus{ - Allocatable: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), + ObjectMeta: v1.ObjectMeta{Name: string(kl.nodeName)}, + Status: v1.NodeStatus{ + Allocatable: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), }, }, }, }} - kl.nodeInfo = testNodeInfo{nodes: []api.Node{ + kl.nodeInfo = testNodeInfo{nodes: []v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: string(kl.nodeName)}, - Status: api.NodeStatus{ - Allocatable: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), + ObjectMeta: v1.ObjectMeta{Name: string(kl.nodeName)}, + Status: v1.NodeStatus{ + Allocatable: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), }, }, }, @@ -1846,16 +1839,16 @@ func TestHandlePodAdditionsInvokesPodAdmitHandlers(t *testing.T) { testKubelet.fakeCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) - pods := []*api.Pod{ + pods := []*v1.Pod{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "123456789", Name: "podA", Namespace: "foo", }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "987654321", Name: "podB", Namespace: "foo", @@ -1864,7 +1857,7 @@ func TestHandlePodAdditionsInvokesPodAdmitHandlers(t *testing.T) { } podToReject := pods[0] podToAdmit := pods[1] - podsToReject := []*api.Pod{podToReject} + podsToReject := []*v1.Pod{podToReject} kl.admitHandlers.AddPodAdmitHandler(&testPodAdmitHandler{podsToReject: podsToReject}) @@ -1873,22 +1866,22 @@ func TestHandlePodAdditionsInvokesPodAdmitHandlers(t *testing.T) { // podToReject should be Failed status, found := kl.statusManager.GetPodStatus(podToReject.UID) require.True(t, found, "Status of pod %q is not found in the status map", podToAdmit.UID) - require.Equal(t, api.PodFailed, status.Phase) + require.Equal(t, v1.PodFailed, status.Phase) // podToAdmit should be Pending status, found = kl.statusManager.GetPodStatus(podToAdmit.UID) require.True(t, found, "Status of pod %q is not found in the status map", podToAdmit.UID) - require.Equal(t, api.PodPending, status.Phase) + require.Equal(t, v1.PodPending, status.Phase) } // testPodSyncLoopHandler is a lifecycle.PodSyncLoopHandler that is used for testing. type testPodSyncLoopHandler struct { // list of pods to sync - podsToSync []*api.Pod + podsToSync []*v1.Pod } // ShouldSync evaluates if the pod should be synced from the kubelet. -func (a *testPodSyncLoopHandler) ShouldSync(pod *api.Pod) bool { +func (a *testPodSyncLoopHandler) ShouldSync(pod *v1.Pod) bool { for _, podToSync := range a.podsToSync { if podToSync.UID == pod.UID { return true @@ -1902,7 +1895,7 @@ func TestGetPodsToSyncInvokesPodSyncLoopHandlers(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kubelet := testKubelet.kubelet pods := newTestPods(5) - expected := []*api.Pod{pods[0]} + expected := []*v1.Pod{pods[0]} kubelet.AddPodSyncLoopHandler(&testPodSyncLoopHandler{expected}) kubelet.podManager.SetPods(pods) @@ -1915,7 +1908,7 @@ func TestGetPodsToSyncInvokesPodSyncLoopHandlers(t *testing.T) { // testPodSyncHandler is a lifecycle.PodSyncHandler that is used for testing. type testPodSyncHandler struct { // list of pods to evict. - podsToEvict []*api.Pod + podsToEvict []*v1.Pod // the reason for the eviction reason string // the message for the eviction @@ -1923,7 +1916,7 @@ type testPodSyncHandler struct { } // ShouldEvict evaluates if the pod should be evicted from the kubelet. -func (a *testPodSyncHandler) ShouldEvict(pod *api.Pod) lifecycle.ShouldEvictResponse { +func (a *testPodSyncHandler) ShouldEvict(pod *v1.Pod) lifecycle.ShouldEvictResponse { for _, podToEvict := range a.podsToEvict { if podToEvict.UID == pod.UID { return lifecycle.ShouldEvictResponse{Evict: true, Reason: a.reason, Message: a.message} @@ -1937,7 +1930,7 @@ func TestGenerateAPIPodStatusInvokesPodSyncHandlers(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kubelet := testKubelet.kubelet pod := newTestPods(1)[0] - podsToEvict := []*api.Pod{pod} + podsToEvict := []*v1.Pod{pod} kubelet.AddPodSyncHandler(&testPodSyncHandler{podsToEvict, "Evicted", "because"}) status := &kubecontainer.PodStatus{ ID: pod.UID, @@ -1945,7 +1938,7 @@ func TestGenerateAPIPodStatusInvokesPodSyncHandlers(t *testing.T) { Namespace: pod.Namespace, } apiStatus := kubelet.generateAPIPodStatus(pod, status) - require.Equal(t, api.PodFailed, apiStatus.Phase) + require.Equal(t, v1.PodFailed, apiStatus.Phase) require.Equal(t, "Evicted", apiStatus.Reason) require.Equal(t, "because", apiStatus.Message) } @@ -1953,14 +1946,14 @@ func TestGenerateAPIPodStatusInvokesPodSyncHandlers(t *testing.T) { func TestSyncPodKillPod(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kl := testKubelet.kubelet - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "foo", }, } - pods := []*api.Pod{pod} + pods := []*v1.Pod{pod} kl.podManager.SetPods(pods) gracePeriodOverride := int64(0) err := kl.syncPod(syncPodOptions{ @@ -1968,9 +1961,9 @@ func TestSyncPodKillPod(t *testing.T) { podStatus: &kubecontainer.PodStatus{}, updateType: kubetypes.SyncPodKill, killPodOptions: &KillPodOptions{ - PodStatusFunc: func(p *api.Pod, podStatus *kubecontainer.PodStatus) api.PodStatus { - return api.PodStatus{ - Phase: api.PodFailed, + PodStatusFunc: func(p *v1.Pod, podStatus *kubecontainer.PodStatus) v1.PodStatus { + return v1.PodStatus{ + Phase: v1.PodFailed, Reason: "reason", Message: "message", } @@ -1982,12 +1975,12 @@ func TestSyncPodKillPod(t *testing.T) { // Check pod status stored in the status map. status, found := kl.statusManager.GetPodStatus(pod.UID) require.True(t, found, "Status of pod %q is not found in the status map", pod.UID) - require.Equal(t, api.PodFailed, status.Phase) + require.Equal(t, v1.PodFailed, status.Phase) } func waitForVolumeUnmount( volumeManager kubeletvolume.VolumeManager, - pod *api.Pod) error { + pod *v1.Pod) error { var podVolumes kubecontainer.VolumeMap err := retryWithExponentialBackOff( time.Duration(50*time.Millisecond), @@ -2013,9 +2006,9 @@ func waitForVolumeUnmount( } func waitForVolumeDetach( - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, volumeManager kubeletvolume.VolumeManager) error { - attachedVolumes := []api.UniqueVolumeName{} + attachedVolumes := []v1.UniqueVolumeName{} err := retryWithExponentialBackOff( time.Duration(50*time.Millisecond), func() (bool, error) { @@ -2044,7 +2037,7 @@ func retryWithExponentialBackOff(initialDuration time.Duration, fn wait.Conditio } func simulateVolumeInUseUpdate( - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, stopCh <-chan struct{}, volumeManager kubeletvolume.VolumeManager) { ticker := time.NewTicker(100 * time.Millisecond) @@ -2053,7 +2046,7 @@ func simulateVolumeInUseUpdate( select { case <-ticker.C: volumeManager.MarkVolumesAsReportedInUse( - []api.UniqueVolumeName{volumeName}) + []v1.UniqueVolumeName{volumeName}) case <-stopCh: return } @@ -2067,7 +2060,7 @@ func runVolumeManager(kubelet *Kubelet) chan struct{} { } // Sort pods by UID. -type podsByUID []*api.Pod +type podsByUID []*v1.Pod func (p podsByUID) Len() int { return len(p) } func (p podsByUID) Swap(i, j int) { p[i], p[j] = p[j], p[i] } diff --git a/pkg/kubelet/kubelet_volumes.go b/pkg/kubelet/kubelet_volumes.go index c7ae64050a6..f9fabcdb9e3 100644 --- a/pkg/kubelet/kubelet_volumes.go +++ b/pkg/kubelet/kubelet_volumes.go @@ -21,7 +21,7 @@ import ( "os" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/types" utilerrors "k8s.io/kubernetes/pkg/util/errors" @@ -65,7 +65,7 @@ func (kl *Kubelet) podVolumesExist(podUID types.UID) bool { // newVolumeMounterFromPlugins attempts to find a plugin by volume spec, pod // and volume options and then creates a Mounter. // Returns a valid Unmounter or an error. -func (kl *Kubelet) newVolumeMounterFromPlugins(spec *volume.Spec, pod *api.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { +func (kl *Kubelet) newVolumeMounterFromPlugins(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { plugin, err := kl.volumePluginMgr.FindPluginBySpec(spec) if err != nil { return nil, fmt.Errorf("can't use volume plugins for %s: %v", spec.Name(), err) @@ -81,7 +81,7 @@ func (kl *Kubelet) newVolumeMounterFromPlugins(spec *volume.Spec, pod *api.Pod, // cleanupOrphanedPodDirs removes the volumes of pods that should not be // running and that have no containers running. func (kl *Kubelet) cleanupOrphanedPodDirs( - pods []*api.Pod, runningPods []*kubecontainer.Pod) error { + pods []*v1.Pod, runningPods []*kubecontainer.Pod) error { allPods := sets.NewString() for _, pod := range pods { allPods.Insert(string(pod.UID)) diff --git a/pkg/kubelet/kubelet_volumes_test.go b/pkg/kubelet/kubelet_volumes_test.go index ec69020f3b6..fb2412753e2 100644 --- a/pkg/kubelet/kubelet_volumes_test.go +++ b/pkg/kubelet/kubelet_volumes_test.go @@ -21,7 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/volume" @@ -33,18 +33,18 @@ func TestPodVolumesExist(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kubelet := testKubelet.kubelet - pods := []*api.Pod{ + pods := []*v1.Pod{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "vol1", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -53,16 +53,16 @@ func TestPodVolumesExist(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "pod2", UID: "pod2uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "vol2", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device2", }, }, @@ -71,16 +71,16 @@ func TestPodVolumesExist(t *testing.T) { }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "pod3", UID: "pod3uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "vol3", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device3", }, }, @@ -117,12 +117,12 @@ func TestVolumeAttachAndMountControllerDisabled(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kubelet := testKubelet.kubelet - pod := podWithUidNameNsSpec("12345678", "foo", "test", api.PodSpec{ - Volumes: []api.Volume{ + pod := podWithUidNameNsSpec("12345678", "foo", "test", v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "vol1", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device", }, }, @@ -135,7 +135,7 @@ func TestVolumeAttachAndMountControllerDisabled(t *testing.T) { close(stopCh) }() - kubelet.podManager.SetPods([]*api.Pod{pod}) + kubelet.podManager.SetPods([]*v1.Pod{pod}) err := kubelet.volumeManager.WaitForAttachAndMount(pod) assert.NoError(t, err) @@ -162,12 +162,12 @@ func TestVolumeUnmountAndDetachControllerDisabled(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) kubelet := testKubelet.kubelet - pod := podWithUidNameNsSpec("12345678", "foo", "test", api.PodSpec{ - Volumes: []api.Volume{ + pod := podWithUidNameNsSpec("12345678", "foo", "test", v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "vol1", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device", }, }, @@ -181,7 +181,7 @@ func TestVolumeUnmountAndDetachControllerDisabled(t *testing.T) { }() // Add pod - kubelet.podManager.SetPods([]*api.Pod{pod}) + kubelet.podManager.SetPods([]*v1.Pod{pod}) // Verify volumes attached err := kubelet.volumeManager.WaitForAttachAndMount(pod) @@ -207,7 +207,7 @@ func TestVolumeUnmountAndDetachControllerDisabled(t *testing.T) { 1 /* expectedSetUpCallCount */, testKubelet.volumePlugin)) // Remove pod - kubelet.podManager.SetPods([]*api.Pod{}) + kubelet.podManager.SetPods([]*v1.Pod{}) assert.NoError(t, waitForVolumeUnmount(kubelet.volumeManager, pod)) @@ -222,7 +222,7 @@ func TestVolumeUnmountAndDetachControllerDisabled(t *testing.T) { 1 /* expectedTearDownCallCount */, testKubelet.volumePlugin)) // Verify volumes detached and no longer reported as in use - assert.NoError(t, waitForVolumeDetach(api.UniqueVolumeName("fake/vol1"), kubelet.volumeManager)) + assert.NoError(t, waitForVolumeDetach(v1.UniqueVolumeName("fake/vol1"), kubelet.volumeManager)) assert.True(t, testKubelet.volumePlugin.GetNewAttacherCallCount() >= 1, "Expected plugin NewAttacher to be called at least once") assert.NoError(t, volumetest.VerifyDetachCallCount( 1 /* expectedDetachCallCount */, testKubelet.volumePlugin)) @@ -234,28 +234,28 @@ func TestVolumeAttachAndMountControllerEnabled(t *testing.T) { kubeClient := testKubelet.fakeKubeClient kubeClient.AddReactor("get", "nodes", func(action core.Action) (bool, runtime.Object, error) { - return true, &api.Node{ - ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, - Status: api.NodeStatus{ - VolumesAttached: []api.AttachedVolume{ + return true, &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}, + Status: v1.NodeStatus{ + VolumesAttached: []v1.AttachedVolume{ { Name: "fake/vol1", DevicePath: "fake/path", }, }}, - Spec: api.NodeSpec{ExternalID: testKubeletHostname}, + Spec: v1.NodeSpec{ExternalID: testKubeletHostname}, }, nil }) kubeClient.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) { return true, nil, fmt.Errorf("no reaction implemented for %s", action) }) - pod := podWithUidNameNsSpec("12345678", "foo", "test", api.PodSpec{ - Volumes: []api.Volume{ + pod := podWithUidNameNsSpec("12345678", "foo", "test", v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "vol1", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device", }, }, @@ -268,11 +268,11 @@ func TestVolumeAttachAndMountControllerEnabled(t *testing.T) { close(stopCh) }() - kubelet.podManager.SetPods([]*api.Pod{pod}) + kubelet.podManager.SetPods([]*v1.Pod{pod}) // Fake node status update go simulateVolumeInUseUpdate( - api.UniqueVolumeName("fake/vol1"), + v1.UniqueVolumeName("fake/vol1"), stopCh, kubelet.volumeManager) @@ -302,28 +302,28 @@ func TestVolumeUnmountAndDetachControllerEnabled(t *testing.T) { kubeClient := testKubelet.fakeKubeClient kubeClient.AddReactor("get", "nodes", func(action core.Action) (bool, runtime.Object, error) { - return true, &api.Node{ - ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, - Status: api.NodeStatus{ - VolumesAttached: []api.AttachedVolume{ + return true, &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: testKubeletHostname}, + Status: v1.NodeStatus{ + VolumesAttached: []v1.AttachedVolume{ { Name: "fake/vol1", DevicePath: "fake/path", }, }}, - Spec: api.NodeSpec{ExternalID: testKubeletHostname}, + Spec: v1.NodeSpec{ExternalID: testKubeletHostname}, }, nil }) kubeClient.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) { return true, nil, fmt.Errorf("no reaction implemented for %s", action) }) - pod := podWithUidNameNsSpec("12345678", "foo", "test", api.PodSpec{ - Volumes: []api.Volume{ + pod := podWithUidNameNsSpec("12345678", "foo", "test", v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "vol1", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device", }, }, @@ -337,11 +337,11 @@ func TestVolumeUnmountAndDetachControllerEnabled(t *testing.T) { }() // Add pod - kubelet.podManager.SetPods([]*api.Pod{pod}) + kubelet.podManager.SetPods([]*v1.Pod{pod}) // Fake node status update go simulateVolumeInUseUpdate( - api.UniqueVolumeName("fake/vol1"), + v1.UniqueVolumeName("fake/vol1"), stopCh, kubelet.volumeManager) @@ -367,7 +367,7 @@ func TestVolumeUnmountAndDetachControllerEnabled(t *testing.T) { 1 /* expectedSetUpCallCount */, testKubelet.volumePlugin)) // Remove pod - kubelet.podManager.SetPods([]*api.Pod{}) + kubelet.podManager.SetPods([]*v1.Pod{}) assert.NoError(t, waitForVolumeUnmount(kubelet.volumeManager, pod)) @@ -382,7 +382,7 @@ func TestVolumeUnmountAndDetachControllerEnabled(t *testing.T) { 1 /* expectedTearDownCallCount */, testKubelet.volumePlugin)) // Verify volumes detached and no longer reported as in use - assert.NoError(t, waitForVolumeDetach(api.UniqueVolumeName("fake/vol1"), kubelet.volumeManager)) + assert.NoError(t, waitForVolumeDetach(v1.UniqueVolumeName("fake/vol1"), kubelet.volumeManager)) assert.True(t, testKubelet.volumePlugin.GetNewAttacherCallCount() >= 1, "Expected plugin NewAttacher to be called at least once") assert.NoError(t, volumetest.VerifyZeroDetachCallCount(testKubelet.volumePlugin)) } diff --git a/pkg/kubelet/kuberuntime/BUILD b/pkg/kubelet/kuberuntime/BUILD index 0af69177f01..391c2b41d79 100644 --- a/pkg/kubelet/kuberuntime/BUILD +++ b/pkg/kubelet/kuberuntime/BUILD @@ -29,8 +29,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/credentialprovider:go_default_library", "//pkg/kubelet/api:go_default_library", @@ -78,8 +78,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/componentconfig:go_default_library", "//pkg/kubelet/api/testing:go_default_library", "//pkg/kubelet/api/v1alpha1/runtime:go_default_library", diff --git a/pkg/kubelet/kuberuntime/doc.go b/pkg/kubelet/kuberuntime/doc.go index c1284ee28c0..61a022910a0 100644 --- a/pkg/kubelet/kuberuntime/doc.go +++ b/pkg/kubelet/kuberuntime/doc.go @@ -15,5 +15,5 @@ limitations under the License. */ // Package kuberuntime contains an implementation of kubecontainer.Runtime using -// the interface in pkg/kubelet/api. +// the interface in pkg/kubelet/v1. package kuberuntime diff --git a/pkg/kubelet/kuberuntime/fake_kuberuntime_manager.go b/pkg/kubelet/kuberuntime/fake_kuberuntime_manager.go index 8d257b4c334..4d67bd6962e 100644 --- a/pkg/kubelet/kuberuntime/fake_kuberuntime_manager.go +++ b/pkg/kubelet/kuberuntime/fake_kuberuntime_manager.go @@ -22,7 +22,7 @@ import ( "time" cadvisorapi "github.com/google/cadvisor/info/v1" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/credentialprovider" internalApi "k8s.io/kubernetes/pkg/kubelet/api" @@ -49,7 +49,7 @@ func (f *fakeHTTP) Get(url string) (*http.Response, error) { // fakeRuntimeHelper implements kubecontainer.RuntimeHelper interfaces for testing purposes. type fakeRuntimeHelper struct{} -func (f *fakeRuntimeHelper) GenerateRunContainerOptions(pod *api.Pod, container *api.Container, podIP string) (*kubecontainer.RunContainerOptions, error) { +func (f *fakeRuntimeHelper) GenerateRunContainerOptions(pod *v1.Pod, container *v1.Container, podIP string) (*kubecontainer.RunContainerOptions, error) { var opts kubecontainer.RunContainerOptions if len(container.TerminationMessagePath) != 0 { testPodContainerDir, err := ioutil.TempDir("", "fooPodContainerDir") @@ -61,12 +61,12 @@ func (f *fakeRuntimeHelper) GenerateRunContainerOptions(pod *api.Pod, container return &opts, nil } -func (f *fakeRuntimeHelper) GetClusterDNS(pod *api.Pod) ([]string, []string, error) { +func (f *fakeRuntimeHelper) GetClusterDNS(pod *v1.Pod) ([]string, []string, error) { return nil, nil, nil } // This is not used by docker runtime. -func (f *fakeRuntimeHelper) GeneratePodHostNameAndDomain(pod *api.Pod) (string, string, error) { +func (f *fakeRuntimeHelper) GeneratePodHostNameAndDomain(pod *v1.Pod) (string, string, error) { return "", "", nil } @@ -74,19 +74,19 @@ func (f *fakeRuntimeHelper) GetPodDir(kubetypes.UID) string { return "" } -func (f *fakeRuntimeHelper) GetExtraSupplementalGroupsForPod(pod *api.Pod) []int64 { +func (f *fakeRuntimeHelper) GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64 { return nil } type fakePodGetter struct { - pods map[types.UID]*api.Pod + pods map[types.UID]*v1.Pod } func newFakePodGetter() *fakePodGetter { - return &fakePodGetter{make(map[types.UID]*api.Pod)} + return &fakePodGetter{make(map[types.UID]*v1.Pod)} } -func (f *fakePodGetter) GetPodByUID(uid types.UID) (*api.Pod, bool) { +func (f *fakePodGetter) GetPodByUID(uid types.UID) (*v1.Pod, bool) { pod, found := f.pods[uid] return pod, found } diff --git a/pkg/kubelet/kuberuntime/helpers.go b/pkg/kubelet/kuberuntime/helpers.go index 91088e56136..d4d2ed92fa4 100644 --- a/pkg/kubelet/kuberuntime/helpers.go +++ b/pkg/kubelet/kuberuntime/helpers.go @@ -22,7 +22,7 @@ import ( "strconv" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/types" @@ -85,12 +85,12 @@ func toKubeContainerState(state runtimeApi.ContainerState) kubecontainer.Contain return kubecontainer.ContainerStateUnknown } -// toRuntimeProtocol converts api.Protocol to runtimeApi.Protocol. -func toRuntimeProtocol(protocol api.Protocol) runtimeApi.Protocol { +// toRuntimeProtocol converts v1.Protocol to runtimeApi.Protocol. +func toRuntimeProtocol(protocol v1.Protocol) runtimeApi.Protocol { switch protocol { - case api.ProtocolTCP: + case v1.ProtocolTCP: return runtimeApi.Protocol_TCP - case api.ProtocolUDP: + case v1.ProtocolUDP: return runtimeApi.Protocol_UDP } @@ -131,7 +131,7 @@ func (m *kubeGenericRuntimeManager) sandboxToKubeContainer(s *runtimeApi.PodSand } // getContainerSpec gets the container spec by containerName. -func getContainerSpec(pod *api.Pod, containerName string) *api.Container { +func getContainerSpec(pod *v1.Pod, containerName string) *v1.Container { for i, c := range pod.Spec.Containers { if containerName == c.Name { return &pod.Spec.Containers[i] @@ -217,7 +217,7 @@ func milliCPUToQuota(milliCPU int64) (quota int64, period int64) { // getStableKey generates a key (string) to uniquely identify a // (pod, container) tuple. The key should include the content of the // container, so that any change to the container generates a new key. -func getStableKey(pod *api.Pod, container *api.Container) string { +func getStableKey(pod *v1.Pod, container *v1.Container) string { hash := strconv.FormatUint(kubecontainer.HashContainer(container), 16) return fmt.Sprintf("%s_%s_%s_%s_%s", pod.Name, pod.Namespace, string(pod.UID), container.Name, hash) } diff --git a/pkg/kubelet/kuberuntime/helpers_test.go b/pkg/kubelet/kuberuntime/helpers_test.go index c1b2782bbdc..7338694fae1 100644 --- a/pkg/kubelet/kuberuntime/helpers_test.go +++ b/pkg/kubelet/kuberuntime/helpers_test.go @@ -20,22 +20,22 @@ import ( "testing" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) func TestStableKey(t *testing.T) { - container := &api.Container{ + container := &v1.Container{ Name: "test_container", Image: "foo/image:v1", } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "test_pod", Namespace: "test_pod_namespace", UID: "test_pod_uid", }, - Spec: api.PodSpec{ - Containers: []api.Container{*container}, + Spec: v1.PodSpec{ + Containers: []v1.Container{*container}, }, } oldKey := getStableKey(pod, container) diff --git a/pkg/kubelet/kuberuntime/kuberuntime_container.go b/pkg/kubelet/kuberuntime/kuberuntime_container.go index b781770e30a..9a2a86a4a4d 100644 --- a/pkg/kubelet/kuberuntime/kuberuntime_container.go +++ b/pkg/kubelet/kuberuntime/kuberuntime_container.go @@ -29,8 +29,8 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/events" @@ -49,7 +49,7 @@ import ( // * create the container // * start the container // * run the post start lifecycle hooks (if applicable) -func (m *kubeGenericRuntimeManager) startContainer(podSandboxID string, podSandboxConfig *runtimeApi.PodSandboxConfig, container *api.Container, pod *api.Pod, podStatus *kubecontainer.PodStatus, pullSecrets []api.Secret, podIP string) (string, error) { +func (m *kubeGenericRuntimeManager) startContainer(podSandboxID string, podSandboxConfig *runtimeApi.PodSandboxConfig, container *v1.Container, pod *v1.Pod, podStatus *kubecontainer.PodStatus, pullSecrets []v1.Secret, podIP string) (string, error) { // Step 1: pull the image. err, msg := m.imagePuller.EnsureImageExists(pod, container, pullSecrets) if err != nil { @@ -72,15 +72,15 @@ func (m *kubeGenericRuntimeManager) startContainer(podSandboxID string, podSandb containerConfig, err := m.generateContainerConfig(container, pod, restartCount, podIP) if err != nil { - m.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToCreateContainer, "Failed to create container with error: %v", err) + m.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedToCreateContainer, "Failed to create container with error: %v", err) return "Generate Container Config Failed", err } containerID, err := m.runtimeService.CreateContainer(podSandboxID, containerConfig, podSandboxConfig) if err != nil { - m.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToCreateContainer, "Failed to create container with error: %v", err) + m.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedToCreateContainer, "Failed to create container with error: %v", err) return "Create Container Failed", err } - m.recorder.Eventf(ref, api.EventTypeNormal, events.CreatedContainer, "Created container with id %v", containerID) + m.recorder.Eventf(ref, v1.EventTypeNormal, events.CreatedContainer, "Created container with id %v", containerID) if ref != nil { m.containerRefManager.SetRef(kubecontainer.ContainerID{ Type: m.runtimeName, @@ -91,11 +91,11 @@ func (m *kubeGenericRuntimeManager) startContainer(podSandboxID string, podSandb // Step 3: start the container. err = m.runtimeService.StartContainer(containerID) if err != nil { - m.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToStartContainer, + m.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedToStartContainer, "Failed to start container with id %v with error: %v", containerID, err) return "Start Container Failed", err } - m.recorder.Eventf(ref, api.EventTypeNormal, events.StartedContainer, "Started container with id %v", containerID) + m.recorder.Eventf(ref, v1.EventTypeNormal, events.StartedContainer, "Started container with id %v", containerID) // Symlink container logs to the legacy container log location for cluster logging // support. @@ -119,7 +119,7 @@ func (m *kubeGenericRuntimeManager) startContainer(podSandboxID string, podSandb msg, handlerErr := m.runner.Run(kubeContainerID, pod, container, container.Lifecycle.PostStart) if handlerErr != nil { err := fmt.Errorf("PostStart handler: %v", handlerErr) - m.generateContainerEvent(kubeContainerID, api.EventTypeWarning, events.FailedPostStartHook, msg) + m.generateContainerEvent(kubeContainerID, v1.EventTypeWarning, events.FailedPostStartHook, msg) m.killContainer(pod, kubeContainerID, container.Name, "FailedPostStartHook", nil) return "PostStart Hook Failed", err } @@ -128,8 +128,8 @@ func (m *kubeGenericRuntimeManager) startContainer(podSandboxID string, podSandb return "", nil } -// generateContainerConfig generates container config for kubelet runtime api. -func (m *kubeGenericRuntimeManager) generateContainerConfig(container *api.Container, pod *api.Pod, restartCount int, podIP string) (*runtimeApi.ContainerConfig, error) { +// generateContainerConfig generates container config for kubelet runtime v1. +func (m *kubeGenericRuntimeManager) generateContainerConfig(container *v1.Container, pod *v1.Pod, restartCount int, podIP string) (*runtimeApi.ContainerConfig, error) { opts, err := m.runtimeHelper.GenerateRunContainerOptions(pod, container, podIP) if err != nil { return nil, err @@ -185,8 +185,8 @@ func (m *kubeGenericRuntimeManager) generateContainerConfig(container *api.Conta return config, nil } -// generateLinuxContainerConfig generates linux container config for kubelet runtime api. -func (m *kubeGenericRuntimeManager) generateLinuxContainerConfig(container *api.Container, pod *api.Pod, uid *int64, username *string) *runtimeApi.LinuxContainerConfig { +// generateLinuxContainerConfig generates linux container config for kubelet runtime v1. +func (m *kubeGenericRuntimeManager) generateLinuxContainerConfig(container *v1.Container, pod *v1.Pod, uid *int64, username *string) *runtimeApi.LinuxContainerConfig { lc := &runtimeApi.LinuxContainerConfig{ Resources: &runtimeApi.LinuxContainerResources{}, SecurityContext: m.determineEffectiveSecurityContext(pod, container, uid, username), @@ -228,7 +228,7 @@ func (m *kubeGenericRuntimeManager) generateLinuxContainerConfig(container *api. return lc } -// makeDevices generates container devices for kubelet runtime api. +// makeDevices generates container devices for kubelet runtime v1. func makeDevices(opts *kubecontainer.RunContainerOptions) []*runtimeApi.Device { devices := make([]*runtimeApi.Device, len(opts.Devices)) @@ -244,8 +244,8 @@ func makeDevices(opts *kubecontainer.RunContainerOptions) []*runtimeApi.Device { return devices } -// makeMounts generates container volume mounts for kubelet runtime api. -func (m *kubeGenericRuntimeManager) makeMounts(opts *kubecontainer.RunContainerOptions, container *api.Container) []*runtimeApi.Mount { +// makeMounts generates container volume mounts for kubelet runtime v1. +func (m *kubeGenericRuntimeManager) makeMounts(opts *kubecontainer.RunContainerOptions, container *v1.Container) []*runtimeApi.Mount { volumeMounts := []*runtimeApi.Mount{} for idx := range opts.Mounts { @@ -416,7 +416,7 @@ func (m *kubeGenericRuntimeManager) generateContainerEvent(containerID kubeconta } // executePreStopHook runs the pre-stop lifecycle hooks if applicable and returns the duration it takes. -func (m *kubeGenericRuntimeManager) executePreStopHook(pod *api.Pod, containerID kubecontainer.ContainerID, containerSpec *api.Container, gracePeriod int64) int64 { +func (m *kubeGenericRuntimeManager) executePreStopHook(pod *v1.Pod, containerID kubecontainer.ContainerID, containerSpec *v1.Container, gracePeriod int64) int64 { glog.V(3).Infof("Running preStop hook for container %q", containerID.String()) start := unversioned.Now() @@ -426,7 +426,7 @@ func (m *kubeGenericRuntimeManager) executePreStopHook(pod *api.Pod, containerID defer utilruntime.HandleCrash() if msg, err := m.runner.Run(containerID, pod, containerSpec, containerSpec.Lifecycle.PreStop); err != nil { glog.Errorf("preStop hook for container %q failed: %v", containerSpec.Name, err) - m.generateContainerEvent(containerID, api.EventTypeWarning, events.FailedPreStopHook, msg) + m.generateContainerEvent(containerID, v1.EventTypeWarning, events.FailedPreStopHook, msg) } }() @@ -448,9 +448,9 @@ func (m *kubeGenericRuntimeManager) executePreStopHook(pod *api.Pod, containerID // TODO(random-liu): Add a node e2e test to test this behaviour. // TODO(random-liu): Change the lifecycle handler to just accept information needed, so that we can // just pass the needed function not create the fake object. -func (m *kubeGenericRuntimeManager) restoreSpecsFromContainerLabels(containerID kubecontainer.ContainerID) (*api.Pod, *api.Container, error) { - var pod *api.Pod - var container *api.Container +func (m *kubeGenericRuntimeManager) restoreSpecsFromContainerLabels(containerID kubecontainer.ContainerID) (*v1.Pod, *v1.Container, error) { + var pod *v1.Pod + var container *v1.Container s, err := m.runtimeService.ContainerStatus(containerID.ID) if err != nil { return nil, nil, err @@ -460,24 +460,24 @@ func (m *kubeGenericRuntimeManager) restoreSpecsFromContainerLabels(containerID a := getContainerInfoFromAnnotations(s.Annotations) // Notice that the followings are not full spec. The container killing code should not use // un-restored fields. - pod = &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod = &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: l.PodUID, Name: l.PodName, Namespace: l.PodNamespace, DeletionGracePeriodSeconds: a.PodDeletionGracePeriod, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ TerminationGracePeriodSeconds: a.PodTerminationGracePeriod, }, } - container = &api.Container{ + container = &v1.Container{ Name: l.ContainerName, Ports: a.ContainerPorts, TerminationMessagePath: a.TerminationMessagePath, } if a.PreStopHandler != nil { - container.Lifecycle = &api.Lifecycle{ + container.Lifecycle = &v1.Lifecycle{ PreStop: a.PreStopHandler, } } @@ -487,8 +487,8 @@ func (m *kubeGenericRuntimeManager) restoreSpecsFromContainerLabels(containerID // killContainer kills a container through the following steps: // * Run the pre-stop lifecycle hooks (if applicable). // * Stop the container. -func (m *kubeGenericRuntimeManager) killContainer(pod *api.Pod, containerID kubecontainer.ContainerID, containerName string, reason string, gracePeriodOverride *int64) error { - var containerSpec *api.Container +func (m *kubeGenericRuntimeManager) killContainer(pod *v1.Pod, containerID kubecontainer.ContainerID, containerName string, reason string, gracePeriodOverride *int64) error { + var containerSpec *v1.Container if pod != nil { containerSpec = getContainerSpec(pod, containerName) } else { @@ -534,14 +534,14 @@ func (m *kubeGenericRuntimeManager) killContainer(pod *api.Pod, containerID kube if reason != "" { message = fmt.Sprint(message, ":", reason) } - m.generateContainerEvent(containerID, api.EventTypeNormal, events.KillingContainer, message) + m.generateContainerEvent(containerID, v1.EventTypeNormal, events.KillingContainer, message) m.containerRefManager.ClearRef(containerID) return err } // killContainersWithSyncResult kills all pod's containers with sync results. -func (m *kubeGenericRuntimeManager) killContainersWithSyncResult(pod *api.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) (syncResults []*kubecontainer.SyncResult) { +func (m *kubeGenericRuntimeManager) killContainersWithSyncResult(pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) (syncResults []*kubecontainer.SyncResult) { containerResults := make(chan *kubecontainer.SyncResult, len(runningPod.Containers)) wg := sync.WaitGroup{} @@ -570,7 +570,7 @@ func (m *kubeGenericRuntimeManager) killContainersWithSyncResult(pod *api.Pod, r // pruneInitContainers ensures that before we begin creating init containers, we have reduced the number // of outstanding init containers still present. This reduces load on the container garbage collector // by only preserving the most recent terminated init container. -func (m *kubeGenericRuntimeManager) pruneInitContainersBeforeStart(pod *api.Pod, podStatus *kubecontainer.PodStatus, initContainersToKeep map[kubecontainer.ContainerID]int) { +func (m *kubeGenericRuntimeManager) pruneInitContainersBeforeStart(pod *v1.Pod, podStatus *kubecontainer.PodStatus, initContainersToKeep map[kubecontainer.ContainerID]int) { // only the last execution of each init container should be preserved, and only preserve it if it is in the // list of init containers to keep. initContainerNames := sets.NewString() @@ -614,7 +614,7 @@ func (m *kubeGenericRuntimeManager) pruneInitContainersBeforeStart(pod *api.Pod, // next init container to start, or done if there are no further init containers. // Status is only returned if an init container is failed, in which case next will // point to the current container. -func findNextInitContainerToRun(pod *api.Pod, podStatus *kubecontainer.PodStatus) (status *kubecontainer.ContainerStatus, next *api.Container, done bool) { +func findNextInitContainerToRun(pod *v1.Pod, podStatus *kubecontainer.PodStatus) (status *kubecontainer.ContainerStatus, next *v1.Container, done bool) { if len(pod.Spec.InitContainers) == 0 { return nil, nil, true } @@ -656,7 +656,7 @@ func findNextInitContainerToRun(pod *api.Pod, podStatus *kubecontainer.PodStatus } // GetContainerLogs returns logs of a specific container. -func (m *kubeGenericRuntimeManager) GetContainerLogs(pod *api.Pod, containerID kubecontainer.ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) (err error) { +func (m *kubeGenericRuntimeManager) GetContainerLogs(pod *v1.Pod, containerID kubecontainer.ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) (err error) { status, err := m.runtimeService.ContainerStatus(containerID.ID) if err != nil { return fmt.Errorf("failed to get container status %q: %v", containerID, err) diff --git a/pkg/kubelet/kuberuntime/kuberuntime_container_test.go b/pkg/kubelet/kuberuntime/kuberuntime_container_test.go index 05bf6996ea2..0e6d4be0dda 100644 --- a/pkg/kubelet/kuberuntime/kuberuntime_container_test.go +++ b/pkg/kubelet/kuberuntime/kuberuntime_container_test.go @@ -21,7 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" ) @@ -29,18 +29,18 @@ import ( // TestRemoveContainer tests removing the container and its corresponding container logs. func TestRemoveContainer(t *testing.T) { fakeRuntime, _, m, err := createTestRuntimeManager() - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "foo", Image: "busybox", - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, }, }, }, diff --git a/pkg/kubelet/kuberuntime/kuberuntime_gc_test.go b/pkg/kubelet/kuberuntime/kuberuntime_gc_test.go index 8ba08c31af0..4e371504a8a 100644 --- a/pkg/kubelet/kuberuntime/kuberuntime_gc_test.go +++ b/pkg/kubelet/kuberuntime/kuberuntime_gc_test.go @@ -24,7 +24,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" @@ -34,12 +34,12 @@ func TestSandboxGC(t *testing.T) { fakeRuntime, _, m, err := createTestRuntimeManager() assert.NoError(t, err) - pods := []*api.Pod{ - makeTestPod("foo1", "new", "1234", []api.Container{ + pods := []*v1.Pod{ + makeTestPod("foo1", "new", "1234", []v1.Container{ makeTestContainer("bar1", "busybox"), makeTestContainer("bar2", "busybox"), }), - makeTestPod("foo2", "new", "5678", []api.Container{ + makeTestPod("foo2", "new", "5678", []v1.Container{ makeTestContainer("bar3", "busybox"), }), } @@ -129,7 +129,7 @@ func TestContainerGC(t *testing.T) { fakePodGetter := m.containerGC.podGetter.(*fakePodGetter) makeGCContainer := func(podName, containerName string, attempt int, createdAt int64, state runtimeApi.ContainerState) containerTemplate { container := makeTestContainer(containerName, "test-image") - pod := makeTestPod(podName, "test-ns", podName, []api.Container{container}) + pod := makeTestPod(podName, "test-ns", podName, []v1.Container{container}) if podName != "deleted" { // initialize the pod getter, explicitly exclude deleted pod fakePodGetter.pods[pod.UID] = pod diff --git a/pkg/kubelet/kuberuntime/kuberuntime_image.go b/pkg/kubelet/kuberuntime/kuberuntime_image.go index 29c57000548..1a9c98f2414 100644 --- a/pkg/kubelet/kuberuntime/kuberuntime_image.go +++ b/pkg/kubelet/kuberuntime/kuberuntime_image.go @@ -18,7 +18,7 @@ package kuberuntime import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/credentialprovider" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" @@ -28,7 +28,7 @@ import ( // PullImage pulls an image from the network to local storage using the supplied // secrets if necessary. -func (m *kubeGenericRuntimeManager) PullImage(image kubecontainer.ImageSpec, pullSecrets []api.Secret) error { +func (m *kubeGenericRuntimeManager) PullImage(image kubecontainer.ImageSpec, pullSecrets []v1.Secret) error { img := image.Image repoToPull, _, _, err := parsers.ParseImageName(img) if err != nil { diff --git a/pkg/kubelet/kuberuntime/kuberuntime_logs.go b/pkg/kubelet/kuberuntime/kuberuntime_logs.go index 5c425015b31..3cc0eb17640 100644 --- a/pkg/kubelet/kuberuntime/kuberuntime_logs.go +++ b/pkg/kubelet/kuberuntime/kuberuntime_logs.go @@ -31,7 +31,7 @@ import ( "github.com/fsnotify/fsnotify" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) // Notice that the current kuberuntime logs implementation doesn't handle @@ -85,8 +85,8 @@ type logOptions struct { timestamp bool } -// newLogOptions convert the api.PodLogOptions to internal logOptions. -func newLogOptions(apiOpts *api.PodLogOptions, now time.Time) *logOptions { +// newLogOptions convert the v1.PodLogOptions to internal logOptions. +func newLogOptions(apiOpts *v1.PodLogOptions, now time.Time) *logOptions { opts := &logOptions{ tail: -1, // -1 by default which means read all logs. bytes: -1, // -1 by default which means read all logs. @@ -109,14 +109,14 @@ func newLogOptions(apiOpts *api.PodLogOptions, now time.Time) *logOptions { } // ReadLogs read the container log and redirect into stdout and stderr. -func ReadLogs(path string, apiOpts *api.PodLogOptions, stdout, stderr io.Writer) error { +func ReadLogs(path string, apiOpts *v1.PodLogOptions, stdout, stderr io.Writer) error { f, err := os.Open(path) if err != nil { return fmt.Errorf("failed to open log file %q: %v", path, err) } defer f.Close() - // Convert api.PodLogOptions into internal log options. + // Convert v1.PodLogOptions into internal log options. opts := newLogOptions(apiOpts, time.Now()) // Search start point based on tail line. diff --git a/pkg/kubelet/kuberuntime/kuberuntime_logs_test.go b/pkg/kubelet/kuberuntime/kuberuntime_logs_test.go index 18538e25ebf..be27ee9f0ab 100644 --- a/pkg/kubelet/kuberuntime/kuberuntime_logs_test.go +++ b/pkg/kubelet/kuberuntime/kuberuntime_logs_test.go @@ -24,8 +24,8 @@ import ( "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" ) func TestLogOptions(t *testing.T) { @@ -36,27 +36,27 @@ func TestLogOptions(t *testing.T) { sinceseconds = int64(10) ) for c, test := range []struct { - apiOpts *api.PodLogOptions + apiOpts *v1.PodLogOptions expect *logOptions }{ { // empty options - apiOpts: &api.PodLogOptions{}, + apiOpts: &v1.PodLogOptions{}, expect: &logOptions{tail: -1, bytes: -1}, }, { // test tail lines - apiOpts: &api.PodLogOptions{TailLines: &line}, + apiOpts: &v1.PodLogOptions{TailLines: &line}, expect: &logOptions{tail: line, bytes: -1}, }, { // test limit bytes - apiOpts: &api.PodLogOptions{LimitBytes: &bytes}, + apiOpts: &v1.PodLogOptions{LimitBytes: &bytes}, expect: &logOptions{tail: -1, bytes: bytes}, }, { // test since timestamp - apiOpts: &api.PodLogOptions{SinceTime: ×tamp}, + apiOpts: &v1.PodLogOptions{SinceTime: ×tamp}, expect: &logOptions{tail: -1, bytes: -1, since: timestamp.Time}, }, { // test since seconds - apiOpts: &api.PodLogOptions{SinceSeconds: &sinceseconds}, + apiOpts: &v1.PodLogOptions{SinceSeconds: &sinceseconds}, expect: &logOptions{tail: -1, bytes: -1, since: timestamp.Add(-10 * time.Second)}, }, } { diff --git a/pkg/kubelet/kuberuntime/kuberuntime_manager.go b/pkg/kubelet/kuberuntime/kuberuntime_manager.go index 587695f2df5..69cd541adb2 100644 --- a/pkg/kubelet/kuberuntime/kuberuntime_manager.go +++ b/pkg/kubelet/kuberuntime/kuberuntime_manager.go @@ -26,7 +26,7 @@ import ( "github.com/golang/glog" cadvisorapi "github.com/google/cadvisor/info/v1" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/credentialprovider" internalApi "k8s.io/kubernetes/pkg/kubelet/api" @@ -64,7 +64,7 @@ var ( // A subset of the pod.Manager interface extracted for garbage collection purposes. type podGetter interface { - GetPodByUID(kubetypes.UID) (*api.Pod, bool) + GetPodByUID(kubetypes.UID) (*v1.Pod, bool) } type kubeGenericRuntimeManager struct { @@ -349,7 +349,7 @@ func (m *kubeGenericRuntimeManager) GetPods(all bool) ([]*kubecontainer.Pod, err // containerToKillInfo contains neccessary information to kill a container. type containerToKillInfo struct { // The spec of the container. - container *api.Container + container *v1.Container // The name of the container. name string // The message indicates why the container will be killed. @@ -388,7 +388,7 @@ type podContainerSpecChanges struct { // podSandboxChanged checks whether the spec of the pod is changed and returns // (changed, new attempt, original sandboxID if exist). -func (m *kubeGenericRuntimeManager) podSandboxChanged(pod *api.Pod, podStatus *kubecontainer.PodStatus) (changed bool, attempt uint32, sandboxID string) { +func (m *kubeGenericRuntimeManager) podSandboxChanged(pod *v1.Pod, podStatus *kubecontainer.PodStatus) (changed bool, attempt uint32, sandboxID string) { if len(podStatus.SandboxStatuses) == 0 { glog.V(2).Infof("No sandbox for pod %q can be found. Need to start a new one", format.Pod(pod)) return true, 0, "" @@ -420,7 +420,7 @@ func (m *kubeGenericRuntimeManager) podSandboxChanged(pod *api.Pod, podStatus *k // checkAndKeepInitContainers keeps all successfully completed init containers. If there // are failing containers, only keep the first failing one. -func checkAndKeepInitContainers(pod *api.Pod, podStatus *kubecontainer.PodStatus, initContainersToKeep map[kubecontainer.ContainerID]int) bool { +func checkAndKeepInitContainers(pod *v1.Pod, podStatus *kubecontainer.PodStatus, initContainersToKeep map[kubecontainer.ContainerID]int) bool { initFailed := false for i, container := range pod.Spec.InitContainers { @@ -448,7 +448,7 @@ func checkAndKeepInitContainers(pod *api.Pod, podStatus *kubecontainer.PodStatus } // computePodContainerChanges checks whether the pod spec has changed and returns the changes if true. -func (m *kubeGenericRuntimeManager) computePodContainerChanges(pod *api.Pod, podStatus *kubecontainer.PodStatus) podContainerSpecChanges { +func (m *kubeGenericRuntimeManager) computePodContainerChanges(pod *v1.Pod, podStatus *kubecontainer.PodStatus) podContainerSpecChanges { glog.V(5).Infof("Syncing Pod %q: %+v", format.Pod(pod), pod) sandboxChanged, attempt, sandboxID := m.podSandboxChanged(pod, podStatus) @@ -484,7 +484,7 @@ func (m *kubeGenericRuntimeManager) computePodContainerChanges(pod *api.Pod, pod continue } if sandboxChanged { - if pod.Spec.RestartPolicy != api.RestartPolicyNever { + if pod.Spec.RestartPolicy != v1.RestartPolicyNever { message := fmt.Sprintf("Container %+v's pod sandbox is dead, the container will be recreated.", container) glog.Info(message) changes.ContainersToStart[index] = message @@ -496,7 +496,7 @@ func (m *kubeGenericRuntimeManager) computePodContainerChanges(pod *api.Pod, pod // Initialization failed and Container exists. // If we have an initialization failure everything will be killed anyway. // If RestartPolicy is Always or OnFailure we restart containers that were running before. - if pod.Spec.RestartPolicy != api.RestartPolicyNever { + if pod.Spec.RestartPolicy != v1.RestartPolicyNever { message := fmt.Sprintf("Failed to initialize pod. %q will be restarted.", container.Name) glog.V(1).Info(message) changes.ContainersToStart[index] = message @@ -519,7 +519,7 @@ func (m *kubeGenericRuntimeManager) computePodContainerChanges(pod *api.Pod, pod changes.ContainersToKeep[containerStatus.ID] = index continue } - if pod.Spec.RestartPolicy != api.RestartPolicyNever { + if pod.Spec.RestartPolicy != v1.RestartPolicyNever { message := fmt.Sprintf("pod %q container %q is unhealthy, it will be killed and re-created.", format.Pod(pod), container.Name) glog.Info(message) changes.ContainersToStart[index] = message @@ -537,7 +537,7 @@ func (m *kubeGenericRuntimeManager) computePodContainerChanges(pod *api.Pod, pod _, keep := changes.ContainersToKeep[containerStatus.ID] _, keepInit := changes.InitContainersToKeep[containerStatus.ID] if !keep && !keepInit { - var podContainer *api.Container + var podContainer *v1.Container var killMessage string for i, c := range pod.Spec.Containers { if c.Name == containerStatus.Name { @@ -566,19 +566,19 @@ func (m *kubeGenericRuntimeManager) computePodContainerChanges(pod *api.Pod, pod // 4. Create sandbox if necessary. // 5. Create init containers. // 6. Create normal containers. -func (m *kubeGenericRuntimeManager) SyncPod(pod *api.Pod, _ api.PodStatus, podStatus *kubecontainer.PodStatus, pullSecrets []api.Secret, backOff *flowcontrol.Backoff) (result kubecontainer.PodSyncResult) { +func (m *kubeGenericRuntimeManager) SyncPod(pod *v1.Pod, _ v1.PodStatus, podStatus *kubecontainer.PodStatus, pullSecrets []v1.Secret, backOff *flowcontrol.Backoff) (result kubecontainer.PodSyncResult) { // Step 1: Compute sandbox and container changes. podContainerChanges := m.computePodContainerChanges(pod, podStatus) glog.V(3).Infof("computePodContainerChanges got %+v for pod %q", podContainerChanges, format.Pod(pod)) if podContainerChanges.CreateSandbox { - ref, err := api.GetReference(pod) + ref, err := v1.GetReference(pod) if err != nil { glog.Errorf("Couldn't make a ref to pod %q: '%v'", format.Pod(pod), err) } if podContainerChanges.SandboxID != "" { - m.recorder.Eventf(ref, api.EventTypeNormal, "SandboxChanged", "Pod sandbox changed, it will be killed and re-created.") + m.recorder.Eventf(ref, v1.EventTypeNormal, "SandboxChanged", "Pod sandbox changed, it will be killed and re-created.") } else { - m.recorder.Eventf(ref, api.EventTypeNormal, "SandboxReceived", "Pod sandbox received, it will be created.") + m.recorder.Eventf(ref, v1.EventTypeNormal, "SandboxReceived", "Pod sandbox received, it will be created.") } } @@ -674,7 +674,7 @@ func (m *kubeGenericRuntimeManager) SyncPod(pod *api.Pod, _ api.PodStatus, podSt initContainerResult := kubecontainer.NewSyncResult(kubecontainer.InitContainer, status.Name) initContainerResult.Fail(kubecontainer.ErrRunInitContainer, fmt.Sprintf("init container %q exited with %d", status.Name, status.ExitCode)) result.AddSyncResult(initContainerResult) - if pod.Spec.RestartPolicy == api.RestartPolicyNever { + if pod.Spec.RestartPolicy == v1.RestartPolicyNever { utilruntime.HandleError(fmt.Errorf("error running pod %q init container %q, restart=Never: %#v", format.Pod(pod), status.Name, status)) return } @@ -745,7 +745,7 @@ func (m *kubeGenericRuntimeManager) SyncPod(pod *api.Pod, _ api.PodStatus, podSt // If a container is still in backoff, the function will return a brief backoff error and // a detailed error message. -func (m *kubeGenericRuntimeManager) doBackOff(pod *api.Pod, container *api.Container, podStatus *kubecontainer.PodStatus, backOff *flowcontrol.Backoff) (bool, string, error) { +func (m *kubeGenericRuntimeManager) doBackOff(pod *v1.Pod, container *v1.Container, podStatus *kubecontainer.PodStatus, backOff *flowcontrol.Backoff) (bool, string, error) { var cStatus *kubecontainer.ContainerStatus for _, c := range podStatus.ContainerStatuses { if c.Name == container.Name && c.State == kubecontainer.ContainerStateExited { @@ -765,7 +765,7 @@ func (m *kubeGenericRuntimeManager) doBackOff(pod *api.Pod, container *api.Conta key := getStableKey(pod, container) if backOff.IsInBackOffSince(key, ts) { if ref, err := kubecontainer.GenerateContainerRef(pod, container); err == nil { - m.recorder.Eventf(ref, api.EventTypeWarning, events.BackOffStartContainer, "Back-off restarting failed container") + m.recorder.Eventf(ref, v1.EventTypeWarning, events.BackOffStartContainer, "Back-off restarting failed container") } err := fmt.Errorf("Back-off %s restarting failed container=%s pod=%s", backOff.Get(key), container.Name, format.Pod(pod)) glog.Infof("%s", err.Error()) @@ -780,14 +780,14 @@ func (m *kubeGenericRuntimeManager) doBackOff(pod *api.Pod, container *api.Conta // gracePeriodOverride if specified allows the caller to override the pod default grace period. // only hard kill paths are allowed to specify a gracePeriodOverride in the kubelet in order to not corrupt user data. // it is useful when doing SIGKILL for hard eviction scenarios, or max grace period during soft eviction scenarios. -func (m *kubeGenericRuntimeManager) KillPod(pod *api.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) error { +func (m *kubeGenericRuntimeManager) KillPod(pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) error { err := m.killPodWithSyncResult(pod, runningPod, gracePeriodOverride) return err.Error() } // killPodWithSyncResult kills a runningPod and returns SyncResult. // Note: The pod passed in could be *nil* when kubelet restarted. -func (m *kubeGenericRuntimeManager) killPodWithSyncResult(pod *api.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) (result kubecontainer.PodSyncResult) { +func (m *kubeGenericRuntimeManager) killPodWithSyncResult(pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) (result kubecontainer.PodSyncResult) { killContainerResults := m.killContainersWithSyncResult(pod, runningPod, gracePeriodOverride) for _, containerResult := range killContainerResults { result.AddSyncResult(containerResult) @@ -808,7 +808,7 @@ func (m *kubeGenericRuntimeManager) killPodWithSyncResult(pod *api.Pod, runningP } // isHostNetwork checks whether the pod is running in host-network mode. -func (m *kubeGenericRuntimeManager) isHostNetwork(podSandBoxID string, pod *api.Pod) (bool, error) { +func (m *kubeGenericRuntimeManager) isHostNetwork(podSandBoxID string, pod *v1.Pod) (bool, error) { if pod != nil { return kubecontainer.IsHostNetworkPod(pod), nil } @@ -848,8 +848,8 @@ func (m *kubeGenericRuntimeManager) GetPodStatus(uid kubetypes.UID, name, namesp return nil, err } - podFullName := format.Pod(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + podFullName := format.Pod(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Namespace: namespace, UID: uid, diff --git a/pkg/kubelet/kuberuntime/kuberuntime_manager_test.go b/pkg/kubelet/kuberuntime/kuberuntime_manager_test.go index 07610e1b92d..3edaf07e405 100644 --- a/pkg/kubelet/kuberuntime/kuberuntime_manager_test.go +++ b/pkg/kubelet/kuberuntime/kuberuntime_manager_test.go @@ -24,7 +24,7 @@ import ( cadvisorapi "github.com/google/cadvisor/info/v1" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" apitest "k8s.io/kubernetes/pkg/kubelet/api/testing" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" @@ -63,7 +63,7 @@ func createTestRuntimeManager() (*apitest.FakeRuntimeService, *apitest.FakeImage // sandboxTemplate is a sandbox template to create fake sandbox. type sandboxTemplate struct { - pod *api.Pod + pod *v1.Pod attempt uint32 createdAt int64 state runtimeApi.PodSandboxState @@ -71,8 +71,8 @@ type sandboxTemplate struct { // containerTemplate is a container template to create fake container. type containerTemplate struct { - pod *api.Pod - container *api.Container + pod *v1.Pod + container *v1.Container sandboxAttempt uint32 attempt int createdAt int64 @@ -82,7 +82,7 @@ type containerTemplate struct { // makeAndSetFakePod is a helper function to create and set one fake sandbox for a pod and // one fake container for each of its container. func makeAndSetFakePod(t *testing.T, m *kubeGenericRuntimeManager, fakeRuntime *apitest.FakeRuntimeService, - pod *api.Pod) (*apitest.FakePodSandbox, []*apitest.FakeContainer) { + pod *v1.Pod) (*apitest.FakePodSandbox, []*apitest.FakeContainer) { sandbox := makeFakePodSandbox(t, m, sandboxTemplate{ pod: pod, createdAt: fakeCreatedAt, @@ -90,7 +90,7 @@ func makeAndSetFakePod(t *testing.T, m *kubeGenericRuntimeManager, fakeRuntime * }) var containers []*apitest.FakeContainer - newTemplate := func(c *api.Container) containerTemplate { + newTemplate := func(c *v1.Container) containerTemplate { return containerTemplate{ pod: pod, container: c, @@ -177,22 +177,22 @@ func makeFakeContainers(t *testing.T, m *kubeGenericRuntimeManager, templates [] } // makeTestContainer creates a test api container. -func makeTestContainer(name, image string) api.Container { - return api.Container{ +func makeTestContainer(name, image string) v1.Container { + return v1.Container{ Name: name, Image: image, } } // makeTestPod creates a test api pod. -func makeTestPod(podName, podNamespace, podUID string, containers []api.Container) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func makeTestPod(podName, podNamespace, podUID string, containers []v1.Container) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: types.UID(podUID), Name: podName, Namespace: podNamespace, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ Containers: containers, }, } @@ -256,25 +256,25 @@ func TestGetPodStatus(t *testing.T) { fakeRuntime, _, m, err := createTestRuntimeManager() assert.NoError(t, err) - containers := []api.Container{ + containers := []v1.Container{ { Name: "foo1", Image: "busybox", - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, }, { Name: "foo2", Image: "busybox", - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, }, } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ Containers: containers, }, } @@ -294,14 +294,14 @@ func TestGetPods(t *testing.T) { fakeRuntime, _, m, err := createTestRuntimeManager() assert.NoError(t, err) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "foo1", Image: "busybox", @@ -370,14 +370,14 @@ func TestGetPodContainerID(t *testing.T) { fakeRuntime, _, m, err := createTestRuntimeManager() assert.NoError(t, err) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "foo1", Image: "busybox", @@ -417,14 +417,14 @@ func TestGetNetNS(t *testing.T) { fakeRuntime, _, m, err := createTestRuntimeManager() assert.NoError(t, err) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "foo1", Image: "busybox", @@ -449,14 +449,14 @@ func TestKillPod(t *testing.T) { fakeRuntime, _, m, err := createTestRuntimeManager() assert.NoError(t, err) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "foo1", Image: "busybox", @@ -520,31 +520,31 @@ func TestSyncPod(t *testing.T) { fakeRuntime, fakeImage, m, err := createTestRuntimeManager() assert.NoError(t, err) - containers := []api.Container{ + containers := []v1.Container{ { Name: "foo1", Image: "busybox", - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, }, { Name: "foo2", Image: "alpine", - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, }, } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ Containers: containers, }, } backOff := flowcontrol.NewBackOff(time.Second, time.Minute) - result := m.SyncPod(pod, api.PodStatus{}, &kubecontainer.PodStatus{}, []api.Secret{}, backOff) + result := m.SyncPod(pod, v1.PodStatus{}, &kubecontainer.PodStatus{}, []v1.Secret{}, backOff) assert.NoError(t, result.Error()) assert.Equal(t, 2, len(fakeRuntime.Containers)) assert.Equal(t, 2, len(fakeImage.Images)) @@ -563,14 +563,14 @@ func TestPruneInitContainers(t *testing.T) { init1 := makeTestContainer("init1", "busybox") init2 := makeTestContainer("init2", "busybox") - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ - InitContainers: []api.Container{init1, init2}, + Spec: v1.PodSpec{ + InitContainers: []v1.Container{init1, init2}, }, } @@ -598,32 +598,32 @@ func TestSyncPodWithInitContainers(t *testing.T) { fakeRuntime, _, m, err := createTestRuntimeManager() assert.NoError(t, err) - initContainers := []api.Container{ + initContainers := []v1.Container{ { Name: "init1", Image: "init", - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, }, } - containers := []api.Container{ + containers := []v1.Container{ { Name: "foo1", Image: "busybox", - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, }, { Name: "foo2", Image: "alpine", - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, }, } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ Containers: containers, InitContainers: initContainers, }, @@ -631,7 +631,7 @@ func TestSyncPodWithInitContainers(t *testing.T) { // buildContainerID is an internal helper function to build container id from api pod // and container with default attempt number 0. - buildContainerID := func(pod *api.Pod, container api.Container) string { + buildContainerID := func(pod *v1.Pod, container v1.Container) string { uid := string(pod.UID) sandboxID := apitest.BuildSandboxName(&runtimeApi.PodSandboxMetadata{ Name: &pod.Name, @@ -646,7 +646,7 @@ func TestSyncPodWithInitContainers(t *testing.T) { // 1. should only create the init container. podStatus, err := m.GetPodStatus(pod.UID, pod.Name, pod.Namespace) assert.NoError(t, err) - result := m.SyncPod(pod, api.PodStatus{}, podStatus, []api.Secret{}, backOff) + result := m.SyncPod(pod, v1.PodStatus{}, podStatus, []v1.Secret{}, backOff) assert.NoError(t, result.Error()) assert.Equal(t, 1, len(fakeRuntime.Containers)) initContainerID := buildContainerID(pod, initContainers[0]) @@ -658,7 +658,7 @@ func TestSyncPodWithInitContainers(t *testing.T) { // 2. should not create app container because init container is still running. podStatus, err = m.GetPodStatus(pod.UID, pod.Name, pod.Namespace) assert.NoError(t, err) - result = m.SyncPod(pod, api.PodStatus{}, podStatus, []api.Secret{}, backOff) + result = m.SyncPod(pod, v1.PodStatus{}, podStatus, []v1.Secret{}, backOff) assert.NoError(t, result.Error()) assert.Equal(t, 1, len(fakeRuntime.Containers)) expectedContainers = []string{initContainerID} @@ -670,7 +670,7 @@ func TestSyncPodWithInitContainers(t *testing.T) { fakeRuntime.StopContainer(initContainerID, 0) podStatus, err = m.GetPodStatus(pod.UID, pod.Name, pod.Namespace) assert.NoError(t, err) - result = m.SyncPod(pod, api.PodStatus{}, podStatus, []api.Secret{}, backOff) + result = m.SyncPod(pod, v1.PodStatus{}, podStatus, []v1.Secret{}, backOff) assert.NoError(t, result.Error()) assert.Equal(t, 3, len(fakeRuntime.Containers)) expectedContainers = []string{initContainerID, buildContainerID(pod, containers[0]), diff --git a/pkg/kubelet/kuberuntime/kuberuntime_sandbox.go b/pkg/kubelet/kuberuntime/kuberuntime_sandbox.go index 2374ecd4e31..97c60ca707d 100644 --- a/pkg/kubelet/kuberuntime/kuberuntime_sandbox.go +++ b/pkg/kubelet/kuberuntime/kuberuntime_sandbox.go @@ -23,7 +23,7 @@ import ( "sort" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/types" @@ -32,7 +32,7 @@ import ( ) // createPodSandbox creates a pod sandbox and returns (podSandBoxID, message, error). -func (m *kubeGenericRuntimeManager) createPodSandbox(pod *api.Pod, attempt uint32) (string, string, error) { +func (m *kubeGenericRuntimeManager) createPodSandbox(pod *v1.Pod, attempt uint32) (string, string, error) { podSandboxConfig, err := m.generatePodSandboxConfig(pod, attempt) if err != nil { message := fmt.Sprintf("GeneratePodSandboxConfig for pod %q failed: %v", format.Pod(pod), err) @@ -58,8 +58,8 @@ func (m *kubeGenericRuntimeManager) createPodSandbox(pod *api.Pod, attempt uint3 return podSandBoxID, "", nil } -// generatePodSandboxConfig generates pod sandbox config from api.Pod. -func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *api.Pod, attempt uint32) (*runtimeApi.PodSandboxConfig, error) { +// generatePodSandboxConfig generates pod sandbox config from v1.Pod. +func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attempt uint32) (*runtimeApi.PodSandboxConfig, error) { // TODO: deprecating podsandbox resource requirements in favor of the pod level cgroup // Refer https://github.com/kubernetes/kubernetes/issues/29871 podUID := string(pod.UID) @@ -128,8 +128,8 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *api.Pod, attem return podSandboxConfig, nil } -// generatePodSandboxLinuxConfig generates LinuxPodSandboxConfig from api.Pod. -func (m *kubeGenericRuntimeManager) generatePodSandboxLinuxConfig(pod *api.Pod, cgroupParent string) *runtimeApi.LinuxPodSandboxConfig { +// generatePodSandboxLinuxConfig generates LinuxPodSandboxConfig from v1.Pod. +func (m *kubeGenericRuntimeManager) generatePodSandboxLinuxConfig(pod *v1.Pod, cgroupParent string) *runtimeApi.LinuxPodSandboxConfig { if pod.Spec.SecurityContext == nil && cgroupParent == "" { return nil } @@ -142,9 +142,9 @@ func (m *kubeGenericRuntimeManager) generatePodSandboxLinuxConfig(pod *api.Pod, sc := pod.Spec.SecurityContext lc.SecurityContext = &runtimeApi.LinuxSandboxSecurityContext{ NamespaceOptions: &runtimeApi.NamespaceOption{ - HostNetwork: &sc.HostNetwork, - HostIpc: &sc.HostIPC, - HostPid: &sc.HostPID, + HostNetwork: &pod.Spec.HostNetwork, + HostIpc: &pod.Spec.HostIPC, + HostPid: &pod.Spec.HostPID, }, RunAsUser: sc.RunAsUser, } diff --git a/pkg/kubelet/kuberuntime/kuberuntime_sandbox_test.go b/pkg/kubelet/kuberuntime/kuberuntime_sandbox_test.go index b9d9e1c924f..0581a0e5388 100644 --- a/pkg/kubelet/kuberuntime/kuberuntime_sandbox_test.go +++ b/pkg/kubelet/kuberuntime/kuberuntime_sandbox_test.go @@ -22,7 +22,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" ) @@ -30,18 +30,18 @@ import ( // TestCreatePodSandbox tests creating sandbox and its corresponding pod log directory. func TestCreatePodSandbox(t *testing.T) { fakeRuntime, _, m, err := createTestRuntimeManager() - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "foo", Image: "busybox", - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, }, }, }, diff --git a/pkg/kubelet/kuberuntime/labels.go b/pkg/kubelet/kuberuntime/labels.go index 2fd475bd7d2..88e383d21bd 100644 --- a/pkg/kubelet/kuberuntime/labels.go +++ b/pkg/kubelet/kuberuntime/labels.go @@ -21,7 +21,7 @@ import ( "strconv" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/kubelet/util/format" @@ -45,7 +45,7 @@ const ( ) type labeledPodSandboxInfo struct { - // Labels from api.Pod + // Labels from v1.Pod Labels map[string]string PodName string PodNamespace string @@ -53,7 +53,7 @@ type labeledPodSandboxInfo struct { } type annotatedPodSandboxInfo struct { - // Annotations from api.Pod + // Annotations from v1.Pod Annotations map[string]string } @@ -70,15 +70,15 @@ type annotatedContainerInfo struct { PodDeletionGracePeriod *int64 PodTerminationGracePeriod *int64 TerminationMessagePath string - PreStopHandler *api.Handler - ContainerPorts []api.ContainerPort + PreStopHandler *v1.Handler + ContainerPorts []v1.ContainerPort } -// newPodLabels creates pod labels from api.Pod. -func newPodLabels(pod *api.Pod) map[string]string { +// newPodLabels creates pod labels from v1.Pod. +func newPodLabels(pod *v1.Pod) map[string]string { labels := map[string]string{} - // Get labels from api.Pod + // Get labels from v1.Pod for k, v := range pod.Labels { labels[k] = v } @@ -91,13 +91,13 @@ func newPodLabels(pod *api.Pod) map[string]string { return labels } -// newPodAnnotations creates pod annotations from api.Pod. -func newPodAnnotations(pod *api.Pod) map[string]string { +// newPodAnnotations creates pod annotations from v1.Pod. +func newPodAnnotations(pod *v1.Pod) map[string]string { return pod.Annotations } -// newContainerLabels creates container labels from api.Container and api.Pod. -func newContainerLabels(container *api.Container, pod *api.Pod) map[string]string { +// newContainerLabels creates container labels from v1.Container and v1.Pod. +func newContainerLabels(container *v1.Container, pod *v1.Pod) map[string]string { labels := map[string]string{} labels[types.KubernetesPodNameLabel] = pod.Name labels[types.KubernetesPodNamespaceLabel] = pod.Namespace @@ -108,8 +108,8 @@ func newContainerLabels(container *api.Container, pod *api.Pod) map[string]strin return labels } -// newContainerAnnotations creates container annotations from api.Container and api.Pod. -func newContainerAnnotations(container *api.Container, pod *api.Pod, restartCount int) map[string]string { +// newContainerAnnotations creates container annotations from v1.Container and v1.Pod. +func newContainerAnnotations(container *v1.Container, pod *v1.Pod, restartCount int) map[string]string { annotations := map[string]string{} annotations[containerHashLabel] = strconv.FormatUint(kubecontainer.HashContainer(container), 16) annotations[containerRestartCountLabel] = strconv.Itoa(restartCount) @@ -153,7 +153,7 @@ func getPodSandboxInfoFromLabels(labels map[string]string) *labeledPodSandboxInf PodUID: kubetypes.UID(getStringValueFromLabel(labels, types.KubernetesPodUIDLabel)), } - // Remain only labels from api.Pod + // Remain only labels from v1.Pod for k, v := range labels { if k != types.KubernetesPodNameLabel && k != types.KubernetesPodNamespaceLabel && k != types.KubernetesPodUIDLabel && k != kubernetesManagedLabel { podSandboxInfo.Labels[k] = v @@ -209,14 +209,14 @@ func getContainerInfoFromAnnotations(annotations map[string]string) *annotatedCo glog.Errorf("Unable to get %q from annotations %q: %v", podTerminationGracePeriodLabel, annotations, err) } - preStopHandler := &api.Handler{} + preStopHandler := &v1.Handler{} if found, err := getJSONObjectFromLabel(annotations, containerPreStopHandlerLabel, preStopHandler); err != nil { glog.Errorf("Unable to get %q from annotations %q: %v", containerPreStopHandlerLabel, annotations, err) } else if found { containerInfo.PreStopHandler = preStopHandler } - containerPorts := []api.ContainerPort{} + containerPorts := []v1.ContainerPort{} if found, err := getJSONObjectFromLabel(annotations, containerPortsLabel, &containerPorts); err != nil { glog.Errorf("Unable to get %q from annotations %q: %v", containerPortsLabel, annotations, err) } else if found { diff --git a/pkg/kubelet/kuberuntime/labels_test.go b/pkg/kubelet/kuberuntime/labels_test.go index 0ece3f4843c..5c52ec49a52 100644 --- a/pkg/kubelet/kuberuntime/labels_test.go +++ b/pkg/kubelet/kuberuntime/labels_test.go @@ -20,7 +20,7 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/util/intstr" ) @@ -28,37 +28,37 @@ import ( func TestContainerLabels(t *testing.T) { deletionGracePeriod := int64(10) terminationGracePeriod := int64(10) - lifecycle := &api.Lifecycle{ + lifecycle := &v1.Lifecycle{ // Left PostStart as nil - PreStop: &api.Handler{ - Exec: &api.ExecAction{ + PreStop: &v1.Handler{ + Exec: &v1.ExecAction{ Command: []string{"action1", "action2"}, }, - HTTPGet: &api.HTTPGetAction{ + HTTPGet: &v1.HTTPGetAction{ Path: "path", Host: "host", Port: intstr.FromInt(8080), Scheme: "scheme", }, - TCPSocket: &api.TCPSocketAction{ + TCPSocket: &v1.TCPSocketAction{ Port: intstr.FromString("80"), }, }, } - container := &api.Container{ + container := &v1.Container{ Name: "test_container", TerminationMessagePath: "/somepath", Lifecycle: lifecycle, } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "test_pod", Namespace: "test_pod_namespace", UID: "test_pod_uid", DeletionGracePeriodSeconds: &deletionGracePeriod, }, - Spec: api.PodSpec{ - Containers: []api.Container{*container}, + Spec: v1.PodSpec{ + Containers: []v1.Container{*container}, TerminationGracePeriodSeconds: &terminationGracePeriod, }, } @@ -81,52 +81,52 @@ func TestContainerAnnotations(t *testing.T) { restartCount := 5 deletionGracePeriod := int64(10) terminationGracePeriod := int64(10) - lifecycle := &api.Lifecycle{ + lifecycle := &v1.Lifecycle{ // Left PostStart as nil - PreStop: &api.Handler{ - Exec: &api.ExecAction{ + PreStop: &v1.Handler{ + Exec: &v1.ExecAction{ Command: []string{"action1", "action2"}, }, - HTTPGet: &api.HTTPGetAction{ + HTTPGet: &v1.HTTPGetAction{ Path: "path", Host: "host", Port: intstr.FromInt(8080), Scheme: "scheme", }, - TCPSocket: &api.TCPSocketAction{ + TCPSocket: &v1.TCPSocketAction{ Port: intstr.FromString("80"), }, }, } - containerPorts := []api.ContainerPort{ + containerPorts := []v1.ContainerPort{ { Name: "http", HostPort: 80, ContainerPort: 8080, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, { Name: "https", HostPort: 443, ContainerPort: 6443, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, } - container := &api.Container{ + container := &v1.Container{ Name: "test_container", Ports: containerPorts, TerminationMessagePath: "/somepath", Lifecycle: lifecycle, } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "test_pod", Namespace: "test_pod_namespace", UID: "test_pod_uid", DeletionGracePeriodSeconds: &deletionGracePeriod, }, - Spec: api.PodSpec{ - Containers: []api.Container{*container}, + Spec: v1.PodSpec{ + Containers: []v1.Container{*container}, TerminationGracePeriodSeconds: &terminationGracePeriod, }, } @@ -165,15 +165,15 @@ func TestContainerAnnotations(t *testing.T) { } func TestPodLabels(t *testing.T) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "test_pod", Namespace: "test_pod_namespace", UID: "test_pod_uid", Labels: map[string]string{"foo": "bar"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{}, + Spec: v1.PodSpec{ + Containers: []v1.Container{}, }, } expected := &labeledPodSandboxInfo{ @@ -192,15 +192,15 @@ func TestPodLabels(t *testing.T) { } func TestPodAnnotations(t *testing.T) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "test_pod", Namespace: "test_pod_namespace", UID: "test_pod_uid", Annotations: map[string]string{"foo": "bar"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{}, + Spec: v1.PodSpec{ + Containers: []v1.Container{}, }, } expected := &annotatedPodSandboxInfo{ diff --git a/pkg/kubelet/kuberuntime/security_context.go b/pkg/kubelet/kuberuntime/security_context.go index fc5940dee5c..a6cba72fe40 100644 --- a/pkg/kubelet/kuberuntime/security_context.go +++ b/pkg/kubelet/kuberuntime/security_context.go @@ -19,13 +19,13 @@ package kuberuntime import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" runtimeapi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" "k8s.io/kubernetes/pkg/securitycontext" ) -// determineEffectiveSecurityContext gets container's security context from api.Pod and api.Container. -func (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *api.Pod, container *api.Container, uid *int64, username *string) *runtimeapi.LinuxContainerSecurityContext { +// determineEffectiveSecurityContext gets container's security context from v1.Pod and v1.Container. +func (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *v1.Pod, container *v1.Container, uid *int64, username *string) *runtimeapi.LinuxContainerSecurityContext { effectiveSc := securitycontext.DetermineEffectiveSecurityContext(pod, container) synthesized := convertToRuntimeSecurityContext(effectiveSc) if synthesized == nil { @@ -44,9 +44,9 @@ func (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *api.P return synthesized } synthesized.NamespaceOptions = &runtimeapi.NamespaceOption{ - HostNetwork: &podSc.HostNetwork, - HostIpc: &podSc.HostIPC, - HostPid: &podSc.HostPID, + HostNetwork: &pod.Spec.HostNetwork, + HostIpc: &pod.Spec.HostIPC, + HostPid: &pod.Spec.HostPID, } if podSc.FSGroup != nil { synthesized.SupplementalGroups = append(synthesized.SupplementalGroups, *podSc.FSGroup) @@ -62,7 +62,7 @@ func (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *api.P } // verifyRunAsNonRoot verifies RunAsNonRoot. -func verifyRunAsNonRoot(pod *api.Pod, container *api.Container, uid int64) error { +func verifyRunAsNonRoot(pod *v1.Pod, container *v1.Container, uid int64) error { effectiveSc := securitycontext.DetermineEffectiveSecurityContext(pod, container) if effectiveSc == nil || effectiveSc.RunAsNonRoot == nil { return nil @@ -82,8 +82,8 @@ func verifyRunAsNonRoot(pod *api.Pod, container *api.Container, uid int64) error return nil } -// convertToRuntimeSecurityContext converts api.SecurityContext to runtimeapi.SecurityContext. -func convertToRuntimeSecurityContext(securityContext *api.SecurityContext) *runtimeapi.LinuxContainerSecurityContext { +// convertToRuntimeSecurityContext converts v1.SecurityContext to runtimeapi.SecurityContext. +func convertToRuntimeSecurityContext(securityContext *v1.SecurityContext) *runtimeapi.LinuxContainerSecurityContext { if securityContext == nil { return nil } @@ -97,8 +97,8 @@ func convertToRuntimeSecurityContext(securityContext *api.SecurityContext) *runt } } -// convertToRuntimeSELinuxOption converts api.SELinuxOptions to runtimeapi.SELinuxOption. -func convertToRuntimeSELinuxOption(opts *api.SELinuxOptions) *runtimeapi.SELinuxOption { +// convertToRuntimeSELinuxOption converts v1.SELinuxOptions to runtimeapi.SELinuxOption. +func convertToRuntimeSELinuxOption(opts *v1.SELinuxOptions) *runtimeapi.SELinuxOption { if opts == nil { return nil } @@ -111,8 +111,8 @@ func convertToRuntimeSELinuxOption(opts *api.SELinuxOptions) *runtimeapi.SELinux } } -// convertToRuntimeCapabilities converts api.Capabilities to runtimeapi.Capability. -func convertToRuntimeCapabilities(opts *api.Capabilities) *runtimeapi.Capability { +// convertToRuntimeCapabilities converts v1.Capabilities to runtimeapi.Capability. +func convertToRuntimeCapabilities(opts *v1.Capabilities) *runtimeapi.Capability { if opts == nil { return nil } diff --git a/pkg/kubelet/lifecycle/BUILD b/pkg/kubelet/lifecycle/BUILD index 7e9be26475a..ebb9356ddc0 100644 --- a/pkg/kubelet/lifecycle/BUILD +++ b/pkg/kubelet/lifecycle/BUILD @@ -21,7 +21,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/types:go_default_library", "//pkg/kubelet/util/format:go_default_library", @@ -40,7 +40,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/util/intstr:go_default_library", ], diff --git a/pkg/kubelet/lifecycle/fake_handler_runner.go b/pkg/kubelet/lifecycle/fake_handler_runner.go index 3979204e425..1ebc5479ab0 100644 --- a/pkg/kubelet/lifecycle/fake_handler_runner.go +++ b/pkg/kubelet/lifecycle/fake_handler_runner.go @@ -20,7 +20,7 @@ import ( "fmt" "sync" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/util/format" ) @@ -35,7 +35,7 @@ func NewFakeHandlerRunner() *FakeHandlerRunner { return &FakeHandlerRunner{HandlerRuns: []string{}} } -func (hr *FakeHandlerRunner) Run(containerID kubecontainer.ContainerID, pod *api.Pod, container *api.Container, handler *api.Handler) (string, error) { +func (hr *FakeHandlerRunner) Run(containerID kubecontainer.ContainerID, pod *v1.Pod, container *v1.Container, handler *v1.Handler) (string, error) { hr.Lock() defer hr.Unlock() diff --git a/pkg/kubelet/lifecycle/handlers.go b/pkg/kubelet/lifecycle/handlers.go index 1d6bc1c1f79..f2ba6e71277 100644 --- a/pkg/kubelet/lifecycle/handlers.go +++ b/pkg/kubelet/lifecycle/handlers.go @@ -24,7 +24,7 @@ import ( "strconv" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/kubelet/util/format" @@ -51,7 +51,7 @@ func NewHandlerRunner(httpGetter kubetypes.HttpGetter, commandRunner kubecontain } } -func (hr *HandlerRunner) Run(containerID kubecontainer.ContainerID, pod *api.Pod, container *api.Container, handler *api.Handler) (string, error) { +func (hr *HandlerRunner) Run(containerID kubecontainer.ContainerID, pod *v1.Pod, container *v1.Container, handler *v1.Handler) (string, error) { switch { case handler.Exec != nil: var msg string @@ -83,7 +83,7 @@ func (hr *HandlerRunner) Run(containerID kubecontainer.ContainerID, pod *api.Pod // an attempt is made to find a port with the same name in the container spec. // If a port with the same name is found, it's ContainerPort value is returned. If no matching // port is found, an error is returned. -func resolvePort(portReference intstr.IntOrString, container *api.Container) (int, error) { +func resolvePort(portReference intstr.IntOrString, container *v1.Container) (int, error) { if portReference.Type == intstr.Int { return portReference.IntValue(), nil } @@ -100,7 +100,7 @@ func resolvePort(portReference intstr.IntOrString, container *api.Container) (in return -1, fmt.Errorf("couldn't find port: %v in %v", portReference, container) } -func (hr *HandlerRunner) runHTTPHandler(pod *api.Pod, container *api.Container, handler *api.Handler) (string, error) { +func (hr *HandlerRunner) runHTTPHandler(pod *v1.Pod, container *v1.Container, handler *v1.Handler) (string, error) { host := handler.HTTPGet.Host if len(host) == 0 { status, err := hr.containerManager.GetPodStatus(pod.UID, pod.Name, pod.Namespace) @@ -151,7 +151,7 @@ type appArmorAdmitHandler struct { func (a *appArmorAdmitHandler) Admit(attrs *PodAdmitAttributes) PodAdmitResult { // If the pod is already running or terminated, no need to recheck AppArmor. - if attrs.Pod.Status.Phase != api.PodPending { + if attrs.Pod.Status.Phase != v1.PodPending { return PodAdmitResult{Admit: true} } diff --git a/pkg/kubelet/lifecycle/handlers_test.go b/pkg/kubelet/lifecycle/handlers_test.go index 23c101e9224..bb238dc2bea 100644 --- a/pkg/kubelet/lifecycle/handlers_test.go +++ b/pkg/kubelet/lifecycle/handlers_test.go @@ -25,14 +25,14 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/util/intstr" ) func TestResolvePortInt(t *testing.T) { expected := 80 - port, err := resolvePort(intstr.FromInt(expected), &api.Container{}) + port, err := resolvePort(intstr.FromInt(expected), &v1.Container{}) if port != expected { t.Errorf("expected: %d, saw: %d", expected, port) } @@ -44,8 +44,8 @@ func TestResolvePortInt(t *testing.T) { func TestResolvePortString(t *testing.T) { expected := 80 name := "foo" - container := &api.Container{ - Ports: []api.ContainerPort{ + container := &v1.Container{ + Ports: []v1.ContainerPort{ {Name: name, ContainerPort: int32(expected)}, }, } @@ -61,8 +61,8 @@ func TestResolvePortString(t *testing.T) { func TestResolvePortStringUnknown(t *testing.T) { expected := int32(80) name := "foo" - container := &api.Container{ - Ports: []api.ContainerPort{ + container := &v1.Container{ + Ports: []v1.ContainerPort{ {Name: "bar", ContainerPort: expected}, }, } @@ -93,21 +93,21 @@ func TestRunHandlerExec(t *testing.T) { containerID := kubecontainer.ContainerID{Type: "test", ID: "abc1234"} containerName := "containerFoo" - container := api.Container{ + container := v1.Container{ Name: containerName, - Lifecycle: &api.Lifecycle{ - PostStart: &api.Handler{ - Exec: &api.ExecAction{ + Lifecycle: &v1.Lifecycle{ + PostStart: &v1.Handler{ + Exec: &v1.ExecAction{ Command: []string{"ls", "-a"}, }, }, }, } - pod := api.Pod{} + pod := v1.Pod{} pod.ObjectMeta.Name = "podFoo" pod.ObjectMeta.Namespace = "nsFoo" - pod.Spec.Containers = []api.Container{container} + pod.Spec.Containers = []v1.Container{container} _, err := handlerRunner.Run(containerID, &pod, &container, container.Lifecycle.PostStart) if err != nil { t.Errorf("unexpected error: %v", err) @@ -136,11 +136,11 @@ func TestRunHandlerHttp(t *testing.T) { containerID := kubecontainer.ContainerID{Type: "test", ID: "abc1234"} containerName := "containerFoo" - container := api.Container{ + container := v1.Container{ Name: containerName, - Lifecycle: &api.Lifecycle{ - PostStart: &api.Handler{ - HTTPGet: &api.HTTPGetAction{ + Lifecycle: &v1.Lifecycle{ + PostStart: &v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Host: "foo", Port: intstr.FromInt(8080), Path: "bar", @@ -148,10 +148,10 @@ func TestRunHandlerHttp(t *testing.T) { }, }, } - pod := api.Pod{} + pod := v1.Pod{} pod.ObjectMeta.Name = "podFoo" pod.ObjectMeta.Namespace = "nsFoo" - pod.Spec.Containers = []api.Container{container} + pod.Spec.Containers = []v1.Container{container} _, err := handlerRunner.Run(containerID, &pod, &container, container.Lifecycle.PostStart) if err != nil { @@ -169,16 +169,16 @@ func TestRunHandlerNil(t *testing.T) { podNamespace := "nsFoo" containerName := "containerFoo" - container := api.Container{ + container := v1.Container{ Name: containerName, - Lifecycle: &api.Lifecycle{ - PostStart: &api.Handler{}, + Lifecycle: &v1.Lifecycle{ + PostStart: &v1.Handler{}, }, } - pod := api.Pod{} + pod := v1.Pod{} pod.ObjectMeta.Name = podName pod.ObjectMeta.Namespace = podNamespace - pod.Spec.Containers = []api.Container{container} + pod.Spec.Containers = []v1.Container{container} _, err := handlerRunner.Run(containerID, &pod, &container, container.Lifecycle.PostStart) if err == nil { t.Errorf("expect error, but got nil") @@ -194,11 +194,11 @@ func TestRunHandlerHttpFailure(t *testing.T) { handlerRunner := NewHandlerRunner(&fakeHttp, &fakeContainerCommandRunner{}, nil) containerName := "containerFoo" containerID := kubecontainer.ContainerID{Type: "test", ID: "abc1234"} - container := api.Container{ + container := v1.Container{ Name: containerName, - Lifecycle: &api.Lifecycle{ - PostStart: &api.Handler{ - HTTPGet: &api.HTTPGetAction{ + Lifecycle: &v1.Lifecycle{ + PostStart: &v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Host: "foo", Port: intstr.FromInt(8080), Path: "bar", @@ -206,10 +206,10 @@ func TestRunHandlerHttpFailure(t *testing.T) { }, }, } - pod := api.Pod{} + pod := v1.Pod{} pod.ObjectMeta.Name = "podFoo" pod.ObjectMeta.Namespace = "nsFoo" - pod.Spec.Containers = []api.Container{container} + pod.Spec.Containers = []v1.Container{container} msg, err := handlerRunner.Run(containerID, &pod, &container, container.Lifecycle.PostStart) if err == nil { t.Errorf("expected error: %v", expectedErr) diff --git a/pkg/kubelet/lifecycle/interfaces.go b/pkg/kubelet/lifecycle/interfaces.go index 38ee01825fe..bde0e51e995 100644 --- a/pkg/kubelet/lifecycle/interfaces.go +++ b/pkg/kubelet/lifecycle/interfaces.go @@ -16,15 +16,15 @@ limitations under the License. package lifecycle -import "k8s.io/kubernetes/pkg/api" +import "k8s.io/kubernetes/pkg/api/v1" // PodAdmitAttributes is the context for a pod admission decision. // The member fields of this struct should never be mutated. type PodAdmitAttributes struct { // the pod to evaluate for admission - Pod *api.Pod + Pod *v1.Pod // all pods bound to the kubelet excluding the pod being evaluated - OtherPods []*api.Pod + OtherPods []*v1.Pod } // PodAdmitResult provides the result of a pod admission decision. @@ -54,7 +54,7 @@ type PodSyncLoopHandler interface { // ShouldSync returns true if the pod needs to be synced. // This operation must return immediately as its called for each pod. // The provided pod should never be modified. - ShouldSync(pod *api.Pod) bool + ShouldSync(pod *v1.Pod) bool } // PodSyncLoopTarget maintains a list of handlers to pod sync loop. @@ -81,7 +81,7 @@ type PodSyncHandler interface { // and the pod is immediately killed. // This operation must return immediately as its called for each sync pod. // The provided pod should never be modified. - ShouldEvict(pod *api.Pod) ShouldEvictResponse + ShouldEvict(pod *v1.Pod) ShouldEvictResponse } // PodSyncTarget maintains a list of handlers to pod sync. diff --git a/pkg/kubelet/lifecycle/predicate.go b/pkg/kubelet/lifecycle/predicate.go index e38e0b6e1ff..6c8f24b7eff 100644 --- a/pkg/kubelet/lifecycle/predicate.go +++ b/pkg/kubelet/lifecycle/predicate.go @@ -20,13 +20,13 @@ import ( "fmt" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/util/format" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) -type getNodeAnyWayFuncType func() (*api.Node, error) +type getNodeAnyWayFuncType func() (*v1.Node, error) type predicateAdmitHandler struct { getNodeAnyWayFunc getNodeAnyWayFuncType } diff --git a/pkg/kubelet/network/BUILD b/pkg/kubelet/network/BUILD index d104dcdfb03..9ea3ad4ec7d 100644 --- a/pkg/kubelet/network/BUILD +++ b/pkg/kubelet/network/BUILD @@ -18,10 +18,10 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/componentconfig:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/util/errors:go_default_library", "//pkg/util/exec:go_default_library", diff --git a/pkg/kubelet/network/cni/BUILD b/pkg/kubelet/network/cni/BUILD index 6355771c287..e967c7a0072 100644 --- a/pkg/kubelet/network/cni/BUILD +++ b/pkg/kubelet/network/cni/BUILD @@ -32,9 +32,9 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/componentconfig:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/container/testing:go_default_library", "//pkg/kubelet/network:go_default_library", diff --git a/pkg/kubelet/network/cni/cni_test.go b/pkg/kubelet/network/cni/cni_test.go index 8aeed7a93fd..6e932f32054 100644 --- a/pkg/kubelet/network/cni/cni_test.go +++ b/pkg/kubelet/network/cni/cni_test.go @@ -29,11 +29,11 @@ import ( "testing" "text/template" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" cnitypes "github.com/containernetworking/cni/pkg/types" "github.com/stretchr/testify/mock" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" @@ -126,7 +126,7 @@ func NewFakeHost(kubeClient clientset.Interface, pods []*containertest.FakePod) return host } -func (fnh *fakeNetworkHost) GetPodByName(name, namespace string) (*api.Pod, bool) { +func (fnh *fakeNetworkHost) GetPodByName(name, namespace string) (*v1.Pod, bool) { return nil, false } diff --git a/pkg/kubelet/network/hostport/BUILD b/pkg/kubelet/network/hostport/BUILD index 483d8174ff6..7dc861254a8 100644 --- a/pkg/kubelet/network/hostport/BUILD +++ b/pkg/kubelet/network/hostport/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/proxy/iptables:go_default_library", "//pkg/util/dbus:go_default_library", @@ -34,7 +34,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/util/iptables:go_default_library", ], diff --git a/pkg/kubelet/network/hostport/hostport.go b/pkg/kubelet/network/hostport/hostport.go index 35d4ac2c8ea..273dab10b5c 100644 --- a/pkg/kubelet/network/hostport/hostport.go +++ b/pkg/kubelet/network/hostport/hostport.go @@ -26,7 +26,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" iptablesproxy "k8s.io/kubernetes/pkg/proxy/iptables" utildbus "k8s.io/kubernetes/pkg/util/dbus" @@ -47,7 +47,7 @@ type HostportHandler interface { } type ActivePod struct { - Pod *api.Pod + Pod *v1.Pod IP net.IP } @@ -87,7 +87,7 @@ func (hp *hostport) String() string { } //openPodHostports opens all hostport for pod and returns the map of hostport and socket -func (h *handler) openHostports(pod *api.Pod) error { +func (h *handler) openHostports(pod *v1.Pod) error { var retErr error ports := make(map[hostport]closeable) for _, container := range pod.Spec.Containers { @@ -131,15 +131,15 @@ func (h *handler) openHostports(pod *api.Pod) error { // gatherAllHostports returns all hostports that should be presented on node, // given the list of pods running on that node and ignoring host network // pods (which don't need hostport <-> container port mapping). -func gatherAllHostports(activePods []*ActivePod) (map[api.ContainerPort]targetPod, error) { - podHostportMap := make(map[api.ContainerPort]targetPod) +func gatherAllHostports(activePods []*ActivePod) (map[v1.ContainerPort]targetPod, error) { + podHostportMap := make(map[v1.ContainerPort]targetPod) for _, r := range activePods { if r.IP.To4() == nil { return nil, fmt.Errorf("Invalid or missing pod %s IP", kubecontainer.GetPodFullName(r.Pod)) } // should not handle hostports for hostnetwork pods - if r.Pod.Spec.SecurityContext != nil && r.Pod.Spec.SecurityContext.HostNetwork { + if r.Pod.Spec.HostNetwork { continue } @@ -164,7 +164,7 @@ func writeLine(buf *bytes.Buffer, words ...string) { // then encoding to base32 and truncating with the prefix "KUBE-SVC-". We do // this because IPTables Chain Names must be <= 28 chars long, and the longer // they are the harder they are to read. -func hostportChainName(cp api.ContainerPort, podFullName string) utiliptables.Chain { +func hostportChainName(cp v1.ContainerPort, podFullName string) utiliptables.Chain { hash := sha256.Sum256([]byte(string(cp.HostPort) + string(cp.Protocol) + podFullName)) encoded := base32.StdEncoding.EncodeToString(hash[:]) return utiliptables.Chain(kubeHostportChainPrefix + encoded[:16]) @@ -364,7 +364,7 @@ func openLocalPort(hp *hostport) (closeable, error) { } // cleanupHostportMap closes obsolete hostports -func (h *handler) cleanupHostportMap(containerPortMap map[api.ContainerPort]targetPod) { +func (h *handler) cleanupHostportMap(containerPortMap map[v1.ContainerPort]targetPod) { // compute hostports that are supposed to be open currentHostports := make(map[hostport]bool) for containerPort := range containerPortMap { diff --git a/pkg/kubelet/network/hostport/hostport_test.go b/pkg/kubelet/network/hostport/hostport_test.go index 0fc4cf85e17..25cbcc24736 100644 --- a/pkg/kubelet/network/hostport/hostport_test.go +++ b/pkg/kubelet/network/hostport/hostport_test.go @@ -22,7 +22,7 @@ import ( "strings" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" utiliptables "k8s.io/kubernetes/pkg/util/iptables" ) @@ -61,27 +61,27 @@ func TestOpenPodHostports(t *testing.T) { } tests := []struct { - pod *api.Pod + pod *v1.Pod ip string matches []*ruleMatch }{ // New pod that we are going to add { - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "test-pod", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, - Spec: api.PodSpec{ - Containers: []api.Container{{ - Ports: []api.ContainerPort{{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ + Ports: []v1.ContainerPort{{ HostPort: 4567, ContainerPort: 80, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, { HostPort: 5678, ContainerPort: 81, - Protocol: api.ProtocolUDP, + Protocol: v1.ProtocolUDP, }}, }}, }, @@ -122,17 +122,17 @@ func TestOpenPodHostports(t *testing.T) { }, // Already running pod { - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "another-test-pod", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, - Spec: api.PodSpec{ - Containers: []api.Container{{ - Ports: []api.ContainerPort{{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ + Ports: []v1.ContainerPort{{ HostPort: 123, ContainerPort: 654, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }}, }}, }, diff --git a/pkg/kubelet/network/kubenet/BUILD b/pkg/kubelet/network/kubenet/BUILD index bf37249dc00..3ab5ca38f82 100644 --- a/pkg/kubelet/network/kubenet/BUILD +++ b/pkg/kubelet/network/kubenet/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["kubenet_linux.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/componentconfig:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/network:go_default_library", diff --git a/pkg/kubelet/network/kubenet/kubenet_linux.go b/pkg/kubelet/network/kubenet/kubenet_linux.go index 7679dce6d76..be5495ee371 100644 --- a/pkg/kubelet/network/kubenet/kubenet_linux.go +++ b/pkg/kubelet/network/kubenet/kubenet_linux.go @@ -27,13 +27,14 @@ import ( "syscall" "time" + "io/ioutil" + "github.com/containernetworking/cni/libcni" cnitypes "github.com/containernetworking/cni/pkg/types" "github.com/golang/glog" "github.com/vishvananda/netlink" "github.com/vishvananda/netlink/nl" - "io/ioutil" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/network" @@ -337,7 +338,7 @@ func (plugin *kubenetNetworkPlugin) Capabilities() utilsets.Int { // setup sets up networking through CNI using the given ns/name and sandbox ID. // TODO: Don't pass the pod to this method, it only needs it for bandwidth // shaping and hostport management. -func (plugin *kubenetNetworkPlugin) setup(namespace string, name string, id kubecontainer.ContainerID, pod *api.Pod) error { +func (plugin *kubenetNetworkPlugin) setup(namespace string, name string, id kubecontainer.ContainerID, pod *v1.Pod) error { // Bring up container loopback interface if _, err := plugin.addContainerToNetwork(plugin.loConfig, "lo", namespace, name, id); err != nil { return err diff --git a/pkg/kubelet/network/plugins.go b/pkg/kubelet/network/plugins.go index 9e7a1b65c26..651c9eceab2 100644 --- a/pkg/kubelet/network/plugins.go +++ b/pkg/kubelet/network/plugins.go @@ -21,11 +21,11 @@ import ( "net" "strings" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" utilerrors "k8s.io/kubernetes/pkg/util/errors" @@ -102,7 +102,7 @@ type PodNetworkStatus struct { type LegacyHost interface { // Get the pod structure by its name, namespace // Only used for hostport management and bw shaping - GetPodByName(namespace, name string) (*api.Pod, bool) + GetPodByName(namespace, name string) (*v1.Pod, bool) // GetKubeClient returns a client interface // Only used in testing diff --git a/pkg/kubelet/network/testing/BUILD b/pkg/kubelet/network/testing/BUILD index ee7db905a6d..7a027f012e3 100644 --- a/pkg/kubelet/network/testing/BUILD +++ b/pkg/kubelet/network/testing/BUILD @@ -15,8 +15,8 @@ go_library( srcs = ["fake_host.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/container/testing:go_default_library", ], diff --git a/pkg/kubelet/network/testing/fake_host.go b/pkg/kubelet/network/testing/fake_host.go index a650be1c2e1..5b278249902 100644 --- a/pkg/kubelet/network/testing/fake_host.go +++ b/pkg/kubelet/network/testing/fake_host.go @@ -20,8 +20,8 @@ package testing // a fake host is created here that can be used by plugins for testing import ( - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" ) @@ -38,7 +38,7 @@ func NewFakeHost(kubeClient clientset.Interface) *fakeNetworkHost { return host } -func (fnh *fakeNetworkHost) GetPodByName(name, namespace string) (*api.Pod, bool) { +func (fnh *fakeNetworkHost) GetPodByName(name, namespace string) (*v1.Pod, bool) { return nil, false } diff --git a/pkg/kubelet/networks.go b/pkg/kubelet/networks.go index 74cfcb6427c..1b258e0ecea 100644 --- a/pkg/kubelet/networks.go +++ b/pkg/kubelet/networks.go @@ -17,8 +17,8 @@ limitations under the License. package kubelet import ( - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" ) @@ -33,7 +33,7 @@ type networkHost struct { kubelet *Kubelet } -func (nh *networkHost) GetPodByName(name, namespace string) (*api.Pod, bool) { +func (nh *networkHost) GetPodByName(name, namespace string) (*v1.Pod, bool) { return nh.kubelet.GetPodByName(name, namespace) } @@ -71,7 +71,7 @@ func (c *criNetworkHost) GetNetNS(containerID string) (string, error) { // like host port and bandwidth shaping. type noOpLegacyHost struct{} -func (n *noOpLegacyHost) GetPodByName(namespace, name string) (*api.Pod, bool) { +func (n *noOpLegacyHost) GetPodByName(namespace, name string) (*v1.Pod, bool) { return nil, true } diff --git a/pkg/kubelet/oom_watcher.go b/pkg/kubelet/oom_watcher.go index ca4c53d9432..be18463eda2 100644 --- a/pkg/kubelet/oom_watcher.go +++ b/pkg/kubelet/oom_watcher.go @@ -20,15 +20,15 @@ import ( "github.com/golang/glog" "github.com/google/cadvisor/events" cadvisorapi "github.com/google/cadvisor/info/v1" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/kubelet/cadvisor" "k8s.io/kubernetes/pkg/util/runtime" ) type OOMWatcher interface { - Start(ref *api.ObjectReference) error + Start(ref *v1.ObjectReference) error } type realOOMWatcher struct { @@ -46,7 +46,7 @@ func NewOOMWatcher(cadvisor cadvisor.Interface, recorder record.EventRecorder) O const systemOOMEvent = "SystemOOM" // Watches cadvisor for system oom's and records an event for every system oom encountered. -func (ow *realOOMWatcher) Start(ref *api.ObjectReference) error { +func (ow *realOOMWatcher) Start(ref *v1.ObjectReference) error { request := events.Request{ EventType: map[cadvisorapi.EventType]bool{ cadvisorapi.EventOom: true, @@ -64,7 +64,7 @@ func (ow *realOOMWatcher) Start(ref *api.ObjectReference) error { for event := range eventChannel.GetChannel() { glog.V(2).Infof("Got sys oom event from cadvisor: %v", event) - ow.recorder.PastEventf(ref, unversioned.Time{Time: event.Timestamp}, api.EventTypeWarning, systemOOMEvent, "System OOM encountered") + ow.recorder.PastEventf(ref, unversioned.Time{Time: event.Timestamp}, v1.EventTypeWarning, systemOOMEvent, "System OOM encountered") } glog.Errorf("Unexpectedly stopped receiving OOM notifications from cAdvisor") }() diff --git a/pkg/kubelet/oom_watcher_test.go b/pkg/kubelet/oom_watcher_test.go index e8915e627ac..6d43bb05d45 100644 --- a/pkg/kubelet/oom_watcher_test.go +++ b/pkg/kubelet/oom_watcher_test.go @@ -19,7 +19,7 @@ package kubelet import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" cadvisortest "k8s.io/kubernetes/pkg/kubelet/cadvisor/testing" ) @@ -27,7 +27,7 @@ import ( func TestBasic(t *testing.T) { fakeRecorder := &record.FakeRecorder{} mockCadvisor := &cadvisortest.Fake{} - node := &api.ObjectReference{} + node := &v1.ObjectReference{} oomWatcher := NewOOMWatcher(mockCadvisor, fakeRecorder) err := oomWatcher.Start(node) if err != nil { diff --git a/pkg/kubelet/pod/BUILD b/pkg/kubelet/pod/BUILD index 2cd4c7efa7e..04532b86114 100644 --- a/pkg/kubelet/pod/BUILD +++ b/pkg/kubelet/pod/BUILD @@ -18,9 +18,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/types:go_default_library", "//pkg/types:go_default_library", @@ -37,7 +37,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/pod/testing:go_default_library", "//pkg/kubelet/types:go_default_library", diff --git a/pkg/kubelet/pod/mirror_client.go b/pkg/kubelet/pod/mirror_client.go index a57d6414d22..071e7ff07b9 100644 --- a/pkg/kubelet/pod/mirror_client.go +++ b/pkg/kubelet/pod/mirror_client.go @@ -18,9 +18,9 @@ package pod import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" ) @@ -31,7 +31,7 @@ type MirrorClient interface { // pod or returns an error. The mirror pod will have the same annotations // as the given pod as well as an extra annotation containing the hash of // the static pod. - CreateMirrorPod(pod *api.Pod) error + CreateMirrorPod(pod *v1.Pod) error // DeleteMirrorPod deletes the mirror pod with the given full name from // the API server or returns an error. DeleteMirrorPod(podFullName string) error @@ -49,7 +49,7 @@ func NewBasicMirrorClient(apiserverClient clientset.Interface) MirrorClient { return &basicMirrorClient{apiserverClient: apiserverClient} } -func (mc *basicMirrorClient) CreateMirrorPod(pod *api.Pod) error { +func (mc *basicMirrorClient) CreateMirrorPod(pod *v1.Pod) error { if mc.apiserverClient == nil { return nil } @@ -83,28 +83,28 @@ func (mc *basicMirrorClient) DeleteMirrorPod(podFullName string) error { } glog.V(2).Infof("Deleting a mirror pod %q", podFullName) // TODO(random-liu): Delete the mirror pod with uid precondition in mirror pod manager - if err := mc.apiserverClient.Core().Pods(namespace).Delete(name, api.NewDeleteOptions(0)); err != nil && !errors.IsNotFound(err) { + if err := mc.apiserverClient.Core().Pods(namespace).Delete(name, v1.NewDeleteOptions(0)); err != nil && !errors.IsNotFound(err) { glog.Errorf("Failed deleting a mirror pod %q: %v", podFullName, err) } return nil } -func IsStaticPod(pod *api.Pod) bool { +func IsStaticPod(pod *v1.Pod) bool { source, err := kubetypes.GetPodSource(pod) return err == nil && source != kubetypes.ApiserverSource } -func IsMirrorPod(pod *api.Pod) bool { +func IsMirrorPod(pod *v1.Pod) bool { _, ok := pod.Annotations[kubetypes.ConfigMirrorAnnotationKey] return ok } -func getHashFromMirrorPod(pod *api.Pod) (string, bool) { +func getHashFromMirrorPod(pod *v1.Pod) (string, bool) { hash, ok := pod.Annotations[kubetypes.ConfigMirrorAnnotationKey] return hash, ok } -func getPodHash(pod *api.Pod) string { +func getPodHash(pod *v1.Pod) string { // The annotation exists for all static pods. return pod.Annotations[kubetypes.ConfigHashAnnotationKey] } diff --git a/pkg/kubelet/pod/pod_manager.go b/pkg/kubelet/pod/pod_manager.go index 712a37d867b..800887e23e2 100644 --- a/pkg/kubelet/pod/pod_manager.go +++ b/pkg/kubelet/pod/pod_manager.go @@ -19,7 +19,7 @@ package pod import ( "sync" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/types" ) @@ -41,35 +41,35 @@ import ( // will also be removed. type Manager interface { // GetPods returns the regular pods bound to the kubelet and their spec. - GetPods() []*api.Pod + GetPods() []*v1.Pod // GetPodByName returns the (non-mirror) pod that matches full name, as well as // whether the pod was found. - GetPodByFullName(podFullName string) (*api.Pod, bool) + GetPodByFullName(podFullName string) (*v1.Pod, bool) // GetPodByName provides the (non-mirror) pod that matches namespace and // name, as well as whether the pod was found. - GetPodByName(namespace, name string) (*api.Pod, bool) + GetPodByName(namespace, name string) (*v1.Pod, bool) // GetPodByUID provides the (non-mirror) pod that matches pod UID, as well as // whether the pod is found. - GetPodByUID(types.UID) (*api.Pod, bool) + GetPodByUID(types.UID) (*v1.Pod, bool) // GetPodByMirrorPod returns the static pod for the given mirror pod and // whether it was known to the pod manger. - GetPodByMirrorPod(*api.Pod) (*api.Pod, bool) + GetPodByMirrorPod(*v1.Pod) (*v1.Pod, bool) // GetMirrorPodByPod returns the mirror pod for the given static pod and // whether it was known to the pod manager. - GetMirrorPodByPod(*api.Pod) (*api.Pod, bool) + GetMirrorPodByPod(*v1.Pod) (*v1.Pod, bool) // GetPodsAndMirrorPods returns the both regular and mirror pods. - GetPodsAndMirrorPods() ([]*api.Pod, []*api.Pod) + GetPodsAndMirrorPods() ([]*v1.Pod, []*v1.Pod) // SetPods replaces the internal pods with the new pods. // It is currently only used for testing. - SetPods(pods []*api.Pod) + SetPods(pods []*v1.Pod) // AddPod adds the given pod to the manager. - AddPod(pod *api.Pod) + AddPod(pod *v1.Pod) // UpdatePod updates the given pod in the manager. - UpdatePod(pod *api.Pod) + UpdatePod(pod *v1.Pod) // DeletePod deletes the given pod from the manager. For mirror pods, // this means deleting the mappings related to mirror pods. For non- // mirror pods, this means deleting from indexes for all non-mirror pods. - DeletePod(pod *api.Pod) + DeletePod(pod *v1.Pod) // DeleteOrphanedMirrorPods deletes all mirror pods which do not have // associated static pods. This method sends deletion requests to the API // server, but does NOT modify the internal pod storage in basicManager. @@ -87,7 +87,7 @@ type Manager interface { GetUIDTranslations() (podToMirror, mirrorToPod map[types.UID]types.UID) // IsMirrorPodOf returns true if mirrorPod is a correct representation of // pod; false otherwise. - IsMirrorPodOf(mirrorPod, pod *api.Pod) bool + IsMirrorPodOf(mirrorPod, pod *v1.Pod) bool MirrorClient } @@ -101,13 +101,13 @@ type basicManager struct { lock sync.RWMutex // Regular pods indexed by UID. - podByUID map[types.UID]*api.Pod + podByUID map[types.UID]*v1.Pod // Mirror pods indexed by UID. - mirrorPodByUID map[types.UID]*api.Pod + mirrorPodByUID map[types.UID]*v1.Pod // Pods indexed by full name for easy access. - podByFullName map[string]*api.Pod - mirrorPodByFullName map[string]*api.Pod + podByFullName map[string]*v1.Pod + mirrorPodByFullName map[string]*v1.Pod // Mirror pod UID to pod UID map. translationByUID map[types.UID]types.UID @@ -125,24 +125,24 @@ func NewBasicPodManager(client MirrorClient) Manager { } // Set the internal pods based on the new pods. -func (pm *basicManager) SetPods(newPods []*api.Pod) { +func (pm *basicManager) SetPods(newPods []*v1.Pod) { pm.lock.Lock() defer pm.lock.Unlock() - pm.podByUID = make(map[types.UID]*api.Pod) - pm.podByFullName = make(map[string]*api.Pod) - pm.mirrorPodByUID = make(map[types.UID]*api.Pod) - pm.mirrorPodByFullName = make(map[string]*api.Pod) + pm.podByUID = make(map[types.UID]*v1.Pod) + pm.podByFullName = make(map[string]*v1.Pod) + pm.mirrorPodByUID = make(map[types.UID]*v1.Pod) + pm.mirrorPodByFullName = make(map[string]*v1.Pod) pm.translationByUID = make(map[types.UID]types.UID) pm.updatePodsInternal(newPods...) } -func (pm *basicManager) AddPod(pod *api.Pod) { +func (pm *basicManager) AddPod(pod *v1.Pod) { pm.UpdatePod(pod) } -func (pm *basicManager) UpdatePod(pod *api.Pod) { +func (pm *basicManager) UpdatePod(pod *v1.Pod) { pm.lock.Lock() defer pm.lock.Unlock() pm.updatePodsInternal(pod) @@ -151,7 +151,7 @@ func (pm *basicManager) UpdatePod(pod *api.Pod) { // updatePodsInternal replaces the given pods in the current state of the // manager, updating the various indices. The caller is assumed to hold the // lock. -func (pm *basicManager) updatePodsInternal(pods ...*api.Pod) { +func (pm *basicManager) updatePodsInternal(pods ...*v1.Pod) { for _, pod := range pods { podFullName := kubecontainer.GetPodFullName(pod) if IsMirrorPod(pod) { @@ -170,7 +170,7 @@ func (pm *basicManager) updatePodsInternal(pods ...*api.Pod) { } } -func (pm *basicManager) DeletePod(pod *api.Pod) { +func (pm *basicManager) DeletePod(pod *v1.Pod) { pm.lock.Lock() defer pm.lock.Unlock() podFullName := kubecontainer.GetPodFullName(pod) @@ -184,13 +184,13 @@ func (pm *basicManager) DeletePod(pod *api.Pod) { } } -func (pm *basicManager) GetPods() []*api.Pod { +func (pm *basicManager) GetPods() []*v1.Pod { pm.lock.RLock() defer pm.lock.RUnlock() return podsMapToPods(pm.podByUID) } -func (pm *basicManager) GetPodsAndMirrorPods() ([]*api.Pod, []*api.Pod) { +func (pm *basicManager) GetPodsAndMirrorPods() ([]*v1.Pod, []*v1.Pod) { pm.lock.RLock() defer pm.lock.RUnlock() pods := podsMapToPods(pm.podByUID) @@ -198,19 +198,19 @@ func (pm *basicManager) GetPodsAndMirrorPods() ([]*api.Pod, []*api.Pod) { return pods, mirrorPods } -func (pm *basicManager) GetPodByUID(uid types.UID) (*api.Pod, bool) { +func (pm *basicManager) GetPodByUID(uid types.UID) (*v1.Pod, bool) { pm.lock.RLock() defer pm.lock.RUnlock() pod, ok := pm.podByUID[uid] return pod, ok } -func (pm *basicManager) GetPodByName(namespace, name string) (*api.Pod, bool) { +func (pm *basicManager) GetPodByName(namespace, name string) (*v1.Pod, bool) { podFullName := kubecontainer.BuildPodFullName(name, namespace) return pm.GetPodByFullName(podFullName) } -func (pm *basicManager) GetPodByFullName(podFullName string) (*api.Pod, bool) { +func (pm *basicManager) GetPodByFullName(podFullName string) (*v1.Pod, bool) { pm.lock.RLock() defer pm.lock.RUnlock() pod, ok := pm.podByFullName[podFullName] @@ -273,7 +273,7 @@ func (pm *basicManager) DeleteOrphanedMirrorPods() { } } -func (pm *basicManager) IsMirrorPodOf(mirrorPod, pod *api.Pod) bool { +func (pm *basicManager) IsMirrorPodOf(mirrorPod, pod *v1.Pod) bool { // Check name and namespace first. if pod.Name != mirrorPod.Name || pod.Namespace != mirrorPod.Namespace { return false @@ -285,22 +285,22 @@ func (pm *basicManager) IsMirrorPodOf(mirrorPod, pod *api.Pod) bool { return hash == getPodHash(pod) } -func podsMapToPods(UIDMap map[types.UID]*api.Pod) []*api.Pod { - pods := make([]*api.Pod, 0, len(UIDMap)) +func podsMapToPods(UIDMap map[types.UID]*v1.Pod) []*v1.Pod { + pods := make([]*v1.Pod, 0, len(UIDMap)) for _, pod := range UIDMap { pods = append(pods, pod) } return pods } -func (pm *basicManager) GetMirrorPodByPod(pod *api.Pod) (*api.Pod, bool) { +func (pm *basicManager) GetMirrorPodByPod(pod *v1.Pod) (*v1.Pod, bool) { pm.lock.RLock() defer pm.lock.RUnlock() mirrorPod, ok := pm.mirrorPodByFullName[kubecontainer.GetPodFullName(pod)] return mirrorPod, ok } -func (pm *basicManager) GetPodByMirrorPod(mirrorPod *api.Pod) (*api.Pod, bool) { +func (pm *basicManager) GetPodByMirrorPod(mirrorPod *v1.Pod) (*v1.Pod, bool) { pm.lock.RLock() defer pm.lock.RUnlock() pod, ok := pm.podByFullName[kubecontainer.GetPodFullName(mirrorPod)] diff --git a/pkg/kubelet/pod/pod_manager_test.go b/pkg/kubelet/pod/pod_manager_test.go index 1d3e61b303c..594a4de11e5 100644 --- a/pkg/kubelet/pod/pod_manager_test.go +++ b/pkg/kubelet/pod/pod_manager_test.go @@ -20,7 +20,7 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" podtest "k8s.io/kubernetes/pkg/kubelet/pod/testing" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" ) @@ -35,8 +35,8 @@ func newTestManager() (*basicManager, *podtest.FakeMirrorClient) { // Tests that pods/maps are properly set after the pod update, and the basic // methods work correctly. func TestGetSetPods(t *testing.T) { - mirrorPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + mirrorPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "987654321", Name: "bar", Namespace: "default", @@ -46,8 +46,8 @@ func TestGetSetPods(t *testing.T) { }, }, } - staticPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + staticPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "123456789", Name: "bar", Namespace: "default", @@ -55,9 +55,9 @@ func TestGetSetPods(t *testing.T) { }, } - expectedPods := []*api.Pod{ + expectedPods := []*v1.Pod{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "999999999", Name: "taco", Namespace: "default", diff --git a/pkg/kubelet/pod/testing/BUILD b/pkg/kubelet/pod/testing/BUILD index d5731dfa294..9cb216965d8 100644 --- a/pkg/kubelet/pod/testing/BUILD +++ b/pkg/kubelet/pod/testing/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["fake_mirror_client.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/util/sets:go_default_library", ], diff --git a/pkg/kubelet/pod/testing/fake_mirror_client.go b/pkg/kubelet/pod/testing/fake_mirror_client.go index 72563485a39..0e9ff513db2 100644 --- a/pkg/kubelet/pod/testing/fake_mirror_client.go +++ b/pkg/kubelet/pod/testing/fake_mirror_client.go @@ -19,7 +19,7 @@ package testing import ( "sync" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/util/sets" ) @@ -41,7 +41,7 @@ func NewFakeMirrorClient() *FakeMirrorClient { return &m } -func (fmc *FakeMirrorClient) CreateMirrorPod(pod *api.Pod) error { +func (fmc *FakeMirrorClient) CreateMirrorPod(pod *v1.Pod) error { fmc.mirrorPodLock.Lock() defer fmc.mirrorPodLock.Unlock() podFullName := kubecontainer.GetPodFullName(pod) diff --git a/pkg/kubelet/pod_workers.go b/pkg/kubelet/pod_workers.go index b6c81b4a7c7..00809ae11ea 100644 --- a/pkg/kubelet/pod_workers.go +++ b/pkg/kubelet/pod_workers.go @@ -22,7 +22,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/events" @@ -39,7 +39,7 @@ import ( type OnCompleteFunc func(err error) // PodStatusFunc is a function that is invoked to generate a pod status. -type PodStatusFunc func(pod *api.Pod, podStatus *kubecontainer.PodStatus) api.PodStatus +type PodStatusFunc func(pod *v1.Pod, podStatus *kubecontainer.PodStatus) v1.PodStatus // KillPodOptions are options when performing a pod update whose update type is kill. type KillPodOptions struct { @@ -52,9 +52,9 @@ type KillPodOptions struct { // UpdatePodOptions is an options struct to pass to a UpdatePod operation. type UpdatePodOptions struct { // pod to update - Pod *api.Pod + Pod *v1.Pod // the mirror pod for the pod to update, if it is a static pod - MirrorPod *api.Pod + MirrorPod *v1.Pod // the type of update (create, update, sync, kill) UpdateType kubetypes.SyncPodType // optional callback function when operation completes @@ -77,9 +77,9 @@ type PodWorkers interface { // syncPodOptions provides the arguments to a SyncPod operation. type syncPodOptions struct { // the mirror pod for the pod to sync, if it is a static pod - mirrorPod *api.Pod + mirrorPod *v1.Pod // pod to sync - pod *api.Pod + pod *v1.Pod // the type of update (create, update, sync) updateType kubetypes.SyncPodType // the current status @@ -182,7 +182,7 @@ func (p *podWorkers) managePodLoop(podUpdates <-chan UpdatePodOptions) { } if err != nil { glog.Errorf("Error syncing pod %s, skipping: %v", update.Pod.UID, err) - p.recorder.Eventf(update.Pod, api.EventTypeWarning, events.FailedSync, "Error syncing pod, skipping: %v", err) + p.recorder.Eventf(update.Pod, v1.EventTypeWarning, events.FailedSync, "Error syncing pod, skipping: %v", err) } p.wrapUp(update.Pod.UID, err) } @@ -283,7 +283,7 @@ func (p *podWorkers) checkForUpdates(uid types.UID) { // killPodNow returns a KillPodFunc that can be used to kill a pod. // It is intended to be injected into other modules that need to kill a pod. func killPodNow(podWorkers PodWorkers, recorder record.EventRecorder) eviction.KillPodFunc { - return func(pod *api.Pod, status api.PodStatus, gracePeriodOverride *int64) error { + return func(pod *v1.Pod, status v1.PodStatus, gracePeriodOverride *int64) error { // determine the grace period to use when killing the pod gracePeriod := int64(0) if gracePeriodOverride != nil { @@ -313,7 +313,7 @@ func killPodNow(podWorkers PodWorkers, recorder record.EventRecorder) eviction.K ch <- response{err: err} }, KillPodOptions: &KillPodOptions{ - PodStatusFunc: func(p *api.Pod, podStatus *kubecontainer.PodStatus) api.PodStatus { + PodStatusFunc: func(p *v1.Pod, podStatus *kubecontainer.PodStatus) v1.PodStatus { return status }, PodTerminationGracePeriodSecondsOverride: gracePeriodOverride, @@ -325,7 +325,7 @@ func killPodNow(podWorkers PodWorkers, recorder record.EventRecorder) eviction.K case r := <-ch: return r.err case <-time.After(timeoutDuration): - recorder.Eventf(pod, api.EventTypeWarning, events.ExceededGracePeriod, "Container runtime did not kill the pod within specified grace period.") + recorder.Eventf(pod, v1.EventTypeWarning, events.ExceededGracePeriod, "Container runtime did not kill the pod within specified grace period.") return fmt.Errorf("timeout waiting to kill pod") } } diff --git a/pkg/kubelet/pod_workers_test.go b/pkg/kubelet/pod_workers_test.go index 3231776aa45..a6946528b65 100644 --- a/pkg/kubelet/pod_workers_test.go +++ b/pkg/kubelet/pod_workers_test.go @@ -22,7 +22,7 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" @@ -64,9 +64,9 @@ type TestingInterface interface { Errorf(format string, args ...interface{}) } -func newPod(uid, name string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func newPod(uid, name string) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: types.UID(uid), Name: name, }, @@ -239,8 +239,8 @@ func TestForgetNonExistingPodWorkers(t *testing.T) { } type simpleFakeKubelet struct { - pod *api.Pod - mirrorPod *api.Pod + pod *v1.Pod + mirrorPod *v1.Pod podStatus *kubecontainer.PodStatus wg sync.WaitGroup } @@ -283,12 +283,12 @@ func TestFakePodWorkers(t *testing.T) { fakePodWorkers := &fakePodWorkers{kubeletForFakeWorkers.syncPod, fakeCache, t} tests := []struct { - pod *api.Pod - mirrorPod *api.Pod + pod *v1.Pod + mirrorPod *v1.Pod }{ { - &api.Pod{}, - &api.Pod{}, + &v1.Pod{}, + &v1.Pod{}, }, { podWithUidNameNs("12345678", "foo", "new"), @@ -336,7 +336,7 @@ func TestKillPodNowFunc(t *testing.T) { killPodFunc := killPodNow(podWorkers, fakeRecorder) pod := newPod("test", "test") gracePeriodOverride := int64(0) - err := killPodFunc(pod, api.PodStatus{Phase: api.PodFailed, Reason: "reason", Message: "message"}, &gracePeriodOverride) + err := killPodFunc(pod, v1.PodStatus{Phase: v1.PodFailed, Reason: "reason", Message: "message"}, &gracePeriodOverride) if err != nil { t.Errorf("Unexpected error: %v", err) } diff --git a/pkg/kubelet/prober/BUILD b/pkg/kubelet/prober/BUILD index a191bf7e004..dbd4e228bc2 100644 --- a/pkg/kubelet/prober/BUILD +++ b/pkg/kubelet/prober/BUILD @@ -19,7 +19,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/events:go_default_library", @@ -51,9 +51,9 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/record:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/container/testing:go_default_library", diff --git a/pkg/kubelet/prober/common_test.go b/pkg/kubelet/prober/common_test.go index 71f43f98a25..b4ea6f0d45c 100644 --- a/pkg/kubelet/prober/common_test.go +++ b/pkg/kubelet/prober/common_test.go @@ -20,9 +20,9 @@ import ( "reflect" "sync" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubepod "k8s.io/kubernetes/pkg/kubelet/pod" @@ -39,27 +39,27 @@ const ( var testContainerID = kubecontainer.ContainerID{Type: "test", ID: "cOnTaInEr_Id"} -func getTestRunningStatus() api.PodStatus { - containerStatus := api.ContainerStatus{ +func getTestRunningStatus() v1.PodStatus { + containerStatus := v1.ContainerStatus{ Name: testContainerName, ContainerID: testContainerID.String(), } - containerStatus.State.Running = &api.ContainerStateRunning{StartedAt: unversioned.Now()} - podStatus := api.PodStatus{ - Phase: api.PodRunning, - ContainerStatuses: []api.ContainerStatus{containerStatus}, + containerStatus.State.Running = &v1.ContainerStateRunning{StartedAt: unversioned.Now()} + podStatus := v1.PodStatus{ + Phase: v1.PodRunning, + ContainerStatuses: []v1.ContainerStatus{containerStatus}, } return podStatus } -func getTestPod() *api.Pod { - container := api.Container{ +func getTestPod() *v1.Pod { + container := v1.Container{ Name: testContainerName, } - pod := api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{container}, - RestartPolicy: api.RestartPolicyNever, + pod := v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{container}, + RestartPolicy: v1.RestartPolicyNever, }, } pod.Name = "testPod" @@ -67,10 +67,10 @@ func getTestPod() *api.Pod { return &pod } -func setTestProbe(pod *api.Pod, probeType probeType, probeSpec api.Probe) { +func setTestProbe(pod *v1.Pod, probeType probeType, probeSpec v1.Probe) { // All tests rely on the fake exec prober. - probeSpec.Handler = api.Handler{ - Exec: &api.ExecAction{}, + probeSpec.Handler = v1.Handler{ + Exec: &v1.ExecAction{}, } // Apply test defaults, overwridden for test speed. @@ -97,7 +97,7 @@ func setTestProbe(pod *api.Pod, probeType probeType, probeSpec api.Probe) { func newTestManager() *manager { refManager := kubecontainer.NewRefManager() - refManager.SetRef(testContainerID, &api.ObjectReference{}) // Suppress prober warnings. + refManager.SetRef(testContainerID, &v1.ObjectReference{}) // Suppress prober warnings. podManager := kubepod.NewBasicPodManager(nil) // Add test pod to pod manager, so that status manager can get the pod from pod manager if needed. podManager.AddPod(getTestPod()) @@ -113,7 +113,7 @@ func newTestManager() *manager { return m } -func newTestWorker(m *manager, probeType probeType, probeSpec api.Probe) *worker { +func newTestWorker(m *manager, probeType probeType, probeSpec v1.Probe) *worker { pod := getTestPod() setTestProbe(pod, probeType, probeSpec) return newWorker(m, probeType, pod, pod.Spec.Containers[0]) diff --git a/pkg/kubelet/prober/prober.go b/pkg/kubelet/prober/prober.go index 248916062c5..941520cd309 100644 --- a/pkg/kubelet/prober/prober.go +++ b/pkg/kubelet/prober/prober.go @@ -26,7 +26,7 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/events" @@ -73,8 +73,8 @@ func newProber( } // probe probes the container. -func (pb *prober) probe(probeType probeType, pod *api.Pod, status api.PodStatus, container api.Container, containerID kubecontainer.ContainerID) (results.Result, error) { - var probeSpec *api.Probe +func (pb *prober) probe(probeType probeType, pod *v1.Pod, status v1.PodStatus, container v1.Container, containerID kubecontainer.ContainerID) (results.Result, error) { + var probeSpec *v1.Probe switch probeType { case readiness: probeSpec = container.ReadinessProbe @@ -100,12 +100,12 @@ func (pb *prober) probe(probeType probeType, pod *api.Pod, status api.PodStatus, if err != nil { glog.V(1).Infof("%s probe for %q errored: %v", probeType, ctrName, err) if hasRef { - pb.recorder.Eventf(ref, api.EventTypeWarning, events.ContainerUnhealthy, "%s probe errored: %v", probeType, err) + pb.recorder.Eventf(ref, v1.EventTypeWarning, events.ContainerUnhealthy, "%s probe errored: %v", probeType, err) } } else { // result != probe.Success glog.V(1).Infof("%s probe for %q failed (%v): %s", probeType, ctrName, result, output) if hasRef { - pb.recorder.Eventf(ref, api.EventTypeWarning, events.ContainerUnhealthy, "%s probe failed: %s", probeType, output) + pb.recorder.Eventf(ref, v1.EventTypeWarning, events.ContainerUnhealthy, "%s probe failed: %s", probeType, output) } } return results.Failure, err @@ -116,7 +116,7 @@ func (pb *prober) probe(probeType probeType, pod *api.Pod, status api.PodStatus, // runProbeWithRetries tries to probe the container in a finite loop, it returns the last result // if it never succeeds. -func (pb *prober) runProbeWithRetries(p *api.Probe, pod *api.Pod, status api.PodStatus, container api.Container, containerID kubecontainer.ContainerID, retries int) (probe.Result, string, error) { +func (pb *prober) runProbeWithRetries(p *v1.Probe, pod *v1.Pod, status v1.PodStatus, container v1.Container, containerID kubecontainer.ContainerID, retries int) (probe.Result, string, error) { var err error var result probe.Result var output string @@ -131,7 +131,7 @@ func (pb *prober) runProbeWithRetries(p *api.Probe, pod *api.Pod, status api.Pod // buildHeaderMap takes a list of HTTPHeader string // pairs and returns a populated string->[]string http.Header map. -func buildHeader(headerList []api.HTTPHeader) http.Header { +func buildHeader(headerList []v1.HTTPHeader) http.Header { headers := make(http.Header) for _, header := range headerList { headers[header.Name] = append(headers[header.Name], header.Value) @@ -139,7 +139,7 @@ func buildHeader(headerList []api.HTTPHeader) http.Header { return headers } -func (pb *prober) runProbe(p *api.Probe, pod *api.Pod, status api.PodStatus, container api.Container, containerID kubecontainer.ContainerID) (probe.Result, string, error) { +func (pb *prober) runProbe(p *v1.Probe, pod *v1.Pod, status v1.PodStatus, container v1.Container, containerID kubecontainer.ContainerID) (probe.Result, string, error) { timeout := time.Duration(p.TimeoutSeconds) * time.Second if p.Exec != nil { glog.V(4).Infof("Exec-Probe Pod: %v, Container: %v, Command: %v", pod, container, p.Exec.Command) @@ -174,7 +174,7 @@ func (pb *prober) runProbe(p *api.Probe, pod *api.Pod, status api.PodStatus, con return probe.Unknown, "", fmt.Errorf("Missing probe handler for %s:%s", format.Pod(pod), container.Name) } -func extractPort(param intstr.IntOrString, container api.Container) (int, error) { +func extractPort(param intstr.IntOrString, container v1.Container) (int, error) { port := -1 var err error switch param.Type { @@ -197,7 +197,7 @@ func extractPort(param intstr.IntOrString, container api.Container) (int, error) } // findPortByName is a helper function to look up a port in a container by name. -func findPortByName(container api.Container, portName string) (int, error) { +func findPortByName(container v1.Container, portName string) (int, error) { for _, port := range container.Ports { if port.Name == portName { return int(port.ContainerPort), nil @@ -226,7 +226,7 @@ type execInContainer struct { run func() ([]byte, error) } -func (pb *prober) newExecInContainer(container api.Container, containerID kubecontainer.ContainerID, cmd []string, timeout time.Duration) exec.Cmd { +func (pb *prober) newExecInContainer(container v1.Container, containerID kubecontainer.ContainerID, cmd []string, timeout time.Duration) exec.Cmd { return execInContainer{func() ([]byte, error) { return pb.runner.RunInContainer(containerID, cmd, timeout) }} diff --git a/pkg/kubelet/prober/prober_manager.go b/pkg/kubelet/prober/prober_manager.go index 32f05fd7070..09f942b025d 100644 --- a/pkg/kubelet/prober/prober_manager.go +++ b/pkg/kubelet/prober/prober_manager.go @@ -20,7 +20,7 @@ import ( "sync" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/prober/results" @@ -39,19 +39,19 @@ import ( type Manager interface { // AddPod creates new probe workers for every container probe. This should be called for every // pod created. - AddPod(pod *api.Pod) + AddPod(pod *v1.Pod) // RemovePod handles cleaning up the removed pod state, including terminating probe workers and // deleting cached results. - RemovePod(pod *api.Pod) + RemovePod(pod *v1.Pod) // CleanupPods handles cleaning up pods which should no longer be running. // It takes a list of "active pods" which should not be cleaned up. - CleanupPods(activePods []*api.Pod) + CleanupPods(activePods []*v1.Pod) // UpdatePodStatus modifies the given PodStatus with the appropriate Ready state for each // container based on container running status, cached probe results and worker states. - UpdatePodStatus(types.UID, *api.PodStatus) + UpdatePodStatus(types.UID, *v1.PodStatus) // Start starts the Manager sync loops. Start() @@ -127,7 +127,7 @@ func (t probeType) String() string { } } -func (m *manager) AddPod(pod *api.Pod) { +func (m *manager) AddPod(pod *v1.Pod) { m.workerLock.Lock() defer m.workerLock.Unlock() @@ -161,7 +161,7 @@ func (m *manager) AddPod(pod *api.Pod) { } } -func (m *manager) RemovePod(pod *api.Pod) { +func (m *manager) RemovePod(pod *v1.Pod) { m.workerLock.RLock() defer m.workerLock.RUnlock() @@ -177,7 +177,7 @@ func (m *manager) RemovePod(pod *api.Pod) { } } -func (m *manager) CleanupPods(activePods []*api.Pod) { +func (m *manager) CleanupPods(activePods []*v1.Pod) { desiredPods := make(map[types.UID]sets.Empty) for _, pod := range activePods { desiredPods[pod.UID] = sets.Empty{} @@ -193,7 +193,7 @@ func (m *manager) CleanupPods(activePods []*api.Pod) { } } -func (m *manager) UpdatePodStatus(podUID types.UID, podStatus *api.PodStatus) { +func (m *manager) UpdatePodStatus(podUID types.UID, podStatus *v1.PodStatus) { for i, c := range podStatus.ContainerStatuses { var ready bool if c.State.Running == nil { diff --git a/pkg/kubelet/prober/prober_manager_test.go b/pkg/kubelet/prober/prober_manager_test.go index 7585ba3898e..244f184c2ca 100644 --- a/pkg/kubelet/prober/prober_manager_test.go +++ b/pkg/kubelet/prober/prober_manager_test.go @@ -23,7 +23,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/prober/results" "k8s.io/kubernetes/pkg/probe" @@ -36,9 +36,9 @@ func init() { runtime.ReallyCrash = true } -var defaultProbe *api.Probe = &api.Probe{ - Handler: api.Handler{ - Exec: &api.ExecAction{}, +var defaultProbe *v1.Probe = &v1.Probe{ + Handler: v1.Handler{ + Exec: &v1.ExecAction{}, }, TimeoutSeconds: 1, PeriodSeconds: 1, @@ -47,12 +47,12 @@ var defaultProbe *api.Probe = &api.Probe{ } func TestAddRemovePods(t *testing.T) { - noProbePod := api.Pod{ - ObjectMeta: api.ObjectMeta{ + noProbePod := v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "no_probe_pod", }, - Spec: api.PodSpec{ - Containers: []api.Container{{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ Name: "no_probe1", }, { Name: "no_probe2", @@ -60,12 +60,12 @@ func TestAddRemovePods(t *testing.T) { }, } - probePod := api.Pod{ - ObjectMeta: api.ObjectMeta{ + probePod := v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "probe_pod", }, - Spec: api.PodSpec{ - Containers: []api.Container{{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ Name: "no_probe1", }, { Name: "readiness", @@ -126,12 +126,12 @@ func TestAddRemovePods(t *testing.T) { func TestCleanupPods(t *testing.T) { m := newTestManager() defer cleanup(t, m) - podToCleanup := api.Pod{ - ObjectMeta: api.ObjectMeta{ + podToCleanup := v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "pod_cleanup", }, - Spec: api.PodSpec{ - Containers: []api.Container{{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ Name: "prober1", ReadinessProbe: defaultProbe, }, { @@ -140,12 +140,12 @@ func TestCleanupPods(t *testing.T) { }}, }, } - podToKeep := api.Pod{ - ObjectMeta: api.ObjectMeta{ + podToKeep := v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "pod_keep", }, - Spec: api.PodSpec{ - Containers: []api.Container{{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ Name: "prober1", ReadinessProbe: defaultProbe, }, { @@ -157,7 +157,7 @@ func TestCleanupPods(t *testing.T) { m.AddPod(&podToCleanup) m.AddPod(&podToKeep) - m.CleanupPods([]*api.Pod{&podToKeep}) + m.CleanupPods([]*v1.Pod{&podToKeep}) removedProbes := []probeKey{ {"pod_cleanup", "prober1", readiness}, @@ -178,9 +178,9 @@ func TestCleanupPods(t *testing.T) { func TestCleanupRepeated(t *testing.T) { m := newTestManager() defer cleanup(t, m) - podTemplate := api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{{ + podTemplate := v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ Name: "prober1", ReadinessProbe: defaultProbe, LivenessProbe: defaultProbe, @@ -196,49 +196,49 @@ func TestCleanupRepeated(t *testing.T) { } for i := 0; i < 10; i++ { - m.CleanupPods([]*api.Pod{}) + m.CleanupPods([]*v1.Pod{}) } } func TestUpdatePodStatus(t *testing.T) { - unprobed := api.ContainerStatus{ + unprobed := v1.ContainerStatus{ Name: "unprobed_container", ContainerID: "test://unprobed_container_id", - State: api.ContainerState{ - Running: &api.ContainerStateRunning{}, + State: v1.ContainerState{ + Running: &v1.ContainerStateRunning{}, }, } - probedReady := api.ContainerStatus{ + probedReady := v1.ContainerStatus{ Name: "probed_container_ready", ContainerID: "test://probed_container_ready_id", - State: api.ContainerState{ - Running: &api.ContainerStateRunning{}, + State: v1.ContainerState{ + Running: &v1.ContainerStateRunning{}, }, } - probedPending := api.ContainerStatus{ + probedPending := v1.ContainerStatus{ Name: "probed_container_pending", ContainerID: "test://probed_container_pending_id", - State: api.ContainerState{ - Running: &api.ContainerStateRunning{}, + State: v1.ContainerState{ + Running: &v1.ContainerStateRunning{}, }, } - probedUnready := api.ContainerStatus{ + probedUnready := v1.ContainerStatus{ Name: "probed_container_unready", ContainerID: "test://probed_container_unready_id", - State: api.ContainerState{ - Running: &api.ContainerStateRunning{}, + State: v1.ContainerState{ + Running: &v1.ContainerStateRunning{}, }, } - terminated := api.ContainerStatus{ + terminated := v1.ContainerStatus{ Name: "terminated_container", ContainerID: "test://terminated_container_id", - State: api.ContainerState{ - Terminated: &api.ContainerStateTerminated{}, + State: v1.ContainerState{ + Terminated: &v1.ContainerStateTerminated{}, }, } - podStatus := api.PodStatus{ - Phase: api.PodRunning, - ContainerStatuses: []api.ContainerStatus{ + podStatus := v1.PodStatus{ + Phase: v1.PodRunning, + ContainerStatuses: []v1.ContainerStatus{ unprobed, probedReady, probedPending, probedUnready, terminated, }, } @@ -254,9 +254,9 @@ func TestUpdatePodStatus(t *testing.T) { probeKey{testPodUID, probedUnready.Name, readiness}: {}, probeKey{testPodUID, terminated.Name, readiness}: {}, } - m.readinessManager.Set(kubecontainer.ParseContainerID(probedReady.ContainerID), results.Success, &api.Pod{}) - m.readinessManager.Set(kubecontainer.ParseContainerID(probedUnready.ContainerID), results.Failure, &api.Pod{}) - m.readinessManager.Set(kubecontainer.ParseContainerID(terminated.ContainerID), results.Success, &api.Pod{}) + m.readinessManager.Set(kubecontainer.ParseContainerID(probedReady.ContainerID), results.Success, &v1.Pod{}) + m.readinessManager.Set(kubecontainer.ParseContainerID(probedUnready.ContainerID), results.Failure, &v1.Pod{}) + m.readinessManager.Set(kubecontainer.ParseContainerID(terminated.ContainerID), results.Success, &v1.Pod{}) m.UpdatePodStatus(testPodUID, &podStatus) @@ -281,7 +281,7 @@ func TestUpdatePodStatus(t *testing.T) { func TestUpdateReadiness(t *testing.T) { testPod := getTestPod() - setTestProbe(testPod, readiness, api.Probe{}) + setTestProbe(testPod, readiness, v1.Probe{}) m := newTestManager() defer cleanup(t, m) @@ -291,7 +291,7 @@ func TestUpdateReadiness(t *testing.T) { defer func() { close(stopCh) // Send an update to exit updateReadiness() - m.readinessManager.Set(kubecontainer.ContainerID{}, results.Success, &api.Pod{}) + m.readinessManager.Set(kubecontainer.ContainerID{}, results.Success, &v1.Pod{}) }() exec := syncExecProber{} diff --git a/pkg/kubelet/prober/prober_test.go b/pkg/kubelet/prober/prober_test.go index 0c529d6c771..5cb6eea6e04 100644 --- a/pkg/kubelet/prober/prober_test.go +++ b/pkg/kubelet/prober/prober_test.go @@ -23,7 +23,7 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" @@ -54,8 +54,8 @@ func TestFormatURL(t *testing.T) { } func TestFindPortByName(t *testing.T) { - container := api.Container{ - Ports: []api.ContainerPort{ + container := v1.Container{ + Ports: []v1.ContainerPort{ { Name: "foo", ContainerPort: 8080, @@ -75,28 +75,28 @@ func TestFindPortByName(t *testing.T) { func TestGetURLParts(t *testing.T) { testCases := []struct { - probe *api.HTTPGetAction + probe *v1.HTTPGetAction ok bool host string port int path string }{ - {&api.HTTPGetAction{Host: "", Port: intstr.FromInt(-1), Path: ""}, false, "", -1, ""}, - {&api.HTTPGetAction{Host: "", Port: intstr.FromString(""), Path: ""}, false, "", -1, ""}, - {&api.HTTPGetAction{Host: "", Port: intstr.FromString("-1"), Path: ""}, false, "", -1, ""}, - {&api.HTTPGetAction{Host: "", Port: intstr.FromString("not-found"), Path: ""}, false, "", -1, ""}, - {&api.HTTPGetAction{Host: "", Port: intstr.FromString("found"), Path: ""}, true, "127.0.0.1", 93, ""}, - {&api.HTTPGetAction{Host: "", Port: intstr.FromInt(76), Path: ""}, true, "127.0.0.1", 76, ""}, - {&api.HTTPGetAction{Host: "", Port: intstr.FromString("118"), Path: ""}, true, "127.0.0.1", 118, ""}, - {&api.HTTPGetAction{Host: "hostname", Port: intstr.FromInt(76), Path: "path"}, true, "hostname", 76, "path"}, + {&v1.HTTPGetAction{Host: "", Port: intstr.FromInt(-1), Path: ""}, false, "", -1, ""}, + {&v1.HTTPGetAction{Host: "", Port: intstr.FromString(""), Path: ""}, false, "", -1, ""}, + {&v1.HTTPGetAction{Host: "", Port: intstr.FromString("-1"), Path: ""}, false, "", -1, ""}, + {&v1.HTTPGetAction{Host: "", Port: intstr.FromString("not-found"), Path: ""}, false, "", -1, ""}, + {&v1.HTTPGetAction{Host: "", Port: intstr.FromString("found"), Path: ""}, true, "127.0.0.1", 93, ""}, + {&v1.HTTPGetAction{Host: "", Port: intstr.FromInt(76), Path: ""}, true, "127.0.0.1", 76, ""}, + {&v1.HTTPGetAction{Host: "", Port: intstr.FromString("118"), Path: ""}, true, "127.0.0.1", 118, ""}, + {&v1.HTTPGetAction{Host: "hostname", Port: intstr.FromInt(76), Path: "path"}, true, "hostname", 76, "path"}, } for _, test := range testCases { - state := api.PodStatus{PodIP: "127.0.0.1"} - container := api.Container{ - Ports: []api.ContainerPort{{Name: "found", ContainerPort: 93}}, - LivenessProbe: &api.Probe{ - Handler: api.Handler{ + state := v1.PodStatus{PodIP: "127.0.0.1"} + container := v1.Container{ + Ports: []v1.ContainerPort{{Name: "found", ContainerPort: 93}}, + LivenessProbe: &v1.Probe{ + Handler: v1.Handler{ HTTPGet: test.probe, }, }, @@ -104,7 +104,7 @@ func TestGetURLParts(t *testing.T) { scheme := test.probe.Scheme if scheme == "" { - scheme = api.URISchemeHTTP + scheme = v1.URISchemeHTTP } host := test.probe.Host if host == "" { @@ -130,26 +130,26 @@ func TestGetURLParts(t *testing.T) { func TestGetTCPAddrParts(t *testing.T) { testCases := []struct { - probe *api.TCPSocketAction + probe *v1.TCPSocketAction ok bool host string port int }{ - {&api.TCPSocketAction{Port: intstr.FromInt(-1)}, false, "", -1}, - {&api.TCPSocketAction{Port: intstr.FromString("")}, false, "", -1}, - {&api.TCPSocketAction{Port: intstr.FromString("-1")}, false, "", -1}, - {&api.TCPSocketAction{Port: intstr.FromString("not-found")}, false, "", -1}, - {&api.TCPSocketAction{Port: intstr.FromString("found")}, true, "1.2.3.4", 93}, - {&api.TCPSocketAction{Port: intstr.FromInt(76)}, true, "1.2.3.4", 76}, - {&api.TCPSocketAction{Port: intstr.FromString("118")}, true, "1.2.3.4", 118}, + {&v1.TCPSocketAction{Port: intstr.FromInt(-1)}, false, "", -1}, + {&v1.TCPSocketAction{Port: intstr.FromString("")}, false, "", -1}, + {&v1.TCPSocketAction{Port: intstr.FromString("-1")}, false, "", -1}, + {&v1.TCPSocketAction{Port: intstr.FromString("not-found")}, false, "", -1}, + {&v1.TCPSocketAction{Port: intstr.FromString("found")}, true, "1.2.3.4", 93}, + {&v1.TCPSocketAction{Port: intstr.FromInt(76)}, true, "1.2.3.4", 76}, + {&v1.TCPSocketAction{Port: intstr.FromString("118")}, true, "1.2.3.4", 118}, } for _, test := range testCases { host := "1.2.3.4" - container := api.Container{ - Ports: []api.ContainerPort{{Name: "found", ContainerPort: 93}}, - LivenessProbe: &api.Probe{ - Handler: api.Handler{ + container := v1.Container{ + Ports: []v1.ContainerPort{{Name: "found", ContainerPort: 93}}, + LivenessProbe: &v1.Probe{ + Handler: v1.Handler{ TCPSocket: test.probe, }, }, @@ -171,19 +171,19 @@ func TestGetTCPAddrParts(t *testing.T) { func TestHTTPHeaders(t *testing.T) { testCases := []struct { - input []api.HTTPHeader + input []v1.HTTPHeader output http.Header }{ - {[]api.HTTPHeader{}, http.Header{}}, - {[]api.HTTPHeader{ + {[]v1.HTTPHeader{}, http.Header{}}, + {[]v1.HTTPHeader{ {Name: "X-Muffins-Or-Cupcakes", Value: "Muffins"}, }, http.Header{"X-Muffins-Or-Cupcakes": {"Muffins"}}}, - {[]api.HTTPHeader{ + {[]v1.HTTPHeader{ {Name: "X-Muffins-Or-Cupcakes", Value: "Muffins"}, {Name: "X-Muffins-Or-Plumcakes", Value: "Muffins!"}, }, http.Header{"X-Muffins-Or-Cupcakes": {"Muffins"}, "X-Muffins-Or-Plumcakes": {"Muffins!"}}}, - {[]api.HTTPHeader{ + {[]v1.HTTPHeader{ {Name: "X-Muffins-Or-Cupcakes", Value: "Muffins"}, {Name: "X-Muffins-Or-Cupcakes", Value: "Cupcakes, too"}, }, http.Header{"X-Muffins-Or-Cupcakes": {"Muffins", "Cupcakes, too"}}}, @@ -203,13 +203,13 @@ func TestProbe(t *testing.T) { } containerID := kubecontainer.ContainerID{Type: "test", ID: "foobar"} - execProbe := &api.Probe{ - Handler: api.Handler{ - Exec: &api.ExecAction{}, + execProbe := &v1.Probe{ + Handler: v1.Handler{ + Exec: &v1.ExecAction{}, }, } tests := []struct { - probe *api.Probe + probe *v1.Probe execError bool expectError bool execResult probe.Result @@ -220,7 +220,7 @@ func TestProbe(t *testing.T) { expectedResult: results.Success, }, { // No handler - probe: &api.Probe{}, + probe: &v1.Probe{}, expectError: true, expectedResult: results.Failure, }, @@ -251,7 +251,7 @@ func TestProbe(t *testing.T) { for i, test := range tests { for _, probeType := range [...]probeType{liveness, readiness} { testID := fmt.Sprintf("%d-%s", i, probeType) - testContainer := api.Container{} + testContainer := v1.Container{} switch probeType { case liveness: testContainer.LivenessProbe = test.probe @@ -264,7 +264,7 @@ func TestProbe(t *testing.T) { prober.exec = fakeExecProber{test.execResult, nil} } - result, err := prober.probe(probeType, &api.Pod{}, api.PodStatus{}, testContainer, containerID) + result, err := prober.probe(probeType, &v1.Pod{}, v1.PodStatus{}, testContainer, containerID) if test.expectError && err == nil { t.Errorf("[%s] Expected probe error but no error was returned.", testID) } @@ -302,7 +302,7 @@ func TestNewExecInContainer(t *testing.T) { runner: runner, } - container := api.Container{} + container := v1.Container{} containerID := kubecontainer.ContainerID{Type: "docker", ID: "containerID"} cmd := []string{"/foo", "bar"} exec := prober.newExecInContainer(container, containerID, cmd, 0) diff --git a/pkg/kubelet/prober/results/BUILD b/pkg/kubelet/prober/results/BUILD index b45a156cc32..82b1a3841c0 100644 --- a/pkg/kubelet/prober/results/BUILD +++ b/pkg/kubelet/prober/results/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["results_manager.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/types:go_default_library", ], @@ -27,7 +27,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/util/wait:go_default_library", "//vendor:github.com/stretchr/testify/assert", diff --git a/pkg/kubelet/prober/results/results_manager.go b/pkg/kubelet/prober/results/results_manager.go index 28703c6c6bf..b7076a0bfea 100644 --- a/pkg/kubelet/prober/results/results_manager.go +++ b/pkg/kubelet/prober/results/results_manager.go @@ -19,7 +19,7 @@ package results import ( "sync" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/types" ) @@ -30,7 +30,7 @@ type Manager interface { Get(kubecontainer.ContainerID) (Result, bool) // Set sets the cached result for the container with the given ID. // The pod is only included to be sent with the update. - Set(kubecontainer.ContainerID, Result, *api.Pod) + Set(kubecontainer.ContainerID, Result, *v1.Pod) // Remove clears the cached result for the container with the given ID. Remove(kubecontainer.ContainerID) // Updates creates a channel that receives an Update whenever its result changes (but not @@ -92,7 +92,7 @@ func (m *manager) Get(id kubecontainer.ContainerID) (Result, bool) { return result, found } -func (m *manager) Set(id kubecontainer.ContainerID, result Result, pod *api.Pod) { +func (m *manager) Set(id kubecontainer.ContainerID, result Result, pod *v1.Pod) { if m.setInternal(id, result) { m.updates <- Update{id, result, pod.UID} } diff --git a/pkg/kubelet/prober/results/results_manager_test.go b/pkg/kubelet/prober/results/results_manager_test.go index 99fb0064ad9..85ae8a3ce8b 100644 --- a/pkg/kubelet/prober/results/results_manager_test.go +++ b/pkg/kubelet/prober/results/results_manager_test.go @@ -21,7 +21,7 @@ import ( "time" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/util/wait" ) @@ -35,7 +35,7 @@ func TestCacheOperations(t *testing.T) { _, found := m.Get(unsetID) assert.False(t, found, "unset result found") - m.Set(setID, Success, &api.Pod{}) + m.Set(setID, Success, &v1.Pod{}) result, found := m.Get(setID) assert.True(t, result == Success, "set result") assert.True(t, found, "set result found") @@ -48,7 +48,7 @@ func TestCacheOperations(t *testing.T) { func TestUpdates(t *testing.T) { m := NewManager() - pod := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "test-pod"}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "test-pod"}} fooID := kubecontainer.ContainerID{Type: "test", ID: "foo"} barID := kubecontainer.ContainerID{Type: "test", ID: "bar"} diff --git a/pkg/kubelet/prober/testing/BUILD b/pkg/kubelet/prober/testing/BUILD index f119201b520..632c5a4ce8b 100644 --- a/pkg/kubelet/prober/testing/BUILD +++ b/pkg/kubelet/prober/testing/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["fake_manager.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", ], ) diff --git a/pkg/kubelet/prober/testing/fake_manager.go b/pkg/kubelet/prober/testing/fake_manager.go index 3fc4212507c..f989cccdcdf 100644 --- a/pkg/kubelet/prober/testing/fake_manager.go +++ b/pkg/kubelet/prober/testing/fake_manager.go @@ -17,19 +17,19 @@ limitations under the License. package testing import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" ) type FakeManager struct{} // Unused methods. -func (_ FakeManager) AddPod(_ *api.Pod) {} -func (_ FakeManager) RemovePod(_ *api.Pod) {} -func (_ FakeManager) CleanupPods(_ []*api.Pod) {} -func (_ FakeManager) Start() {} +func (_ FakeManager) AddPod(_ *v1.Pod) {} +func (_ FakeManager) RemovePod(_ *v1.Pod) {} +func (_ FakeManager) CleanupPods(_ []*v1.Pod) {} +func (_ FakeManager) Start() {} -func (_ FakeManager) UpdatePodStatus(_ types.UID, podStatus *api.PodStatus) { +func (_ FakeManager) UpdatePodStatus(_ types.UID, podStatus *v1.PodStatus) { for i := range podStatus.ContainerStatuses { podStatus.ContainerStatuses[i].Ready = true } diff --git a/pkg/kubelet/prober/worker.go b/pkg/kubelet/prober/worker.go index 1bb2e57353b..889c8733f05 100644 --- a/pkg/kubelet/prober/worker.go +++ b/pkg/kubelet/prober/worker.go @@ -21,7 +21,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/prober/results" "k8s.io/kubernetes/pkg/kubelet/util/format" @@ -37,13 +37,13 @@ type worker struct { stopCh chan struct{} // The pod containing this probe (read-only) - pod *api.Pod + pod *v1.Pod // The container to probe (read-only) - container api.Container + container v1.Container // Describes the probe configuration (read-only) - spec *api.Probe + spec *v1.Probe // The type of the worker. probeType probeType @@ -70,8 +70,8 @@ type worker struct { func newWorker( m *manager, probeType probeType, - pod *api.Pod, - container api.Container) *worker { + pod *v1.Pod, + container v1.Container) *worker { w := &worker{ stopCh: make(chan struct{}, 1), // Buffer so stop() can be non-blocking. @@ -149,13 +149,13 @@ func (w *worker) doProbe() (keepGoing bool) { } // Worker should terminate if pod is terminated. - if status.Phase == api.PodFailed || status.Phase == api.PodSucceeded { + if status.Phase == v1.PodFailed || status.Phase == v1.PodSucceeded { glog.V(3).Infof("Pod %v %v, exiting probe worker", format.Pod(w.pod), status.Phase) return false } - c, ok := api.GetContainerStatus(status.ContainerStatuses, w.container.Name) + c, ok := v1.GetContainerStatus(status.ContainerStatuses, w.container.Name) if !ok || len(c.ContainerID) == 0 { // Either the container has not been created yet, or it was deleted. glog.V(3).Infof("Probe target container not found: %v - %v", @@ -186,7 +186,7 @@ func (w *worker) doProbe() (keepGoing bool) { } // Abort if the container will not be restarted. return c.State.Terminated == nil || - w.pod.Spec.RestartPolicy != api.RestartPolicyNever + w.pod.Spec.RestartPolicy != v1.RestartPolicyNever } if int32(time.Since(c.State.Running.StartedAt.Time).Seconds()) < w.spec.InitialDelaySeconds { diff --git a/pkg/kubelet/prober/worker_test.go b/pkg/kubelet/prober/worker_test.go index 95ea99213b5..516a75dde4a 100644 --- a/pkg/kubelet/prober/worker_test.go +++ b/pkg/kubelet/prober/worker_test.go @@ -21,9 +21,9 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubepod "k8s.io/kubernetes/pkg/kubelet/pod" @@ -48,17 +48,17 @@ func TestDoProbe(t *testing.T) { pendingStatus.ContainerStatuses[0].State.Running = nil terminatedStatus := getTestRunningStatus() terminatedStatus.ContainerStatuses[0].State.Running = nil - terminatedStatus.ContainerStatuses[0].State.Terminated = &api.ContainerStateTerminated{ + terminatedStatus.ContainerStatuses[0].State.Terminated = &v1.ContainerStateTerminated{ StartedAt: unversioned.Now(), } otherStatus := getTestRunningStatus() otherStatus.ContainerStatuses[0].Name = "otherContainer" failedStatus := getTestRunningStatus() - failedStatus.Phase = api.PodFailed + failedStatus.Phase = v1.PodFailed tests := []struct { - probe api.Probe - podStatus *api.PodStatus + probe v1.Probe + podStatus *v1.PodStatus expectContinue bool expectSet bool expectedResult results.Result @@ -90,7 +90,7 @@ func TestDoProbe(t *testing.T) { }, { // Initial delay passed podStatus: &runningStatus, - probe: api.Probe{ + probe: v1.Probe{ InitialDelaySeconds: -100, }, expectContinue: true, @@ -127,7 +127,7 @@ func TestInitialDelay(t *testing.T) { m := newTestManager() for _, probeType := range [...]probeType{liveness, readiness} { - w := newTestWorker(m, probeType, api.Probe{ + w := newTestWorker(m, probeType, v1.Probe{ InitialDelaySeconds: 10, }) m.statusManager.SetPodStatus(w.pod, getTestRunningStatus()) @@ -149,7 +149,7 @@ func TestInitialDelay(t *testing.T) { func TestFailureThreshold(t *testing.T) { m := newTestManager() - w := newTestWorker(m, readiness, api.Probe{SuccessThreshold: 1, FailureThreshold: 3}) + w := newTestWorker(m, readiness, v1.Probe{SuccessThreshold: 1, FailureThreshold: 3}) m.statusManager.SetPodStatus(w.pod, getTestRunningStatus()) for i := 0; i < 2; i++ { @@ -183,11 +183,11 @@ func TestFailureThreshold(t *testing.T) { func TestSuccessThreshold(t *testing.T) { m := newTestManager() - w := newTestWorker(m, readiness, api.Probe{SuccessThreshold: 3, FailureThreshold: 1}) + w := newTestWorker(m, readiness, v1.Probe{SuccessThreshold: 3, FailureThreshold: 1}) m.statusManager.SetPodStatus(w.pod, getTestRunningStatus()) // Start out failure. - w.resultsManager.Set(testContainerID, results.Failure, &api.Pod{}) + w.resultsManager.Set(testContainerID, results.Failure, &v1.Pod{}) for i := 0; i < 2; i++ { // Probe defaults to Failure. @@ -220,7 +220,7 @@ func TestCleanUp(t *testing.T) { for _, probeType := range [...]probeType{liveness, readiness} { key := probeKey{testPodUID, testContainerName, probeType} - w := newTestWorker(m, probeType, api.Probe{}) + w := newTestWorker(m, probeType, v1.Probe{}) m.statusManager.SetPodStatus(w.pod, getTestRunningStatus()) go w.run() m.workers[key] = w @@ -256,7 +256,7 @@ func TestHandleCrash(t *testing.T) { runtime.ReallyCrash = false // Test that we *don't* really crash. m := newTestManager() - w := newTestWorker(m, readiness, api.Probe{}) + w := newTestWorker(m, readiness, v1.Probe{}) m.statusManager.SetPodStatus(w.pod, getTestRunningStatus()) expectContinue(t, w, w.doProbe(), "Initial successful probe.") @@ -308,7 +308,7 @@ func (p crashingExecProber) Probe(_ exec.Cmd) (probe.Result, string, error) { func TestOnHoldOnLivenessCheckFailure(t *testing.T) { m := newTestManager() - w := newTestWorker(m, liveness, api.Probe{SuccessThreshold: 1, FailureThreshold: 1}) + w := newTestWorker(m, liveness, v1.Probe{SuccessThreshold: 1, FailureThreshold: 1}) status := getTestRunningStatus() m.statusManager.SetPodStatus(w.pod, getTestRunningStatus()) diff --git a/pkg/kubelet/qos/BUILD b/pkg/kubelet/qos/BUILD index f505128a0a1..4dea41216c5 100644 --- a/pkg/kubelet/qos/BUILD +++ b/pkg/kubelet/qos/BUILD @@ -22,6 +22,7 @@ go_library( deps = [ "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/util/sets:go_default_library", ], ) @@ -35,7 +36,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", ], ) diff --git a/pkg/kubelet/qos/policy.go b/pkg/kubelet/qos/policy.go index 7c142f5cd10..075bcc85439 100644 --- a/pkg/kubelet/qos/policy.go +++ b/pkg/kubelet/qos/policy.go @@ -16,9 +16,7 @@ limitations under the License. package qos -import ( - "k8s.io/kubernetes/pkg/api" -) +import "k8s.io/kubernetes/pkg/api/v1" const ( // PodInfraOOMAdj is very docker specific. For arbitrary runtime, it may not make @@ -39,7 +37,7 @@ const ( // multiplied by 10 (barring exceptional cases) + a configurable quantity which is between -1000 // and 1000. Containers with higher OOM scores are killed if the system runs out of memory. // See https://lwn.net/Articles/391222/ for more information. -func GetContainerOOMScoreAdjust(pod *api.Pod, container *api.Container, memoryCapacity int64) int { +func GetContainerOOMScoreAdjust(pod *v1.Pod, container *v1.Container, memoryCapacity int64) int { switch GetPodQOS(pod) { case Guaranteed: // Guaranteed containers should be the last to get killed. diff --git a/pkg/kubelet/qos/policy_test.go b/pkg/kubelet/qos/policy_test.go index 50c9b163497..ea35de56527 100644 --- a/pkg/kubelet/qos/policy_test.go +++ b/pkg/kubelet/qos/policy_test.go @@ -20,8 +20,8 @@ import ( "strconv" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" ) const ( @@ -29,13 +29,13 @@ const ( ) var ( - cpuLimit = api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + cpuLimit = v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), + Resources: v1.ResourceRequirements{ + Limits: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("10"), }, }, }, @@ -43,16 +43,16 @@ var ( }, } - memoryLimitCPURequest = api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + memoryLimitCPURequest = v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("0"), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("0"), }, - Limits: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Limits: v1.ResourceList{ + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, }, @@ -60,13 +60,13 @@ var ( }, } - zeroMemoryLimit = api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + zeroMemoryLimit = v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse("0"), + Resources: v1.ResourceRequirements{ + Limits: v1.ResourceList{ + v1.ResourceName(v1.ResourceMemory): resource.MustParse("0"), }, }, }, @@ -74,28 +74,28 @@ var ( }, } - noRequestLimit = api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + noRequestLimit = v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{}, + Resources: v1.ResourceRequirements{}, }, }, }, } - equalRequestLimitCPUMemory = api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + equalRequestLimitCPUMemory = v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - api.ResourceName(api.ResourceCPU): resource.MustParse("5m"), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), + v1.ResourceName(v1.ResourceCPU): resource.MustParse("5m"), }, - Limits: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("5m"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Limits: v1.ResourceList{ + v1.ResourceName(v1.ResourceCPU): resource.MustParse("5m"), + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, }, @@ -103,17 +103,17 @@ var ( }, } - cpuUnlimitedMemoryLimitedWithRequests = api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + cpuUnlimitedMemoryLimitedWithRequests = v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse(strconv.Itoa(standardMemoryAmount / 2)), - api.ResourceName(api.ResourceCPU): resource.MustParse("5m"), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceMemory): resource.MustParse(strconv.Itoa(standardMemoryAmount / 2)), + v1.ResourceName(v1.ResourceCPU): resource.MustParse("5m"), }, - Limits: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), + Limits: v1.ResourceList{ + v1.ResourceName(v1.ResourceMemory): resource.MustParse("10G"), }, }, }, @@ -121,14 +121,14 @@ var ( }, } - requestNoLimit = api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + requestNoLimit = v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse(strconv.Itoa(standardMemoryAmount - 1)), - api.ResourceName(api.ResourceCPU): resource.MustParse("5m"), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceMemory): resource.MustParse(strconv.Itoa(standardMemoryAmount - 1)), + v1.ResourceName(v1.ResourceCPU): resource.MustParse("5m"), }, }, }, @@ -138,7 +138,7 @@ var ( ) type oomTest struct { - pod *api.Pod + pod *v1.Pod 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. diff --git a/pkg/kubelet/qos/qos.go b/pkg/kubelet/qos/qos.go index 00e347f9acd..f515ca30dc2 100644 --- a/pkg/kubelet/qos/qos.go +++ b/pkg/kubelet/qos/qos.go @@ -19,11 +19,12 @@ package qos import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/sets" ) // isResourceGuaranteed returns true if the container's resource requirements are Guaranteed. -func isResourceGuaranteed(container *api.Container, resource api.ResourceName) bool { +func isResourceGuaranteed(container *v1.Container, resource v1.ResourceName) bool { // A container resource is guaranteed if its request == limit. // If request == limit, the user is very confident of resource consumption. req, hasReq := container.Resources.Requests[resource] @@ -35,7 +36,7 @@ func isResourceGuaranteed(container *api.Container, resource api.ResourceName) b } // isResourceBestEffort returns true if the container's resource requirements are best-effort. -func isResourceBestEffort(container *api.Container, resource api.ResourceName) bool { +func isResourceBestEffort(container *v1.Container, resource v1.ResourceName) bool { // A container resource is best-effort if its request is unspecified or 0. // If a request is specified, then the user expects some kind of resource guarantee. req, hasReq := container.Resources.Requests[resource] @@ -46,9 +47,9 @@ func isResourceBestEffort(container *api.Container, resource api.ResourceName) b // A pod is besteffort if none of its containers have specified any requests or limits. // A pod is guaranteed only when requests and limits are specified for all the containers and they are equal. // A pod is burstable if limits and requests do not match across all containers. -func GetPodQOS(pod *api.Pod) QOSClass { - requests := api.ResourceList{} - limits := api.ResourceList{} +func GetPodQOS(pod *v1.Pod) QOSClass { + requests := v1.ResourceList{} + limits := v1.ResourceList{} zeroQuantity := resource.MustParse("0") isGuaranteed := true for _, container := range pod.Spec.Containers { @@ -108,11 +109,78 @@ func GetPodQOS(pod *api.Pod) QOSClass { return Burstable } +// InternalGetPodQOS returns the QoS class of a pod. +// A pod is besteffort if none of its containers have specified any requests or limits. +// A pod is guaranteed only when requests and limits are specified for all the containers and they are equal. +// A pod is burstable if limits and requests do not match across all containers. +func InternalGetPodQOS(pod *api.Pod) QOSClass { + requests := api.ResourceList{} + limits := api.ResourceList{} + zeroQuantity := resource.MustParse("0") + isGuaranteed := true + var supportedQoSComputeResources = sets.NewString(string(api.ResourceCPU), string(api.ResourceMemory)) + for _, container := range pod.Spec.Containers { + // process requests + for name, quantity := range container.Resources.Requests { + if !supportedQoSComputeResources.Has(string(name)) { + continue + } + if quantity.Cmp(zeroQuantity) == 1 { + delta := quantity.Copy() + if _, exists := requests[name]; !exists { + requests[name] = *delta + } else { + delta.Add(requests[name]) + requests[name] = *delta + } + } + } + // process limits + qosLimitsFound := sets.NewString() + for name, quantity := range container.Resources.Limits { + if !supportedQoSComputeResources.Has(string(name)) { + continue + } + if quantity.Cmp(zeroQuantity) == 1 { + qosLimitsFound.Insert(string(name)) + delta := quantity.Copy() + if _, exists := limits[name]; !exists { + limits[name] = *delta + } else { + delta.Add(limits[name]) + limits[name] = *delta + } + } + } + + if len(qosLimitsFound) != len(supportedQoSComputeResources) { + isGuaranteed = false + } + } + if len(requests) == 0 && len(limits) == 0 { + return BestEffort + } + // Check is requests match limits for all resources. + if isGuaranteed { + for name, req := range requests { + if lim, exists := limits[name]; !exists || lim.Cmp(req) != 0 { + isGuaranteed = false + break + } + } + } + if isGuaranteed && + len(requests) == len(limits) { + return Guaranteed + } + return Burstable +} + // QOSList is a set of (resource name, QoS class) pairs. -type QOSList map[api.ResourceName]QOSClass +type QOSList map[v1.ResourceName]QOSClass // GetQOS returns a mapping of resource name to QoS class of a container -func GetQOS(container *api.Container) QOSList { +func GetQOS(container *v1.Container) QOSList { resourceToQOS := QOSList{} for resource := range allResources(container) { switch { @@ -128,13 +196,13 @@ func GetQOS(container *api.Container) QOSList { } // supportedComputeResources is the list of compute resources for with QoS is supported. -var supportedQoSComputeResources = sets.NewString(string(api.ResourceCPU), string(api.ResourceMemory)) +var supportedQoSComputeResources = sets.NewString(string(v1.ResourceCPU), string(v1.ResourceMemory)) // allResources returns a set of all possible resources whose mapped key value is true if present on the container -func allResources(container *api.Container) map[api.ResourceName]bool { - resources := map[api.ResourceName]bool{} +func allResources(container *v1.Container) map[v1.ResourceName]bool { + resources := map[v1.ResourceName]bool{} for _, resource := range supportedQoSComputeResources.List() { - resources[api.ResourceName(resource)] = false + resources[v1.ResourceName(resource)] = false } for resource := range container.Resources.Requests { resources[resource] = true diff --git a/pkg/kubelet/qos/qos_test.go b/pkg/kubelet/qos/qos_test.go index de490d44ef1..9f6ffdc7b60 100644 --- a/pkg/kubelet/qos/qos_test.go +++ b/pkg/kubelet/qos/qos_test.go @@ -19,46 +19,46 @@ package qos import ( "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" ) -func getResourceList(cpu, memory string) api.ResourceList { - res := api.ResourceList{} +func getResourceList(cpu, memory string) v1.ResourceList { + res := v1.ResourceList{} if cpu != "" { - res[api.ResourceCPU] = resource.MustParse(cpu) + res[v1.ResourceCPU] = resource.MustParse(cpu) } if memory != "" { - res[api.ResourceMemory] = resource.MustParse(memory) + res[v1.ResourceMemory] = resource.MustParse(memory) } return res } -func addResource(rName, value string, rl api.ResourceList) api.ResourceList { - rl[api.ResourceName(rName)] = resource.MustParse(value) +func addResource(rName, value string, rl v1.ResourceList) v1.ResourceList { + rl[v1.ResourceName(rName)] = resource.MustParse(value) return rl } -func getResourceRequirements(requests, limits api.ResourceList) api.ResourceRequirements { - res := api.ResourceRequirements{} +func getResourceRequirements(requests, limits v1.ResourceList) v1.ResourceRequirements { + res := v1.ResourceRequirements{} res.Requests = requests res.Limits = limits return res } -func newContainer(name string, requests api.ResourceList, limits api.ResourceList) api.Container { - return api.Container{ +func newContainer(name string, requests v1.ResourceList, limits v1.ResourceList) v1.Container { + return v1.Container{ Name: name, Resources: getResourceRequirements(requests, limits), } } -func newPod(name string, containers []api.Container) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func newPod(name string, containers []v1.Container) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ Containers: containers, }, } @@ -66,103 +66,103 @@ func newPod(name string, containers []api.Container) *api.Pod { func TestGetPodQOS(t *testing.T) { testCases := []struct { - pod *api.Pod + pod *v1.Pod expected QOSClass }{ { - pod: newPod("guaranteed", []api.Container{ + pod: newPod("guaranteed", []v1.Container{ newContainer("guaranteed", getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")), }), expected: Guaranteed, }, { - pod: newPod("guaranteed-with-gpu", []api.Container{ + pod: newPod("guaranteed-with-gpu", []v1.Container{ newContainer("guaranteed", getResourceList("100m", "100Mi"), addResource("nvidia-gpu", "2", getResourceList("100m", "100Mi"))), }), expected: Guaranteed, }, { - pod: newPod("guaranteed-guaranteed", []api.Container{ + pod: newPod("guaranteed-guaranteed", []v1.Container{ newContainer("guaranteed", getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")), newContainer("guaranteed", getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")), }), expected: Guaranteed, }, { - pod: newPod("guaranteed-guaranteed-with-gpu", []api.Container{ + pod: newPod("guaranteed-guaranteed-with-gpu", []v1.Container{ newContainer("guaranteed", getResourceList("100m", "100Mi"), addResource("nvidia-gpu", "2", getResourceList("100m", "100Mi"))), newContainer("guaranteed", getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")), }), expected: Guaranteed, }, { - pod: newPod("best-effort-best-effort", []api.Container{ + pod: newPod("best-effort-best-effort", []v1.Container{ newContainer("best-effort", getResourceList("", ""), getResourceList("", "")), newContainer("best-effort", getResourceList("", ""), getResourceList("", "")), }), expected: BestEffort, }, { - pod: newPod("best-effort-best-effort-with-gpu", []api.Container{ + pod: newPod("best-effort-best-effort-with-gpu", []v1.Container{ newContainer("best-effort", getResourceList("", ""), addResource("nvidia-gpu", "2", getResourceList("", ""))), newContainer("best-effort", getResourceList("", ""), getResourceList("", "")), }), expected: BestEffort, }, { - pod: newPod("best-effort-with-gpu", []api.Container{ + pod: newPod("best-effort-with-gpu", []v1.Container{ newContainer("best-effort", getResourceList("", ""), addResource("nvidia-gpu", "2", getResourceList("", ""))), }), expected: BestEffort, }, { - pod: newPod("best-effort-burstable", []api.Container{ + pod: newPod("best-effort-burstable", []v1.Container{ newContainer("best-effort", getResourceList("", ""), addResource("nvidia-gpu", "2", getResourceList("", ""))), newContainer("burstable", getResourceList("1", ""), getResourceList("2", "")), }), expected: Burstable, }, { - pod: newPod("best-effort-guaranteed", []api.Container{ + pod: newPod("best-effort-guaranteed", []v1.Container{ newContainer("best-effort", getResourceList("", ""), addResource("nvidia-gpu", "2", getResourceList("", ""))), newContainer("guaranteed", getResourceList("10m", "100Mi"), getResourceList("10m", "100Mi")), }), expected: Burstable, }, { - pod: newPod("burstable-cpu-guaranteed-memory", []api.Container{ + pod: newPod("burstable-cpu-guaranteed-memory", []v1.Container{ newContainer("burstable", getResourceList("", "100Mi"), getResourceList("", "100Mi")), }), expected: Burstable, }, { - pod: newPod("burstable-no-limits", []api.Container{ + pod: newPod("burstable-no-limits", []v1.Container{ newContainer("burstable", getResourceList("100m", "100Mi"), getResourceList("", "")), }), expected: Burstable, }, { - pod: newPod("burstable-guaranteed", []api.Container{ + pod: newPod("burstable-guaranteed", []v1.Container{ newContainer("burstable", getResourceList("1", "100Mi"), getResourceList("2", "100Mi")), newContainer("guaranteed", getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")), }), expected: Burstable, }, { - pod: newPod("burstable-unbounded-but-requests-match-limits", []api.Container{ + pod: newPod("burstable-unbounded-but-requests-match-limits", []v1.Container{ newContainer("burstable", getResourceList("100m", "100Mi"), getResourceList("200m", "200Mi")), newContainer("burstable-unbounded", getResourceList("100m", "100Mi"), getResourceList("", "")), }), expected: Burstable, }, { - pod: newPod("burstable-1", []api.Container{ + pod: newPod("burstable-1", []v1.Container{ newContainer("burstable", getResourceList("10m", "100Mi"), getResourceList("100m", "200Mi")), }), expected: Burstable, }, { - pod: newPod("burstable-2", []api.Container{ + pod: newPod("burstable-2", []v1.Container{ newContainer("burstable", getResourceList("0", "0"), addResource("nvidia-gpu", "2", getResourceList("100m", "200Mi"))), }), expected: Burstable, diff --git a/pkg/kubelet/rkt/BUILD b/pkg/kubelet/rkt/BUILD index 3326d13e8e6..13f49521a56 100644 --- a/pkg/kubelet/rkt/BUILD +++ b/pkg/kubelet/rkt/BUILD @@ -25,8 +25,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/credentialprovider:go_default_library", "//pkg/kubelet/container:go_default_library", @@ -72,8 +72,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/container/testing:go_default_library", "//pkg/kubelet/lifecycle:go_default_library", diff --git a/pkg/kubelet/rkt/fake_rkt_interface_test.go b/pkg/kubelet/rkt/fake_rkt_interface_test.go index 6de54564edc..39b24135366 100644 --- a/pkg/kubelet/rkt/fake_rkt_interface_test.go +++ b/pkg/kubelet/rkt/fake_rkt_interface_test.go @@ -26,7 +26,7 @@ import ( rktapi "github.com/coreos/rkt/api/v1alpha" "golang.org/x/net/context" "google.golang.org/grpc" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/types" ) @@ -159,15 +159,15 @@ type fakeRuntimeHelper struct { err error } -func (f *fakeRuntimeHelper) GenerateRunContainerOptions(pod *api.Pod, container *api.Container, podIP string) (*kubecontainer.RunContainerOptions, error) { +func (f *fakeRuntimeHelper) GenerateRunContainerOptions(pod *v1.Pod, container *v1.Container, podIP string) (*kubecontainer.RunContainerOptions, error) { return nil, fmt.Errorf("Not implemented") } -func (f *fakeRuntimeHelper) GetClusterDNS(pod *api.Pod) ([]string, []string, error) { +func (f *fakeRuntimeHelper) GetClusterDNS(pod *v1.Pod) ([]string, []string, error) { return f.dnsServers, f.dnsSearches, f.err } -func (f *fakeRuntimeHelper) GeneratePodHostNameAndDomain(pod *api.Pod) (string, string, error) { +func (f *fakeRuntimeHelper) GeneratePodHostNameAndDomain(pod *v1.Pod) (string, string, error) { return f.hostName, f.hostDomain, nil } @@ -175,7 +175,7 @@ func (f *fakeRuntimeHelper) GetPodDir(podUID types.UID) string { return "/poddir/" + string(podUID) } -func (f *fakeRuntimeHelper) GetExtraSupplementalGroupsForPod(pod *api.Pod) []int64 { +func (f *fakeRuntimeHelper) GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64 { return nil } @@ -208,14 +208,14 @@ func (f *fakeRktCli) Reset() { } type fakePodGetter struct { - pods map[types.UID]*api.Pod + pods map[types.UID]*v1.Pod } func newFakePodGetter() *fakePodGetter { - return &fakePodGetter{pods: make(map[types.UID]*api.Pod)} + return &fakePodGetter{pods: make(map[types.UID]*v1.Pod)} } -func (f fakePodGetter) GetPodByUID(uid types.UID) (*api.Pod, bool) { +func (f fakePodGetter) GetPodByUID(uid types.UID) (*v1.Pod, bool) { p, found := f.pods[uid] return p, found } diff --git a/pkg/kubelet/rkt/image.go b/pkg/kubelet/rkt/image.go index 8fefad93098..b16f53bcc05 100644 --- a/pkg/kubelet/rkt/image.go +++ b/pkg/kubelet/rkt/image.go @@ -33,7 +33,7 @@ import ( dockertypes "github.com/docker/engine-api/types" "github.com/golang/glog" "golang.org/x/net/context" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/credentialprovider" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/util/parsers" @@ -45,7 +45,7 @@ import ( // // http://issue.k8s.io/7203 // -func (r *Runtime) PullImage(image kubecontainer.ImageSpec, pullSecrets []api.Secret) error { +func (r *Runtime) PullImage(image kubecontainer.ImageSpec, pullSecrets []v1.Secret) error { img := image.Image // TODO(yifan): The credential operation is a copy from dockertools package, // Need to resolve the code duplication. diff --git a/pkg/kubelet/rkt/log.go b/pkg/kubelet/rkt/log.go index 46543820b68..f6f1c059522 100644 --- a/pkg/kubelet/rkt/log.go +++ b/pkg/kubelet/rkt/log.go @@ -26,8 +26,8 @@ import ( "golang.org/x/net/context" rktapi "github.com/coreos/rkt/api/v1alpha" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/util/format" ) @@ -37,7 +37,7 @@ const ( ) // processLines write the lines into stdout in the required format. -func processLines(lines []string, logOptions *api.PodLogOptions, stdout, stderr io.Writer) { +func processLines(lines []string, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) { msgKey := "MESSAGE=" for _, line := range lines { @@ -75,7 +75,7 @@ func processLines(lines []string, logOptions *api.PodLogOptions, stdout, stderr // "100" or "all") to tail the log. // // TODO(yifan): This doesn't work with lkvm stage1 yet. -func (r *Runtime) GetContainerLogs(pod *api.Pod, containerID kubecontainer.ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error { +func (r *Runtime) GetContainerLogs(pod *v1.Pod, containerID kubecontainer.ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) error { id, err := parseContainerID(containerID) if err != nil { return err diff --git a/pkg/kubelet/rkt/rkt.go b/pkg/kubelet/rkt/rkt.go index 5be3f8b9db0..ce797fed97d 100644 --- a/pkg/kubelet/rkt/rkt.go +++ b/pkg/kubelet/rkt/rkt.go @@ -41,7 +41,7 @@ import ( "github.com/golang/glog" "golang.org/x/net/context" "google.golang.org/grpc" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/credentialprovider" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" @@ -185,7 +185,7 @@ var _ kubecontainer.DirectStreamingRuntime = &Runtime{} // TODO(yifan): This duplicates the podGetter in dockertools. type podGetter interface { - GetPodByUID(kubetypes.UID) (*api.Pod, bool) + GetPodByUID(kubetypes.UID) (*v1.Pod, bool) } // cliInterface wrapps the command line calls for testing purpose. @@ -338,7 +338,7 @@ func getRktUUIDFromServiceFileName(filename string) string { } // setIsolators sets the apps' isolators according to the security context and resource spec. -func setIsolators(app *appctypes.App, c *api.Container, ctx *api.SecurityContext) error { +func setIsolators(app *appctypes.App, c *v1.Container, ctx *v1.SecurityContext) error { var isolators []appctypes.Isolator // Capabilities isolators. @@ -374,7 +374,7 @@ func setIsolators(app *appctypes.App, c *api.Container, ctx *api.SecurityContext } // If limit is empty, populate it with request and vice versa. - resources := make(map[api.ResourceName]*resource) + resources := make(map[v1.ResourceName]*resource) for name, quantity := range c.Resources.Limits { resources[name] = &resource{limit: quantity.String(), request: quantity.String()} } @@ -389,13 +389,13 @@ func setIsolators(app *appctypes.App, c *api.Container, ctx *api.SecurityContext for name, res := range resources { switch name { - case api.ResourceCPU: + case v1.ResourceCPU: cpu, err := appctypes.NewResourceCPUIsolator(res.request, res.limit) if err != nil { return err } isolators = append(isolators, cpu.AsIsolator()) - case api.ResourceMemory: + case v1.ResourceMemory: memory, err := appctypes.NewResourceMemoryIsolator(res.request, res.limit) if err != nil { return err @@ -493,7 +493,7 @@ func mergePortMappings(app *appctypes.App, containerPorts []appctypes.Port) { } } -func verifyNonRoot(app *appctypes.App, ctx *api.SecurityContext) error { +func verifyNonRoot(app *appctypes.App, ctx *v1.SecurityContext) error { if ctx != nil && ctx.RunAsNonRoot != nil && *ctx.RunAsNonRoot { if ctx.RunAsUser != nil && *ctx.RunAsUser == 0 { return fmt.Errorf("container's runAsUser breaks non-root policy") @@ -505,7 +505,7 @@ func verifyNonRoot(app *appctypes.App, ctx *api.SecurityContext) error { return nil } -func setSupplementalGIDs(app *appctypes.App, podCtx *api.PodSecurityContext, supplementalGids []int64) { +func setSupplementalGIDs(app *appctypes.App, podCtx *v1.PodSecurityContext, supplementalGids []int64) { if podCtx != nil || len(supplementalGids) != 0 { app.SupplementaryGIDs = app.SupplementaryGIDs[:0] } @@ -523,9 +523,9 @@ func setSupplementalGIDs(app *appctypes.App, podCtx *api.PodSecurityContext, sup } // setApp merges the container spec with the image's manifest. -func setApp(imgManifest *appcschema.ImageManifest, c *api.Container, +func setApp(imgManifest *appcschema.ImageManifest, c *v1.Container, mountPoints []appctypes.MountPoint, containerPorts []appctypes.Port, envs []kubecontainer.EnvVar, - ctx *api.SecurityContext, podCtx *api.PodSecurityContext, supplementalGids []int64) error { + ctx *v1.SecurityContext, podCtx *v1.PodSecurityContext, supplementalGids []int64) error { app := imgManifest.App @@ -598,7 +598,7 @@ func setApp(imgManifest *appcschema.ImageManifest, c *api.Container, } // makePodManifest transforms a kubelet pod spec to the rkt pod manifest. -func (r *Runtime) makePodManifest(pod *api.Pod, podIP string, pullSecrets []api.Secret) (*appcschema.PodManifest, error) { +func (r *Runtime) makePodManifest(pod *v1.Pod, podIP string, pullSecrets []v1.Secret) (*appcschema.PodManifest, error) { manifest := appcschema.BlankPodManifest() ctx, cancel := context.WithTimeout(context.Background(), r.requestTimeout) @@ -732,7 +732,7 @@ func (r *Runtime) podFinishedAt(podUID kubetypes.UID, rktUID string) time.Time { return stat.ModTime() } -func (r *Runtime) makeContainerLogMount(opts *kubecontainer.RunContainerOptions, container *api.Container) (*kubecontainer.Mount, error) { +func (r *Runtime) makeContainerLogMount(opts *kubecontainer.RunContainerOptions, container *v1.Container) (*kubecontainer.Mount, error) { if opts.PodContainerDir == "" || container.TerminationMessagePath == "" { return nil, nil } @@ -767,7 +767,7 @@ func (r *Runtime) makeContainerLogMount(opts *kubecontainer.RunContainerOptions, return &mnt, nil } -func (r *Runtime) newAppcRuntimeApp(pod *api.Pod, podIP string, c api.Container, requiresPrivileged bool, pullSecrets []api.Secret, manifest *appcschema.PodManifest) error { +func (r *Runtime) newAppcRuntimeApp(pod *v1.Pod, podIP string, c v1.Container, requiresPrivileged bool, pullSecrets []v1.Secret, manifest *appcschema.PodManifest) error { var annotations appctypes.Annotations = []appctypes.Annotation{ { Name: *appctypes.MustACIdentifier(k8sRktContainerHashAnno), @@ -912,8 +912,8 @@ func newUnitOption(section, name, value string) *unit.UnitOption { return &unit.UnitOption{Section: section, Name: name, Value: value} } -// apiPodToruntimePod converts an api.Pod to kubelet/container.Pod. -func apiPodToruntimePod(uuid string, pod *api.Pod) *kubecontainer.Pod { +// apiPodToruntimePod converts an v1.Pod to kubelet/container.Pod. +func apiPodToruntimePod(uuid string, pod *v1.Pod) *kubecontainer.Pod { p := &kubecontainer.Pod{ ID: pod.UID, Name: pod.Name, @@ -939,19 +939,19 @@ func serviceFilePath(serviceName string) string { // shouldCreateNetns returns true if: // The pod does not run in host network. And // The pod runs inside a netns created outside of rkt. -func (r *Runtime) shouldCreateNetns(pod *api.Pod) bool { +func (r *Runtime) shouldCreateNetns(pod *v1.Pod) bool { return !kubecontainer.IsHostNetworkPod(pod) && r.networkPlugin.Name() != network.DefaultPluginName } // usesRktHostNetwork returns true if: // The pod runs in the host network. Or // The pod runs inside a netns created outside of rkt. -func (r *Runtime) usesRktHostNetwork(pod *api.Pod) bool { +func (r *Runtime) usesRktHostNetwork(pod *v1.Pod) bool { return kubecontainer.IsHostNetworkPod(pod) || r.shouldCreateNetns(pod) } // generateRunCommand crafts a 'rkt run-prepared' command with necessary parameters. -func (r *Runtime) generateRunCommand(pod *api.Pod, uuid, netnsName string) (string, error) { +func (r *Runtime) generateRunCommand(pod *v1.Pod, uuid, netnsName string) (string, error) { config := *r.config privileged := true @@ -1040,7 +1040,7 @@ func (r *Runtime) generateRunCommand(pod *api.Pod, uuid, netnsName string) (stri return strings.Join(runPrepared, " "), nil } -func (r *Runtime) cleanupPodNetwork(pod *api.Pod) error { +func (r *Runtime) cleanupPodNetwork(pod *v1.Pod) error { glog.V(3).Infof("Calling network plugin %s to tear down pod for %s", r.networkPlugin.Name(), format.Pod(pod)) // No-op if the pod is not running in a created netns. @@ -1083,7 +1083,7 @@ func (r *Runtime) preparePodArgs(manifest *appcschema.PodManifest, manifestFileN return cmds } -func (r *Runtime) getSelinuxContext(opt *api.SELinuxOptions) (string, error) { +func (r *Runtime) getSelinuxContext(opt *v1.SELinuxOptions) (string, error) { selinuxRunner := selinux.NewSELinuxRunner() str, err := selinuxRunner.Getfilecon(r.config.Dir) if err != nil { @@ -1118,7 +1118,7 @@ func (r *Runtime) getSelinuxContext(opt *api.SELinuxOptions) (string, error) { // // On success, it will return a string that represents name of the unit file // and the runtime pod. -func (r *Runtime) preparePod(pod *api.Pod, podIP string, pullSecrets []api.Secret, netnsName string) (string, *kubecontainer.Pod, error) { +func (r *Runtime) preparePod(pod *v1.Pod, podIP string, pullSecrets []v1.Secret, netnsName string) (string, *kubecontainer.Pod, error) { // Generate the appc pod manifest from the k8s pod spec. manifest, err := r.makePodManifest(pod, podIP, pullSecrets) if err != nil { @@ -1230,13 +1230,13 @@ func (r *Runtime) generateEvents(runtimePod *kubecontainer.Pod, reason string, f uuid := utilstrings.ShortenString(id.uuid, 8) switch reason { case "Created": - r.recorder.Eventf(ref, api.EventTypeNormal, events.CreatedContainer, "Created with rkt id %v", uuid) + r.recorder.Eventf(ref, v1.EventTypeNormal, events.CreatedContainer, "Created with rkt id %v", uuid) case "Started": - r.recorder.Eventf(ref, api.EventTypeNormal, events.StartedContainer, "Started with rkt id %v", uuid) + r.recorder.Eventf(ref, v1.EventTypeNormal, events.StartedContainer, "Started with rkt id %v", uuid) case "Failed": - r.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToStartContainer, "Failed to start with rkt id %v with error %v", uuid, failure) + r.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedToStartContainer, "Failed to start with rkt id %v with error %v", uuid, failure) case "Killing": - r.recorder.Eventf(ref, api.EventTypeNormal, events.KillingContainer, "Killing with rkt id %v", uuid) + r.recorder.Eventf(ref, v1.EventTypeNormal, events.KillingContainer, "Killing with rkt id %v", uuid) default: glog.Errorf("rkt: Unexpected event %q", reason) } @@ -1258,7 +1258,7 @@ func netnsPathFromName(netnsName string) string { // one occurred. // // If the pod is running in host network or is running using the no-op plugin, then nothing will be done. -func (r *Runtime) setupPodNetwork(pod *api.Pod) (string, string, error) { +func (r *Runtime) setupPodNetwork(pod *v1.Pod) (string, string, error) { glog.V(3).Infof("Calling network plugin %s to set up pod for %s", r.networkPlugin.Name(), format.Pod(pod)) // No-op if the pod is not running in a created netns. @@ -1298,7 +1298,7 @@ func (r *Runtime) setupPodNetwork(pod *api.Pod) (string, string, error) { // RunPod first creates the unit file for a pod, and then // starts the unit over d-bus. -func (r *Runtime) RunPod(pod *api.Pod, pullSecrets []api.Secret) error { +func (r *Runtime) RunPod(pod *v1.Pod, pullSecrets []v1.Secret) error { glog.V(4).Infof("Rkt starts to run pod: name %q.", format.Pod(pod)) var err error @@ -1322,7 +1322,7 @@ func (r *Runtime) RunPod(pod *api.Pod, pullSecrets []api.Secret) error { continue } if prepareErr != nil { - r.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToCreateContainer, "Failed to create rkt container with error: %v", prepareErr) + r.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedToCreateContainer, "Failed to create rkt container with error: %v", prepareErr) continue } containerID := runtimePod.Containers[i].ID @@ -1369,7 +1369,7 @@ func (r *Runtime) RunPod(pod *api.Pod, pullSecrets []api.Secret) error { return nil } -func (r *Runtime) runPreStopHook(containerID kubecontainer.ContainerID, pod *api.Pod, container *api.Container) error { +func (r *Runtime) runPreStopHook(containerID kubecontainer.ContainerID, pod *v1.Pod, container *v1.Container) error { glog.V(4).Infof("rkt: Running pre-stop hook for container %q of pod %q", container.Name, format.Pod(pod)) msg, err := r.runner.Run(containerID, pod, container, container.Lifecycle.PreStop) if err != nil { @@ -1377,13 +1377,13 @@ func (r *Runtime) runPreStopHook(containerID kubecontainer.ContainerID, pod *api if !ok { glog.Warningf("No ref for container %q", containerID) } else { - r.recorder.Eventf(ref, api.EventTypeWarning, events.FailedPreStopHook, msg) + r.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedPreStopHook, msg) } } return err } -func (r *Runtime) runPostStartHook(containerID kubecontainer.ContainerID, pod *api.Pod, container *api.Container) error { +func (r *Runtime) runPostStartHook(containerID kubecontainer.ContainerID, pod *v1.Pod, container *v1.Container) error { glog.V(4).Infof("rkt: Running post-start hook for container %q of pod %q", container.Name, format.Pod(pod)) cid, err := parseContainerID(containerID) if err != nil { @@ -1419,7 +1419,7 @@ func (r *Runtime) runPostStartHook(containerID kubecontainer.ContainerID, pod *a if !ok { glog.Warningf("No ref for container %q", containerID) } else { - r.recorder.Eventf(ref, api.EventTypeWarning, events.FailedPostStartHook, msg) + r.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedPostStartHook, msg) } } return err @@ -1432,7 +1432,7 @@ const ( lifecyclePreStopHook lifecycleHookType = "pre-stop" ) -func (r *Runtime) runLifecycleHooks(pod *api.Pod, runtimePod *kubecontainer.Pod, typ lifecycleHookType) error { +func (r *Runtime) runLifecycleHooks(pod *v1.Pod, runtimePod *kubecontainer.Pod, typ lifecycleHookType) error { var wg sync.WaitGroup var errlist []error errCh := make(chan error, len(pod.Spec.Containers)) @@ -1440,7 +1440,7 @@ func (r *Runtime) runLifecycleHooks(pod *api.Pod, runtimePod *kubecontainer.Pod, wg.Add(len(pod.Spec.Containers)) for i, c := range pod.Spec.Containers { - var hookFunc func(kubecontainer.ContainerID, *api.Pod, *api.Container) error + var hookFunc func(kubecontainer.ContainerID, *v1.Pod, *v1.Container) error switch typ { case lifecyclePostStartHook: @@ -1601,7 +1601,7 @@ func (r *Runtime) GetPods(all bool) ([]*kubecontainer.Pod, error) { return result, nil } -func getPodTerminationGracePeriodInSecond(pod *api.Pod) int64 { +func getPodTerminationGracePeriodInSecond(pod *v1.Pod) int64 { var gracePeriod int64 switch { case pod.DeletionGracePeriodSeconds != nil: @@ -1615,7 +1615,7 @@ func getPodTerminationGracePeriodInSecond(pod *api.Pod) int64 { return gracePeriod } -func (r *Runtime) waitPreStopHooks(pod *api.Pod, runningPod *kubecontainer.Pod) { +func (r *Runtime) waitPreStopHooks(pod *v1.Pod, runningPod *kubecontainer.Pod) { gracePeriod := getPodTerminationGracePeriodInSecond(pod) done := make(chan struct{}) @@ -1635,7 +1635,7 @@ func (r *Runtime) waitPreStopHooks(pod *api.Pod, runningPod *kubecontainer.Pod) // KillPod invokes 'systemctl kill' to kill the unit that runs the pod. // TODO: add support for gracePeriodOverride which is used in eviction scenarios -func (r *Runtime) KillPod(pod *api.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) error { +func (r *Runtime) KillPod(pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) error { glog.V(4).Infof("Rkt is killing pod: name %q.", runningPod.Name) if len(runningPod.Containers) == 0 { @@ -1706,7 +1706,7 @@ func (r *Runtime) Status() (*kubecontainer.RuntimeStatus, error) { } // SyncPod syncs the running pod to match the specified desired pod. -func (r *Runtime) SyncPod(pod *api.Pod, _ api.PodStatus, podStatus *kubecontainer.PodStatus, pullSecrets []api.Secret, backOff *flowcontrol.Backoff) (result kubecontainer.PodSyncResult) { +func (r *Runtime) SyncPod(pod *v1.Pod, _ v1.PodStatus, podStatus *kubecontainer.PodStatus, pullSecrets []v1.Secret, backOff *flowcontrol.Backoff) (result kubecontainer.PodSyncResult) { var err error defer func() { if err != nil { @@ -1748,7 +1748,7 @@ func (r *Runtime) SyncPod(pod *api.Pod, _ api.PodStatus, podStatus *kubecontaine } liveness, found := r.livenessManager.Get(c.ID) - if found && liveness != proberesults.Success && pod.Spec.RestartPolicy != api.RestartPolicyNever { + if found && liveness != proberesults.Success && pod.Spec.RestartPolicy != v1.RestartPolicyNever { glog.Infof("Pod %q container %q is unhealthy, it will be killed and re-created.", format.Pod(pod), container.Name) restartPod = true break @@ -1969,16 +1969,14 @@ func (r *Runtime) cleanupPodNetworkFromServiceFile(serviceFilePath string) error if err != nil { return err } - return r.cleanupPodNetwork(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + return r.cleanupPodNetwork(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: kubetypes.UID(id), Name: name, Namespace: namespace, }, - Spec: api.PodSpec{ - SecurityContext: &api.PodSecurityContext{ - HostNetwork: hostnetwork, - }, + Spec: v1.PodSpec{ + HostNetwork: hostnetwork, }, }) } @@ -2260,7 +2258,7 @@ func populateContainerStatus(pod rktapi.Pod, app rktapi.App, runtimeApp appcsche ExitCode: int(app.ExitCode), // By default, the version returned by rkt API service will be "latest" if not specified. Image: fmt.Sprintf("%s:%s", app.Image.Name, app.Image.Version), - ImageID: "rkt://" + app.Image.Id, // TODO(yifan): Add the prefix only in api.PodStatus. + ImageID: "rkt://" + app.Image.Id, // TODO(yifan): Add the prefix only in v1.PodStatus. Hash: hashNum, // TODO(yifan): Note that now all apps share the same restart count, this might // change once apps don't share the same lifecycle. diff --git a/pkg/kubelet/rkt/rkt_test.go b/pkg/kubelet/rkt/rkt_test.go index 472ccc697f2..f17e0c227d8 100644 --- a/pkg/kubelet/rkt/rkt_test.go +++ b/pkg/kubelet/rkt/rkt_test.go @@ -31,8 +31,8 @@ import ( rktapi "github.com/coreos/rkt/api/v1alpha" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" containertesting "k8s.io/kubernetes/pkg/kubelet/container/testing" kubetesting "k8s.io/kubernetes/pkg/kubelet/container/testing" @@ -967,19 +967,19 @@ func TestSetApp(t *testing.T) { fsgid := int64(3) tests := []struct { - container *api.Container + container *v1.Container mountPoints []appctypes.MountPoint containerPorts []appctypes.Port envs []kubecontainer.EnvVar - ctx *api.SecurityContext - podCtx *api.PodSecurityContext + ctx *v1.SecurityContext + podCtx *v1.PodSecurityContext supplementalGids []int64 expect *appctypes.App err error }{ // Nothing should change, but the "User" and "Group" should be filled. { - container: &api.Container{}, + container: &v1.Container{}, mountPoints: []appctypes.MountPoint{}, containerPorts: []appctypes.Port{}, envs: []kubecontainer.EnvVar{}, @@ -992,11 +992,11 @@ func TestSetApp(t *testing.T) { // error verifying non-root. { - container: &api.Container{}, + container: &v1.Container{}, mountPoints: []appctypes.MountPoint{}, containerPorts: []appctypes.Port{}, envs: []kubecontainer.EnvVar{}, - ctx: &api.SecurityContext{ + ctx: &v1.SecurityContext{ RunAsNonRoot: &runAsNonRootTrue, RunAsUser: &rootUser, }, @@ -1008,7 +1008,7 @@ func TestSetApp(t *testing.T) { // app's args should be changed. { - container: &api.Container{ + container: &v1.Container{ Args: []string{"foo"}, }, mountPoints: []appctypes.MountPoint{}, @@ -1044,12 +1044,12 @@ func TestSetApp(t *testing.T) { // app should be changed. { - container: &api.Container{ + container: &v1.Container{ Command: []string{"/bin/bar", "$(env-bar)"}, WorkingDir: tmpDir, - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{"cpu": resource.MustParse("50m"), "memory": resource.MustParse("50M")}, - Requests: api.ResourceList{"cpu": resource.MustParse("5m"), "memory": resource.MustParse("5M")}, + Resources: v1.ResourceRequirements{ + Limits: v1.ResourceList{"cpu": resource.MustParse("50m"), "memory": resource.MustParse("50M")}, + Requests: v1.ResourceList{"cpu": resource.MustParse("5m"), "memory": resource.MustParse("5M")}, }, }, mountPoints: []appctypes.MountPoint{ @@ -1061,15 +1061,15 @@ func TestSetApp(t *testing.T) { envs: []kubecontainer.EnvVar{ {Name: "env-bar", Value: "foo"}, }, - ctx: &api.SecurityContext{ - Capabilities: &api.Capabilities{ - Add: []api.Capability{"CAP_SYS_CHROOT", "CAP_SYS_BOOT"}, - Drop: []api.Capability{"CAP_SETUID", "CAP_SETGID"}, + ctx: &v1.SecurityContext{ + Capabilities: &v1.Capabilities{ + Add: []v1.Capability{"CAP_SYS_CHROOT", "CAP_SYS_BOOT"}, + Drop: []v1.Capability{"CAP_SETUID", "CAP_SETGID"}, }, RunAsUser: &nonRootUser, RunAsNonRoot: &runAsNonRootTrue, }, - podCtx: &api.PodSecurityContext{ + podCtx: &v1.PodSecurityContext{ SupplementalGroups: []int64{1, 2}, FSGroup: &fsgid, }, @@ -1103,14 +1103,14 @@ func TestSetApp(t *testing.T) { // app should be changed. (env, mounts, ports, are overrided). { - container: &api.Container{ + container: &v1.Container{ Name: "hello-world", Command: []string{"/bin/hello", "$(env-foo)"}, Args: []string{"hello", "world", "$(env-bar)"}, WorkingDir: tmpDir, - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{"cpu": resource.MustParse("50m")}, - Requests: api.ResourceList{"memory": resource.MustParse("5M")}, + Resources: v1.ResourceRequirements{ + Limits: v1.ResourceList{"cpu": resource.MustParse("50m")}, + Requests: v1.ResourceList{"memory": resource.MustParse("5M")}, }, }, mountPoints: []appctypes.MountPoint{ @@ -1123,15 +1123,15 @@ func TestSetApp(t *testing.T) { {Name: "env-foo", Value: "foo"}, {Name: "env-bar", Value: "bar"}, }, - ctx: &api.SecurityContext{ - Capabilities: &api.Capabilities{ - Add: []api.Capability{"CAP_SYS_CHROOT", "CAP_SYS_BOOT"}, - Drop: []api.Capability{"CAP_SETUID", "CAP_SETGID"}, + ctx: &v1.SecurityContext{ + Capabilities: &v1.Capabilities{ + Add: []v1.Capability{"CAP_SYS_CHROOT", "CAP_SYS_BOOT"}, + Drop: []v1.Capability{"CAP_SETUID", "CAP_SETGID"}, }, RunAsUser: &nonRootUser, RunAsNonRoot: &runAsNonRootTrue, }, - podCtx: &api.PodSecurityContext{ + podCtx: &v1.PodSecurityContext{ SupplementalGroups: []int64{1, 2}, FSGroup: &fsgid, }, @@ -1188,7 +1188,7 @@ func TestGenerateRunCommand(t *testing.T) { tests := []struct { networkPlugin network.NetworkPlugin - pod *api.Pod + pod *v1.Pod uuid string netnsName string @@ -1202,12 +1202,12 @@ func TestGenerateRunCommand(t *testing.T) { // Case #0, returns error. { kubenet.NewPlugin("/tmp"), - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-name-foo", }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "container-foo"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Name: "container-foo"}}, }, }, "rkt-uuid-foo", @@ -1221,12 +1221,12 @@ func TestGenerateRunCommand(t *testing.T) { // Case #1, returns no dns, with private-net. { kubenet.NewPlugin("/tmp"), - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-name-foo", }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "container-foo"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Name: "container-foo"}}, }, }, "rkt-uuid-foo", @@ -1240,15 +1240,14 @@ func TestGenerateRunCommand(t *testing.T) { // Case #2, returns no dns, with host-net. { kubenet.NewPlugin("/tmp"), - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-name-foo", }, - Spec: api.PodSpec{ - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, - Containers: []api.Container{{Name: "container-foo"}}, + Spec: v1.PodSpec{ + HostNetwork: true, + + Containers: []v1.Container{{Name: "container-foo"}}, }, }, "rkt-uuid-foo", @@ -1262,15 +1261,14 @@ func TestGenerateRunCommand(t *testing.T) { // Case #3, returns dns, dns searches, with private-net. { kubenet.NewPlugin("/tmp"), - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-name-foo", }, - Spec: api.PodSpec{ - SecurityContext: &api.PodSecurityContext{ - HostNetwork: false, - }, - Containers: []api.Container{{Name: "container-foo"}}, + Spec: v1.PodSpec{ + HostNetwork: false, + + Containers: []v1.Container{{Name: "container-foo"}}, }, }, "rkt-uuid-foo", @@ -1284,15 +1282,14 @@ func TestGenerateRunCommand(t *testing.T) { // Case #4, returns no dns, dns searches, with host-network. { kubenet.NewPlugin("/tmp"), - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-name-foo", }, - Spec: api.PodSpec{ - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, - Containers: []api.Container{{Name: "container-foo"}}, + Spec: v1.PodSpec{ + HostNetwork: true, + + Containers: []v1.Container{{Name: "container-foo"}}, }, }, "rkt-uuid-foo", @@ -1306,12 +1303,12 @@ func TestGenerateRunCommand(t *testing.T) { // Case #5, with no-op plugin, returns --net=rkt.kubernetes.io, with dns and dns search. { &network.NoopNetworkPlugin{}, - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-name-foo", }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "container-foo"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Name: "container-foo"}}, }, }, "rkt-uuid-foo", @@ -1325,14 +1322,14 @@ func TestGenerateRunCommand(t *testing.T) { // Case #6, if all containers are privileged, the result should have 'insecure-options=all-run' { kubenet.NewPlugin("/tmp"), - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-name-foo", }, - Spec: api.PodSpec{ - Containers: []api.Container{ - {Name: "container-foo", SecurityContext: &api.SecurityContext{Privileged: &boolTrue}}, - {Name: "container-bar", SecurityContext: &api.SecurityContext{Privileged: &boolTrue}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{ + {Name: "container-foo", SecurityContext: &v1.SecurityContext{Privileged: &boolTrue}}, + {Name: "container-bar", SecurityContext: &v1.SecurityContext{Privileged: &boolTrue}}, }, }, }, @@ -1347,14 +1344,14 @@ func TestGenerateRunCommand(t *testing.T) { // Case #7, if not all containers are privileged, the result should not have 'insecure-options=all-run' { kubenet.NewPlugin("/tmp"), - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-name-foo", }, - Spec: api.PodSpec{ - Containers: []api.Container{ - {Name: "container-foo", SecurityContext: &api.SecurityContext{Privileged: &boolTrue}}, - {Name: "container-bar", SecurityContext: &api.SecurityContext{Privileged: &boolFalse}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{ + {Name: "container-foo", SecurityContext: &v1.SecurityContext{Privileged: &boolTrue}}, + {Name: "container-bar", SecurityContext: &v1.SecurityContext{Privileged: &boolFalse}}, }, }, }, @@ -1409,7 +1406,7 @@ func TestLifeCycleHooks(t *testing.T) { } tests := []struct { - pod *api.Pod + pod *v1.Pod runtimePod *kubecontainer.Pod postStartRuns []string preStopRuns []string @@ -1417,14 +1414,14 @@ func TestLifeCycleHooks(t *testing.T) { }{ { // Case 0, container without any hooks. - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-1", Namespace: "ns-1", UID: "uid-1", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Name: "container-name-1"}, }, }, @@ -1440,43 +1437,43 @@ func TestLifeCycleHooks(t *testing.T) { }, { // Case 1, containers with post-start and pre-stop hooks. - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-1", Namespace: "ns-1", UID: "uid-1", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "container-name-1", - Lifecycle: &api.Lifecycle{ - PostStart: &api.Handler{ - Exec: &api.ExecAction{}, + Lifecycle: &v1.Lifecycle{ + PostStart: &v1.Handler{ + Exec: &v1.ExecAction{}, }, }, }, { Name: "container-name-2", - Lifecycle: &api.Lifecycle{ - PostStart: &api.Handler{ - HTTPGet: &api.HTTPGetAction{}, + Lifecycle: &v1.Lifecycle{ + PostStart: &v1.Handler{ + HTTPGet: &v1.HTTPGetAction{}, }, }, }, { Name: "container-name-3", - Lifecycle: &api.Lifecycle{ - PreStop: &api.Handler{ - Exec: &api.ExecAction{}, + Lifecycle: &v1.Lifecycle{ + PreStop: &v1.Handler{ + Exec: &v1.ExecAction{}, }, }, }, { Name: "container-name-4", - Lifecycle: &api.Lifecycle{ - PreStop: &api.Handler{ - HTTPGet: &api.HTTPGetAction{}, + Lifecycle: &v1.Lifecycle{ + PreStop: &v1.Handler{ + HTTPGet: &v1.HTTPGetAction{}, }, }, }, @@ -1515,19 +1512,19 @@ func TestLifeCycleHooks(t *testing.T) { }, { // Case 2, one container with invalid hooks. - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-1", Namespace: "ns-1", UID: "uid-1", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "container-name-1", - Lifecycle: &api.Lifecycle{ - PostStart: &api.Handler{}, - PreStop: &api.Handler{}, + Lifecycle: &v1.Lifecycle{ + PostStart: &v1.Handler{}, + PreStop: &v1.Handler{}, }, }, }, @@ -1543,7 +1540,7 @@ func TestLifeCycleHooks(t *testing.T) { }, []string{}, []string{}, - errors.NewAggregate([]error{fmt.Errorf("Invalid handler: %v", &api.Handler{})}), + errors.NewAggregate([]error{fmt.Errorf("Invalid handler: %v", &v1.Handler{})}), }, } @@ -1618,7 +1615,7 @@ func TestGarbageCollect(t *testing.T) { tests := []struct { gcPolicy kubecontainer.ContainerGCPolicy - apiPods []*api.Pod + apiPods []*v1.Pod pods []*rktapi.Pod serviceFilesOnDisk []string expectedCommands []string @@ -1634,11 +1631,11 @@ func TestGarbageCollect(t *testing.T) { MinAge: 0, MaxContainers: 0, }, - []*api.Pod{ - {ObjectMeta: api.ObjectMeta{UID: "pod-uid-1"}}, - {ObjectMeta: api.ObjectMeta{UID: "pod-uid-2"}}, - {ObjectMeta: api.ObjectMeta{UID: "pod-uid-3"}}, - {ObjectMeta: api.ObjectMeta{UID: "pod-uid-4"}}, + []*v1.Pod{ + {ObjectMeta: v1.ObjectMeta{UID: "pod-uid-1"}}, + {ObjectMeta: v1.ObjectMeta{UID: "pod-uid-2"}}, + {ObjectMeta: v1.ObjectMeta{UID: "pod-uid-3"}}, + {ObjectMeta: v1.ObjectMeta{UID: "pod-uid-4"}}, }, []*rktapi.Pod{ { @@ -1718,10 +1715,10 @@ func TestGarbageCollect(t *testing.T) { MinAge: 0, MaxContainers: 1, }, - []*api.Pod{ - {ObjectMeta: api.ObjectMeta{UID: "pod-uid-0"}}, - {ObjectMeta: api.ObjectMeta{UID: "pod-uid-1"}}, - {ObjectMeta: api.ObjectMeta{UID: "pod-uid-2"}}, + []*v1.Pod{ + {ObjectMeta: v1.ObjectMeta{UID: "pod-uid-0"}}, + {ObjectMeta: v1.ObjectMeta{UID: "pod-uid-1"}}, + {ObjectMeta: v1.ObjectMeta{UID: "pod-uid-2"}}, }, []*rktapi.Pod{ { @@ -1817,7 +1814,7 @@ func TestGarbageCollect(t *testing.T) { ctrl.Finish() fakeOS.Removes = []string{} fs.resetFailedUnits = []string{} - getter.pods = make(map[kubetypes.UID]*api.Pod) + getter.pods = make(map[kubetypes.UID]*v1.Pod) } } @@ -1836,13 +1833,13 @@ func TestMakePodManifestAnnotations(t *testing.T) { r := &Runtime{apisvc: fr, systemd: fs} testCases := []struct { - in *api.Pod + in *v1.Pod out *appcschema.PodManifest outerr error }{ { - in: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + in: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "uid-1", Name: "name-1", Namespace: "namespace-1", @@ -1889,7 +1886,7 @@ func TestMakePodManifestAnnotations(t *testing.T) { for i, testCase := range testCases { hint := fmt.Sprintf("case #%d", i) - result, err := r.makePodManifest(testCase.in, "", []api.Secret{}) + result, err := r.makePodManifest(testCase.in, "", []v1.Secret{}) assert.Equal(t, testCase.outerr, err, hint) if err == nil { sort.Sort(annotationsByName(result.Annotations)) diff --git a/pkg/kubelet/runonce.go b/pkg/kubelet/runonce.go index 9ad3c476af3..3b73a9fe7c0 100644 --- a/pkg/kubelet/runonce.go +++ b/pkg/kubelet/runonce.go @@ -22,7 +22,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/kubelet/util/format" @@ -36,7 +36,7 @@ const ( ) type RunPodResult struct { - Pod *api.Pod + Pod *v1.Pod Err error } @@ -66,9 +66,9 @@ func (kl *Kubelet) RunOnce(updates <-chan kubetypes.PodUpdate) ([]RunPodResult, } // runOnce runs a given set of pods and returns their status. -func (kl *Kubelet) runOnce(pods []*api.Pod, retryDelay time.Duration) (results []RunPodResult, err error) { +func (kl *Kubelet) runOnce(pods []*v1.Pod, retryDelay time.Duration) (results []RunPodResult, err error) { ch := make(chan RunPodResult) - admitted := []*api.Pod{} + admitted := []*v1.Pod{} for _, pod := range pods { // Check if we can admit the pod. if ok, reason, message := kl.canAdmitPod(admitted, pod); !ok { @@ -78,7 +78,7 @@ func (kl *Kubelet) runOnce(pods []*api.Pod, retryDelay time.Duration) (results [ } admitted = append(admitted, pod) - go func(pod *api.Pod) { + go func(pod *v1.Pod) { err := kl.runPod(pod, retryDelay) ch <- RunPodResult{pod, err} }(pod) @@ -105,7 +105,7 @@ func (kl *Kubelet) runOnce(pods []*api.Pod, retryDelay time.Duration) (results [ } // runPod runs a single pod and wait until all containers are running. -func (kl *Kubelet) runPod(pod *api.Pod, retryDelay time.Duration) error { +func (kl *Kubelet) runPod(pod *v1.Pod, retryDelay time.Duration) error { delay := retryDelay retry := 0 for { @@ -145,7 +145,7 @@ func (kl *Kubelet) runPod(pod *api.Pod, retryDelay time.Duration) error { } // isPodRunning returns true if all containers of a manifest are running. -func (kl *Kubelet) isPodRunning(pod *api.Pod, status *kubecontainer.PodStatus) bool { +func (kl *Kubelet) isPodRunning(pod *v1.Pod, status *kubecontainer.PodStatus) bool { for _, c := range pod.Spec.Containers { cs := status.FindContainerStatusByName(c.Name) if cs == nil || cs.State != kubecontainer.ContainerStateRunning { diff --git a/pkg/kubelet/runonce_test.go b/pkg/kubelet/runonce_test.go index 4e7de76def7..f212089fda2 100644 --- a/pkg/kubelet/runonce_test.go +++ b/pkg/kubelet/runonce_test.go @@ -23,9 +23,9 @@ import ( cadvisorapi "github.com/google/cadvisor/info/v1" cadvisorapiv2 "github.com/google/cadvisor/info/v2" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/record" cadvisortest "k8s.io/kubernetes/pkg/kubelet/cadvisor/testing" "k8s.io/kubernetes/pkg/kubelet/cm" @@ -109,13 +109,13 @@ func TestRunOnce(t *testing.T) { // TODO: Factor out "StatsProvider" from Kubelet so we don't have a cyclic dependency volumeStatsAggPeriod := time.Second * 10 kb.resourceAnalyzer = stats.NewResourceAnalyzer(kb, volumeStatsAggPeriod, kb.containerRuntime) - nodeRef := &api.ObjectReference{ + nodeRef := &v1.ObjectReference{ Kind: "Node", Name: string(kb.nodeName), UID: types.UID(kb.nodeName), Namespace: "", } - fakeKillPodFunc := func(pod *api.Pod, podStatus api.PodStatus, gracePeriodOverride *int64) error { + fakeKillPodFunc := func(pod *v1.Pod, podStatus v1.PodStatus, gracePeriodOverride *int64) error { return nil } evictionManager, evictionAdmitHandler, err := eviction.NewManager(kb.resourceAnalyzer, eviction.Config{}, fakeKillPodFunc, nil, kb.recorder, nodeRef, kb.clock) @@ -128,15 +128,15 @@ func TestRunOnce(t *testing.T) { t.Errorf("Failed to init data dirs: %v", err) } - pods := []*api.Pod{ + pods := []*v1.Pod{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Name: "bar"}, }, }, diff --git a/pkg/kubelet/server/BUILD b/pkg/kubelet/server/BUILD index b6bc30809ab..f5f619779ef 100644 --- a/pkg/kubelet/server/BUILD +++ b/pkg/kubelet/server/BUILD @@ -23,7 +23,7 @@ go_library( "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", "//pkg/api/v1:go_default_library", - "//pkg/api/validation:go_default_library", + "//pkg/api/v1/validation:go_default_library", "//pkg/auth/authenticator:go_default_library", "//pkg/auth/authorizer:go_default_library", "//pkg/auth/user:go_default_library", @@ -61,6 +61,7 @@ go_test( deps = [ "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/auth/authorizer:go_default_library", "//pkg/auth/user:go_default_library", "//pkg/kubelet/cm:go_default_library", diff --git a/pkg/kubelet/server/server.go b/pkg/kubelet/server/server.go index ededae92e3c..a070393500a 100644 --- a/pkg/kubelet/server/server.go +++ b/pkg/kubelet/server/server.go @@ -39,7 +39,7 @@ import ( apierrs "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/api/validation" + "k8s.io/kubernetes/pkg/api/v1/validation" "k8s.io/kubernetes/pkg/auth/authenticator" "k8s.io/kubernetes/pkg/auth/authorizer" "k8s.io/kubernetes/pkg/healthz" @@ -162,19 +162,19 @@ type HostInterface interface { GetContainerInfoV2(name string, options cadvisorapiv2.RequestOptions) (map[string]cadvisorapiv2.ContainerInfo, error) GetRawContainerInfo(containerName string, req *cadvisorapi.ContainerInfoRequest, subcontainers bool) (map[string]*cadvisorapi.ContainerInfo, error) GetCachedMachineInfo() (*cadvisorapi.MachineInfo, error) - GetPods() []*api.Pod - GetRunningPods() ([]*api.Pod, error) - GetPodByName(namespace, name string) (*api.Pod, bool) + GetPods() []*v1.Pod + GetRunningPods() ([]*v1.Pod, error) + GetPodByName(namespace, name string) (*v1.Pod, bool) RunInContainer(name string, uid types.UID, container string, cmd []string) ([]byte, error) ExecInContainer(name string, uid types.UID, container string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size, timeout time.Duration) error AttachContainer(name string, uid types.UID, container string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size) error - GetKubeletContainerLogs(podFullName, containerName string, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error + GetKubeletContainerLogs(podFullName, containerName string, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) error ServeLogs(w http.ResponseWriter, req *http.Request) PortForward(name string, uid types.UID, port uint16, stream io.ReadWriteCloser) error StreamingConnectionIdleTimeout() time.Duration ResyncInterval() time.Duration GetHostname() string - GetNode() (*api.Node, error) + GetNode() (*v1.Node, error) GetNodeConfig() cm.NodeConfig LatestLoopEntryTime() time.Time ImagesFsInfo() (cadvisorapiv2.FsInfo, error) @@ -456,7 +456,7 @@ func (s *Server) getContainerLogs(request *restful.Request, response *restful.Re } } // container logs on the kubelet are locked to the v1 API version of PodLogOptions - logOptions := &api.PodLogOptions{} + logOptions := &v1.PodLogOptions{} if err := api.ParameterCodec.DecodeParameters(query, v1.SchemeGroupVersion, logOptions); err != nil { response.WriteError(http.StatusBadRequest, fmt.Errorf(`{"message": "Unable to decode query."}`)) return @@ -511,17 +511,17 @@ func (s *Server) getContainerLogs(request *restful.Request, response *restful.Re } } -// encodePods creates an api.PodList object from pods and returns the encoded +// encodePods creates an v1.PodList object from pods and returns the encoded // PodList. -func encodePods(pods []*api.Pod) (data []byte, err error) { - podList := new(api.PodList) +func encodePods(pods []*v1.Pod) (data []byte, err error) { + podList := new(v1.PodList) for _, pod := range pods { podList.Items = append(podList.Items, *pod) } // TODO: this needs to be parameterized to the kubelet, not hardcoded. Depends on Kubelet // as API server refactor. // TODO: Locked to v1, needs to be made generic - codec := api.Codecs.LegacyCodec(unversioned.GroupVersion{Group: api.GroupName, Version: "v1"}) + codec := api.Codecs.LegacyCodec(unversioned.GroupVersion{Group: v1.GroupName, Version: "v1"}) return runtime.Encode(codec, podList) } diff --git a/pkg/kubelet/server/server_test.go b/pkg/kubelet/server/server_test.go index 648eaa30d18..99bf3e335d4 100644 --- a/pkg/kubelet/server/server_test.go +++ b/pkg/kubelet/server/server_test.go @@ -40,6 +40,7 @@ import ( "github.com/stretchr/testify/require" "k8s.io/kubernetes/pkg/api" apierrs "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/auth/authorizer" "k8s.io/kubernetes/pkg/auth/user" "k8s.io/kubernetes/pkg/kubelet/cm" @@ -62,18 +63,18 @@ const ( ) type fakeKubelet struct { - podByNameFunc func(namespace, name string) (*api.Pod, bool) + podByNameFunc func(namespace, name string) (*v1.Pod, bool) containerInfoFunc func(podFullName string, uid types.UID, containerName string, req *cadvisorapi.ContainerInfoRequest) (*cadvisorapi.ContainerInfo, error) rawInfoFunc func(query *cadvisorapi.ContainerInfoRequest) (map[string]*cadvisorapi.ContainerInfo, error) machineInfoFunc func() (*cadvisorapi.MachineInfo, error) - podsFunc func() []*api.Pod - runningPodsFunc func() ([]*api.Pod, error) + podsFunc func() []*v1.Pod + runningPodsFunc func() ([]*v1.Pod, error) logFunc func(w http.ResponseWriter, req *http.Request) runFunc func(podFullName string, uid types.UID, containerName string, cmd []string) ([]byte, error) execFunc func(pod string, uid types.UID, container string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool) error attachFunc func(pod string, uid types.UID, container string, in io.Reader, out, err io.WriteCloser, tty bool) error portForwardFunc func(name string, uid types.UID, port uint16, stream io.ReadWriteCloser) error - containerLogsFunc func(podFullName, containerName string, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error + containerLogsFunc func(podFullName, containerName string, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) error streamingConnectionIdleTimeoutFunc func() time.Duration hostnameFunc func() string resyncInterval time.Duration @@ -90,7 +91,7 @@ func (fk *fakeKubelet) LatestLoopEntryTime() time.Time { return fk.loopEntryTime } -func (fk *fakeKubelet) GetPodByName(namespace, name string) (*api.Pod, bool) { +func (fk *fakeKubelet) GetPodByName(namespace, name string) (*v1.Pod, bool) { return fk.podByNameFunc(namespace, name) } @@ -106,11 +107,11 @@ func (fk *fakeKubelet) GetCachedMachineInfo() (*cadvisorapi.MachineInfo, error) return fk.machineInfoFunc() } -func (fk *fakeKubelet) GetPods() []*api.Pod { +func (fk *fakeKubelet) GetPods() []*v1.Pod { return fk.podsFunc() } -func (fk *fakeKubelet) GetRunningPods() ([]*api.Pod, error) { +func (fk *fakeKubelet) GetRunningPods() ([]*v1.Pod, error) { return fk.runningPodsFunc() } @@ -118,7 +119,7 @@ func (fk *fakeKubelet) ServeLogs(w http.ResponseWriter, req *http.Request) { fk.logFunc(w, req) } -func (fk *fakeKubelet) GetKubeletContainerLogs(podFullName, containerName string, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error { +func (fk *fakeKubelet) GetKubeletContainerLogs(podFullName, containerName string, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) error { return fk.containerLogsFunc(podFullName, containerName, logOptions, stdout, stderr) } @@ -173,7 +174,7 @@ func (_ *fakeKubelet) RootFsInfo() (cadvisorapiv2.FsInfo, error) { return cadvisorapiv2.FsInfo{}, fmt.Errorf("Unsupport Operation RootFsInfo") } -func (_ *fakeKubelet) GetNode() (*api.Node, error) { return nil, nil } +func (_ *fakeKubelet) GetNode() (*v1.Node, error) { return nil, nil } func (_ *fakeKubelet) GetNodeConfig() cm.NodeConfig { return cm.NodeConfig{} } func (fk *fakeKubelet) ListVolumesForPod(podUID types.UID) (map[string]volume.Volume, bool) { @@ -210,9 +211,9 @@ func newServerTest() *serverTestFramework { hostnameFunc: func() string { return "127.0.0.1" }, - podByNameFunc: func(namespace, name string) (*api.Pod, bool) { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ + podByNameFunc: func(namespace, name string) (*v1.Pod, bool) { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: namespace, Name: name, UID: testUID, @@ -902,14 +903,14 @@ func assertHealthIsOk(t *testing.T, httpURL string) { } func setPodByNameFunc(fw *serverTestFramework, namespace, pod, container string) { - fw.fakeKubelet.podByNameFunc = func(namespace, name string) (*api.Pod, bool) { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ + fw.fakeKubelet.podByNameFunc = func(namespace, name string) (*v1.Pod, bool) { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: namespace, Name: pod, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: container, }, @@ -919,8 +920,8 @@ func setPodByNameFunc(fw *serverTestFramework, namespace, pod, container string) } } -func setGetContainerLogsFunc(fw *serverTestFramework, t *testing.T, expectedPodName, expectedContainerName string, expectedLogOptions *api.PodLogOptions, output string) { - fw.fakeKubelet.containerLogsFunc = func(podFullName, containerName string, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error { +func setGetContainerLogsFunc(fw *serverTestFramework, t *testing.T, expectedPodName, expectedContainerName string, expectedLogOptions *v1.PodLogOptions, output string) { + fw.fakeKubelet.containerLogsFunc = func(podFullName, containerName string, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) error { if podFullName != expectedPodName { t.Errorf("expected %s, got %s", expectedPodName, podFullName) } @@ -946,7 +947,7 @@ func TestContainerLogs(t *testing.T) { expectedPodName := getPodName(podName, podNamespace) expectedContainerName := "baz" setPodByNameFunc(fw, podNamespace, podName, expectedContainerName) - setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &api.PodLogOptions{}, output) + setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &v1.PodLogOptions{}, output) resp, err := http.Get(fw.testHTTPServer.URL + "/containerLogs/" + podNamespace + "/" + podName + "/" + expectedContainerName) if err != nil { t.Errorf("Got error GETing: %v", err) @@ -973,7 +974,7 @@ func TestContainerLogsWithLimitBytes(t *testing.T) { expectedContainerName := "baz" bytes := int64(3) setPodByNameFunc(fw, podNamespace, podName, expectedContainerName) - setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &api.PodLogOptions{LimitBytes: &bytes}, output) + setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &v1.PodLogOptions{LimitBytes: &bytes}, output) resp, err := http.Get(fw.testHTTPServer.URL + "/containerLogs/" + podNamespace + "/" + podName + "/" + expectedContainerName + "?limitBytes=3") if err != nil { t.Errorf("Got error GETing: %v", err) @@ -1000,7 +1001,7 @@ func TestContainerLogsWithTail(t *testing.T) { expectedContainerName := "baz" expectedTail := int64(5) setPodByNameFunc(fw, podNamespace, podName, expectedContainerName) - setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &api.PodLogOptions{TailLines: &expectedTail}, output) + setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &v1.PodLogOptions{TailLines: &expectedTail}, output) resp, err := http.Get(fw.testHTTPServer.URL + "/containerLogs/" + podNamespace + "/" + podName + "/" + expectedContainerName + "?tailLines=5") if err != nil { t.Errorf("Got error GETing: %v", err) @@ -1027,7 +1028,7 @@ func TestContainerLogsWithLegacyTail(t *testing.T) { expectedContainerName := "baz" expectedTail := int64(5) setPodByNameFunc(fw, podNamespace, podName, expectedContainerName) - setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &api.PodLogOptions{TailLines: &expectedTail}, output) + setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &v1.PodLogOptions{TailLines: &expectedTail}, output) resp, err := http.Get(fw.testHTTPServer.URL + "/containerLogs/" + podNamespace + "/" + podName + "/" + expectedContainerName + "?tail=5") if err != nil { t.Errorf("Got error GETing: %v", err) @@ -1053,7 +1054,7 @@ func TestContainerLogsWithTailAll(t *testing.T) { expectedPodName := getPodName(podName, podNamespace) expectedContainerName := "baz" setPodByNameFunc(fw, podNamespace, podName, expectedContainerName) - setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &api.PodLogOptions{}, output) + setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &v1.PodLogOptions{}, output) resp, err := http.Get(fw.testHTTPServer.URL + "/containerLogs/" + podNamespace + "/" + podName + "/" + expectedContainerName + "?tail=all") if err != nil { t.Errorf("Got error GETing: %v", err) @@ -1079,7 +1080,7 @@ func TestContainerLogsWithInvalidTail(t *testing.T) { expectedPodName := getPodName(podName, podNamespace) expectedContainerName := "baz" setPodByNameFunc(fw, podNamespace, podName, expectedContainerName) - setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &api.PodLogOptions{}, output) + setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &v1.PodLogOptions{}, output) resp, err := http.Get(fw.testHTTPServer.URL + "/containerLogs/" + podNamespace + "/" + podName + "/" + expectedContainerName + "?tail=-1") if err != nil { t.Errorf("Got error GETing: %v", err) @@ -1099,7 +1100,7 @@ func TestContainerLogsWithFollow(t *testing.T) { expectedPodName := getPodName(podName, podNamespace) expectedContainerName := "baz" setPodByNameFunc(fw, podNamespace, podName, expectedContainerName) - setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &api.PodLogOptions{Follow: true}, output) + setGetContainerLogsFunc(fw, t, expectedPodName, expectedContainerName, &v1.PodLogOptions{Follow: true}, output) resp, err := http.Get(fw.testHTTPServer.URL + "/containerLogs/" + podNamespace + "/" + podName + "/" + expectedContainerName + "?follow=1") if err != nil { t.Errorf("Got error GETing: %v", err) diff --git a/pkg/kubelet/server/stats/BUILD b/pkg/kubelet/server/stats/BUILD index 62c31378e15..a2227c2d2d6 100644 --- a/pkg/kubelet/server/stats/BUILD +++ b/pkg/kubelet/server/stats/BUILD @@ -22,8 +22,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/api/v1alpha1/stats:go_default_library", "//pkg/kubelet/cm:go_default_library", "//pkg/kubelet/container:go_default_library", @@ -50,8 +50,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/api/v1alpha1/stats:go_default_library", "//pkg/kubelet/cm:go_default_library", "//pkg/kubelet/container:go_default_library", diff --git a/pkg/kubelet/server/stats/handler.go b/pkg/kubelet/server/stats/handler.go index 3f0dc63417d..fddeaaaa8a1 100644 --- a/pkg/kubelet/server/stats/handler.go +++ b/pkg/kubelet/server/stats/handler.go @@ -29,7 +29,7 @@ import ( cadvisorapiv2 "github.com/google/cadvisor/info/v2" "github.com/emicklei/go-restful" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/cm" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/types" @@ -41,13 +41,13 @@ type StatsProvider interface { GetContainerInfo(podFullName string, uid types.UID, containerName string, req *cadvisorapi.ContainerInfoRequest) (*cadvisorapi.ContainerInfo, error) GetContainerInfoV2(name string, options cadvisorapiv2.RequestOptions) (map[string]cadvisorapiv2.ContainerInfo, error) GetRawContainerInfo(containerName string, req *cadvisorapi.ContainerInfoRequest, subcontainers bool) (map[string]*cadvisorapi.ContainerInfo, error) - GetPodByName(namespace, name string) (*api.Pod, bool) - GetNode() (*api.Node, error) + GetPodByName(namespace, name string) (*v1.Pod, bool) + GetNode() (*v1.Node, error) GetNodeConfig() cm.NodeConfig ImagesFsInfo() (cadvisorapiv2.FsInfo, error) RootFsInfo() (cadvisorapiv2.FsInfo, error) ListVolumesForPod(podUID types.UID) (map[string]volume.Volume, bool) - GetPods() []*api.Pod + GetPods() []*v1.Pod } type handler struct { @@ -197,7 +197,7 @@ func (h *handler) handlePodContainer(request *restful.Request, response *restful // Default parameters. params := map[string]string{ - "namespace": api.NamespaceDefault, + "namespace": v1.NamespaceDefault, "uid": "", } for k, v := range request.PathParameters() { diff --git a/pkg/kubelet/server/stats/mocks_test.go b/pkg/kubelet/server/stats/mocks_test.go index bb5d013cbd4..892dcdae99c 100644 --- a/pkg/kubelet/server/stats/mocks_test.go +++ b/pkg/kubelet/server/stats/mocks_test.go @@ -16,15 +16,15 @@ limitations under the License. package stats -import "github.com/stretchr/testify/mock" - -import cadvisorapi "github.com/google/cadvisor/info/v1" -import cadvisorapiv2 "github.com/google/cadvisor/info/v2" -import "k8s.io/kubernetes/pkg/api" -import "k8s.io/kubernetes/pkg/kubelet/cm" - -import "k8s.io/kubernetes/pkg/types" -import "k8s.io/kubernetes/pkg/volume" +import ( + cadvisorapi "github.com/google/cadvisor/info/v1" + cadvisorapiv2 "github.com/google/cadvisor/info/v2" + "github.com/stretchr/testify/mock" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/kubelet/cm" + "k8s.io/kubernetes/pkg/types" + "k8s.io/kubernetes/pkg/volume" +) // DO NOT EDIT // GENERATED BY mockery @@ -103,15 +103,15 @@ func (_m *MockStatsProvider) GetRawContainerInfo(containerName string, req *cadv } // GetPodByName provides a mock function with given fields: namespace, name -func (_m *MockStatsProvider) GetPodByName(namespace string, name string) (*api.Pod, bool) { +func (_m *MockStatsProvider) GetPodByName(namespace string, name string) (*v1.Pod, bool) { ret := _m.Called(namespace, name) - var r0 *api.Pod - if rf, ok := ret.Get(0).(func(string, string) *api.Pod); ok { + var r0 *v1.Pod + if rf, ok := ret.Get(0).(func(string, string) *v1.Pod); ok { r0 = rf(namespace, name) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*api.Pod) + r0 = ret.Get(0).(*v1.Pod) } } @@ -126,15 +126,15 @@ func (_m *MockStatsProvider) GetPodByName(namespace string, name string) (*api.P } // GetNode provides a mock function with given fields: -func (_m *MockStatsProvider) GetNode() (*api.Node, error) { +func (_m *MockStatsProvider) GetNode() (*v1.Node, error) { ret := _m.Called() - var r0 *api.Node - if rf, ok := ret.Get(0).(func() *api.Node); ok { + var r0 *v1.Node + if rf, ok := ret.Get(0).(func() *v1.Node); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*api.Node) + r0 = ret.Get(0).(*v1.Node) } } @@ -228,15 +228,15 @@ func (_m *MockStatsProvider) ListVolumesForPod(podUID types.UID) (map[string]vol } // GetPods provides a mock function with given fields: -func (_m *MockStatsProvider) GetPods() []*api.Pod { +func (_m *MockStatsProvider) GetPods() []*v1.Pod { ret := _m.Called() - var r0 []*api.Pod - if rf, ok := ret.Get(0).(func() []*api.Pod); ok { + var r0 []*v1.Pod + if rf, ok := ret.Get(0).(func() []*v1.Pod); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]*api.Pod) + r0 = ret.Get(0).([]*v1.Pod) } } diff --git a/pkg/kubelet/server/stats/summary.go b/pkg/kubelet/server/stats/summary.go index 9faa7ee5e6a..0ece3d2b9d9 100644 --- a/pkg/kubelet/server/stats/summary.go +++ b/pkg/kubelet/server/stats/summary.go @@ -21,8 +21,8 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" "k8s.io/kubernetes/pkg/kubelet/cm" "k8s.io/kubernetes/pkg/kubelet/container" @@ -100,7 +100,7 @@ func (sp *summaryProviderImpl) Get() (*stats.Summary, error) { // summaryBuilder aggregates the datastructures provided by cadvisor into a Summary result type summaryBuilder struct { fsResourceAnalyzer fsResourceAnalyzerInterface - node *api.Node + node *v1.Node nodeConfig cm.NodeConfig rootFsInfo cadvisorapiv2.FsInfo imageFsInfo cadvisorapiv2.FsInfo diff --git a/pkg/kubelet/server/stats/summary_test.go b/pkg/kubelet/server/stats/summary_test.go index 7f17170112a..92c52c304bc 100644 --- a/pkg/kubelet/server/stats/summary_test.go +++ b/pkg/kubelet/server/stats/summary_test.go @@ -25,8 +25,8 @@ import ( fuzz "github.com/google/gofuzz" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + k8sv1 "k8s.io/kubernetes/pkg/api/v1" kubestats "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" "k8s.io/kubernetes/pkg/kubelet/cm" "k8s.io/kubernetes/pkg/kubelet/container" @@ -54,7 +54,7 @@ var ( ) func TestBuildSummary(t *testing.T) { - node := api.Node{} + node := k8sv1.Node{} node.Name = "FooNode" nodeConfig := cm.NodeConfig{ RuntimeCgroupsName: "/docker-daemon", diff --git a/pkg/kubelet/server/stats/volume_stat_calculator.go b/pkg/kubelet/server/stats/volume_stat_calculator.go index 9eb5b3921e9..ce7ab109f52 100644 --- a/pkg/kubelet/server/stats/volume_stat_calculator.go +++ b/pkg/kubelet/server/stats/volume_stat_calculator.go @@ -21,7 +21,7 @@ import ( "sync/atomic" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" "k8s.io/kubernetes/pkg/kubelet/util/format" "k8s.io/kubernetes/pkg/util/wait" @@ -34,7 +34,7 @@ import ( type volumeStatCalculator struct { statsProvider StatsProvider jitterPeriod time.Duration - pod *api.Pod + pod *v1.Pod stopChannel chan struct{} startO sync.Once stopO sync.Once @@ -47,7 +47,7 @@ type PodVolumeStats struct { } // newVolumeStatCalculator creates a new VolumeStatCalculator -func newVolumeStatCalculator(statsProvider StatsProvider, jitterPeriod time.Duration, pod *api.Pod) *volumeStatCalculator { +func newVolumeStatCalculator(statsProvider StatsProvider, jitterPeriod time.Duration, pod *v1.Pod) *volumeStatCalculator { return &volumeStatCalculator{ statsProvider: statsProvider, jitterPeriod: jitterPeriod, diff --git a/pkg/kubelet/status/BUILD b/pkg/kubelet/status/BUILD index 71aef44c1e6..915515524ce 100644 --- a/pkg/kubelet/status/BUILD +++ b/pkg/kubelet/status/BUILD @@ -21,7 +21,9 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/pod:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/pod:go_default_library", "//pkg/kubelet/types:go_default_library", @@ -45,8 +47,9 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/pod:go_default_library", diff --git a/pkg/kubelet/status/generate.go b/pkg/kubelet/status/generate.go index aca89076e28..9826d9ac91a 100644 --- a/pkg/kubelet/status/generate.go +++ b/pkg/kubelet/status/generate.go @@ -20,24 +20,24 @@ import ( "fmt" "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) // GeneratePodReadyCondition returns ready condition if all containers in a pod are ready, else it // returns an unready condition. -func GeneratePodReadyCondition(spec *api.PodSpec, containerStatuses []api.ContainerStatus, podPhase api.PodPhase) api.PodCondition { +func GeneratePodReadyCondition(spec *v1.PodSpec, containerStatuses []v1.ContainerStatus, podPhase v1.PodPhase) v1.PodCondition { // Find if all containers are ready or not. if containerStatuses == nil { - return api.PodCondition{ - Type: api.PodReady, - Status: api.ConditionFalse, + return v1.PodCondition{ + Type: v1.PodReady, + Status: v1.ConditionFalse, Reason: "UnknownContainerStatuses", } } unknownContainers := []string{} unreadyContainers := []string{} for _, container := range spec.Containers { - if containerStatus, ok := api.GetContainerStatus(containerStatuses, container.Name); ok { + if containerStatus, ok := v1.GetContainerStatus(containerStatuses, container.Name); ok { if !containerStatus.Ready { unreadyContainers = append(unreadyContainers, container.Name) } @@ -47,10 +47,10 @@ func GeneratePodReadyCondition(spec *api.PodSpec, containerStatuses []api.Contai } // If all containers are known and succeeded, just return PodCompleted. - if podPhase == api.PodSucceeded && len(unknownContainers) == 0 { - return api.PodCondition{ - Type: api.PodReady, - Status: api.ConditionFalse, + if podPhase == v1.PodSucceeded && len(unknownContainers) == 0 { + return v1.PodCondition{ + Type: v1.PodReady, + Status: v1.ConditionFalse, Reason: "PodCompleted", } } @@ -64,35 +64,35 @@ func GeneratePodReadyCondition(spec *api.PodSpec, containerStatuses []api.Contai } unreadyMessage := strings.Join(unreadyMessages, ", ") if unreadyMessage != "" { - return api.PodCondition{ - Type: api.PodReady, - Status: api.ConditionFalse, + return v1.PodCondition{ + Type: v1.PodReady, + Status: v1.ConditionFalse, Reason: "ContainersNotReady", Message: unreadyMessage, } } - return api.PodCondition{ - Type: api.PodReady, - Status: api.ConditionTrue, + return v1.PodCondition{ + Type: v1.PodReady, + Status: v1.ConditionTrue, } } // GeneratePodInitializedCondition returns initialized condition if all init containers in a pod are ready, else it // returns an uninitialized condition. -func GeneratePodInitializedCondition(spec *api.PodSpec, containerStatuses []api.ContainerStatus, podPhase api.PodPhase) api.PodCondition { +func GeneratePodInitializedCondition(spec *v1.PodSpec, containerStatuses []v1.ContainerStatus, podPhase v1.PodPhase) v1.PodCondition { // Find if all containers are ready or not. if containerStatuses == nil && len(spec.InitContainers) > 0 { - return api.PodCondition{ - Type: api.PodInitialized, - Status: api.ConditionFalse, + return v1.PodCondition{ + Type: v1.PodInitialized, + Status: v1.ConditionFalse, Reason: "UnknownContainerStatuses", } } unknownContainers := []string{} unreadyContainers := []string{} for _, container := range spec.InitContainers { - if containerStatus, ok := api.GetContainerStatus(containerStatuses, container.Name); ok { + if containerStatus, ok := v1.GetContainerStatus(containerStatuses, container.Name); ok { if !containerStatus.Ready { unreadyContainers = append(unreadyContainers, container.Name) } @@ -102,10 +102,10 @@ func GeneratePodInitializedCondition(spec *api.PodSpec, containerStatuses []api. } // If all init containers are known and succeeded, just return PodCompleted. - if podPhase == api.PodSucceeded && len(unknownContainers) == 0 { - return api.PodCondition{ - Type: api.PodInitialized, - Status: api.ConditionTrue, + if podPhase == v1.PodSucceeded && len(unknownContainers) == 0 { + return v1.PodCondition{ + Type: v1.PodInitialized, + Status: v1.ConditionTrue, Reason: "PodCompleted", } } @@ -119,16 +119,16 @@ func GeneratePodInitializedCondition(spec *api.PodSpec, containerStatuses []api. } unreadyMessage := strings.Join(unreadyMessages, ", ") if unreadyMessage != "" { - return api.PodCondition{ - Type: api.PodInitialized, - Status: api.ConditionFalse, + return v1.PodCondition{ + Type: v1.PodInitialized, + Status: v1.ConditionFalse, Reason: "ContainersNotInitialized", Message: unreadyMessage, } } - return api.PodCondition{ - Type: api.PodInitialized, - Status: api.ConditionTrue, + return v1.PodCondition{ + Type: v1.PodInitialized, + Status: v1.ConditionTrue, } } diff --git a/pkg/kubelet/status/generate_test.go b/pkg/kubelet/status/generate_test.go index 768e5898ae7..783c9b05344 100644 --- a/pkg/kubelet/status/generate_test.go +++ b/pkg/kubelet/status/generate_test.go @@ -20,89 +20,89 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) func TestGeneratePodReadyCondition(t *testing.T) { tests := []struct { - spec *api.PodSpec - containerStatuses []api.ContainerStatus - podPhase api.PodPhase - expected api.PodCondition + spec *v1.PodSpec + containerStatuses []v1.ContainerStatus + podPhase v1.PodPhase + expected v1.PodCondition }{ { spec: nil, containerStatuses: nil, - podPhase: api.PodRunning, + podPhase: v1.PodRunning, expected: getReadyCondition(false, "UnknownContainerStatuses", ""), }, { - spec: &api.PodSpec{}, - containerStatuses: []api.ContainerStatus{}, - podPhase: api.PodRunning, + spec: &v1.PodSpec{}, + containerStatuses: []v1.ContainerStatus{}, + podPhase: v1.PodRunning, expected: getReadyCondition(true, "", ""), }, { - spec: &api.PodSpec{ - Containers: []api.Container{ + spec: &v1.PodSpec{ + Containers: []v1.Container{ {Name: "1234"}, }, }, - containerStatuses: []api.ContainerStatus{}, - podPhase: api.PodRunning, + containerStatuses: []v1.ContainerStatus{}, + podPhase: v1.PodRunning, expected: getReadyCondition(false, "ContainersNotReady", "containers with unknown status: [1234]"), }, { - spec: &api.PodSpec{ - Containers: []api.Container{ + spec: &v1.PodSpec{ + Containers: []v1.Container{ {Name: "1234"}, {Name: "5678"}, }, }, - containerStatuses: []api.ContainerStatus{ + containerStatuses: []v1.ContainerStatus{ getReadyStatus("1234"), getReadyStatus("5678"), }, - podPhase: api.PodRunning, + podPhase: v1.PodRunning, expected: getReadyCondition(true, "", ""), }, { - spec: &api.PodSpec{ - Containers: []api.Container{ + spec: &v1.PodSpec{ + Containers: []v1.Container{ {Name: "1234"}, {Name: "5678"}, }, }, - containerStatuses: []api.ContainerStatus{ + containerStatuses: []v1.ContainerStatus{ getReadyStatus("1234"), }, - podPhase: api.PodRunning, + podPhase: v1.PodRunning, expected: getReadyCondition(false, "ContainersNotReady", "containers with unknown status: [5678]"), }, { - spec: &api.PodSpec{ - Containers: []api.Container{ + spec: &v1.PodSpec{ + Containers: []v1.Container{ {Name: "1234"}, {Name: "5678"}, }, }, - containerStatuses: []api.ContainerStatus{ + containerStatuses: []v1.ContainerStatus{ getReadyStatus("1234"), getNotReadyStatus("5678"), }, - podPhase: api.PodRunning, + podPhase: v1.PodRunning, expected: getReadyCondition(false, "ContainersNotReady", "containers with unready status: [5678]"), }, { - spec: &api.PodSpec{ - Containers: []api.Container{ + spec: &v1.PodSpec{ + Containers: []v1.Container{ {Name: "1234"}, }, }, - containerStatuses: []api.ContainerStatus{ + containerStatuses: []v1.ContainerStatus{ getNotReadyStatus("1234"), }, - podPhase: api.PodSucceeded, + podPhase: v1.PodSucceeded, expected: getReadyCondition(false, "PodCompleted", ""), }, } @@ -115,28 +115,28 @@ func TestGeneratePodReadyCondition(t *testing.T) { } } -func getReadyCondition(ready bool, reason, message string) api.PodCondition { - status := api.ConditionFalse +func getReadyCondition(ready bool, reason, message string) v1.PodCondition { + status := v1.ConditionFalse if ready { - status = api.ConditionTrue + status = v1.ConditionTrue } - return api.PodCondition{ - Type: api.PodReady, + return v1.PodCondition{ + Type: v1.PodReady, Status: status, Reason: reason, Message: message, } } -func getReadyStatus(cName string) api.ContainerStatus { - return api.ContainerStatus{ +func getReadyStatus(cName string) v1.ContainerStatus { + return v1.ContainerStatus{ Name: cName, Ready: true, } } -func getNotReadyStatus(cName string) api.ContainerStatus { - return api.ContainerStatus{ +func getNotReadyStatus(cName string) v1.ContainerStatus { + return v1.ContainerStatus{ Name: cName, Ready: false, } diff --git a/pkg/kubelet/status/status_manager.go b/pkg/kubelet/status/status_manager.go index 8c509e35f1f..8d0b9b4f23f 100644 --- a/pkg/kubelet/status/status_manager.go +++ b/pkg/kubelet/status/status_manager.go @@ -21,12 +21,14 @@ import ( "sync" "time" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + podutil "k8s.io/kubernetes/pkg/api/v1/pod" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubepod "k8s.io/kubernetes/pkg/kubelet/pod" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" @@ -36,10 +38,10 @@ import ( "k8s.io/kubernetes/pkg/util/wait" ) -// A wrapper around api.PodStatus that includes a version to enforce that stale pod statuses are +// A wrapper around v1.PodStatus that includes a version to enforce that stale pod statuses are // not sent to the API server. type versionedPodStatus struct { - status api.PodStatus + status v1.PodStatus // Monotonically increasing version number (per pod). version uint64 // Pod name & namespace, for sending updates to API server. @@ -71,11 +73,11 @@ type manager struct { type PodStatusProvider interface { // GetPodStatus returns the cached status for the provided pod UID, as well as whether it // was a cache hit. - GetPodStatus(uid types.UID) (api.PodStatus, bool) + GetPodStatus(uid types.UID) (v1.PodStatus, bool) } // Manager is the Source of truth for kubelet pod status, and should be kept up-to-date with -// the latest api.PodStatus. It also syncs updates back to the API server. +// the latest v1.PodStatus. It also syncs updates back to the API server. type Manager interface { PodStatusProvider @@ -83,7 +85,7 @@ type Manager interface { Start() // SetPodStatus caches updates the cached status for the given pod, and triggers a status update. - SetPodStatus(pod *api.Pod, status api.PodStatus) + SetPodStatus(pod *v1.Pod, status v1.PodStatus) // SetContainerReadiness updates the cached container status with the given readiness, and // triggers a status update. @@ -91,7 +93,7 @@ type Manager interface { // TerminatePod resets the container status for the provided pod to terminated and triggers // a status update. - TerminatePod(pod *api.Pod) + TerminatePod(pod *v1.Pod) // RemoveOrphanedStatuses scans the status cache and removes any entries for pods not included in // the provided podUIDs. @@ -113,7 +115,7 @@ func NewManager(kubeClient clientset.Interface, podManager kubepod.Manager) Mana // isStatusEqual returns true if the given pod statuses are equal, false otherwise. // This method normalizes the status before comparing so as to make sure that meaningless // changes will be ignored. -func isStatusEqual(oldStatus, status *api.PodStatus) bool { +func isStatusEqual(oldStatus, status *v1.PodStatus) bool { return api.Semantic.DeepEqual(status, oldStatus) } @@ -139,14 +141,14 @@ func (m *manager) Start() { }, 0) } -func (m *manager) GetPodStatus(uid types.UID) (api.PodStatus, bool) { +func (m *manager) GetPodStatus(uid types.UID) (v1.PodStatus, bool) { m.podStatusesLock.RLock() defer m.podStatusesLock.RUnlock() status, ok := m.podStatuses[m.podManager.TranslatePodUID(uid)] return status.status, ok } -func (m *manager) SetPodStatus(pod *api.Pod, status api.PodStatus) { +func (m *manager) SetPodStatus(pod *v1.Pod, status v1.PodStatus) { m.podStatusesLock.Lock() defer m.podStatusesLock.Unlock() // Make sure we're caching a deep copy. @@ -202,7 +204,7 @@ func (m *manager) SetContainerReadiness(podUID types.UID, containerID kubecontai // Update pod condition. readyConditionIndex := -1 for i, condition := range status.Conditions { - if condition.Type == api.PodReady { + if condition.Type == v1.PodReady { readyConditionIndex = i break } @@ -218,7 +220,7 @@ func (m *manager) SetContainerReadiness(podUID types.UID, containerID kubecontai m.updateStatusInternal(pod, status, false) } -func findContainerStatus(status *api.PodStatus, containerID string) (containerStatus *api.ContainerStatus, init bool, ok bool) { +func findContainerStatus(status *v1.PodStatus, containerID string) (containerStatus *v1.ContainerStatus, init bool, ok bool) { // Find the container to update. for i, c := range status.ContainerStatuses { if c.ContainerID == containerID { @@ -236,7 +238,7 @@ func findContainerStatus(status *api.PodStatus, containerID string) (containerSt } -func (m *manager) TerminatePod(pod *api.Pod) { +func (m *manager) TerminatePod(pod *v1.Pod) { m.podStatusesLock.Lock() defer m.podStatusesLock.Unlock() oldStatus := &pod.Status @@ -248,13 +250,13 @@ func (m *manager) TerminatePod(pod *api.Pod) { return } for i := range status.ContainerStatuses { - status.ContainerStatuses[i].State = api.ContainerState{ - Terminated: &api.ContainerStateTerminated{}, + status.ContainerStatuses[i].State = v1.ContainerState{ + Terminated: &v1.ContainerStateTerminated{}, } } for i := range status.InitContainerStatuses { - status.InitContainerStatuses[i].State = api.ContainerState{ - Terminated: &api.ContainerStateTerminated{}, + status.InitContainerStatuses[i].State = v1.ContainerState{ + Terminated: &v1.ContainerStateTerminated{}, } } m.updateStatusInternal(pod, pod.Status, true) @@ -263,8 +265,8 @@ func (m *manager) TerminatePod(pod *api.Pod) { // updateStatusInternal updates the internal status cache, and queues an update to the api server if // necessary. Returns whether an update was triggered. // This method IS NOT THREAD SAFE and must be called from a locked function. -func (m *manager) updateStatusInternal(pod *api.Pod, status api.PodStatus, forceUpdate bool) bool { - var oldStatus api.PodStatus +func (m *manager) updateStatusInternal(pod *v1.Pod, status v1.PodStatus, forceUpdate bool) bool { + var oldStatus v1.PodStatus cachedStatus, isCached := m.podStatuses[pod.UID] if isCached { oldStatus = cachedStatus.status @@ -275,10 +277,10 @@ func (m *manager) updateStatusInternal(pod *api.Pod, status api.PodStatus, force } // Set ReadyCondition.LastTransitionTime. - if _, readyCondition := api.GetPodCondition(&status, api.PodReady); readyCondition != nil { + if _, readyCondition := v1.GetPodCondition(&status, v1.PodReady); readyCondition != nil { // Need to set LastTransitionTime. lastTransitionTime := unversioned.Now() - _, oldReadyCondition := api.GetPodCondition(&oldStatus, api.PodReady) + _, oldReadyCondition := v1.GetPodCondition(&oldStatus, v1.PodReady) if oldReadyCondition != nil && readyCondition.Status == oldReadyCondition.Status { lastTransitionTime = oldReadyCondition.LastTransitionTime } @@ -286,10 +288,10 @@ func (m *manager) updateStatusInternal(pod *api.Pod, status api.PodStatus, force } // Set InitializedCondition.LastTransitionTime. - if _, initCondition := api.GetPodCondition(&status, api.PodInitialized); initCondition != nil { + if _, initCondition := v1.GetPodCondition(&status, v1.PodInitialized); initCondition != nil { // Need to set LastTransitionTime. lastTransitionTime := unversioned.Now() - _, oldInitCondition := api.GetPodCondition(&oldStatus, api.PodInitialized) + _, oldInitCondition := v1.GetPodCondition(&oldStatus, v1.PodInitialized) if oldInitCondition != nil && initCondition.Status == oldInitCondition.Status { lastTransitionTime = oldInitCondition.LastTransitionTime } @@ -419,6 +421,9 @@ func (m *manager) syncPod(uid types.UID, status versionedPodStatus) { return } pod.Status = status.status + if err := podutil.SetInitContainersStatusesAnnotations(pod); err != nil { + glog.Error(err) + } // TODO: handle conflict as a retry, make that easier too. pod, err = m.kubeClient.Core().Pods(pod.Namespace).UpdateStatus(pod) if err == nil { @@ -435,10 +440,9 @@ func (m *manager) syncPod(uid types.UID, status versionedPodStatus) { glog.V(3).Infof("Pod %q is terminated, but some containers are still running", format.Pod(pod)) return } - deleteOptions := api.NewDeleteOptions(0) + deleteOptions := v1.NewDeleteOptions(0) // Use the pod UID as the precondition for deletion to prevent deleting a newly created pod with the same name and namespace. - deleteOptions.Preconditions = api.NewUIDPreconditions(string(pod.UID)) - glog.V(2).Infof("Removing Pod %q from etcd", format.Pod(pod)) + deleteOptions.Preconditions = v1.NewUIDPreconditions(string(pod.UID)) if err = m.kubeClient.Core().Pods(pod.Namespace).Delete(pod.Name, deleteOptions); err == nil { glog.V(3).Infof("Pod %q fully terminated and removed from etcd", format.Pod(pod)) m.deletePodStatus(uid) @@ -467,7 +471,7 @@ func (m *manager) needsUpdate(uid types.UID, status versionedPodStatus) bool { // now the pod manager only supports getting mirror pod by static pod, so we have to pass // static pod uid here. // TODO(random-liu): Simplify the logic when mirror pod manager is added. -func (m *manager) needsReconcile(uid types.UID, status api.PodStatus) bool { +func (m *manager) needsReconcile(uid types.UID, status v1.PodStatus) bool { // The pod could be a static pod, so we should translate first. pod, ok := m.podManager.GetPodByUID(uid) if !ok { @@ -508,11 +512,11 @@ func (m *manager) needsReconcile(uid types.UID, status api.PodStatus) bool { // In fact, the best way to solve this is to do it on api side. However, for now, we normalize the status locally in // kubelet temporarily. // TODO(random-liu): Remove timestamp related logic after apiserver supports nanosecond or makes it consistent. -func normalizeStatus(pod *api.Pod, status *api.PodStatus) *api.PodStatus { +func normalizeStatus(pod *v1.Pod, status *v1.PodStatus) *v1.PodStatus { normalizeTimeStamp := func(t *unversioned.Time) { *t = t.Rfc3339Copy() } - normalizeContainerState := func(c *api.ContainerState) { + normalizeContainerState := func(c *v1.ContainerState) { if c.Running != nil { normalizeTimeStamp(&c.Running.StartedAt) } @@ -553,7 +557,7 @@ func normalizeStatus(pod *api.Pod, status *api.PodStatus) *api.PodStatus { // notRunning returns true if every status is terminated or waiting, or the status list // is empty. -func notRunning(statuses []api.ContainerStatus) bool { +func notRunning(statuses []v1.ContainerStatus) bool { for _, status := range statuses { if status.State.Terminated == nil && status.State.Waiting == nil { return false @@ -562,12 +566,12 @@ func notRunning(statuses []api.ContainerStatus) bool { return true } -func copyStatus(source *api.PodStatus) (api.PodStatus, error) { +func copyStatus(source *v1.PodStatus) (v1.PodStatus, error) { clone, err := api.Scheme.DeepCopy(source) if err != nil { glog.Errorf("Failed to clone status %+v: %v", source, err) - return api.PodStatus{}, err + return v1.PodStatus{}, err } - status := *clone.(*api.PodStatus) + status := *clone.(*v1.PodStatus) return status, nil } diff --git a/pkg/kubelet/status/status_manager_test.go b/pkg/kubelet/status/status_manager_test.go index 1587eea4570..3394a53cbe3 100644 --- a/pkg/kubelet/status/status_manager_test.go +++ b/pkg/kubelet/status/status_manager_test.go @@ -23,8 +23,8 @@ import ( "testing" "time" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/testing/core" "github.com/stretchr/testify/assert" @@ -32,6 +32,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" kubepod "k8s.io/kubernetes/pkg/kubelet/pod" podtest "k8s.io/kubernetes/pkg/kubelet/pod/testing" @@ -40,9 +41,9 @@ import ( ) // Generate new instance of test pod with the same initial value. -func getTestPod() *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func getTestPod() *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", @@ -78,8 +79,8 @@ func generateRandomMessage() string { return strconv.Itoa(rand.Int()) } -func getRandomPodStatus() api.PodStatus { - return api.PodStatus{ +func getRandomPodStatus() v1.PodStatus { + return v1.PodStatus{ Message: generateRandomMessage(), } } @@ -135,13 +136,13 @@ func TestNewStatus(t *testing.T) { func TestNewStatusPreservesPodStartTime(t *testing.T) { syncer := newTestManager(&fake.Clientset{}) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Status: api.PodStatus{}, + Status: v1.PodStatus{}, } now := unversioned.Now() startTime := unversioned.NewTime(now.Time.Add(-1 * time.Minute)) @@ -154,12 +155,12 @@ func TestNewStatusPreservesPodStartTime(t *testing.T) { } } -func getReadyPodStatus() api.PodStatus { - return api.PodStatus{ - Conditions: []api.PodCondition{ +func getReadyPodStatus() v1.PodStatus { + return v1.PodStatus{ + Conditions: []v1.PodCondition{ { - Type: api.PodReady, - Status: api.ConditionTrue, + Type: v1.PodReady, + Status: v1.ConditionTrue, }, }, } @@ -168,18 +169,18 @@ func getReadyPodStatus() api.PodStatus { func TestNewStatusSetsReadyTransitionTime(t *testing.T) { syncer := newTestManager(&fake.Clientset{}) podStatus := getReadyPodStatus() - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Status: api.PodStatus{}, + Status: v1.PodStatus{}, } syncer.SetPodStatus(pod, podStatus) verifyUpdates(t, syncer, 1) status := expectPodStatus(t, syncer, pod) - readyCondition := api.GetPodReadyCondition(status) + readyCondition := v1.GetPodReadyCondition(status) if readyCondition.LastTransitionTime.IsZero() { t.Errorf("Unexpected: last transition time not set") } @@ -215,25 +216,25 @@ func TestChangedStatusKeepsStartTime(t *testing.T) { func TestChangedStatusUpdatesLastTransitionTime(t *testing.T) { syncer := newTestManager(&fake.Clientset{}) podStatus := getReadyPodStatus() - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Status: api.PodStatus{}, + Status: v1.PodStatus{}, } syncer.SetPodStatus(pod, podStatus) verifyUpdates(t, syncer, 1) oldStatus := expectPodStatus(t, syncer, pod) anotherStatus := getReadyPodStatus() - anotherStatus.Conditions[0].Status = api.ConditionFalse + anotherStatus.Conditions[0].Status = v1.ConditionFalse syncer.SetPodStatus(pod, anotherStatus) verifyUpdates(t, syncer, 1) newStatus := expectPodStatus(t, syncer, pod) - oldReadyCondition := api.GetPodReadyCondition(oldStatus) - newReadyCondition := api.GetPodReadyCondition(newStatus) + oldReadyCondition := v1.GetPodReadyCondition(oldStatus) + newReadyCondition := v1.GetPodReadyCondition(newStatus) if newReadyCondition.LastTransitionTime.IsZero() { t.Errorf("Unexpected: last transition time not set") } @@ -254,13 +255,13 @@ func TestUnchangedStatus(t *testing.T) { func TestUnchangedStatusPreservesLastTransitionTime(t *testing.T) { syncer := newTestManager(&fake.Clientset{}) podStatus := getReadyPodStatus() - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, - Status: api.PodStatus{}, + Status: v1.PodStatus{}, } syncer.SetPodStatus(pod, podStatus) verifyUpdates(t, syncer, 1) @@ -271,8 +272,8 @@ func TestUnchangedStatusPreservesLastTransitionTime(t *testing.T) { verifyUpdates(t, syncer, 0) newStatus := expectPodStatus(t, syncer, pod) - oldReadyCondition := api.GetPodReadyCondition(oldStatus) - newReadyCondition := api.GetPodReadyCondition(newStatus) + oldReadyCondition := v1.GetPodReadyCondition(oldStatus) + newReadyCondition := v1.GetPodReadyCondition(newStatus) if newReadyCondition.LastTransitionTime.IsZero() { t.Errorf("Unexpected: last transition time not set") } @@ -330,21 +331,21 @@ func TestSyncBatchNoDeadlock(t *testing.T) { pod := getTestPod() // Setup fake client. - var ret api.Pod + var ret v1.Pod var err error client.AddReactor("*", "pods", func(action core.Action) (bool, runtime.Object, error) { switch action := action.(type) { case core.GetAction: assert.Equal(t, pod.Name, action.GetName(), "Unexpeted GetAction: %+v", action) case core.UpdateAction: - assert.Equal(t, pod.Name, action.GetObject().(*api.Pod).Name, "Unexpeted UpdateAction: %+v", action) + assert.Equal(t, pod.Name, action.GetObject().(*v1.Pod).Name, "Unexpeted UpdateAction: %+v", action) default: assert.Fail(t, "Unexpected Action: %+v", action) } return true, &ret, err }) - pod.Status.ContainerStatuses = []api.ContainerStatus{{State: api.ContainerState{Running: &api.ContainerStateRunning{}}}} + pod.Status.ContainerStatuses = []v1.ContainerStatus{{State: v1.ContainerState{Running: &v1.ContainerStateRunning{}}}} getAction := core.GetActionImpl{ActionImpl: core.ActionImpl{Verb: "get", Resource: unversioned.GroupVersionResource{Resource: "pods"}}} updateAction := core.UpdateActionImpl{ActionImpl: core.ActionImpl{Verb: "update", Resource: unversioned.GroupVersionResource{Resource: "pods"}, Subresource: "status"}} @@ -381,7 +382,7 @@ func TestSyncBatchNoDeadlock(t *testing.T) { // Pod is terminated successfully. pod.Status.ContainerStatuses[0].State.Running = nil - pod.Status.ContainerStatuses[0].State.Terminated = &api.ContainerStateTerminated{} + pod.Status.ContainerStatuses[0].State.Terminated = &v1.ContainerStateTerminated{} m.SetPodStatus(pod, getRandomPodStatus()) m.testSyncBatch() verifyActions(t, client, []core.Action{getAction, updateAction}) @@ -400,7 +401,7 @@ func TestStaleUpdates(t *testing.T) { client := fake.NewSimpleClientset(pod) m := newTestManager(client) - status := api.PodStatus{Message: "initial status"} + status := v1.PodStatus{Message: "initial status"} m.SetPodStatus(pod, status) status.Message = "first version bump" m.SetPodStatus(pod, status) @@ -441,10 +442,10 @@ func TestStaleUpdates(t *testing.T) { } // shuffle returns a new shuffled list of container statuses. -func shuffle(statuses []api.ContainerStatus) []api.ContainerStatus { +func shuffle(statuses []v1.ContainerStatus) []v1.ContainerStatus { numStatuses := len(statuses) randIndexes := rand.Perm(numStatuses) - shuffled := make([]api.ContainerStatus, numStatuses) + shuffled := make([]v1.ContainerStatus, numStatuses) for i := 0; i < numStatuses; i++ { shuffled[i] = statuses[randIndexes[i]] } @@ -452,21 +453,21 @@ func shuffle(statuses []api.ContainerStatus) []api.ContainerStatus { } func TestStatusEquality(t *testing.T) { - pod := api.Pod{ - Spec: api.PodSpec{}, + pod := v1.Pod{ + Spec: v1.PodSpec{}, } - containerStatus := []api.ContainerStatus{} + containerStatus := []v1.ContainerStatus{} for i := 0; i < 10; i++ { - s := api.ContainerStatus{ + s := v1.ContainerStatus{ Name: fmt.Sprintf("container%d", i), } containerStatus = append(containerStatus, s) } - podStatus := api.PodStatus{ + podStatus := v1.PodStatus{ ContainerStatuses: containerStatus, } for i := 0; i < 10; i++ { - oldPodStatus := api.PodStatus{ + oldPodStatus := v1.PodStatus{ ContainerStatuses: shuffle(podStatus.ContainerStatuses), } normalizeStatus(&pod, &oldPodStatus) @@ -524,7 +525,7 @@ func TestStaticPod(t *testing.T) { core.UpdateActionImpl{ActionImpl: core.ActionImpl{Verb: "update", Resource: unversioned.GroupVersionResource{Resource: "pods"}, Subresource: "status"}}, }) updateAction := client.Actions()[1].(core.UpdateActionImpl) - updatedPod := updateAction.Object.(*api.Pod) + updatedPod := updateAction.Object.(*v1.Pod) assert.Equal(t, mirrorPod.UID, updatedPod.UID, "Expected mirrorPod (%q), but got %q", mirrorPod.UID, updatedPod.UID) assert.True(t, isStatusEqual(&status, &updatedPod.Status), "Expected: %+v, Got: %+v", status, updatedPod.Status) client.ClearActions() @@ -536,7 +537,7 @@ func TestStaticPod(t *testing.T) { // Change mirror pod identity. m.podManager.DeletePod(mirrorPod) mirrorPod.UID = "new-mirror-pod" - mirrorPod.Status = api.PodStatus{} + mirrorPod.Status = v1.PodStatus{} m.podManager.AddPod(mirrorPod) // Should not update to mirror pod, because UID has changed. @@ -549,7 +550,7 @@ func TestStaticPod(t *testing.T) { func TestSetContainerReadiness(t *testing.T) { cID1 := kubecontainer.ContainerID{Type: "test", ID: "1"} cID2 := kubecontainer.ContainerID{Type: "test", ID: "2"} - containerStatuses := []api.ContainerStatus{ + containerStatuses := []v1.ContainerStatus{ { Name: "c1", ContainerID: cID1.String(), @@ -560,18 +561,18 @@ func TestSetContainerReadiness(t *testing.T) { Ready: false, }, } - status := api.PodStatus{ + status := v1.PodStatus{ ContainerStatuses: containerStatuses, - Conditions: []api.PodCondition{{ - Type: api.PodReady, - Status: api.ConditionFalse, + Conditions: []v1.PodCondition{{ + Type: v1.PodReady, + Status: v1.ConditionFalse, }}, } pod := getTestPod() - pod.Spec.Containers = []api.Container{{Name: "c1"}, {Name: "c2"}} + pod.Spec.Containers = []v1.Container{{Name: "c1"}, {Name: "c2"}} // Verify expected readiness of containers & pod. - verifyReadiness := func(step string, status *api.PodStatus, c1Ready, c2Ready, podReady bool) { + verifyReadiness := func(step string, status *v1.PodStatus, c1Ready, c2Ready, podReady bool) { for _, c := range status.ContainerStatuses { switch c.ContainerID { case cID1.String(): @@ -586,9 +587,9 @@ func TestSetContainerReadiness(t *testing.T) { t.Fatalf("[%s] Unexpected container: %+v", step, c) } } - if status.Conditions[0].Type != api.PodReady { + if status.Conditions[0].Type != v1.PodReady { t.Fatalf("[%s] Unexpected condition: %+v", step, status.Conditions[0]) - } else if ready := (status.Conditions[0].Status == api.ConditionTrue); ready != podReady { + } else if ready := (status.Conditions[0].Status == v1.ConditionTrue); ready != podReady { t.Errorf("[%s] Expected readiness of pod to be %v but was %v", step, podReady, ready) } } @@ -727,7 +728,7 @@ func TestReconcilePodStatus(t *testing.T) { }) } -func expectPodStatus(t *testing.T, m *manager, pod *api.Pod) api.PodStatus { +func expectPodStatus(t *testing.T, m *manager, pod *v1.Pod) v1.PodStatus { status, ok := m.GetPodStatus(pod.UID) if !ok { t.Fatalf("Expected PodStatus for %q not found", pod.UID) diff --git a/pkg/kubelet/sysctl/BUILD b/pkg/kubelet/sysctl/BUILD index 19f3ed6e348..be005c349d3 100644 --- a/pkg/kubelet/sysctl/BUILD +++ b/pkg/kubelet/sysctl/BUILD @@ -19,7 +19,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/api/validation:go_default_library", "//pkg/apis/extensions/validation:go_default_library", "//pkg/kubelet/container:go_default_library", @@ -36,5 +36,5 @@ go_test( ], library = "go_default_library", tags = ["automanaged"], - deps = ["//pkg/api:go_default_library"], + deps = ["//pkg/api/v1:go_default_library"], ) diff --git a/pkg/kubelet/sysctl/runtime.go b/pkg/kubelet/sysctl/runtime.go index b72753e6932..727919021ed 100644 --- a/pkg/kubelet/sysctl/runtime.go +++ b/pkg/kubelet/sysctl/runtime.go @@ -19,7 +19,7 @@ package sysctl import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/dockertools" "k8s.io/kubernetes/pkg/kubelet/lifecycle" @@ -81,7 +81,7 @@ func NewRuntimeAdmitHandler(runtime container.Runtime) (*runtimeAdmitHandler, er // Admit checks whether the runtime supports sysctls. func (w *runtimeAdmitHandler) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult { - sysctls, unsafeSysctls, err := api.SysctlsFromPodAnnotations(attrs.Pod.Annotations) + sysctls, unsafeSysctls, err := v1.SysctlsFromPodAnnotations(attrs.Pod.Annotations) if err != nil { return lifecycle.PodAdmitResult{ Admit: false, diff --git a/pkg/kubelet/sysctl/whitelist.go b/pkg/kubelet/sysctl/whitelist.go index 5a5b608d917..7626a3f5d3b 100644 --- a/pkg/kubelet/sysctl/whitelist.go +++ b/pkg/kubelet/sysctl/whitelist.go @@ -20,7 +20,7 @@ import ( "fmt" "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/api/validation" extvalidation "k8s.io/kubernetes/pkg/apis/extensions/validation" "k8s.io/kubernetes/pkg/kubelet/lifecycle" @@ -47,9 +47,9 @@ func SafeSysctlWhitelist() []string { // Whitelist provides a list of allowed sysctls and sysctl patterns (ending in *) // and a function to check whether a given sysctl matches this list. type Whitelist interface { - // Validate checks that all sysctls given in a api.SysctlsPodAnnotationKey annotation + // Validate checks that all sysctls given in a v1.SysctlsPodAnnotationKey annotation // are valid according to the whitelist. - Validate(pod *api.Pod) error + Validate(pod *v1.Pod) error } // patternWhitelist takes a list of sysctls or sysctl patterns (ending in *) and @@ -129,7 +129,7 @@ func (w *patternWhitelist) validateSysctl(sysctl string, hostNet, hostIPC bool) return fmt.Errorf("%q not whitelisted", sysctl) } -// Admit checks that all sysctls given in a api.SysctlsPodAnnotationKey annotation +// Admit checks that all sysctls given in a v1.SysctlsPodAnnotationKey annotation // are valid according to the whitelist. func (w *patternWhitelist) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult { pod := attrs.Pod @@ -140,7 +140,7 @@ func (w *patternWhitelist) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle. } } - sysctls, err := api.SysctlsFromPodAnnotation(a) + sysctls, err := v1.SysctlsFromPodAnnotation(a) if err != nil { return lifecycle.PodAdmitResult{ Admit: false, @@ -151,8 +151,8 @@ func (w *patternWhitelist) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle. var hostNet, hostIPC bool if pod.Spec.SecurityContext != nil { - hostNet = pod.Spec.SecurityContext.HostNetwork - hostIPC = pod.Spec.SecurityContext.HostIPC + hostNet = pod.Spec.HostNetwork + hostIPC = pod.Spec.HostIPC } for _, s := range sysctls { if err := w.validateSysctl(s.Name, hostNet, hostIPC); err != nil { diff --git a/pkg/kubelet/sysctl/whitelist_test.go b/pkg/kubelet/sysctl/whitelist_test.go index 27d3728e099..ea6a54c78b7 100644 --- a/pkg/kubelet/sysctl/whitelist_test.go +++ b/pkg/kubelet/sysctl/whitelist_test.go @@ -19,7 +19,7 @@ package sysctl import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) func TestNewWhitelist(t *testing.T) { @@ -35,7 +35,7 @@ func TestNewWhitelist(t *testing.T) { {sysctls: []string{"net.*.foo"}, err: true}, {sysctls: []string{"foo"}, err: true}, } { - _, err := NewWhitelist(append(SafeSysctlWhitelist(), test.sysctls...), api.SysctlsPodAnnotationKey) + _, err := NewWhitelist(append(SafeSysctlWhitelist(), test.sysctls...), v1.SysctlsPodAnnotationKey) if test.err && err == nil { t.Errorf("expected an error creating a whitelist for %v", test.sysctls) } else if !test.err && err != nil { @@ -65,7 +65,7 @@ func TestWhitelist(t *testing.T) { {sysctl: "kernel.sem", hostIPC: true}, } - w, err := NewWhitelist(append(SafeSysctlWhitelist(), "kernel.msg*", "kernel.sem"), api.SysctlsPodAnnotationKey) + w, err := NewWhitelist(append(SafeSysctlWhitelist(), "kernel.msg*", "kernel.sem"), v1.SysctlsPodAnnotationKey) if err != nil { t.Fatalf("failed to create whitelist: %v", err) } diff --git a/pkg/kubelet/types/BUILD b/pkg/kubelet/types/BUILD index 5f186f4ec97..184938bdb26 100644 --- a/pkg/kubelet/types/BUILD +++ b/pkg/kubelet/types/BUILD @@ -20,7 +20,7 @@ go_library( "types.go", ], tags = ["automanaged"], - deps = ["//pkg/api:go_default_library"], + deps = ["//pkg/api/v1:go_default_library"], ) go_test( @@ -32,7 +32,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//vendor:github.com/stretchr/testify/require", ], ) diff --git a/pkg/kubelet/types/pod_update.go b/pkg/kubelet/types/pod_update.go index e98489df6b1..e560a9b91f6 100644 --- a/pkg/kubelet/types/pod_update.go +++ b/pkg/kubelet/types/pod_update.go @@ -19,7 +19,7 @@ package types import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) const ConfigSourceAnnotationKey = "kubernetes.io/config.source" @@ -55,7 +55,7 @@ const ( // Updates from all sources AllSource = "*" - NamespaceDefault = api.NamespaceDefault + NamespaceDefault = v1.NamespaceDefault ) // PodUpdate defines an operation sent on the channel. You can add or remove single services by @@ -68,7 +68,7 @@ const ( // functionally similar, this helps our unit tests properly check that the correct PodUpdates // are generated. type PodUpdate struct { - Pods []*api.Pod + Pods []*v1.Pod Op PodOperation Source string } @@ -93,7 +93,7 @@ func GetValidatedSources(sources []string) ([]string, error) { } // GetPodSource returns the source of the pod based on the annotation. -func GetPodSource(pod *api.Pod) (string, error) { +func GetPodSource(pod *v1.Pod) (string, error) { if pod.Annotations != nil { if source, ok := pod.Annotations[ConfigSourceAnnotationKey]; ok { return source, nil diff --git a/pkg/kubelet/types/types.go b/pkg/kubelet/types/types.go index 017c3c8cb31..35359c7aa6b 100644 --- a/pkg/kubelet/types/types.go +++ b/pkg/kubelet/types/types.go @@ -20,7 +20,7 @@ import ( "net/http" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) // TODO: Reconcile custom types in kubelet/types and this subpackage @@ -59,7 +59,7 @@ func (t *Timestamp) GetString() string { } // A type to help sort container statuses based on container names. -type SortedContainerStatuses []api.ContainerStatus +type SortedContainerStatuses []v1.ContainerStatus func (s SortedContainerStatuses) Len() int { return len(s) } func (s SortedContainerStatuses) Swap(i, j int) { s[i], s[j] = s[j], s[i] } @@ -70,7 +70,7 @@ func (s SortedContainerStatuses) Less(i, j int) bool { // SortInitContainerStatuses ensures that statuses are in the order that their // init container appears in the pod spec -func SortInitContainerStatuses(p *api.Pod, statuses []api.ContainerStatus) { +func SortInitContainerStatuses(p *v1.Pod, statuses []v1.ContainerStatus) { containers := p.Spec.InitContainers current := 0 for _, container := range containers { @@ -87,7 +87,7 @@ func SortInitContainerStatuses(p *api.Pod, statuses []api.ContainerStatus) { // Reservation represents reserved resources for non-pod components. type Reservation struct { // System represents resources reserved for non-kubernetes components. - System api.ResourceList + System v1.ResourceList // Kubernetes represents resources reserved for kubernetes system components. - Kubernetes api.ResourceList + Kubernetes v1.ResourceList } diff --git a/pkg/kubelet/types/types_test.go b/pkg/kubelet/types/types_test.go index b7476b81269..9bb9acbea8d 100644 --- a/pkg/kubelet/types/types_test.go +++ b/pkg/kubelet/types/types_test.go @@ -20,37 +20,37 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) func TestSortInitContainerStatuses(t *testing.T) { - pod := api.Pod{ - Spec: api.PodSpec{}, + pod := v1.Pod{ + Spec: v1.PodSpec{}, } var cases = []struct { - containers []api.Container - statuses []api.ContainerStatus - sortedStatuses []api.ContainerStatus + containers []v1.Container + statuses []v1.ContainerStatus + sortedStatuses []v1.ContainerStatus }{ { - containers: []api.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - statuses: []api.ContainerStatus{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - sortedStatuses: []api.ContainerStatus{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, + containers: []v1.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, + statuses: []v1.ContainerStatus{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, + sortedStatuses: []v1.ContainerStatus{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, }, { - containers: []api.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - statuses: []api.ContainerStatus{{Name: "second"}, {Name: "first"}, {Name: "fourth"}, {Name: "third"}}, - sortedStatuses: []api.ContainerStatus{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, + containers: []v1.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, + statuses: []v1.ContainerStatus{{Name: "second"}, {Name: "first"}, {Name: "fourth"}, {Name: "third"}}, + sortedStatuses: []v1.ContainerStatus{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, }, { - containers: []api.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - statuses: []api.ContainerStatus{{Name: "fourth"}, {Name: "first"}}, - sortedStatuses: []api.ContainerStatus{{Name: "first"}, {Name: "fourth"}}, + containers: []v1.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, + statuses: []v1.ContainerStatus{{Name: "fourth"}, {Name: "first"}}, + sortedStatuses: []v1.ContainerStatus{{Name: "first"}, {Name: "fourth"}}, }, { - containers: []api.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - statuses: []api.ContainerStatus{{Name: "first"}, {Name: "third"}}, - sortedStatuses: []api.ContainerStatus{{Name: "first"}, {Name: "third"}}, + containers: []v1.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, + statuses: []v1.ContainerStatus{{Name: "first"}, {Name: "third"}}, + sortedStatuses: []v1.ContainerStatus{{Name: "first"}, {Name: "third"}}, }, } for _, data := range cases { diff --git a/pkg/kubelet/util.go b/pkg/kubelet/util.go index 20afbf30099..f58b2beecc4 100644 --- a/pkg/kubelet/util.go +++ b/pkg/kubelet/util.go @@ -20,14 +20,14 @@ import ( "fmt" "os" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/capabilities" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/securitycontext" ) // Check whether we have the capabilities to run the specified pod. -func canRunPod(pod *api.Pod) error { +func canRunPod(pod *v1.Pod) error { if !capabilities.Get().AllowPrivileged { for _, container := range pod.Spec.Containers { if securitycontext.HasPrivilegedRequest(&container) { @@ -41,11 +41,7 @@ func canRunPod(pod *api.Pod) error { } } - if pod.Spec.SecurityContext == nil { - return nil - } - - if pod.Spec.SecurityContext.HostNetwork { + if pod.Spec.HostNetwork { allowed, err := allowHostNetwork(pod) if err != nil { return err @@ -55,7 +51,7 @@ func canRunPod(pod *api.Pod) error { } } - if pod.Spec.SecurityContext.HostPID { + if pod.Spec.HostPID { allowed, err := allowHostPID(pod) if err != nil { return err @@ -65,7 +61,7 @@ func canRunPod(pod *api.Pod) error { } } - if pod.Spec.SecurityContext.HostIPC { + if pod.Spec.HostIPC { allowed, err := allowHostIPC(pod) if err != nil { return err @@ -79,7 +75,7 @@ func canRunPod(pod *api.Pod) error { } // Determined whether the specified pod is allowed to use host networking -func allowHostNetwork(pod *api.Pod) (bool, error) { +func allowHostNetwork(pod *v1.Pod) (bool, error) { podSource, err := kubetypes.GetPodSource(pod) if err != nil { return false, err @@ -93,7 +89,7 @@ func allowHostNetwork(pod *api.Pod) (bool, error) { } // Determined whether the specified pod is allowed to use host networking -func allowHostPID(pod *api.Pod) (bool, error) { +func allowHostPID(pod *v1.Pod) (bool, error) { podSource, err := kubetypes.GetPodSource(pod) if err != nil { return false, err @@ -107,7 +103,7 @@ func allowHostPID(pod *api.Pod) (bool, error) { } // Determined whether the specified pod is allowed to use host ipc -func allowHostIPC(pod *api.Pod) (bool, error) { +func allowHostIPC(pod *v1.Pod) (bool, error) { podSource, err := kubetypes.GetPodSource(pod) if err != nil { return false, err diff --git a/pkg/kubelet/util/csr/BUILD b/pkg/kubelet/util/csr/BUILD index a8ab9b15365..d9fdf72dc3f 100644 --- a/pkg/kubelet/util/csr/BUILD +++ b/pkg/kubelet/util/csr/BUILD @@ -15,10 +15,10 @@ go_library( srcs = ["csr.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/certificates:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/certificates/internalversion:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/certificates/v1alpha1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/certificates/v1alpha1:go_default_library", "//pkg/fields:go_default_library", "//pkg/types:go_default_library", "//pkg/util/cert:go_default_library", diff --git a/pkg/kubelet/util/csr/csr.go b/pkg/kubelet/util/csr/csr.go index e68576fe093..1fc43ff4795 100644 --- a/pkg/kubelet/util/csr/csr.go +++ b/pkg/kubelet/util/csr/csr.go @@ -20,10 +20,10 @@ import ( "crypto/x509/pkix" "fmt" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/certificates" - unversionedcertificates "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/internalversion" + "k8s.io/kubernetes/pkg/api/v1" + certificates "k8s.io/kubernetes/pkg/apis/certificates/v1alpha1" + unversionedcertificates "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/certificates/v1alpha1" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/types" certutil "k8s.io/kubernetes/pkg/util/cert" @@ -52,7 +52,7 @@ func RequestNodeCertificate(client unversionedcertificates.CertificateSigningReq req, err := client.Create(&certificates.CertificateSigningRequest{ // Username, UID, Groups will be injected by API server. TypeMeta: unversioned.TypeMeta{Kind: "CertificateSigningRequest"}, - ObjectMeta: api.ObjectMeta{GenerateName: "csr-"}, + ObjectMeta: v1.ObjectMeta{GenerateName: "csr-"}, // TODO: For now, this is a request for a certificate with allowed usage of "TLS Web Client Authentication". // Need to figure out whether/how to surface the allowed usage in the spec. @@ -65,10 +65,10 @@ func RequestNodeCertificate(client unversionedcertificates.CertificateSigningReq // Make a default timeout = 3600s. var defaultTimeoutSeconds int64 = 3600 - resultCh, err := client.Watch(api.ListOptions{ + resultCh, err := client.Watch(v1.ListOptions{ Watch: true, TimeoutSeconds: &defaultTimeoutSeconds, - FieldSelector: fields.OneTermEqualSelector("metadata.name", req.Name), + FieldSelector: fields.OneTermEqualSelector("metadata.name", req.Name).String(), }) if err != nil { return nil, fmt.Errorf("cannot watch on the certificate signing request: %v", err) diff --git a/pkg/kubelet/util/format/BUILD b/pkg/kubelet/util/format/BUILD index 52879359cd3..f74d7b51524 100644 --- a/pkg/kubelet/util/format/BUILD +++ b/pkg/kubelet/util/format/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", ], ) @@ -29,7 +29,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", ], ) diff --git a/pkg/kubelet/util/format/pod.go b/pkg/kubelet/util/format/pod.go index 13bfc764430..16092f063e2 100644 --- a/pkg/kubelet/util/format/pod.go +++ b/pkg/kubelet/util/format/pod.go @@ -21,15 +21,15 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" ) -type podHandler func(*api.Pod) string +type podHandler func(*v1.Pod) string // Pod returns a string representing a pod in a consistent human readable format, // with pod UID as part of the string. -func Pod(pod *api.Pod) string { +func Pod(pod *v1.Pod) string { return PodDesc(pod.Name, pod.Namespace, pod.UID) } @@ -43,7 +43,7 @@ func PodDesc(podName, podNamespace string, podUID types.UID) string { // PodWithDeletionTimestamp is the same as Pod. In addition, it prints the // deletion timestamp of the pod if it's not nil. -func PodWithDeletionTimestamp(pod *api.Pod) string { +func PodWithDeletionTimestamp(pod *v1.Pod) string { var deletionTimestamp string if pod.DeletionTimestamp != nil { deletionTimestamp = ":DeletionTimestamp=" + pod.DeletionTimestamp.UTC().Format(time.RFC3339) @@ -53,17 +53,17 @@ func PodWithDeletionTimestamp(pod *api.Pod) string { // Pods returns a string representating a list of pods in a human // readable format. -func Pods(pods []*api.Pod) string { +func Pods(pods []*v1.Pod) string { return aggregatePods(pods, Pod) } // PodsWithDeletiontimestamps is the same as Pods. In addition, it prints the // deletion timestamps of the pods if they are not nil. -func PodsWithDeletiontimestamps(pods []*api.Pod) string { +func PodsWithDeletiontimestamps(pods []*v1.Pod) string { return aggregatePods(pods, PodWithDeletionTimestamp) } -func aggregatePods(pods []*api.Pod, handler podHandler) string { +func aggregatePods(pods []*v1.Pod, handler podHandler) string { podStrings := make([]string, 0, len(pods)) for _, pod := range pods { podStrings = append(podStrings, handler(pod)) diff --git a/pkg/kubelet/util/format/resources.go b/pkg/kubelet/util/format/resources.go index f37c4335604..bc50bc9c695 100644 --- a/pkg/kubelet/util/format/resources.go +++ b/pkg/kubelet/util/format/resources.go @@ -21,11 +21,11 @@ import ( "sort" "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) // ResourceList returns a string representation of a resource list in a human readable format. -func ResourceList(resources api.ResourceList) string { +func ResourceList(resources v1.ResourceList) string { resourceStrings := make([]string, 0, len(resources)) for key, value := range resources { resourceStrings = append(resourceStrings, fmt.Sprintf("%v=%v", key, value.String())) diff --git a/pkg/kubelet/util/format/resources_test.go b/pkg/kubelet/util/format/resources_test.go index 177229c116f..2ff0833c14d 100644 --- a/pkg/kubelet/util/format/resources_test.go +++ b/pkg/kubelet/util/format/resources_test.go @@ -19,14 +19,14 @@ package format import ( "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" ) func TestResourceList(t *testing.T) { - resourceList := api.ResourceList{} - resourceList[api.ResourceCPU] = resource.MustParse("100m") - resourceList[api.ResourceMemory] = resource.MustParse("5Gi") + resourceList := v1.ResourceList{} + resourceList[v1.ResourceCPU] = resource.MustParse("100m") + resourceList[v1.ResourceMemory] = resource.MustParse("5Gi") actual := ResourceList(resourceList) expected := "cpu=100m,memory=5Gi" if actual != expected { diff --git a/pkg/kubelet/util/sliceutils/BUILD b/pkg/kubelet/util/sliceutils/BUILD index 639f71ced72..f652add8ffb 100644 --- a/pkg/kubelet/util/sliceutils/BUILD +++ b/pkg/kubelet/util/sliceutils/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["sliceutils.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/container:go_default_library", ], ) diff --git a/pkg/kubelet/util/sliceutils/sliceutils.go b/pkg/kubelet/util/sliceutils/sliceutils.go index 55448f17ffd..285cfeb44a3 100644 --- a/pkg/kubelet/util/sliceutils/sliceutils.go +++ b/pkg/kubelet/util/sliceutils/sliceutils.go @@ -17,7 +17,7 @@ limitations under the License. package sliceutils import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" ) @@ -33,7 +33,7 @@ func StringInSlice(s string, list []string) bool { // PodsByCreationTime makes an array of pods sortable by their creation // timestamps in ascending order. -type PodsByCreationTime []*api.Pod +type PodsByCreationTime []*v1.Pod func (s PodsByCreationTime) Len() int { return len(s) diff --git a/pkg/kubelet/volume_host.go b/pkg/kubelet/volume_host.go index 9d017b82349..1a86487ffaa 100644 --- a/pkg/kubelet/volume_host.go +++ b/pkg/kubelet/volume_host.go @@ -20,8 +20,8 @@ import ( "fmt" "net" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/io" @@ -72,14 +72,14 @@ func (kvh *kubeletVolumeHost) GetPodPluginDir(podUID types.UID, pluginName strin return kvh.kubelet.getPodPluginDir(podUID, pluginName) } -func (kvh *kubeletVolumeHost) GetKubeClient() internalclientset.Interface { +func (kvh *kubeletVolumeHost) GetKubeClient() clientset.Interface { return kvh.kubelet.kubeClient } func (kvh *kubeletVolumeHost) NewWrapperMounter( volName string, spec volume.Spec, - pod *api.Pod, + pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { // The name of wrapper volume is set to "wrapped_{wrapped_volume_name}" wrapperVolumeName := "wrapped_" + volName @@ -125,7 +125,7 @@ func (kvh *kubeletVolumeHost) GetHostIP() (net.IP, error) { return kvh.kubelet.GetHostIP() } -func (kvh *kubeletVolumeHost) GetNodeAllocatable() (api.ResourceList, error) { +func (kvh *kubeletVolumeHost) GetNodeAllocatable() (v1.ResourceList, error) { node, err := kvh.kubelet.getNodeAnyWay() if err != nil { return nil, fmt.Errorf("error retrieving node: %v", err) diff --git a/pkg/kubelet/volumemanager/BUILD b/pkg/kubelet/volumemanager/BUILD index 4d6e74cf574..7f5ce076c19 100644 --- a/pkg/kubelet/volumemanager/BUILD +++ b/pkg/kubelet/volumemanager/BUILD @@ -15,8 +15,8 @@ go_library( srcs = ["volume_manager.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/record:go_default_library", "//pkg/kubelet/config:go_default_library", "//pkg/kubelet/container:go_default_library", @@ -44,9 +44,9 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/record:go_default_library", "//pkg/kubelet/config:go_default_library", "//pkg/kubelet/container/testing:go_default_library", diff --git a/pkg/kubelet/volumemanager/cache/BUILD b/pkg/kubelet/volumemanager/cache/BUILD index 4ccc6774908..7b5598b2dad 100644 --- a/pkg/kubelet/volumemanager/cache/BUILD +++ b/pkg/kubelet/volumemanager/cache/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/volume:go_default_library", "//pkg/volume/util/operationexecutor:go_default_library", @@ -37,7 +37,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/volume:go_default_library", "//pkg/volume/testing:go_default_library", "//pkg/volume/util/types:go_default_library", diff --git a/pkg/kubelet/volumemanager/cache/actual_state_of_world.go b/pkg/kubelet/volumemanager/cache/actual_state_of_world.go index b29cfec8071..e0376ac3fbd 100644 --- a/pkg/kubelet/volumemanager/cache/actual_state_of_world.go +++ b/pkg/kubelet/volumemanager/cache/actual_state_of_world.go @@ -26,7 +26,7 @@ import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/util/operationexecutor" @@ -58,7 +58,7 @@ type ActualStateOfWorld interface { // volume, this is a no-op. // If a volume with the name volumeName does not exist in the list of // attached volumes, an error is returned. - AddPodToVolume(podName volumetypes.UniquePodName, podUID types.UID, volumeName api.UniqueVolumeName, mounter volume.Mounter, outerVolumeSpecName string, volumeGidValue string) error + AddPodToVolume(podName volumetypes.UniquePodName, podUID types.UID, volumeName v1.UniqueVolumeName, mounter volume.Mounter, outerVolumeSpecName string, volumeGidValue string) error // MarkRemountRequired marks each volume that is successfully attached and // mounted for the specified pod as requiring remount (if the plugin for the @@ -73,7 +73,7 @@ type ActualStateOfWorld interface { // must unmounted prior to detach. // If a volume with the name volumeName does not exist in the list of // attached volumes, an error is returned. - SetVolumeGloballyMounted(volumeName api.UniqueVolumeName, globallyMounted bool) error + SetVolumeGloballyMounted(volumeName v1.UniqueVolumeName, globallyMounted bool) error // DeletePodFromVolume removes the given pod from the given volume in the // cache indicating the volume has been successfully unmounted from the pod. @@ -81,7 +81,7 @@ type ActualStateOfWorld interface { // volume, this is a no-op. // If a volume with the name volumeName does not exist in the list of // attached volumes, an error is returned. - DeletePodFromVolume(podName volumetypes.UniquePodName, volumeName api.UniqueVolumeName) error + DeletePodFromVolume(podName volumetypes.UniquePodName, volumeName v1.UniqueVolumeName) error // DeleteVolume removes the given volume from the list of attached volumes // in the cache indicating the volume has been successfully detached from @@ -90,7 +90,7 @@ type ActualStateOfWorld interface { // attached volumes, this is a no-op. // If a volume with the name volumeName exists and its list of mountedPods // is not empty, an error is returned. - DeleteVolume(volumeName api.UniqueVolumeName) error + DeleteVolume(volumeName v1.UniqueVolumeName) error // PodExistsInVolume returns true if the given pod exists in the list of // mountedPods for the given volume in the cache, indicating that the volume @@ -107,12 +107,12 @@ type ActualStateOfWorld interface { // volumes, depend on this to update the contents of the volume. // All volume mounting calls should be idempotent so a second mount call for // volumes that do not need to update contents should not fail. - PodExistsInVolume(podName volumetypes.UniquePodName, volumeName api.UniqueVolumeName) (bool, string, error) + PodExistsInVolume(podName volumetypes.UniquePodName, volumeName v1.UniqueVolumeName) (bool, string, error) // VolumeExists returns true if the given volume exists in the list of // attached volumes in the cache, indicating the volume is attached to this // node. - VolumeExists(volumeName api.UniqueVolumeName) bool + VolumeExists(volumeName v1.UniqueVolumeName) bool // GetMountedVolumes generates and returns a list of volumes and the pods // they are successfully attached and mounted for based on the current @@ -164,7 +164,7 @@ func NewActualStateOfWorld( volumePluginMgr *volume.VolumePluginMgr) ActualStateOfWorld { return &actualStateOfWorld{ nodeName: nodeName, - attachedVolumes: make(map[api.UniqueVolumeName]attachedVolume), + attachedVolumes: make(map[v1.UniqueVolumeName]attachedVolume), volumePluginMgr: volumePluginMgr, } } @@ -193,7 +193,7 @@ type actualStateOfWorld struct { // state by default. // The key in this map is the name of the volume and the value is an object // containing more information about the attached volume. - attachedVolumes map[api.UniqueVolumeName]attachedVolume + attachedVolumes map[v1.UniqueVolumeName]attachedVolume // volumePluginMgr is the volume plugin manager used to create volume // plugin objects. @@ -206,7 +206,7 @@ type actualStateOfWorld struct { // implement an attacher are assumed to be in this state. type attachedVolume struct { // volumeName contains the unique identifier for this volume. - volumeName api.UniqueVolumeName + volumeName v1.UniqueVolumeName // mountedPods is a map containing the set of pods that this volume has been // successfully mounted to. The key in this map is the name of the pod and @@ -273,19 +273,19 @@ type mountedPod struct { } func (asw *actualStateOfWorld) MarkVolumeAsAttached( - volumeName api.UniqueVolumeName, volumeSpec *volume.Spec, _ types.NodeName, devicePath string) error { + volumeName v1.UniqueVolumeName, volumeSpec *volume.Spec, _ types.NodeName, devicePath string) error { return asw.addVolume(volumeName, volumeSpec, devicePath) } func (asw *actualStateOfWorld) MarkVolumeAsDetached( - volumeName api.UniqueVolumeName, nodeName types.NodeName) { + volumeName v1.UniqueVolumeName, nodeName types.NodeName) { asw.DeleteVolume(volumeName) } func (asw *actualStateOfWorld) MarkVolumeAsMounted( podName volumetypes.UniquePodName, podUID types.UID, - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, mounter volume.Mounter, outerVolumeSpecName string, volumeGidValue string) error { @@ -298,27 +298,27 @@ func (asw *actualStateOfWorld) MarkVolumeAsMounted( volumeGidValue) } -func (asw *actualStateOfWorld) AddVolumeToReportAsAttached(volumeName api.UniqueVolumeName, nodeName types.NodeName) { +func (asw *actualStateOfWorld) AddVolumeToReportAsAttached(volumeName v1.UniqueVolumeName, nodeName types.NodeName) { // no operation for kubelet side } -func (asw *actualStateOfWorld) RemoveVolumeFromReportAsAttached(volumeName api.UniqueVolumeName, nodeName types.NodeName) error { +func (asw *actualStateOfWorld) RemoveVolumeFromReportAsAttached(volumeName v1.UniqueVolumeName, nodeName types.NodeName) error { // no operation for kubelet side return nil } func (asw *actualStateOfWorld) MarkVolumeAsUnmounted( - podName volumetypes.UniquePodName, volumeName api.UniqueVolumeName) error { + podName volumetypes.UniquePodName, volumeName v1.UniqueVolumeName) error { return asw.DeletePodFromVolume(podName, volumeName) } func (asw *actualStateOfWorld) MarkDeviceAsMounted( - volumeName api.UniqueVolumeName) error { + volumeName v1.UniqueVolumeName) error { return asw.SetVolumeGloballyMounted(volumeName, true /* globallyMounted */) } func (asw *actualStateOfWorld) MarkDeviceAsUnmounted( - volumeName api.UniqueVolumeName) error { + volumeName v1.UniqueVolumeName) error { return asw.SetVolumeGloballyMounted(volumeName, false /* globallyMounted */) } @@ -329,7 +329,7 @@ func (asw *actualStateOfWorld) MarkDeviceAsUnmounted( // volume plugin can support the given volumeSpec or more than one plugin can // support it, an error is returned. func (asw *actualStateOfWorld) addVolume( - volumeName api.UniqueVolumeName, volumeSpec *volume.Spec, devicePath string) error { + volumeName v1.UniqueVolumeName, volumeSpec *volume.Spec, devicePath string) error { asw.Lock() defer asw.Unlock() @@ -383,7 +383,7 @@ func (asw *actualStateOfWorld) addVolume( func (asw *actualStateOfWorld) AddPodToVolume( podName volumetypes.UniquePodName, podUID types.UID, - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, mounter volume.Mounter, outerVolumeSpecName string, volumeGidValue string) error { @@ -447,7 +447,7 @@ func (asw *actualStateOfWorld) MarkRemountRequired( } func (asw *actualStateOfWorld) SetVolumeGloballyMounted( - volumeName api.UniqueVolumeName, globallyMounted bool) error { + volumeName v1.UniqueVolumeName, globallyMounted bool) error { asw.Lock() defer asw.Unlock() @@ -464,7 +464,7 @@ func (asw *actualStateOfWorld) SetVolumeGloballyMounted( } func (asw *actualStateOfWorld) DeletePodFromVolume( - podName volumetypes.UniquePodName, volumeName api.UniqueVolumeName) error { + podName volumetypes.UniquePodName, volumeName v1.UniqueVolumeName) error { asw.Lock() defer asw.Unlock() @@ -483,7 +483,7 @@ func (asw *actualStateOfWorld) DeletePodFromVolume( return nil } -func (asw *actualStateOfWorld) DeleteVolume(volumeName api.UniqueVolumeName) error { +func (asw *actualStateOfWorld) DeleteVolume(volumeName v1.UniqueVolumeName) error { asw.Lock() defer asw.Unlock() @@ -505,7 +505,7 @@ func (asw *actualStateOfWorld) DeleteVolume(volumeName api.UniqueVolumeName) err func (asw *actualStateOfWorld) PodExistsInVolume( podName volumetypes.UniquePodName, - volumeName api.UniqueVolumeName) (bool, string, error) { + volumeName v1.UniqueVolumeName) (bool, string, error) { asw.RLock() defer asw.RUnlock() @@ -523,7 +523,7 @@ func (asw *actualStateOfWorld) PodExistsInVolume( } func (asw *actualStateOfWorld) VolumeExists( - volumeName api.UniqueVolumeName) bool { + volumeName v1.UniqueVolumeName) bool { asw.RLock() defer asw.RUnlock() @@ -628,7 +628,7 @@ var _ error = volumeNotAttachedError{} // volumeNotAttachedError is an error returned when PodExistsInVolume() fails to // find specified volume in the list of attached volumes. type volumeNotAttachedError struct { - volumeName api.UniqueVolumeName + volumeName v1.UniqueVolumeName } func (err volumeNotAttachedError) Error() string { @@ -637,7 +637,7 @@ func (err volumeNotAttachedError) Error() string { err.volumeName) } -func newVolumeNotAttachedError(volumeName api.UniqueVolumeName) error { +func newVolumeNotAttachedError(volumeName v1.UniqueVolumeName) error { return volumeNotAttachedError{ volumeName: volumeName, } @@ -651,7 +651,7 @@ var _ error = remountRequiredError{} // given volume should be remounted to the pod to reflect changes in the // referencing pod. type remountRequiredError struct { - volumeName api.UniqueVolumeName + volumeName v1.UniqueVolumeName podName volumetypes.UniquePodName } @@ -662,7 +662,7 @@ func (err remountRequiredError) Error() string { } func newRemountRequiredError( - volumeName api.UniqueVolumeName, podName volumetypes.UniquePodName) error { + volumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName) error { return remountRequiredError{ volumeName: volumeName, podName: podName, diff --git a/pkg/kubelet/volumemanager/cache/actual_state_of_world_test.go b/pkg/kubelet/volumemanager/cache/actual_state_of_world_test.go index d38fbe3e7fd..bec23f6cef8 100644 --- a/pkg/kubelet/volumemanager/cache/actual_state_of_world_test.go +++ b/pkg/kubelet/volumemanager/cache/actual_state_of_world_test.go @@ -19,14 +19,14 @@ package cache import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/volume" volumetesting "k8s.io/kubernetes/pkg/volume/testing" volumetypes "k8s.io/kubernetes/pkg/volume/util/types" "k8s.io/kubernetes/pkg/volume/util/volumehelper" ) -var emptyVolumeName = api.UniqueVolumeName("") +var emptyVolumeName = v1.UniqueVolumeName("") // Calls MarkVolumeAsAttached() once to add volume // Verifies newly added volume exists in GetUnmountedVolumes() @@ -35,17 +35,17 @@ func Test_MarkVolumeAsAttached_Positive_NewVolume(t *testing.T) { // Arrange volumePluginMgr, plugin := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld("mynode" /* nodeName */, volumePluginMgr) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -79,17 +79,17 @@ func Test_MarkVolumeAsAttached_SuppliedVolumeName_Positive_NewVolume(t *testing. // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld("mynode" /* nodeName */, volumePluginMgr) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -99,7 +99,7 @@ func Test_MarkVolumeAsAttached_SuppliedVolumeName_Positive_NewVolume(t *testing. } volumeSpec := &volume.Spec{Volume: &pod.Spec.Volumes[0]} devicePath := "fake/device/path" - volumeName := api.UniqueVolumeName("this-would-never-be-a-volume-name") + volumeName := v1.UniqueVolumeName("this-would-never-be-a-volume-name") // Act err := asw.MarkVolumeAsAttached(volumeName, volumeSpec, "" /* nodeName */, devicePath) @@ -123,17 +123,17 @@ func Test_MarkVolumeAsAttached_Positive_ExistingVolume(t *testing.T) { volumePluginMgr, plugin := volumetesting.GetTestVolumePluginMgr(t) devicePath := "fake/device/path" asw := NewActualStateOfWorld("mynode" /* nodeName */, volumePluginMgr) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -171,17 +171,17 @@ func Test_AddPodToVolume_Positive_ExistingVolumeNewNode(t *testing.T) { asw := NewActualStateOfWorld("mynode" /* nodeName */, volumePluginMgr) devicePath := "fake/device/path" - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -228,17 +228,17 @@ func Test_AddPodToVolume_Positive_ExistingVolumeExistingNode(t *testing.T) { asw := NewActualStateOfWorld("mynode" /* nodeName */, volumePluginMgr) devicePath := "fake/device/path" - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -290,17 +290,17 @@ func Test_AddPodToVolume_Negative_VolumeDoesntExist(t *testing.T) { volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld("mynode" /* nodeName */, volumePluginMgr) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -355,17 +355,17 @@ func Test_MarkDeviceAsMounted_Positive_NewVolume(t *testing.T) { // Arrange volumePluginMgr, plugin := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld("mynode" /* nodeName */, volumePluginMgr) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -396,7 +396,7 @@ func Test_MarkDeviceAsMounted_Positive_NewVolume(t *testing.T) { } func verifyVolumeExistsInGloballyMountedVolumes( - t *testing.T, expectedVolumeName api.UniqueVolumeName, asw ActualStateOfWorld) { + t *testing.T, expectedVolumeName v1.UniqueVolumeName, asw ActualStateOfWorld) { globallyMountedVolumes := asw.GetGloballyMountedVolumes() for _, volume := range globallyMountedVolumes { if volume.VolumeName == expectedVolumeName { @@ -411,7 +411,7 @@ func verifyVolumeExistsInGloballyMountedVolumes( } func verifyVolumeDoesntExistInGloballyMountedVolumes( - t *testing.T, volumeToCheck api.UniqueVolumeName, asw ActualStateOfWorld) { + t *testing.T, volumeToCheck v1.UniqueVolumeName, asw ActualStateOfWorld) { globallyMountedVolumes := asw.GetGloballyMountedVolumes() for _, volume := range globallyMountedVolumes { if volume.VolumeName == volumeToCheck { @@ -424,7 +424,7 @@ func verifyVolumeDoesntExistInGloballyMountedVolumes( func verifyVolumeExistsAsw( t *testing.T, - expectedVolumeName api.UniqueVolumeName, + expectedVolumeName v1.UniqueVolumeName, shouldExist bool, asw ActualStateOfWorld) { volumeExists := asw.VolumeExists(expectedVolumeName) @@ -438,7 +438,7 @@ func verifyVolumeExistsAsw( } func verifyVolumeExistsInUnmountedVolumes( - t *testing.T, expectedVolumeName api.UniqueVolumeName, asw ActualStateOfWorld) { + t *testing.T, expectedVolumeName v1.UniqueVolumeName, asw ActualStateOfWorld) { unmountedVolumes := asw.GetUnmountedVolumes() for _, volume := range unmountedVolumes { if volume.VolumeName == expectedVolumeName { @@ -453,7 +453,7 @@ func verifyVolumeExistsInUnmountedVolumes( } func verifyVolumeDoesntExistInUnmountedVolumes( - t *testing.T, volumeToCheck api.UniqueVolumeName, asw ActualStateOfWorld) { + t *testing.T, volumeToCheck v1.UniqueVolumeName, asw ActualStateOfWorld) { unmountedVolumes := asw.GetUnmountedVolumes() for _, volume := range unmountedVolumes { if volume.VolumeName == volumeToCheck { @@ -467,7 +467,7 @@ func verifyVolumeDoesntExistInUnmountedVolumes( func verifyPodExistsInVolumeAsw( t *testing.T, expectedPodName volumetypes.UniquePodName, - expectedVolumeName api.UniqueVolumeName, + expectedVolumeName v1.UniqueVolumeName, expectedDevicePath string, asw ActualStateOfWorld) { podExistsInVolume, devicePath, err := @@ -494,7 +494,7 @@ func verifyPodExistsInVolumeAsw( func verifyPodDoesntExistInVolumeAsw( t *testing.T, podToCheck volumetypes.UniquePodName, - volumeToCheck api.UniqueVolumeName, + volumeToCheck v1.UniqueVolumeName, expectVolumeToExist bool, asw ActualStateOfWorld) { podExistsInVolume, devicePath, err := diff --git a/pkg/kubelet/volumemanager/cache/desired_state_of_world.go b/pkg/kubelet/volumemanager/cache/desired_state_of_world.go index 65b4765f9eb..e06aa925301 100644 --- a/pkg/kubelet/volumemanager/cache/desired_state_of_world.go +++ b/pkg/kubelet/volumemanager/cache/desired_state_of_world.go @@ -24,7 +24,7 @@ import ( "fmt" "sync" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/util/operationexecutor" "k8s.io/kubernetes/pkg/volume/util/types" @@ -51,7 +51,7 @@ type DesiredStateOfWorld interface { // added. // If a pod with the same unique name already exists under the specified // volume, this is a no-op. - AddPodToVolume(podName types.UniquePodName, pod *api.Pod, volumeSpec *volume.Spec, outerVolumeSpecName string, volumeGidValue string) (api.UniqueVolumeName, error) + AddPodToVolume(podName types.UniquePodName, pod *v1.Pod, volumeSpec *volume.Spec, outerVolumeSpecName string, volumeGidValue string) (v1.UniqueVolumeName, error) // MarkVolumesReportedInUse sets the ReportedInUse value to true for the // reportedVolumes. For volumes not in the reportedVolumes list, the @@ -62,7 +62,7 @@ type DesiredStateOfWorld interface { // to check this value before issuing the operation. // If a volume in the reportedVolumes list does not exist in the list of // volumes that should be attached to this node, it is skipped without error. - MarkVolumesReportedInUse(reportedVolumes []api.UniqueVolumeName) + MarkVolumesReportedInUse(reportedVolumes []v1.UniqueVolumeName) // DeletePodFromVolume removes the given pod from the given volume in the // cache indicating the specified pod no longer requires the specified @@ -73,13 +73,13 @@ type DesiredStateOfWorld interface { // attached volumes, this is a no-op. // If after deleting the pod, the specified volume contains no other child // pods, the volume is also deleted. - DeletePodFromVolume(podName types.UniquePodName, volumeName api.UniqueVolumeName) + DeletePodFromVolume(podName types.UniquePodName, volumeName v1.UniqueVolumeName) // VolumeExists returns true if the given volume exists in the list of // volumes that should be attached to this node. // If a pod with the same unique name does not exist under the specified // volume, false is returned. - VolumeExists(volumeName api.UniqueVolumeName) bool + VolumeExists(volumeName v1.UniqueVolumeName) bool // PodExistsInVolume returns true if the given pod exists in the list of // podsToMount for the given volume in the cache. @@ -87,7 +87,7 @@ type DesiredStateOfWorld interface { // volume, false is returned. // If a volume with the name volumeName does not exist in the list of // attached volumes, false is returned. - PodExistsInVolume(podName types.UniquePodName, volumeName api.UniqueVolumeName) bool + PodExistsInVolume(podName types.UniquePodName, volumeName v1.UniqueVolumeName) bool // GetVolumesToMount generates and returns a list of volumes that should be // attached to this node and the pods they should be mounted to based on the @@ -109,7 +109,7 @@ type VolumeToMount struct { // NewDesiredStateOfWorld returns a new instance of DesiredStateOfWorld. func NewDesiredStateOfWorld(volumePluginMgr *volume.VolumePluginMgr) DesiredStateOfWorld { return &desiredStateOfWorld{ - volumesToMount: make(map[api.UniqueVolumeName]volumeToMount), + volumesToMount: make(map[v1.UniqueVolumeName]volumeToMount), volumePluginMgr: volumePluginMgr, } } @@ -119,7 +119,7 @@ type desiredStateOfWorld struct { // attached to this node and mounted to the pods referencing it. The key in // the map is the name of the volume and the value is a volume object // containing more information about the volume. - volumesToMount map[api.UniqueVolumeName]volumeToMount + volumesToMount map[v1.UniqueVolumeName]volumeToMount // volumePluginMgr is the volume plugin manager used to create volume // plugin objects. volumePluginMgr *volume.VolumePluginMgr @@ -131,7 +131,7 @@ type desiredStateOfWorld struct { // and mounted to podsToMount. type volumeToMount struct { // volumeName contains the unique identifier for this volume. - volumeName api.UniqueVolumeName + volumeName v1.UniqueVolumeName // podsToMount is a map containing the set of pods that reference this // volume and should mount it once it is attached. The key in the map is @@ -158,7 +158,7 @@ type podToMount struct { podName types.UniquePodName // Pod to mount the volume to. Used to create NewMounter. - pod *api.Pod + pod *v1.Pod // volume spec containing the specification for this volume. Used to // generate the volume plugin object, and passed to plugin methods. @@ -175,10 +175,10 @@ type podToMount struct { func (dsw *desiredStateOfWorld) AddPodToVolume( podName types.UniquePodName, - pod *api.Pod, + pod *v1.Pod, volumeSpec *volume.Spec, outerVolumeSpecName string, - volumeGidValue string) (api.UniqueVolumeName, error) { + volumeGidValue string) (v1.UniqueVolumeName, error) { dsw.Lock() defer dsw.Unlock() @@ -190,7 +190,7 @@ func (dsw *desiredStateOfWorld) AddPodToVolume( err) } - var volumeName api.UniqueVolumeName + var volumeName v1.UniqueVolumeName // The unique volume name used depends on whether the volume is attachable // or not. @@ -239,12 +239,12 @@ func (dsw *desiredStateOfWorld) AddPodToVolume( } func (dsw *desiredStateOfWorld) MarkVolumesReportedInUse( - reportedVolumes []api.UniqueVolumeName) { + reportedVolumes []v1.UniqueVolumeName) { dsw.Lock() defer dsw.Unlock() reportedVolumesMap := make( - map[api.UniqueVolumeName]bool, len(reportedVolumes) /* capacity */) + map[v1.UniqueVolumeName]bool, len(reportedVolumes) /* capacity */) for _, reportedVolume := range reportedVolumes { reportedVolumesMap[reportedVolume] = true @@ -258,7 +258,7 @@ func (dsw *desiredStateOfWorld) MarkVolumesReportedInUse( } func (dsw *desiredStateOfWorld) DeletePodFromVolume( - podName types.UniquePodName, volumeName api.UniqueVolumeName) { + podName types.UniquePodName, volumeName v1.UniqueVolumeName) { dsw.Lock() defer dsw.Unlock() @@ -281,7 +281,7 @@ func (dsw *desiredStateOfWorld) DeletePodFromVolume( } func (dsw *desiredStateOfWorld) VolumeExists( - volumeName api.UniqueVolumeName) bool { + volumeName v1.UniqueVolumeName) bool { dsw.RLock() defer dsw.RUnlock() @@ -290,7 +290,7 @@ func (dsw *desiredStateOfWorld) VolumeExists( } func (dsw *desiredStateOfWorld) PodExistsInVolume( - podName types.UniquePodName, volumeName api.UniqueVolumeName) bool { + podName types.UniquePodName, volumeName v1.UniqueVolumeName) bool { dsw.RLock() defer dsw.RUnlock() diff --git a/pkg/kubelet/volumemanager/cache/desired_state_of_world_test.go b/pkg/kubelet/volumemanager/cache/desired_state_of_world_test.go index 9d07a7850b0..3bb7467c5eb 100644 --- a/pkg/kubelet/volumemanager/cache/desired_state_of_world_test.go +++ b/pkg/kubelet/volumemanager/cache/desired_state_of_world_test.go @@ -19,7 +19,7 @@ package cache import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/volume" volumetesting "k8s.io/kubernetes/pkg/volume/testing" volumetypes "k8s.io/kubernetes/pkg/volume/util/types" @@ -33,17 +33,17 @@ func Test_AddPodToVolume_Positive_NewPodNewVolume(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) dsw := NewDesiredStateOfWorld(volumePluginMgr) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod3", UID: "pod3uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -77,17 +77,17 @@ func Test_AddPodToVolume_Positive_ExistingPodExistingVolume(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) dsw := NewDesiredStateOfWorld(volumePluginMgr) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod3", UID: "pod3uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -121,17 +121,17 @@ func Test_DeletePodFromVolume_Positive_PodExistsVolumeExists(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) dsw := NewDesiredStateOfWorld(volumePluginMgr) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod3", UID: "pod3uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -173,17 +173,17 @@ func Test_MarkVolumesReportedInUse_Positive_NewPodNewVolume(t *testing.T) { volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) dsw := NewDesiredStateOfWorld(volumePluginMgr) - pod1 := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod1 := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume1-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -195,17 +195,17 @@ func Test_MarkVolumesReportedInUse_Positive_NewPodNewVolume(t *testing.T) { volume1Spec := &volume.Spec{Volume: &pod1.Spec.Volumes[0]} pod1Name := volumehelper.GetUniquePodName(pod1) - pod2 := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod2 := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod2", UID: "pod2uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume2-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device2", }, }, @@ -217,17 +217,17 @@ func Test_MarkVolumesReportedInUse_Positive_NewPodNewVolume(t *testing.T) { volume2Spec := &volume.Spec{Volume: &pod2.Spec.Volumes[0]} pod2Name := volumehelper.GetUniquePodName(pod2) - pod3 := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod3 := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod3", UID: "pod3uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume3-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device3", }, }, @@ -258,7 +258,7 @@ func Test_MarkVolumesReportedInUse_Positive_NewPodNewVolume(t *testing.T) { } // Act - volumesReportedInUse := []api.UniqueVolumeName{generatedVolume2Name} + volumesReportedInUse := []v1.UniqueVolumeName{generatedVolume2Name} dsw.MarkVolumesReportedInUse(volumesReportedInUse) // Assert @@ -276,7 +276,7 @@ func Test_MarkVolumesReportedInUse_Positive_NewPodNewVolume(t *testing.T) { verifyPodExistsInVolumeDsw(t, pod3Name, generatedVolume3Name, dsw) // Act - volumesReportedInUse = []api.UniqueVolumeName{generatedVolume3Name} + volumesReportedInUse = []v1.UniqueVolumeName{generatedVolume3Name} dsw.MarkVolumesReportedInUse(volumesReportedInUse) // Assert @@ -295,7 +295,7 @@ func Test_MarkVolumesReportedInUse_Positive_NewPodNewVolume(t *testing.T) { } func verifyVolumeExistsDsw( - t *testing.T, expectedVolumeName api.UniqueVolumeName, dsw DesiredStateOfWorld) { + t *testing.T, expectedVolumeName v1.UniqueVolumeName, dsw DesiredStateOfWorld) { volumeExists := dsw.VolumeExists(expectedVolumeName) if !volumeExists { t.Fatalf( @@ -306,7 +306,7 @@ func verifyVolumeExistsDsw( } func verifyVolumeDoesntExist( - t *testing.T, expectedVolumeName api.UniqueVolumeName, dsw DesiredStateOfWorld) { + t *testing.T, expectedVolumeName v1.UniqueVolumeName, dsw DesiredStateOfWorld) { volumeExists := dsw.VolumeExists(expectedVolumeName) if volumeExists { t.Fatalf( @@ -318,7 +318,7 @@ func verifyVolumeDoesntExist( func verifyVolumeExistsInVolumesToMount( t *testing.T, - expectedVolumeName api.UniqueVolumeName, + expectedVolumeName v1.UniqueVolumeName, expectReportedInUse bool, dsw DesiredStateOfWorld) { volumesToMount := dsw.GetVolumesToMount() @@ -343,7 +343,7 @@ func verifyVolumeExistsInVolumesToMount( } func verifyVolumeDoesntExistInVolumesToMount( - t *testing.T, volumeToCheck api.UniqueVolumeName, dsw DesiredStateOfWorld) { + t *testing.T, volumeToCheck v1.UniqueVolumeName, dsw DesiredStateOfWorld) { volumesToMount := dsw.GetVolumesToMount() for _, volume := range volumesToMount { if volume.VolumeName == volumeToCheck { @@ -357,7 +357,7 @@ func verifyVolumeDoesntExistInVolumesToMount( func verifyPodExistsInVolumeDsw( t *testing.T, expectedPodName volumetypes.UniquePodName, - expectedVolumeName api.UniqueVolumeName, + expectedVolumeName v1.UniqueVolumeName, dsw DesiredStateOfWorld) { if podExistsInVolume := dsw.PodExistsInVolume( expectedPodName, expectedVolumeName); !podExistsInVolume { @@ -370,7 +370,7 @@ func verifyPodExistsInVolumeDsw( func verifyPodDoesntExistInVolumeDsw( t *testing.T, expectedPodName volumetypes.UniquePodName, - expectedVolumeName api.UniqueVolumeName, + expectedVolumeName v1.UniqueVolumeName, dsw DesiredStateOfWorld) { if podExistsInVolume := dsw.PodExistsInVolume( expectedPodName, expectedVolumeName); podExistsInVolume { diff --git a/pkg/kubelet/volumemanager/populator/BUILD b/pkg/kubelet/volumemanager/populator/BUILD index b202577df00..b5d4a7cfa43 100644 --- a/pkg/kubelet/volumemanager/populator/BUILD +++ b/pkg/kubelet/volumemanager/populator/BUILD @@ -16,7 +16,8 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/kubelet/container:go_default_library", "//pkg/kubelet/pod:go_default_library", "//pkg/kubelet/util/format:go_default_library", diff --git a/pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go b/pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go index 888cf9c3439..9f3c14b6dae 100644 --- a/pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go +++ b/pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go @@ -28,7 +28,8 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/pod" "k8s.io/kubernetes/pkg/kubelet/util/format" @@ -64,7 +65,7 @@ type DesiredStateOfWorldPopulator interface { // that exist on this host // desiredStateOfWorld - the cache to populate func NewDesiredStateOfWorldPopulator( - kubeClient internalclientset.Interface, + kubeClient clientset.Interface, loopSleepDuration time.Duration, getPodStatusRetryDuration time.Duration, podManager pod.Manager, @@ -83,7 +84,7 @@ func NewDesiredStateOfWorldPopulator( } type desiredStateOfWorldPopulator struct { - kubeClient internalclientset.Interface + kubeClient clientset.Interface loopSleepDuration time.Duration getPodStatusRetryDuration time.Duration podManager pod.Manager @@ -129,8 +130,8 @@ func (dswp *desiredStateOfWorldPopulator) populatorLoopFunc() func() { } } -func isPodTerminated(pod *api.Pod) bool { - return pod.Status.Phase == api.PodFailed || pod.Status.Phase == api.PodSucceeded +func isPodTerminated(pod *v1.Pod) bool { + return pod.Status.Phase == v1.PodFailed || pod.Status.Phase == v1.PodSucceeded } // Iterate through all pods and add to desired state of world if they don't @@ -160,7 +161,7 @@ func (dswp *desiredStateOfWorldPopulator) findAndRemoveDeletedPods() { } // Skip non-memory backed volumes belonging to terminated pods volume := volumeToMount.VolumeSpec.Volume - if (volume.EmptyDir == nil || volume.EmptyDir.Medium != api.StorageMediumMemory) && + if (volume.EmptyDir == nil || volume.EmptyDir.Medium != v1.StorageMediumMemory) && volume.ConfigMap == nil && volume.Secret == nil { continue } @@ -216,7 +217,7 @@ func (dswp *desiredStateOfWorldPopulator) findAndRemoveDeletedPods() { // processPodVolumes processes the volumes in the given pod and adds them to the // desired state of the world. -func (dswp *desiredStateOfWorldPopulator) processPodVolumes(pod *api.Pod) { +func (dswp *desiredStateOfWorldPopulator) processPodVolumes(pod *v1.Pod) { if pod == nil { return } @@ -294,7 +295,7 @@ func (dswp *desiredStateOfWorldPopulator) deleteProcessedPod( // createVolumeSpec creates and returns a mutatable volume.Spec object for the // specified volume. It dereference any PVC to get PV objects, if needed. func (dswp *desiredStateOfWorldPopulator) createVolumeSpec( - podVolume api.Volume, podNamespace string) (*volume.Spec, string, error) { + podVolume v1.Volume, podNamespace string) (*volume.Spec, string, error) { if pvcSource := podVolume.VolumeSource.PersistentVolumeClaim; pvcSource != nil { glog.V(10).Infof( @@ -349,10 +350,10 @@ func (dswp *desiredStateOfWorldPopulator) createVolumeSpec( "failed to deep copy %q volume object. err=%v", podVolume.Name, err) } - clonedPodVolume, ok := clonedPodVolumeObj.(api.Volume) + clonedPodVolume, ok := clonedPodVolumeObj.(v1.Volume) if !ok { return nil, "", fmt.Errorf( - "failed to cast clonedPodVolume %#v to api.Volume", + "failed to cast clonedPodVolume %#v to v1.Volume", clonedPodVolumeObj) } @@ -374,7 +375,7 @@ func (dswp *desiredStateOfWorldPopulator) getPVCExtractPV( err) } - if pvc.Status.Phase != api.ClaimBound || pvc.Spec.VolumeName == "" { + if pvc.Status.Phase != v1.ClaimBound || pvc.Spec.VolumeName == "" { return "", "", fmt.Errorf( "PVC %s/%s has non-bound phase (%q) or empty pvc.Spec.VolumeName (%q)", namespace, @@ -417,7 +418,7 @@ func (dswp *desiredStateOfWorldPopulator) getPVSpec( return volume.NewSpecFromPersistentVolume(pv, pvcReadOnly), volumeGidValue, nil } -func getPVVolumeGidAnnotationValue(pv *api.PersistentVolume) string { +func getPVVolumeGidAnnotationValue(pv *v1.PersistentVolume) string { if volumeGid, ok := pv.Annotations[volumehelper.VolumeGidAnnotationKey]; ok { return volumeGid } diff --git a/pkg/kubelet/volumemanager/reconciler/BUILD b/pkg/kubelet/volumemanager/reconciler/BUILD index eb0361c315c..04057de091c 100644 --- a/pkg/kubelet/volumemanager/reconciler/BUILD +++ b/pkg/kubelet/volumemanager/reconciler/BUILD @@ -16,8 +16,8 @@ go_library( tags = ["automanaged"], deps = [ "//cmd/kubelet/app/options:go_default_library", - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/kubelet/config:go_default_library", "//pkg/kubelet/volumemanager/cache:go_default_library", "//pkg/types:go_default_library", @@ -41,8 +41,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/kubelet/config:go_default_library", diff --git a/pkg/kubelet/volumemanager/reconciler/reconciler.go b/pkg/kubelet/volumemanager/reconciler/reconciler.go index 3db72963756..c2da681dfdf 100644 --- a/pkg/kubelet/volumemanager/reconciler/reconciler.go +++ b/pkg/kubelet/volumemanager/reconciler/reconciler.go @@ -27,8 +27,8 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/cmd/kubelet/app/options" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/kubelet/config" "k8s.io/kubernetes/pkg/kubelet/volumemanager/cache" "k8s.io/kubernetes/pkg/types" @@ -85,7 +85,7 @@ type Reconciler interface { // mounter - mounter passed in from kubelet, passed down unmount path // volumePluginMrg - volume plugin manager passed from kubelet func NewReconciler( - kubeClient internalclientset.Interface, + kubeClient clientset.Interface, controllerAttachDetachEnabled bool, loopSleepDuration time.Duration, syncDuration time.Duration, @@ -115,7 +115,7 @@ func NewReconciler( } type reconciler struct { - kubeClient internalclientset.Interface + kubeClient clientset.Interface controllerAttachDetachEnabled bool loopSleepDuration time.Duration syncDuration time.Duration @@ -401,11 +401,11 @@ type podVolume struct { } type reconstructedVolume struct { - volumeName api.UniqueVolumeName + volumeName v1.UniqueVolumeName podName volumetypes.UniquePodName volumeSpec *volumepkg.Spec outerVolumeSpecName string - pod *api.Pod + pod *v1.Pod pluginIsAttachable bool volumeGidValue string devicePath string @@ -426,7 +426,7 @@ func (rc *reconciler) syncStates(podsDir string) { return } - volumesNeedUpdate := make(map[api.UniqueVolumeName]*reconstructedVolume) + volumesNeedUpdate := make(map[v1.UniqueVolumeName]*reconstructedVolume) for _, volume := range podVolumes { reconstructedVolume, err := rc.reconstructVolume(volume) if err != nil { @@ -493,8 +493,8 @@ func (rc *reconciler) reconstructVolume(volume podVolume) (*reconstructedVolume, if err != nil { return nil, err } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ UID: types.UID(volume.podName), }, } @@ -507,7 +507,7 @@ func (rc *reconciler) reconstructVolume(volume podVolume) (*reconstructedVolume, if err != nil { return nil, err } - var uniqueVolumeName api.UniqueVolumeName + var uniqueVolumeName v1.UniqueVolumeName if attachablePlugin != nil { uniqueVolumeName = volumehelper.GetUniqueVolumeName(volume.pluginName, volumeName) } else { @@ -546,7 +546,7 @@ func (rc *reconciler) reconstructVolume(volume podVolume) (*reconstructedVolume, return reconstructedVolume, nil } -func (rc *reconciler) updateStates(volumesNeedUpdate map[api.UniqueVolumeName]*reconstructedVolume) error { +func (rc *reconciler) updateStates(volumesNeedUpdate map[v1.UniqueVolumeName]*reconstructedVolume) error { // Get the node status to retrieve volume device path information. node, fetchErr := rc.kubeClient.Core().Nodes().Get(string(rc.nodeName)) if fetchErr != nil { diff --git a/pkg/kubelet/volumemanager/reconciler/reconciler_test.go b/pkg/kubelet/volumemanager/reconciler/reconciler_test.go index 89fedb823da..3ddd5cd94f3 100644 --- a/pkg/kubelet/volumemanager/reconciler/reconciler_test.go +++ b/pkg/kubelet/volumemanager/reconciler/reconciler_test.go @@ -22,8 +22,8 @@ import ( "time" "github.com/stretchr/testify/assert" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/kubelet/config" @@ -111,17 +111,17 @@ func Test_Run_Positive_VolumeAttachAndMount(t *testing.T) { &mount.FakeMounter{}, volumePluginMgr, kubeletPodsDir) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -182,17 +182,17 @@ func Test_Run_Positive_VolumeMountControllerAttachEnabled(t *testing.T) { &mount.FakeMounter{}, volumePluginMgr, kubeletPodsDir) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -205,7 +205,7 @@ func Test_Run_Positive_VolumeMountControllerAttachEnabled(t *testing.T) { podName := volumehelper.GetUniquePodName(pod) generatedVolumeName, err := dsw.AddPodToVolume( podName, pod, volumeSpec, volumeSpec.Name(), "" /* volumeGidValue */) - dsw.MarkVolumesReportedInUse([]api.UniqueVolumeName{generatedVolumeName}) + dsw.MarkVolumesReportedInUse([]v1.UniqueVolumeName{generatedVolumeName}) // Assert if err != nil { @@ -254,17 +254,17 @@ func Test_Run_Positive_VolumeAttachMountUnmountDetach(t *testing.T) { &mount.FakeMounter{}, volumePluginMgr, kubeletPodsDir) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -337,17 +337,17 @@ func Test_Run_Positive_VolumeUnmountControllerAttachEnabled(t *testing.T) { &mount.FakeMounter{}, volumePluginMgr, kubeletPodsDir) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", UID: "pod1uid", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "volume-name", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device1", }, }, @@ -369,7 +369,7 @@ func Test_Run_Positive_VolumeUnmountControllerAttachEnabled(t *testing.T) { // Act runReconciler(reconciler) - dsw.MarkVolumesReportedInUse([]api.UniqueVolumeName{generatedVolumeName}) + dsw.MarkVolumesReportedInUse([]v1.UniqueVolumeName{generatedVolumeName}) waitForMount(t, fakePlugin, generatedVolumeName, asw) // Assert @@ -396,7 +396,7 @@ func Test_Run_Positive_VolumeUnmountControllerAttachEnabled(t *testing.T) { func waitForMount( t *testing.T, fakePlugin *volumetesting.FakeVolumePlugin, - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, asw cache.ActualStateOfWorld) { err := retryWithExponentialBackOff( time.Duration(5*time.Millisecond), @@ -420,7 +420,7 @@ func waitForMount( func waitForDetach( t *testing.T, fakePlugin *volumetesting.FakeVolumePlugin, - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, asw cache.ActualStateOfWorld) { err := retryWithExponentialBackOff( time.Duration(5*time.Millisecond), @@ -452,16 +452,16 @@ func createTestClient() *fake.Clientset { fakeClient := &fake.Clientset{} fakeClient.AddReactor("get", "nodes", func(action core.Action) (bool, runtime.Object, error) { - return true, &api.Node{ - ObjectMeta: api.ObjectMeta{Name: string(nodeName)}, - Status: api.NodeStatus{ - VolumesAttached: []api.AttachedVolume{ + return true, &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: string(nodeName)}, + Status: v1.NodeStatus{ + VolumesAttached: []v1.AttachedVolume{ { Name: "fake-plugin/volume-name", DevicePath: "fake/path", }, }}, - Spec: api.NodeSpec{ExternalID: string(nodeName)}, + Spec: v1.NodeSpec{ExternalID: string(nodeName)}, }, nil }) fakeClient.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) { diff --git a/pkg/kubelet/volumemanager/volume_manager.go b/pkg/kubelet/volumemanager/volume_manager.go index f70590e134f..42929ffae6c 100644 --- a/pkg/kubelet/volumemanager/volume_manager.go +++ b/pkg/kubelet/volumemanager/volume_manager.go @@ -22,8 +22,8 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/kubelet/config" "k8s.io/kubernetes/pkg/kubelet/container" @@ -101,7 +101,7 @@ type VolumeManager interface { // actual state of the world). // An error is returned if all volumes are not attached and mounted within // the duration defined in podAttachAndMountTimeout. - WaitForAttachAndMount(pod *api.Pod) error + WaitForAttachAndMount(pod *v1.Pod) error // GetMountedVolumesForPod returns a VolumeMap containing the volumes // referenced by the specified pod that are successfully attached and @@ -113,7 +113,7 @@ type VolumeManager interface { // GetExtraSupplementalGroupsForPod returns a list of the extra // supplemental groups for the Pod. These extra supplemental groups come // from annotations on persistent volumes that the pod depends on. - GetExtraSupplementalGroupsForPod(pod *api.Pod) []int64 + GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64 // GetVolumesInUse returns a list of all volumes that implement the volume.Attacher // interface and are currently in use according to the actual and desired @@ -124,7 +124,7 @@ type VolumeManager interface { // has been unmounted (as indicated in actual state of world). // TODO(#27653): VolumesInUse should be handled gracefully on kubelet' // restarts. - GetVolumesInUse() []api.UniqueVolumeName + GetVolumesInUse() []v1.UniqueVolumeName // ReconcilerStatesHasBeenSynced returns true only after the actual states in reconciler // has been synced at least once after kubelet starts so that it is safe to update mounted @@ -133,11 +133,11 @@ type VolumeManager interface { // VolumeIsAttached returns true if the given volume is attached to this // node. - VolumeIsAttached(volumeName api.UniqueVolumeName) bool + VolumeIsAttached(volumeName v1.UniqueVolumeName) bool // Marks the specified volume as having successfully been reported as "in // use" in the nodes's volume status. - MarkVolumesAsReportedInUse(volumesReportedAsInUse []api.UniqueVolumeName) + MarkVolumesAsReportedInUse(volumesReportedAsInUse []v1.UniqueVolumeName) } // NewVolumeManager returns a new concrete instance implementing the @@ -151,7 +151,7 @@ func NewVolumeManager( controllerAttachDetachEnabled bool, nodeName k8stypes.NodeName, podManager pod.Manager, - kubeClient internalclientset.Interface, + kubeClient clientset.Interface, volumePluginMgr *volume.VolumePluginMgr, kubeContainerRuntime kubecontainer.Runtime, mounter mount.Interface, @@ -199,7 +199,7 @@ func NewVolumeManager( type volumeManager struct { // kubeClient is the kube API client used by DesiredStateOfWorldPopulator to // communicate with the API server to fetch PV and PVC objects - kubeClient internalclientset.Interface + kubeClient clientset.Interface // volumePluginMgr is the volume plugin manager used to access volume // plugins. It must be pre-initialized. @@ -255,7 +255,7 @@ func (vm *volumeManager) GetMountedVolumesForPod( return podVolumes } -func (vm *volumeManager) GetExtraSupplementalGroupsForPod(pod *api.Pod) []int64 { +func (vm *volumeManager) GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64 { podName := volumehelper.GetUniquePodName(pod) supplementalGroups := sets.NewString() @@ -278,7 +278,7 @@ func (vm *volumeManager) GetExtraSupplementalGroupsForPod(pod *api.Pod) []int64 return result } -func (vm *volumeManager) GetVolumesInUse() []api.UniqueVolumeName { +func (vm *volumeManager) GetVolumesInUse() []v1.UniqueVolumeName { // Report volumes in desired state of world and actual state of world so // that volumes are marked in use as soon as the decision is made that the // volume *should* be attached to this node until it is safely unmounted. @@ -286,12 +286,12 @@ func (vm *volumeManager) GetVolumesInUse() []api.UniqueVolumeName { mountedVolumes := vm.actualStateOfWorld.GetGloballyMountedVolumes() volumesToReportInUse := make( - []api.UniqueVolumeName, + []v1.UniqueVolumeName, 0, /* len */ len(desiredVolumes)+len(mountedVolumes) /* cap */) desiredVolumesMap := make( - map[api.UniqueVolumeName]bool, + map[v1.UniqueVolumeName]bool, len(desiredVolumes)+len(mountedVolumes) /* cap */) for _, volume := range desiredVolumes { @@ -317,16 +317,16 @@ func (vm *volumeManager) ReconcilerStatesHasBeenSynced() bool { } func (vm *volumeManager) VolumeIsAttached( - volumeName api.UniqueVolumeName) bool { + volumeName v1.UniqueVolumeName) bool { return vm.actualStateOfWorld.VolumeExists(volumeName) } func (vm *volumeManager) MarkVolumesAsReportedInUse( - volumesReportedAsInUse []api.UniqueVolumeName) { + volumesReportedAsInUse []v1.UniqueVolumeName) { vm.desiredStateOfWorld.MarkVolumesReportedInUse(volumesReportedAsInUse) } -func (vm *volumeManager) WaitForAttachAndMount(pod *api.Pod) error { +func (vm *volumeManager) WaitForAttachAndMount(pod *v1.Pod) error { expectedVolumes := getExpectedVolumes(pod) if len(expectedVolumes) == 0 { // No volumes to verify @@ -402,7 +402,7 @@ func filterUnmountedVolumes( // getExpectedVolumes returns a list of volumes that must be mounted in order to // consider the volume setup step for this pod satisfied. -func getExpectedVolumes(pod *api.Pod) []string { +func getExpectedVolumes(pod *v1.Pod) []string { expectedVolumes := []string{} if pod == nil { return expectedVolumes @@ -418,7 +418,7 @@ func getExpectedVolumes(pod *api.Pod) []string { // getExtraSupplementalGid returns the value of an extra supplemental GID as // defined by an annotation on a volume and a boolean indicating whether the // volume defined a GID that the pod doesn't already request. -func getExtraSupplementalGid(volumeGidValue string, pod *api.Pod) (int64, bool) { +func getExtraSupplementalGid(volumeGidValue string, pod *v1.Pod) (int64, bool) { if volumeGidValue == "" { return 0, false } diff --git a/pkg/kubelet/volumemanager/volume_manager_test.go b/pkg/kubelet/volumemanager/volume_manager_test.go index a000949b92a..6ffbc2d2fa9 100644 --- a/pkg/kubelet/volumemanager/volume_manager_test.go +++ b/pkg/kubelet/volumemanager/volume_manager_test.go @@ -23,9 +23,9 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/kubelet/config" containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" @@ -64,11 +64,11 @@ func TestGetMountedVolumesForPodAndGetVolumesInUse(t *testing.T) { stopCh := runVolumeManager(manager) defer close(stopCh) - podManager.SetPods([]*api.Pod{pod}) + podManager.SetPods([]*v1.Pod{pod}) // Fake node status update go simulateVolumeInUseUpdate( - api.UniqueVolumeName(node.Status.VolumesAttached[0].Name), + v1.UniqueVolumeName(node.Status.VolumesAttached[0].Name), stopCh, manager) @@ -83,7 +83,7 @@ func TestGetMountedVolumesForPodAndGetVolumesInUse(t *testing.T) { t.Errorf("Expected %v to be mounted to pod but got %v", expectedMounted, actualMounted) } - expectedInUse := []api.UniqueVolumeName{api.UniqueVolumeName(node.Status.VolumesAttached[0].Name)} + expectedInUse := []v1.UniqueVolumeName{v1.UniqueVolumeName(node.Status.VolumesAttached[0].Name)} actualInUse := manager.GetVolumesInUse() if !reflect.DeepEqual(expectedInUse, actualInUse) { t.Errorf("Expected %v to be in use but got %v", expectedInUse, actualInUse) @@ -125,20 +125,20 @@ func TestGetExtraSupplementalGroupsForPod(t *testing.T) { } for _, tc := range cases { - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", Annotations: map[string]string{ volumehelper.VolumeGidAnnotationKey: tc.gidAnnotation, }, }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device", }, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: claim.ObjectMeta.Name, }, }, @@ -156,11 +156,11 @@ func TestGetExtraSupplementalGroupsForPod(t *testing.T) { close(stopCh) }() - podManager.SetPods([]*api.Pod{pod}) + podManager.SetPods([]*v1.Pod{pod}) // Fake node status update go simulateVolumeInUseUpdate( - api.UniqueVolumeName(node.Status.VolumesAttached[0].Name), + v1.UniqueVolumeName(node.Status.VolumesAttached[0].Name), stopCh, manager) @@ -180,7 +180,7 @@ func TestGetExtraSupplementalGroupsForPod(t *testing.T) { func newTestVolumeManager( tmpDir string, podManager pod.Manager, - kubeClient internalclientset.Interface) (VolumeManager, error) { + kubeClient clientset.Interface) (VolumeManager, error) { plug := &volumetest.FakeVolumePlugin{PluginName: "fake", Host: nil} fakeRecorder := &record.FakeRecorder{} plugMgr := &volume.VolumePluginMgr{} @@ -203,72 +203,72 @@ func newTestVolumeManager( // createObjects returns objects for making a fake clientset. The pv is // already attached to the node and bound to the claim used by the pod. -func createObjects() (*api.Node, *api.Pod, *api.PersistentVolume, *api.PersistentVolumeClaim) { - node := &api.Node{ - ObjectMeta: api.ObjectMeta{Name: testHostname}, - Status: api.NodeStatus{ - VolumesAttached: []api.AttachedVolume{ +func createObjects() (*v1.Node, *v1.Pod, *v1.PersistentVolume, *v1.PersistentVolumeClaim) { + node := &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: testHostname}, + Status: v1.NodeStatus{ + VolumesAttached: []v1.AttachedVolume{ { Name: "fake/pvA", DevicePath: "fake/path", }, }}, - Spec: api.NodeSpec{ExternalID: testHostname}, + Spec: v1.NodeSpec{ExternalID: testHostname}, } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "abc", Namespace: "nsA", UID: "1234", }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "vol1", - VolumeSource: api.VolumeSource{ - PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ + VolumeSource: v1.VolumeSource{ + PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: "claimA", }, }, }, }, - SecurityContext: &api.PodSecurityContext{ + SecurityContext: &v1.PodSecurityContext{ SupplementalGroups: []int64{555}, }, }, } - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "fake-device", }, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, + Status: v1.PersistentVolumeClaimStatus{ + Phase: v1.ClaimBound, }, } return node, pod, pv, claim } func simulateVolumeInUseUpdate( - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, stopCh <-chan struct{}, volumeManager VolumeManager) { ticker := time.NewTicker(100 * time.Millisecond) @@ -277,7 +277,7 @@ func simulateVolumeInUseUpdate( select { case <-ticker.C: volumeManager.MarkVolumesAsReportedInUse( - []api.UniqueVolumeName{volumeName}) + []v1.UniqueVolumeName{volumeName}) case <-stopCh: return } diff --git a/pkg/kubemark/BUILD b/pkg/kubemark/BUILD index feb67030c90..f7a4d03aa09 100644 --- a/pkg/kubemark/BUILD +++ b/pkg/kubemark/BUILD @@ -25,6 +25,7 @@ go_library( "//pkg/apis/componentconfig:go_default_library", "//pkg/apis/componentconfig/v1alpha1:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/record:go_default_library", "//pkg/kubelet:go_default_library", "//pkg/kubelet/cadvisor:go_default_library", diff --git a/pkg/kubemark/hollow_kubelet.go b/pkg/kubemark/hollow_kubelet.go index 7847ad0488e..b0bd0ceb465 100644 --- a/pkg/kubemark/hollow_kubelet.go +++ b/pkg/kubemark/hollow_kubelet.go @@ -23,7 +23,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/componentconfig" "k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/kubelet" "k8s.io/kubernetes/pkg/kubelet/cadvisor" "k8s.io/kubernetes/pkg/kubelet/cm" diff --git a/pkg/master/BUILD b/pkg/master/BUILD index 335ad257023..5eee04fc692 100644 --- a/pkg/master/BUILD +++ b/pkg/master/BUILD @@ -51,6 +51,7 @@ go_library( "//pkg/apis/storage/install:go_default_library", "//pkg/apis/storage/v1beta1:go_default_library", "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/genericapiserver:go_default_library", "//pkg/genericapiserver/options:go_default_library", "//pkg/healthz:go_default_library", @@ -113,6 +114,7 @@ go_test( "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/apis/rbac:go_default_library", "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/generated/openapi:go_default_library", diff --git a/pkg/master/master.go b/pkg/master/master.go index 81f2b1d07eb..d8a60961653 100644 --- a/pkg/master/master.go +++ b/pkg/master/master.go @@ -38,6 +38,7 @@ import ( rbacapi "k8s.io/kubernetes/pkg/apis/rbac/v1alpha1" storageapiv1beta1 "k8s.io/kubernetes/pkg/apis/storage/v1beta1" coreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + corev1client "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/genericapiserver" "k8s.io/kubernetes/pkg/genericapiserver/options" "k8s.io/kubernetes/pkg/healthz" @@ -258,7 +259,7 @@ func (c completedConfig) New() (*Master, error) { m.InstallAPIs(c.Config.GenericConfig.APIResourceConfigSource, restOptionsFactory.NewFor, restStorageProviders...) if c.Tunneler != nil { - m.installTunneler(c.Tunneler, coreclient.NewForConfigOrDie(c.GenericConfig.LoopbackClientConfig).Nodes()) + m.installTunneler(c.Tunneler, corev1client.NewForConfigOrDie(c.GenericConfig.LoopbackClientConfig).Nodes()) } return m, nil @@ -283,7 +284,7 @@ func (m *Master) InstallLegacyAPI(c *Config, restOptionsGetter genericapiserver. } } -func (m *Master) installTunneler(tunneler genericapiserver.Tunneler, nodeClient coreclient.NodeInterface) { +func (m *Master) installTunneler(tunneler genericapiserver.Tunneler, nodeClient corev1client.NodeInterface) { tunneler.Run(nodeAddressProvider{nodeClient}.externalAddresses) m.GenericAPIServer.AddHealthzChecks(healthz.NamedCheck("SSH Tunnel Check", genericapiserver.TunnelSyncHealthChecker(tunneler))) prometheus.NewGaugeFunc(prometheus.GaugeOpts{ @@ -352,15 +353,15 @@ func (f restOptionsFactory) NewFor(resource unversioned.GroupResource) generic.R } type nodeAddressProvider struct { - nodeClient coreclient.NodeInterface + nodeClient corev1client.NodeInterface } func (n nodeAddressProvider) externalAddresses() (addresses []string, err error) { - preferredAddressTypes := []api.NodeAddressType{ - api.NodeExternalIP, - api.NodeLegacyHostIP, + preferredAddressTypes := []apiv1.NodeAddressType{ + apiv1.NodeExternalIP, + apiv1.NodeLegacyHostIP, } - nodes, err := n.nodeClient.List(api.ListOptions{}) + nodes, err := n.nodeClient.List(apiv1.ListOptions{}) if err != nil { return nil, err } diff --git a/pkg/master/master_test.go b/pkg/master/master_test.go index 224dae6ef83..1fdde09fe1e 100644 --- a/pkg/master/master_test.go +++ b/pkg/master/master_test.go @@ -42,12 +42,11 @@ import ( "k8s.io/kubernetes/pkg/apis/extensions" extensionsapiv1beta1 "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/apis/rbac" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/restclient" openapigen "k8s.io/kubernetes/pkg/generated/openapi" "k8s.io/kubernetes/pkg/genericapiserver" kubeletclient "k8s.io/kubernetes/pkg/kubelet/client" - "k8s.io/kubernetes/pkg/registry/registrytest" "k8s.io/kubernetes/pkg/runtime" etcdtesting "k8s.io/kubernetes/pkg/storage/etcd/testing" utilnet "k8s.io/kubernetes/pkg/util/net" @@ -173,25 +172,36 @@ func (*fakeEndpointReconciler) ReconcileEndpoints(serviceName string, ip net.IP, return nil } +func makeNodeList(nodes []string, nodeResources apiv1.NodeResources) *apiv1.NodeList { + list := apiv1.NodeList{ + Items: make([]apiv1.Node, len(nodes)), + } + for i := range nodes { + list.Items[i].Name = nodes[i] + list.Items[i].Status.Capacity = nodeResources.Capacity + } + return &list +} + // TestGetNodeAddresses verifies that proper results are returned // when requesting node addresses. func TestGetNodeAddresses(t *testing.T) { assert := assert.New(t) - fakeNodeClient := fake.NewSimpleClientset(registrytest.MakeNodeList([]string{"node1", "node2"}, api.NodeResources{})).Core().Nodes() + fakeNodeClient := fake.NewSimpleClientset(makeNodeList([]string{"node1", "node2"}, apiv1.NodeResources{})).Core().Nodes() addressProvider := nodeAddressProvider{fakeNodeClient} // Fail case (no addresses associated with nodes) - nodes, _ := fakeNodeClient.List(api.ListOptions{}) + nodes, _ := fakeNodeClient.List(apiv1.ListOptions{}) addrs, err := addressProvider.externalAddresses() assert.Error(err, "addresses should have caused an error as there are no addresses.") assert.Equal([]string(nil), addrs) // Pass case with External type IP - nodes, _ = fakeNodeClient.List(api.ListOptions{}) + nodes, _ = fakeNodeClient.List(apiv1.ListOptions{}) for index := range nodes.Items { - nodes.Items[index].Status.Addresses = []api.NodeAddress{{Type: api.NodeExternalIP, Address: "127.0.0.1"}} + nodes.Items[index].Status.Addresses = []apiv1.NodeAddress{{Type: apiv1.NodeExternalIP, Address: "127.0.0.1"}} fakeNodeClient.Update(&nodes.Items[index]) } addrs, err = addressProvider.externalAddresses() @@ -199,9 +209,9 @@ func TestGetNodeAddresses(t *testing.T) { assert.Equal([]string{"127.0.0.1", "127.0.0.1"}, addrs) // Pass case with LegacyHost type IP - nodes, _ = fakeNodeClient.List(api.ListOptions{}) + nodes, _ = fakeNodeClient.List(apiv1.ListOptions{}) for index := range nodes.Items { - nodes.Items[index].Status.Addresses = []api.NodeAddress{{Type: api.NodeLegacyHostIP, Address: "127.0.0.2"}} + nodes.Items[index].Status.Addresses = []apiv1.NodeAddress{{Type: apiv1.NodeLegacyHostIP, Address: "127.0.0.2"}} fakeNodeClient.Update(&nodes.Items[index]) } addrs, err = addressProvider.externalAddresses() diff --git a/pkg/metrics/BUILD b/pkg/metrics/BUILD index f7c958e1bcd..8401e37c3ab 100644 --- a/pkg/metrics/BUILD +++ b/pkg/metrics/BUILD @@ -23,7 +23,8 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/fields:go_default_library", "//pkg/master/ports:go_default_library", "//pkg/util/system:go_default_library", diff --git a/pkg/metrics/metrics_grabber.go b/pkg/metrics/metrics_grabber.go index 61dfccc7949..f9d61f4aa41 100644 --- a/pkg/metrics/metrics_grabber.go +++ b/pkg/metrics/metrics_grabber.go @@ -21,7 +21,8 @@ import ( "time" "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/master/ports" "k8s.io/kubernetes/pkg/util/system" @@ -53,7 +54,7 @@ type MetricsGrabber struct { func NewMetricsGrabber(c clientset.Interface, kubelets bool, scheduler bool, controllers bool, apiServer bool) (*MetricsGrabber, error) { registeredMaster := false masterName := "" - nodeList, err := c.Core().Nodes().List(api.ListOptions{}) + nodeList, err := c.Core().Nodes().List(v1.ListOptions{}) if err != nil { return nil, err } @@ -61,7 +62,7 @@ func NewMetricsGrabber(c clientset.Interface, kubelets bool, scheduler bool, con glog.Warning("Can't find any Nodes in the API server to grab metrics from") } for _, node := range nodeList.Items { - if system.IsMasterNode(&node) { + if system.IsMasterNode(node.Name) { registeredMaster = true masterName = node.Name break @@ -85,7 +86,7 @@ func NewMetricsGrabber(c clientset.Interface, kubelets bool, scheduler bool, con } func (g *MetricsGrabber) GrabFromKubelet(nodeName string) (KubeletMetrics, error) { - nodes, err := g.client.Core().Nodes().List(api.ListOptions{FieldSelector: fields.Set{api.ObjectNameField: nodeName}.AsSelector()}) + nodes, err := g.client.Core().Nodes().List(v1.ListOptions{FieldSelector: fields.Set{api.ObjectNameField: nodeName}.AsSelector().String()}) if err != nil { return KubeletMetrics{}, err } @@ -166,7 +167,7 @@ func (g *MetricsGrabber) Grab() (MetricsCollection, error) { } if g.grabFromKubelets { result.KubeletMetrics = make(map[string]KubeletMetrics) - nodes, err := g.client.Core().Nodes().List(api.ListOptions{}) + nodes, err := g.client.Core().Nodes().List(v1.ListOptions{}) if err != nil { errs = append(errs, err) } else { diff --git a/pkg/proxy/config/BUILD b/pkg/proxy/config/BUILD index d3252f20f51..df9741474ae 100644 --- a/pkg/proxy/config/BUILD +++ b/pkg/proxy/config/BUILD @@ -36,6 +36,7 @@ go_test( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/runtime:go_default_library", "//pkg/watch:go_default_library", diff --git a/pkg/proxy/config/api_test.go b/pkg/proxy/config/api_test.go index 69256605826..8e0b1016a4f 100644 --- a/pkg/proxy/config/api_test.go +++ b/pkg/proxy/config/api_test.go @@ -21,6 +21,7 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/watch" @@ -31,11 +32,11 @@ type fakeLW struct { watchResp watch.Interface } -func (lw fakeLW) List(options api.ListOptions) (runtime.Object, error) { +func (lw fakeLW) List(options v1.ListOptions) (runtime.Object, error) { return lw.listResp, nil } -func (lw fakeLW) Watch(options api.ListOptions) (watch.Interface, error) { +func (lw fakeLW) Watch(options v1.ListOptions) (watch.Interface, error) { return lw.watchResp, nil } diff --git a/pkg/quota/BUILD b/pkg/quota/BUILD index 6dfe69bf462..86b30799886 100644 --- a/pkg/quota/BUILD +++ b/pkg/quota/BUILD @@ -22,6 +22,7 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/runtime:go_default_library", "//pkg/util/sets:go_default_library", ], diff --git a/pkg/quota/evaluator/core/BUILD b/pkg/quota/evaluator/core/BUILD index 26cd8d9ade1..aa91bb37d08 100644 --- a/pkg/quota/evaluator/core/BUILD +++ b/pkg/quota/evaluator/core/BUILD @@ -29,8 +29,9 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/api/validation:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/controller/informers:go_default_library", "//pkg/kubelet/qos:go_default_library", "//pkg/quota:go_default_library", @@ -54,7 +55,7 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/quota:go_default_library", ], ) diff --git a/pkg/quota/evaluator/core/configmap.go b/pkg/quota/evaluator/core/configmap.go index 3358df60f3c..476537f95d0 100644 --- a/pkg/quota/evaluator/core/configmap.go +++ b/pkg/quota/evaluator/core/configmap.go @@ -19,7 +19,8 @@ package core import ( "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/quota/generic" "k8s.io/kubernetes/pkg/runtime" @@ -38,7 +39,7 @@ func NewConfigMapEvaluator(kubeClient clientset.Interface) quota.Evaluator { MatchesScopeFunc: generic.MatchesNoScopeFunc, ConstraintsFunc: generic.ObjectCountConstraintsFunc(api.ResourceConfigMaps), UsageFunc: generic.ObjectCountUsageFunc(api.ResourceConfigMaps), - ListFuncByNamespace: func(namespace string, options api.ListOptions) ([]runtime.Object, error) { + ListFuncByNamespace: func(namespace string, options v1.ListOptions) ([]runtime.Object, error) { itemList, err := kubeClient.Core().ConfigMaps(namespace).List(options) if err != nil { return nil, err diff --git a/pkg/quota/evaluator/core/persistent_volume_claims.go b/pkg/quota/evaluator/core/persistent_volume_claims.go index fc1fc6ab207..e3c1e033e83 100644 --- a/pkg/quota/evaluator/core/persistent_volume_claims.go +++ b/pkg/quota/evaluator/core/persistent_volume_claims.go @@ -24,7 +24,8 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller/informers" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/quota/generic" @@ -37,7 +38,7 @@ func listPersistentVolumeClaimsByNamespaceFuncUsingClient(kubeClient clientset.I // TODO: ideally, we could pass dynamic client pool down into this code, and have one way of doing this. // unfortunately, dynamic client works with Unstructured objects, and when we calculate Usage, we require // structured objects. - return func(namespace string, options api.ListOptions) ([]runtime.Object, error) { + return func(namespace string, options v1.ListOptions) ([]runtime.Object, error) { itemList, err := kubeClient.Core().PersistentVolumeClaims(namespace).List(options) if err != nil { return nil, err @@ -75,13 +76,21 @@ func NewPersistentVolumeClaimEvaluator(kubeClient clientset.Interface, f informe // PersistentVolumeClaimUsageFunc knows how to measure usage associated with persistent volume claims func PersistentVolumeClaimUsageFunc(object runtime.Object) api.ResourceList { - pvc, ok := object.(*api.PersistentVolumeClaim) - if !ok { - return api.ResourceList{} - } result := api.ResourceList{} + var found bool + var request resource.Quantity + + switch t := object.(type) { + case *v1.PersistentVolumeClaim: + request, found = t.Spec.Resources.Requests[v1.ResourceStorage] + case *api.PersistentVolumeClaim: + request, found = t.Spec.Resources.Requests[api.ResourceStorage] + default: + panic(fmt.Sprintf("expect *api.PersistenVolumeClaim or *v1.PersistentVolumeClaim, got %v", t)) + } + result[api.ResourcePersistentVolumeClaims] = resource.MustParse("1") - if request, found := pvc.Spec.Resources.Requests[api.ResourceStorage]; found { + if found { result[api.ResourceRequestsStorage] = request } return result diff --git a/pkg/quota/evaluator/core/persistent_volume_claims_test.go b/pkg/quota/evaluator/core/persistent_volume_claims_test.go index 775e3df4fb5..7d24ba38dd0 100644 --- a/pkg/quota/evaluator/core/persistent_volume_claims_test.go +++ b/pkg/quota/evaluator/core/persistent_volume_claims_test.go @@ -22,7 +22,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/quota" ) diff --git a/pkg/quota/evaluator/core/pods.go b/pkg/quota/evaluator/core/pods.go index 4d5d8ea75d4..c270211128f 100644 --- a/pkg/quota/evaluator/core/pods.go +++ b/pkg/quota/evaluator/core/pods.go @@ -24,8 +24,9 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/api/validation" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller/informers" "k8s.io/kubernetes/pkg/kubelet/qos" "k8s.io/kubernetes/pkg/quota" @@ -40,7 +41,7 @@ func listPodsByNamespaceFuncUsingClient(kubeClient clientset.Interface) generic. // TODO: ideally, we could pass dynamic client pool down into this code, and have one way of doing this. // unfortunately, dynamic client works with Unstructured objects, and when we calculate Usage, we require // structured objects. - return func(namespace string, options api.ListOptions) ([]runtime.Object, error) { + return func(namespace string, options v1.ListOptions) ([]runtime.Object, error) { itemList, err := kubeClient.Core().Pods(namespace).List(options) if err != nil { return nil, err @@ -163,23 +164,32 @@ func podUsageHelper(requests api.ResourceList, limits api.ResourceList) api.Reso return result } -// PodUsageFunc knows how to measure usage associated with pods -func PodUsageFunc(object runtime.Object) api.ResourceList { - pod, ok := object.(*api.Pod) - if !ok { - return api.ResourceList{} +func toInternalPodOrDie(obj runtime.Object) *api.Pod { + pod := &api.Pod{} + switch t := obj.(type) { + case *v1.Pod: + if err := v1.Convert_v1_Pod_To_api_Pod(t, pod, nil); err != nil { + panic(err) + } + case *api.Pod: + pod = t + default: + panic(fmt.Sprintf("expect *api.Pod or *v1.Pod, got %v", t)) } + return pod +} +// PodUsageFunc knows how to measure usage associated with pods +func PodUsageFunc(obj runtime.Object) api.ResourceList { + pod := toInternalPodOrDie(obj) // by convention, we do not quota pods that have reached an end-of-life state if !QuotaPod(pod) { return api.ResourceList{} } - - // TODO: fix this when we have pod level cgroups - // when we have pod level cgroups, we can just read pod level requests/limits requests := api.ResourceList{} limits := api.ResourceList{} - + // TODO: fix this when we have pod level cgroups + // when we have pod level cgroups, we can just read pod level requests/limits for i := range pod.Spec.Containers { requests = quota.Add(requests, pod.Spec.Containers[i].Resources.Requests) limits = quota.Add(limits, pod.Spec.Containers[i].Resources.Limits) @@ -197,10 +207,7 @@ func PodUsageFunc(object runtime.Object) api.ResourceList { // PodMatchesScopeFunc is a function that knows how to evaluate if a pod matches a scope func PodMatchesScopeFunc(scope api.ResourceQuotaScope, object runtime.Object) bool { - pod, ok := object.(*api.Pod) - if !ok { - return false - } + pod := toInternalPodOrDie(object) switch scope { case api.ResourceQuotaScopeTerminating: return isTerminating(pod) @@ -215,7 +222,7 @@ func PodMatchesScopeFunc(scope api.ResourceQuotaScope, object runtime.Object) bo } func isBestEffort(pod *api.Pod) bool { - return qos.GetPodQOS(pod) == qos.BestEffort + return qos.InternalGetPodQOS(pod) == qos.BestEffort } func isTerminating(pod *api.Pod) bool { @@ -228,7 +235,11 @@ func isTerminating(pod *api.Pod) bool { // QuotaPod returns true if the pod is eligible to track against a quota // if it's not in a terminal state according to its phase. func QuotaPod(pod *api.Pod) bool { - // see GetPhase in kubelet.go for details on how it covers all restart policy conditions - // https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet.go#L3001 return !(api.PodFailed == pod.Status.Phase || api.PodSucceeded == pod.Status.Phase) } + +// QuotaV1Pod returns true if the pod is eligible to track against a quota +// if it's not in a terminal state according to its phase. +func QuotaV1Pod(pod *v1.Pod) bool { + return !(v1.PodFailed == pod.Status.Phase || v1.PodSucceeded == pod.Status.Phase) +} diff --git a/pkg/quota/evaluator/core/pods_test.go b/pkg/quota/evaluator/core/pods_test.go index 32c454fb4d8..79ed8783e15 100644 --- a/pkg/quota/evaluator/core/pods_test.go +++ b/pkg/quota/evaluator/core/pods_test.go @@ -21,7 +21,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/quota" ) diff --git a/pkg/quota/evaluator/core/registry.go b/pkg/quota/evaluator/core/registry.go index 7768848abde..093a61798d4 100644 --- a/pkg/quota/evaluator/core/registry.go +++ b/pkg/quota/evaluator/core/registry.go @@ -18,7 +18,7 @@ package core import ( "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller/informers" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/quota/generic" diff --git a/pkg/quota/evaluator/core/replication_controllers.go b/pkg/quota/evaluator/core/replication_controllers.go index c95da8c34de..bf1c63e9712 100644 --- a/pkg/quota/evaluator/core/replication_controllers.go +++ b/pkg/quota/evaluator/core/replication_controllers.go @@ -19,7 +19,8 @@ package core import ( "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/quota/generic" "k8s.io/kubernetes/pkg/runtime" @@ -38,7 +39,7 @@ func NewReplicationControllerEvaluator(kubeClient clientset.Interface) quota.Eva MatchesScopeFunc: generic.MatchesNoScopeFunc, ConstraintsFunc: generic.ObjectCountConstraintsFunc(api.ResourceReplicationControllers), UsageFunc: generic.ObjectCountUsageFunc(api.ResourceReplicationControllers), - ListFuncByNamespace: func(namespace string, options api.ListOptions) ([]runtime.Object, error) { + ListFuncByNamespace: func(namespace string, options v1.ListOptions) ([]runtime.Object, error) { itemList, err := kubeClient.Core().ReplicationControllers(namespace).List(options) if err != nil { return nil, err diff --git a/pkg/quota/evaluator/core/resource_quotas.go b/pkg/quota/evaluator/core/resource_quotas.go index 5652ea5b545..6ea1fc28f46 100644 --- a/pkg/quota/evaluator/core/resource_quotas.go +++ b/pkg/quota/evaluator/core/resource_quotas.go @@ -19,7 +19,8 @@ package core import ( "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/quota/generic" "k8s.io/kubernetes/pkg/runtime" @@ -38,7 +39,7 @@ func NewResourceQuotaEvaluator(kubeClient clientset.Interface) quota.Evaluator { MatchesScopeFunc: generic.MatchesNoScopeFunc, ConstraintsFunc: generic.ObjectCountConstraintsFunc(api.ResourceQuotas), UsageFunc: generic.ObjectCountUsageFunc(api.ResourceQuotas), - ListFuncByNamespace: func(namespace string, options api.ListOptions) ([]runtime.Object, error) { + ListFuncByNamespace: func(namespace string, options v1.ListOptions) ([]runtime.Object, error) { itemList, err := kubeClient.Core().ResourceQuotas(namespace).List(options) if err != nil { return nil, err diff --git a/pkg/quota/evaluator/core/secrets.go b/pkg/quota/evaluator/core/secrets.go index 48676f35ab8..d664480ea3a 100644 --- a/pkg/quota/evaluator/core/secrets.go +++ b/pkg/quota/evaluator/core/secrets.go @@ -19,7 +19,8 @@ package core import ( "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/quota/generic" "k8s.io/kubernetes/pkg/runtime" @@ -38,7 +39,7 @@ func NewSecretEvaluator(kubeClient clientset.Interface) quota.Evaluator { MatchesScopeFunc: generic.MatchesNoScopeFunc, ConstraintsFunc: generic.ObjectCountConstraintsFunc(api.ResourceSecrets), UsageFunc: generic.ObjectCountUsageFunc(api.ResourceSecrets), - ListFuncByNamespace: func(namespace string, options api.ListOptions) ([]runtime.Object, error) { + ListFuncByNamespace: func(namespace string, options v1.ListOptions) ([]runtime.Object, error) { itemList, err := kubeClient.Core().Secrets(namespace).List(options) if err != nil { return nil, err diff --git a/pkg/quota/evaluator/core/services.go b/pkg/quota/evaluator/core/services.go index 3d07335f9fa..d6a6378c9df 100644 --- a/pkg/quota/evaluator/core/services.go +++ b/pkg/quota/evaluator/core/services.go @@ -23,7 +23,8 @@ import ( "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/quota/generic" "k8s.io/kubernetes/pkg/runtime" @@ -48,7 +49,7 @@ func NewServiceEvaluator(kubeClient clientset.Interface) quota.Evaluator { MatchesScopeFunc: generic.MatchesNoScopeFunc, ConstraintsFunc: ServiceConstraintsFunc, UsageFunc: ServiceUsageFunc, - ListFuncByNamespace: func(namespace string, options api.ListOptions) ([]runtime.Object, error) { + ListFuncByNamespace: func(namespace string, options v1.ListOptions) ([]runtime.Object, error) { itemList, err := kubeClient.Core().Services(namespace).List(options) if err != nil { return nil, err @@ -65,42 +66,54 @@ func NewServiceEvaluator(kubeClient clientset.Interface) quota.Evaluator { // ServiceUsageFunc knows how to measure usage associated with services func ServiceUsageFunc(object runtime.Object) api.ResourceList { result := api.ResourceList{} - if service, ok := object.(*api.Service); ok { - // default service usage - result[api.ResourceServices] = resource.MustParse("1") - result[api.ResourceServicesLoadBalancers] = resource.MustParse("0") - result[api.ResourceServicesNodePorts] = resource.MustParse("0") - switch service.Spec.Type { - case api.ServiceTypeNodePort: - // node port services need to count node ports - value := resource.NewQuantity(int64(len(service.Spec.Ports)), resource.DecimalSI) - result[api.ResourceServicesNodePorts] = *value - case api.ServiceTypeLoadBalancer: - // load balancer services need to count load balancers - result[api.ResourceServicesLoadBalancers] = resource.MustParse("1") - } + var serviceType api.ServiceType + var ports int + + switch t := object.(type) { + case *v1.Service: + serviceType = api.ServiceType(t.Spec.Type) + ports = len(t.Spec.Ports) + case *api.Service: + serviceType = t.Spec.Type + ports = len(t.Spec.Ports) + default: + panic(fmt.Sprintf("expect *api.Service or *v1.Service, got %v", t)) + } + + // default service usage + result[api.ResourceServices] = resource.MustParse("1") + result[api.ResourceServicesLoadBalancers] = resource.MustParse("0") + result[api.ResourceServicesNodePorts] = resource.MustParse("0") + switch serviceType { + case api.ServiceTypeNodePort: + // node port services need to count node ports + value := resource.NewQuantity(int64(ports), resource.DecimalSI) + result[api.ResourceServicesNodePorts] = *value + case api.ServiceTypeLoadBalancer: + // load balancer services need to count load balancers + result[api.ResourceServicesLoadBalancers] = resource.MustParse("1") } return result } // QuotaServiceType returns true if the service type is eligible to track against a quota -func QuotaServiceType(service *api.Service) bool { +func QuotaServiceType(service *v1.Service) bool { switch service.Spec.Type { - case api.ServiceTypeNodePort, api.ServiceTypeLoadBalancer: + case v1.ServiceTypeNodePort, v1.ServiceTypeLoadBalancer: return true } return false } //GetQuotaServiceType returns ServiceType if the service type is eligible to track against a quota, nor return "" -func GetQuotaServiceType(service *api.Service) api.ServiceType { +func GetQuotaServiceType(service *v1.Service) v1.ServiceType { switch service.Spec.Type { - case api.ServiceTypeNodePort: - return api.ServiceTypeNodePort - case api.ServiceTypeLoadBalancer: - return api.ServiceTypeLoadBalancer + case v1.ServiceTypeNodePort: + return v1.ServiceTypeNodePort + case v1.ServiceTypeLoadBalancer: + return v1.ServiceTypeLoadBalancer } - return api.ServiceType("") + return v1.ServiceType("") } // ServiceConstraintsFunc verifies that all required resources are captured in service usage. diff --git a/pkg/quota/evaluator/core/services_test.go b/pkg/quota/evaluator/core/services_test.go index fc0c5a5bec8..d5f17955fdc 100644 --- a/pkg/quota/evaluator/core/services_test.go +++ b/pkg/quota/evaluator/core/services_test.go @@ -21,7 +21,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/quota" ) diff --git a/pkg/quota/generic/BUILD b/pkg/quota/generic/BUILD index 7bad635e237..312be816d01 100644 --- a/pkg/quota/generic/BUILD +++ b/pkg/quota/generic/BUILD @@ -22,6 +22,7 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/controller/informers:go_default_library", "//pkg/labels:go_default_library", "//pkg/quota:go_default_library", diff --git a/pkg/quota/generic/evaluator.go b/pkg/quota/generic/evaluator.go index 9c8bda66d30..554756f35e9 100644 --- a/pkg/quota/generic/evaluator.go +++ b/pkg/quota/generic/evaluator.go @@ -23,6 +23,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/controller/informers" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/quota" @@ -31,12 +32,16 @@ import ( // ListResourceUsingInformerFunc returns a listing function based on the shared informer factory for the specified resource. func ListResourceUsingInformerFunc(f informers.SharedInformerFactory, groupResource unversioned.GroupResource) ListFuncByNamespace { - return func(namespace string, options api.ListOptions) ([]runtime.Object, error) { + return func(namespace string, options v1.ListOptions) ([]runtime.Object, error) { + labelSelector, err := labels.Parse(options.LabelSelector) + if err != nil { + return nil, err + } informer, err := f.ForResource(groupResource) if err != nil { return nil, err } - return informer.Lister().ByNamespace(namespace).List(options.LabelSelector) + return informer.Lister().ByNamespace(namespace).List(labelSelector) } } @@ -47,7 +52,7 @@ type ConstraintsFunc func(required []api.ResourceName, item runtime.Object) erro type GetFuncByNamespace func(namespace, name string) (runtime.Object, error) // ListFuncByNamespace knows how to list resources in a namespace -type ListFuncByNamespace func(namespace string, options api.ListOptions) ([]runtime.Object, error) +type ListFuncByNamespace func(namespace string, options v1.ListOptions) ([]runtime.Object, error) // MatchesScopeFunc knows how to evaluate if an object matches a scope type MatchesScopeFunc func(scope api.ResourceQuotaScope, object runtime.Object) bool @@ -183,8 +188,8 @@ func (g *GenericEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.Us for _, resourceName := range g.MatchedResourceNames { result.Used[resourceName] = resource.MustParse("0") } - items, err := g.ListFuncByNamespace(options.Namespace, api.ListOptions{ - LabelSelector: labels.Everything(), + items, err := g.ListFuncByNamespace(options.Namespace, v1.ListOptions{ + LabelSelector: labels.Everything().String(), }) if err != nil { return result, fmt.Errorf("%s: Failed to list %v: %v", g.Name, g.GroupKind(), err) diff --git a/pkg/quota/install/BUILD b/pkg/quota/install/BUILD index 8055b14fa09..bad7181de83 100644 --- a/pkg/quota/install/BUILD +++ b/pkg/quota/install/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["registry.go"], tags = ["automanaged"], deps = [ - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/controller/informers:go_default_library", "//pkg/quota:go_default_library", "//pkg/quota/evaluator/core:go_default_library", diff --git a/pkg/quota/install/registry.go b/pkg/quota/install/registry.go index 563702b4413..0e910d42feb 100644 --- a/pkg/quota/install/registry.go +++ b/pkg/quota/install/registry.go @@ -17,7 +17,7 @@ limitations under the License. package install import ( - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller/informers" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/quota/evaluator/core" diff --git a/pkg/quota/resources.go b/pkg/quota/resources.go index 94e0f6b3c98..4629faec5ab 100644 --- a/pkg/quota/resources.go +++ b/pkg/quota/resources.go @@ -19,6 +19,7 @@ package quota import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/sets" ) @@ -45,6 +46,29 @@ func Equals(a api.ResourceList, b api.ResourceList) bool { return true } +// V1Equals returns true if the two lists are equivalent +func V1Equals(a v1.ResourceList, b v1.ResourceList) bool { + for key, value1 := range a { + value2, found := b[key] + if !found { + return false + } + if value1.Cmp(value2) != 0 { + return false + } + } + for key, value1 := range b { + value2, found := a[key] + if !found { + return false + } + if value1.Cmp(value2) != 0 { + return false + } + } + return true +} + // LessThanOrEqual returns true if a < b for each key in b // If false, it returns the keys in a that exceeded b func LessThanOrEqual(a api.ResourceList, b api.ResourceList) (bool, []api.ResourceName) { diff --git a/pkg/registry/core/node/etcd/BUILD b/pkg/registry/core/node/etcd/BUILD index 0054cb5ea98..da64c2a115d 100644 --- a/pkg/registry/core/node/etcd/BUILD +++ b/pkg/registry/core/node/etcd/BUILD @@ -17,6 +17,7 @@ go_library( deps = [ "//pkg/api:go_default_library", "//pkg/api/rest:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/client:go_default_library", "//pkg/registry/cachesize:go_default_library", "//pkg/registry/core/node:go_default_library", diff --git a/pkg/registry/core/node/etcd/etcd.go b/pkg/registry/core/node/etcd/etcd.go index ed5e0bae7ad..f78548b528d 100644 --- a/pkg/registry/core/node/etcd/etcd.go +++ b/pkg/registry/core/node/etcd/etcd.go @@ -23,6 +23,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/client" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/core/node" @@ -115,7 +116,7 @@ func NewStorage(opts generic.RESTOptions, kubeletClientConfig client.KubeletClie proxyREST := &noderest.ProxyREST{Store: store, ProxyTransport: proxyTransport} // Build a NodeGetter that looks up nodes using the REST handler - nodeGetter := client.NodeGetterFunc(func(nodeName string) (*api.Node, error) { + nodeGetter := client.NodeGetterFunc(func(nodeName string) (*v1.Node, error) { obj, err := nodeREST.Get(api.NewContext(), nodeName) if err != nil { return nil, err @@ -124,7 +125,13 @@ func NewStorage(opts generic.RESTOptions, kubeletClientConfig client.KubeletClie if !ok { return nil, fmt.Errorf("unexpected type %T", obj) } - return node, nil + // TODO: Remove the conversion. Consider only return the NodeAddresses + externalNode := &v1.Node{} + err = v1.Convert_api_Node_To_v1_Node(node, externalNode, nil) + if err != nil { + return nil, fmt.Errorf("failed to convert to v1.Node: %v", err) + } + return externalNode, nil }) connectionInfoGetter, err := client.NewNodeConnectionInfoGetter(nodeGetter, kubeletClientConfig) if err != nil { diff --git a/pkg/registry/core/pod/etcd/etcd_test.go b/pkg/registry/core/pod/etcd/etcd_test.go index a89bb93a923..a67ffd7d76f 100644 --- a/pkg/registry/core/pod/etcd/etcd_test.go +++ b/pkg/registry/core/pod/etcd/etcd_test.go @@ -63,7 +63,7 @@ func validNewPod() *api.Pod { ImagePullPolicy: api.PullAlways, TerminationMessagePath: api.TerminationMessagePathDefault, - SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), + SecurityContext: securitycontext.ValidInternalSecurityContextWithContainerDefaults(), }, }, SecurityContext: &api.PodSecurityContext{}, @@ -658,7 +658,7 @@ func TestEtcdUpdateScheduled(t *testing.T) { { Name: "foobar", Image: "foo:v1", - SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), + SecurityContext: securitycontext.ValidInternalSecurityContextWithContainerDefaults(), }, }, SecurityContext: &api.PodSecurityContext{}, @@ -683,7 +683,7 @@ func TestEtcdUpdateScheduled(t *testing.T) { Image: "foo:v2", ImagePullPolicy: api.PullIfNotPresent, TerminationMessagePath: api.TerminationMessagePathDefault, - SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), + SecurityContext: securitycontext.ValidInternalSecurityContextWithContainerDefaults(), }}, RestartPolicy: api.RestartPolicyAlways, DNSPolicy: api.DNSClusterFirst, @@ -727,7 +727,7 @@ func TestEtcdUpdateStatus(t *testing.T) { Containers: []api.Container{ { Image: "foo:v1", - SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), + SecurityContext: securitycontext.ValidInternalSecurityContextWithContainerDefaults(), }, }, SecurityContext: &api.PodSecurityContext{}, diff --git a/pkg/security/apparmor/BUILD b/pkg/security/apparmor/BUILD index 63cbee69b4b..06aa72e0cc3 100644 --- a/pkg/security/apparmor/BUILD +++ b/pkg/security/apparmor/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/util:go_default_library", "//pkg/util/config:go_default_library", ], @@ -33,7 +33,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//vendor:github.com/stretchr/testify/assert", ], ) diff --git a/pkg/security/apparmor/helpers.go b/pkg/security/apparmor/helpers.go index eb576bf3824..4412d2a9a1d 100644 --- a/pkg/security/apparmor/helpers.go +++ b/pkg/security/apparmor/helpers.go @@ -19,7 +19,7 @@ package apparmor import ( "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) // TODO: Move these values into the API package. @@ -38,7 +38,7 @@ const ( ) // Checks whether app armor is required for pod to be run. -func isRequired(pod *api.Pod) bool { +func isRequired(pod *v1.Pod) bool { for key := range pod.Annotations { if strings.HasPrefix(key, ContainerAnnotationKeyPrefix) { return true @@ -48,7 +48,7 @@ func isRequired(pod *api.Pod) bool { } // Returns the name of the profile to use with the container. -func GetProfileName(pod *api.Pod, containerName string) string { +func GetProfileName(pod *v1.Pod, containerName string) string { return GetProfileNameFromPodAnnotations(pod.Annotations, containerName) } @@ -59,10 +59,19 @@ func GetProfileNameFromPodAnnotations(annotations map[string]string, containerNa } // Sets the name of the profile to use with the container. -func SetProfileName(pod *api.Pod, containerName, profileName string) error { +func SetProfileName(pod *v1.Pod, containerName, profileName string) error { if pod.Annotations == nil { pod.Annotations = map[string]string{} } pod.Annotations[ContainerAnnotationKeyPrefix+containerName] = profileName return nil } + +// Sets the name of the profile to use with the container. +func SetProfileNameFromPodAnnotations(annotations map[string]string, containerName, profileName string) error { + if annotations == nil { + return nil + } + annotations[ContainerAnnotationKeyPrefix+containerName] = profileName + return nil +} diff --git a/pkg/security/apparmor/validate.go b/pkg/security/apparmor/validate.go index 79790c2a0c2..deed85fcec1 100644 --- a/pkg/security/apparmor/validate.go +++ b/pkg/security/apparmor/validate.go @@ -25,7 +25,7 @@ import ( "path" "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util" utilconfig "k8s.io/kubernetes/pkg/util/config" ) @@ -36,7 +36,7 @@ var isDisabledBuild bool // Interface for validating that a pod with with an AppArmor profile can be run by a Node. type Validator interface { - Validate(pod *api.Pod) error + Validate(pod *v1.Pod) error ValidateHost() error } @@ -60,7 +60,7 @@ type validator struct { appArmorFS string } -func (v *validator) Validate(pod *api.Pod) error { +func (v *validator) Validate(pod *v1.Pod) error { if !isRequired(pod) { return nil } diff --git a/pkg/security/apparmor/validate_test.go b/pkg/security/apparmor/validate_test.go index 5085b6ab4e8..2c293a5f3dd 100644 --- a/pkg/security/apparmor/validate_test.go +++ b/pkg/security/apparmor/validate_test.go @@ -21,7 +21,7 @@ import ( "fmt" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "github.com/stretchr/testify/assert" ) @@ -133,19 +133,19 @@ func TestValidateValidHost(t *testing.T) { } // Test multi-container pod. - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ ContainerAnnotationKeyPrefix + "init": ProfileNamePrefix + "foo-container", ContainerAnnotationKeyPrefix + "test1": ProfileRuntimeDefault, ContainerAnnotationKeyPrefix + "test2": ProfileNamePrefix + "docker-default", }, }, - Spec: api.PodSpec{ - InitContainers: []api.Container{ + Spec: v1.PodSpec{ + InitContainers: []v1.Container{ {Name: "init"}, }, - Containers: []api.Container{ + Containers: []v1.Container{ {Name: "test1"}, {Name: "test2"}, {Name: "no-profile"}, @@ -172,7 +172,7 @@ func TestParseProfileName(t *testing.T) { } } -func getPodWithProfile(profile string) *api.Pod { +func getPodWithProfile(profile string) *v1.Pod { annotations := map[string]string{ ContainerAnnotationKeyPrefix + "test": profile, } @@ -181,12 +181,12 @@ func getPodWithProfile(profile string) *api.Pod { "foo": "bar", } } - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: annotations, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "test", }, diff --git a/pkg/security/podsecuritypolicy/BUILD b/pkg/security/podsecuritypolicy/BUILD index 4b4e5213612..f522207598c 100644 --- a/pkg/security/podsecuritypolicy/BUILD +++ b/pkg/security/podsecuritypolicy/BUILD @@ -43,6 +43,7 @@ go_test( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/extensions:go_default_library", "//pkg/security/apparmor:go_default_library", "//pkg/security/podsecuritypolicy/seccomp:go_default_library", diff --git a/pkg/security/podsecuritypolicy/apparmor/strategy.go b/pkg/security/podsecuritypolicy/apparmor/strategy.go index 2fa8bff6878..d2a1963e198 100644 --- a/pkg/security/podsecuritypolicy/apparmor/strategy.go +++ b/pkg/security/podsecuritypolicy/apparmor/strategy.go @@ -92,7 +92,7 @@ func (s *strategy) Validate(pod *api.Pod, container *api.Container) field.ErrorL allErrs := field.ErrorList{} fieldPath := field.NewPath("pod", "metadata", "annotations").Key(apparmor.ContainerAnnotationKeyPrefix + container.Name) - profile := apparmor.GetProfileName(pod, container.Name) + profile := apparmor.GetProfileNameFromPodAnnotations(pod.Annotations, container.Name) if profile == "" { if len(s.allowedProfiles) > 0 { allErrs = append(allErrs, field.Forbidden(fieldPath, "AppArmor profile must be set")) diff --git a/pkg/security/podsecuritypolicy/provider_test.go b/pkg/security/podsecuritypolicy/provider_test.go index 26702032ad6..26e5749cc2b 100644 --- a/pkg/security/podsecuritypolicy/provider_test.go +++ b/pkg/security/podsecuritypolicy/provider_test.go @@ -25,6 +25,7 @@ import ( "github.com/davecgh/go-spew/spew" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/security/apparmor" "k8s.io/kubernetes/pkg/security/podsecuritypolicy/seccomp" @@ -373,8 +374,11 @@ func TestValidateContainerSecurityContextFailures(t *testing.T) { } failNilAppArmorPod := defaultPod() - failInvalidAppArmorPod := defaultPod() - apparmor.SetProfileName(failInvalidAppArmorPod, defaultContainerName, apparmor.ProfileNamePrefix+"foo") + v1FailInvalidAppArmorPod := defaultV1Pod() + apparmor.SetProfileName(v1FailInvalidAppArmorPod, defaultContainerName, apparmor.ProfileNamePrefix+"foo") + failInvalidAppArmorPod := &api.Pod{} + v1.Convert_v1_Pod_To_api_Pod(v1FailInvalidAppArmorPod, failInvalidAppArmorPod, nil) + failAppArmorPSP := defaultPSP() failAppArmorPSP.Annotations = map[string]string{ apparmor.AllowedProfilesAnnotationKey: apparmor.ProfileRuntimeDefault, @@ -669,8 +673,10 @@ func TestValidateContainerSecurityContextSuccess(t *testing.T) { appArmorPSP.Annotations = map[string]string{ apparmor.AllowedProfilesAnnotationKey: apparmor.ProfileRuntimeDefault, } - appArmorPod := defaultPod() - apparmor.SetProfileName(appArmorPod, defaultContainerName, apparmor.ProfileRuntimeDefault) + v1AppArmorPod := defaultV1Pod() + apparmor.SetProfileName(v1AppArmorPod, defaultContainerName, apparmor.ProfileRuntimeDefault) + appArmorPod := &api.Pod{} + v1.Convert_v1_Pod_To_api_Pod(v1AppArmorPod, appArmorPod, nil) privPSP := defaultPSP() privPSP.Spec.Privileged = true @@ -930,6 +936,30 @@ func defaultPod() *api.Pod { } } +func defaultV1Pod() *v1.Pod { + var notPriv bool = false + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ + Annotations: map[string]string{}, + }, + Spec: v1.PodSpec{ + SecurityContext: &v1.PodSecurityContext{ + // fill in for test cases + }, + Containers: []v1.Container{ + { + Name: defaultContainerName, + SecurityContext: &v1.SecurityContext{ + // expected to be set by defaulting mechanisms + Privileged: ¬Priv, + // fill in the rest for test cases + }, + }, + }, + }, + } +} + // TestValidateAllowedVolumes will test that for every field of VolumeSource we can create // a pod with that type of volume and deny it, accept it explicitly, or accept it with // the FSTypeAll wildcard. diff --git a/pkg/securitycontext/BUILD b/pkg/securitycontext/BUILD index 2c7613604c5..05541864581 100644 --- a/pkg/securitycontext/BUILD +++ b/pkg/securitycontext/BUILD @@ -22,6 +22,7 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/kubelet/leaky:go_default_library", "//vendor:github.com/docker/engine-api/types/container", ], @@ -36,8 +37,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/testing:go_default_library", + "//pkg/api/v1:go_default_library", "//vendor:github.com/docker/engine-api/types/container", ], ) diff --git a/pkg/securitycontext/fake.go b/pkg/securitycontext/fake.go index ef86de3c868..f40d64b75cf 100644 --- a/pkg/securitycontext/fake.go +++ b/pkg/securitycontext/fake.go @@ -18,16 +18,17 @@ package securitycontext import ( "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" dockercontainer "github.com/docker/engine-api/types/container" ) // ValidSecurityContextWithContainerDefaults creates a valid security context provider based on // empty container defaults. Used for testing. -func ValidSecurityContextWithContainerDefaults() *api.SecurityContext { +func ValidSecurityContextWithContainerDefaults() *v1.SecurityContext { priv := false - return &api.SecurityContext{ - Capabilities: &api.Capabilities{}, + return &v1.SecurityContext{ + Capabilities: &v1.Capabilities{}, Privileged: &priv, } } @@ -39,7 +40,17 @@ func NewFakeSecurityContextProvider() SecurityContextProvider { type FakeSecurityContextProvider struct{} -func (p FakeSecurityContextProvider) ModifyContainerConfig(pod *api.Pod, container *api.Container, config *dockercontainer.Config) { +func (p FakeSecurityContextProvider) ModifyContainerConfig(pod *v1.Pod, container *v1.Container, config *dockercontainer.Config) { } -func (p FakeSecurityContextProvider) ModifyHostConfig(pod *api.Pod, container *api.Container, hostConfig *dockercontainer.HostConfig, supplementalGids []int64) { +func (p FakeSecurityContextProvider) ModifyHostConfig(pod *v1.Pod, container *v1.Container, hostConfig *dockercontainer.HostConfig, supplementalGids []int64) { +} + +// ValidInternalSecurityContextWithContainerDefaults creates a valid security context provider based on +// empty container defaults. Used for testing. +func ValidInternalSecurityContextWithContainerDefaults() *api.SecurityContext { + priv := false + return &api.SecurityContext{ + Capabilities: &api.Capabilities{}, + Privileged: &priv, + } } diff --git a/pkg/securitycontext/provider.go b/pkg/securitycontext/provider.go index 1b17a2abc0c..57953d7c33a 100644 --- a/pkg/securitycontext/provider.go +++ b/pkg/securitycontext/provider.go @@ -21,6 +21,7 @@ import ( "strconv" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/leaky" dockercontainer "github.com/docker/engine-api/types/container" @@ -37,7 +38,7 @@ type SimpleSecurityContextProvider struct{} // ModifyContainerConfig is called before the Docker createContainer call. // The security context provider can make changes to the Config with which // the container is created. -func (p SimpleSecurityContextProvider) ModifyContainerConfig(pod *api.Pod, container *api.Container, config *dockercontainer.Config) { +func (p SimpleSecurityContextProvider) ModifyContainerConfig(pod *v1.Pod, container *v1.Container, config *dockercontainer.Config) { effectiveSC := DetermineEffectiveSecurityContext(pod, container) if effectiveSC == nil { return @@ -50,7 +51,7 @@ func (p SimpleSecurityContextProvider) ModifyContainerConfig(pod *api.Pod, conta // ModifyHostConfig is called before the Docker runContainer call. The // security context provider can make changes to the HostConfig, affecting // security options, whether the container is privileged, volume binds, etc. -func (p SimpleSecurityContextProvider) ModifyHostConfig(pod *api.Pod, container *api.Container, hostConfig *dockercontainer.HostConfig, supplementalGids []int64) { +func (p SimpleSecurityContextProvider) ModifyHostConfig(pod *v1.Pod, container *v1.Container, hostConfig *dockercontainer.HostConfig, supplementalGids []int64) { // Apply supplemental groups if container.Name != leaky.PodInfraContainerName { // TODO: We skip application of supplemental groups to the @@ -96,7 +97,7 @@ func (p SimpleSecurityContextProvider) ModifyHostConfig(pod *api.Pod, container } // ModifySecurityOptions adds SELinux options to config. -func ModifySecurityOptions(config []string, selinuxOpts *api.SELinuxOptions) []string { +func ModifySecurityOptions(config []string, selinuxOpts *v1.SELinuxOptions) []string { config = modifySecurityOption(config, DockerLabelUser, selinuxOpts.User) config = modifySecurityOption(config, DockerLabelRole, selinuxOpts.Role) config = modifySecurityOption(config, DockerLabelType, selinuxOpts.Type) @@ -115,7 +116,7 @@ func modifySecurityOption(config []string, name, value string) []string { } // MakeCapabilities creates string slices from Capability slices -func MakeCapabilities(capAdd []api.Capability, capDrop []api.Capability) ([]string, []string) { +func MakeCapabilities(capAdd []v1.Capability, capDrop []v1.Capability) ([]string, []string) { var ( addCaps []string dropCaps []string @@ -129,7 +130,7 @@ func MakeCapabilities(capAdd []api.Capability, capDrop []api.Capability) ([]stri return addCaps, dropCaps } -func DetermineEffectiveSecurityContext(pod *api.Pod, container *api.Container) *api.SecurityContext { +func DetermineEffectiveSecurityContext(pod *v1.Pod, container *v1.Container) *v1.SecurityContext { effectiveSc := securityContextFromPodSecurityContext(pod) containerSc := container.SecurityContext @@ -143,6 +144,78 @@ func DetermineEffectiveSecurityContext(pod *api.Pod, container *api.Container) * return containerSc } + if containerSc.SELinuxOptions != nil { + effectiveSc.SELinuxOptions = new(v1.SELinuxOptions) + *effectiveSc.SELinuxOptions = *containerSc.SELinuxOptions + } + + if containerSc.Capabilities != nil { + effectiveSc.Capabilities = new(v1.Capabilities) + *effectiveSc.Capabilities = *containerSc.Capabilities + } + + if containerSc.Privileged != nil { + effectiveSc.Privileged = new(bool) + *effectiveSc.Privileged = *containerSc.Privileged + } + + if containerSc.RunAsUser != nil { + effectiveSc.RunAsUser = new(int64) + *effectiveSc.RunAsUser = *containerSc.RunAsUser + } + + if containerSc.RunAsNonRoot != nil { + effectiveSc.RunAsNonRoot = new(bool) + *effectiveSc.RunAsNonRoot = *containerSc.RunAsNonRoot + } + + if containerSc.ReadOnlyRootFilesystem != nil { + effectiveSc.ReadOnlyRootFilesystem = new(bool) + *effectiveSc.ReadOnlyRootFilesystem = *containerSc.ReadOnlyRootFilesystem + } + + return effectiveSc +} + +func securityContextFromPodSecurityContext(pod *v1.Pod) *v1.SecurityContext { + if pod.Spec.SecurityContext == nil { + return nil + } + + synthesized := &v1.SecurityContext{} + + if pod.Spec.SecurityContext.SELinuxOptions != nil { + synthesized.SELinuxOptions = &v1.SELinuxOptions{} + *synthesized.SELinuxOptions = *pod.Spec.SecurityContext.SELinuxOptions + } + if pod.Spec.SecurityContext.RunAsUser != nil { + synthesized.RunAsUser = new(int64) + *synthesized.RunAsUser = *pod.Spec.SecurityContext.RunAsUser + } + + if pod.Spec.SecurityContext.RunAsNonRoot != nil { + synthesized.RunAsNonRoot = new(bool) + *synthesized.RunAsNonRoot = *pod.Spec.SecurityContext.RunAsNonRoot + } + + return synthesized +} + +// TODO: remove the duplicate code +func InternalDetermineEffectiveSecurityContext(pod *api.Pod, container *api.Container) *api.SecurityContext { + effectiveSc := internalSecurityContextFromPodSecurityContext(pod) + containerSc := container.SecurityContext + + if effectiveSc == nil && containerSc == nil { + return nil + } + if effectiveSc != nil && containerSc == nil { + return effectiveSc + } + if effectiveSc == nil && containerSc != nil { + return containerSc + } + if containerSc.SELinuxOptions != nil { effectiveSc.SELinuxOptions = new(api.SELinuxOptions) *effectiveSc.SELinuxOptions = *containerSc.SELinuxOptions @@ -176,7 +249,7 @@ func DetermineEffectiveSecurityContext(pod *api.Pod, container *api.Container) * return effectiveSc } -func securityContextFromPodSecurityContext(pod *api.Pod) *api.SecurityContext { +func internalSecurityContextFromPodSecurityContext(pod *api.Pod) *api.SecurityContext { if pod.Spec.SecurityContext == nil { return nil } diff --git a/pkg/securitycontext/provider_test.go b/pkg/securitycontext/provider_test.go index 0c955647ba4..2f848ee42a4 100644 --- a/pkg/securitycontext/provider_test.go +++ b/pkg/securitycontext/provider_test.go @@ -23,8 +23,8 @@ import ( "testing" dockercontainer "github.com/docker/engine-api/types/container" - "k8s.io/kubernetes/pkg/api" apitesting "k8s.io/kubernetes/pkg/api/testing" + "k8s.io/kubernetes/pkg/api/v1" ) func TestModifyContainerConfig(t *testing.T) { @@ -33,13 +33,13 @@ func TestModifyContainerConfig(t *testing.T) { cases := []struct { name string - podSc *api.PodSecurityContext - sc *api.SecurityContext + podSc *v1.PodSecurityContext + sc *v1.SecurityContext expected *dockercontainer.Config }{ { name: "container.SecurityContext.RunAsUser set", - sc: &api.SecurityContext{ + sc: &v1.SecurityContext{ RunAsUser: &uid, }, expected: &dockercontainer.Config{ @@ -48,12 +48,12 @@ func TestModifyContainerConfig(t *testing.T) { }, { name: "no RunAsUser value set", - sc: &api.SecurityContext{}, + sc: &v1.SecurityContext{}, expected: &dockercontainer.Config{}, }, { name: "pod.Spec.SecurityContext.RunAsUser set", - podSc: &api.PodSecurityContext{ + podSc: &v1.PodSecurityContext{ RunAsUser: &uid, }, expected: &dockercontainer.Config{ @@ -62,10 +62,10 @@ func TestModifyContainerConfig(t *testing.T) { }, { name: "container.SecurityContext.RunAsUser overrides pod.Spec.SecurityContext.RunAsUser", - podSc: &api.PodSecurityContext{ + podSc: &v1.PodSecurityContext{ RunAsUser: &uid, }, - sc: &api.SecurityContext{ + sc: &v1.SecurityContext{ RunAsUser: &overrideUid, }, expected: &dockercontainer.Config{ @@ -75,9 +75,9 @@ func TestModifyContainerConfig(t *testing.T) { } provider := NewSimpleSecurityContextProvider() - dummyContainer := &api.Container{} + dummyContainer := &v1.Container{} for _, tc := range cases { - pod := &api.Pod{Spec: api.PodSpec{SecurityContext: tc.podSc}} + pod := &v1.Pod{Spec: v1.PodSpec{SecurityContext: tc.podSc}} dummyContainer.SecurityContext = tc.sc dockerCfg := &dockercontainer.Config{} @@ -91,7 +91,7 @@ func TestModifyContainerConfig(t *testing.T) { func TestModifyHostConfig(t *testing.T) { priv := true - setPrivSC := &api.SecurityContext{} + setPrivSC := &v1.SecurityContext{} setPrivSC.Privileged = &priv setPrivHC := &dockercontainer.HostConfig{ Privileged: true, @@ -115,8 +115,8 @@ func TestModifyHostConfig(t *testing.T) { cases := []struct { name string - podSc *api.PodSecurityContext - sc *api.SecurityContext + podSc *v1.PodSecurityContext + sc *v1.SecurityContext expected *dockercontainer.HostConfig }{ { @@ -131,21 +131,21 @@ func TestModifyHostConfig(t *testing.T) { }, { name: "container.SecurityContext.Capabilities", - sc: &api.SecurityContext{ + sc: &v1.SecurityContext{ Capabilities: inputCapabilities(), }, expected: setCapsHC, }, { name: "container.SecurityContext.SELinuxOptions", - sc: &api.SecurityContext{ + sc: &v1.SecurityContext{ SELinuxOptions: inputSELinuxOptions(), }, expected: setSELinuxHC, }, { name: "pod.Spec.SecurityContext.SELinuxOptions", - podSc: &api.PodSecurityContext{ + podSc: &v1.PodSecurityContext{ SELinuxOptions: inputSELinuxOptions(), }, expected: setSELinuxHC, @@ -159,10 +159,10 @@ func TestModifyHostConfig(t *testing.T) { } provider := NewSimpleSecurityContextProvider() - dummyContainer := &api.Container{} + dummyContainer := &v1.Container{} for _, tc := range cases { - pod := &api.Pod{Spec: api.PodSpec{SecurityContext: tc.podSc}} + pod := &v1.Pod{Spec: v1.PodSpec{SecurityContext: tc.podSc}} dummyContainer.SecurityContext = tc.sc dockerCfg := &dockercontainer.HostConfig{} @@ -175,7 +175,7 @@ func TestModifyHostConfig(t *testing.T) { } func TestModifyHostConfigPodSecurityContext(t *testing.T) { - supplementalGroupsSC := &api.PodSecurityContext{} + supplementalGroupsSC := &v1.PodSecurityContext{} supplementalGroupsSC.SupplementalGroups = []int64{2222} supplementalGroupHC := fullValidHostConfig() supplementalGroupHC.GroupAdd = []string{"2222"} @@ -189,7 +189,7 @@ func TestModifyHostConfigPodSecurityContext(t *testing.T) { extraSupplementalGroup := []int64{1234} testCases := map[string]struct { - securityContext *api.PodSecurityContext + securityContext *v1.PodSecurityContext expected *dockercontainer.HostConfig extraSupplementalGroups []int64 }{ @@ -204,12 +204,12 @@ func TestModifyHostConfigPodSecurityContext(t *testing.T) { extraSupplementalGroups: nil, }, "FSGroup": { - securityContext: &api.PodSecurityContext{FSGroup: &fsGroup}, + securityContext: &v1.PodSecurityContext{FSGroup: &fsGroup}, expected: fsGroupHC, extraSupplementalGroups: nil, }, "FSGroup + SupplementalGroups": { - securityContext: &api.PodSecurityContext{ + securityContext: &v1.PodSecurityContext{ SupplementalGroups: []int64{2222}, FSGroup: &fsGroup, }, @@ -229,10 +229,10 @@ func TestModifyHostConfigPodSecurityContext(t *testing.T) { } provider := NewSimpleSecurityContextProvider() - dummyContainer := &api.Container{} + dummyContainer := &v1.Container{} dummyContainer.SecurityContext = fullValidSecurityContext() - dummyPod := &api.Pod{ - Spec: apitesting.DeepEqualSafePodSpec(), + dummyPod := &v1.Pod{ + Spec: apitesting.V1DeepEqualSafePodSpec(), } for k, v := range testCases { @@ -277,9 +277,9 @@ func TestModifySecurityOption(t *testing.T) { } } -func overridePodSecurityContext() *api.PodSecurityContext { - return &api.PodSecurityContext{ - SELinuxOptions: &api.SELinuxOptions{ +func overridePodSecurityContext() *v1.PodSecurityContext { + return &v1.PodSecurityContext{ + SELinuxOptions: &v1.SELinuxOptions{ User: "user2", Role: "role2", Type: "type2", @@ -288,30 +288,30 @@ func overridePodSecurityContext() *api.PodSecurityContext { } } -func fullValidPodSecurityContext() *api.PodSecurityContext { - return &api.PodSecurityContext{ +func fullValidPodSecurityContext() *v1.PodSecurityContext { + return &v1.PodSecurityContext{ SELinuxOptions: inputSELinuxOptions(), } } -func fullValidSecurityContext() *api.SecurityContext { +func fullValidSecurityContext() *v1.SecurityContext { priv := true - return &api.SecurityContext{ + return &v1.SecurityContext{ Privileged: &priv, Capabilities: inputCapabilities(), SELinuxOptions: inputSELinuxOptions(), } } -func inputCapabilities() *api.Capabilities { - return &api.Capabilities{ - Add: []api.Capability{"addCapA", "addCapB"}, - Drop: []api.Capability{"dropCapA", "dropCapB"}, +func inputCapabilities() *v1.Capabilities { + return &v1.Capabilities{ + Add: []v1.Capability{"addCapA", "addCapB"}, + Drop: []v1.Capability{"dropCapA", "dropCapB"}, } } -func inputSELinuxOptions() *api.SELinuxOptions { - return &api.SELinuxOptions{ +func inputSELinuxOptions() *v1.SELinuxOptions { + return &v1.SELinuxOptions{ User: "user", Role: "role", Type: "type", diff --git a/pkg/securitycontext/types.go b/pkg/securitycontext/types.go index 500c2ba2b64..fba98398a52 100644 --- a/pkg/securitycontext/types.go +++ b/pkg/securitycontext/types.go @@ -17,7 +17,7 @@ limitations under the License. package securitycontext import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" dockercontainer "github.com/docker/engine-api/types/container" ) @@ -26,7 +26,7 @@ type SecurityContextProvider interface { // ModifyContainerConfig is called before the Docker createContainer call. // The security context provider can make changes to the Config with which // the container is created. - ModifyContainerConfig(pod *api.Pod, container *api.Container, config *dockercontainer.Config) + ModifyContainerConfig(pod *v1.Pod, container *v1.Container, config *dockercontainer.Config) // ModifyHostConfig is called before the Docker createContainer call. // The security context provider can make changes to the HostConfig, affecting @@ -37,7 +37,7 @@ type SecurityContextProvider interface { // - pod: the pod to modify the docker hostconfig for // - container: the container to modify the hostconfig for // - supplementalGids: additional supplemental GIDs associated with the pod's volumes - ModifyHostConfig(pod *api.Pod, container *api.Container, hostConfig *dockercontainer.HostConfig, supplementalGids []int64) + ModifyHostConfig(pod *v1.Pod, container *v1.Container, hostConfig *dockercontainer.HostConfig, supplementalGids []int64) } const ( diff --git a/pkg/securitycontext/util.go b/pkg/securitycontext/util.go index 13d48a258f6..0d71b1d667e 100644 --- a/pkg/securitycontext/util.go +++ b/pkg/securitycontext/util.go @@ -20,12 +20,12 @@ import ( "fmt" "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) // HasPrivilegedRequest returns the value of SecurityContext.Privileged, taking into account // the possibility of nils -func HasPrivilegedRequest(container *api.Container) bool { +func HasPrivilegedRequest(container *v1.Container) bool { if container.SecurityContext == nil { return false } @@ -37,7 +37,7 @@ func HasPrivilegedRequest(container *api.Container) bool { // HasCapabilitiesRequest returns true if Adds or Drops are defined in the security context // capabilities, taking into account nils -func HasCapabilitiesRequest(container *api.Container) bool { +func HasCapabilitiesRequest(container *v1.Container) bool { if container.SecurityContext == nil { return false } @@ -52,14 +52,14 @@ const expectedSELinuxFields = 4 // ParseSELinuxOptions parses a string containing a full SELinux context // (user, role, type, and level) into an SELinuxOptions object. If the // context is malformed, an error is returned. -func ParseSELinuxOptions(context string) (*api.SELinuxOptions, error) { +func ParseSELinuxOptions(context string) (*v1.SELinuxOptions, error) { fields := strings.SplitN(context, ":", expectedSELinuxFields) if len(fields) != expectedSELinuxFields { return nil, fmt.Errorf("expected %v fields in selinux; got %v (context: %v)", expectedSELinuxFields, len(fields), context) } - return &api.SELinuxOptions{ + return &v1.SELinuxOptions{ User: fields[0], Role: fields[1], Type: fields[2], @@ -68,7 +68,7 @@ func ParseSELinuxOptions(context string) (*api.SELinuxOptions, error) { } // HasNonRootUID returns true if the runAsUser is set and is greater than 0. -func HasRootUID(container *api.Container) bool { +func HasRootUID(container *v1.Container) bool { if container.SecurityContext == nil { return false } @@ -79,11 +79,11 @@ func HasRootUID(container *api.Container) bool { } // HasRunAsUser determines if the sc's runAsUser field is set. -func HasRunAsUser(container *api.Container) bool { +func HasRunAsUser(container *v1.Container) bool { return container.SecurityContext != nil && container.SecurityContext.RunAsUser != nil } // HasRootRunAsUser returns true if the run as user is set and it is set to 0. -func HasRootRunAsUser(container *api.Container) bool { +func HasRootRunAsUser(container *v1.Container) bool { return HasRunAsUser(container) && HasRootUID(container) } diff --git a/pkg/securitycontext/util_test.go b/pkg/securitycontext/util_test.go index 523a7f52d21..92a61054742 100644 --- a/pkg/securitycontext/util_test.go +++ b/pkg/securitycontext/util_test.go @@ -19,19 +19,19 @@ package securitycontext import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) func TestParseSELinuxOptions(t *testing.T) { cases := []struct { name string input string - expected *api.SELinuxOptions + expected *v1.SELinuxOptions }{ { name: "simple", input: "user_t:role_t:type_t:s0", - expected: &api.SELinuxOptions{ + expected: &v1.SELinuxOptions{ User: "user_t", Role: "role_t", Type: "type_t", @@ -41,7 +41,7 @@ func TestParseSELinuxOptions(t *testing.T) { { name: "simple + categories", input: "user_t:role_t:type_t:s0:c0", - expected: &api.SELinuxOptions{ + expected: &v1.SELinuxOptions{ User: "user_t", Role: "role_t", Type: "type_t", @@ -69,7 +69,7 @@ func TestParseSELinuxOptions(t *testing.T) { } } -func compareContexts(name string, ex, ac *api.SELinuxOptions, t *testing.T) { +func compareContexts(name string, ex, ac *v1.SELinuxOptions, t *testing.T) { if e, a := ex.User, ac.User; e != a { t.Errorf("%v: expected user: %v, got: %v", name, e, a) } @@ -84,8 +84,8 @@ func compareContexts(name string, ex, ac *api.SELinuxOptions, t *testing.T) { } } -func containerWithUser(ptr *int64) *api.Container { - return &api.Container{SecurityContext: &api.SecurityContext{RunAsUser: ptr}} +func containerWithUser(ptr *int64) *v1.Container { + return &v1.Container{SecurityContext: &v1.SecurityContext{RunAsUser: ptr}} } func TestHaRootUID(t *testing.T) { @@ -93,11 +93,11 @@ func TestHaRootUID(t *testing.T) { var root int64 = 0 tests := map[string]struct { - container *api.Container + container *v1.Container expect bool }{ "nil sc": { - container: &api.Container{SecurityContext: nil}, + container: &v1.Container{SecurityContext: nil}, }, "nil runAsuser": { container: containerWithUser(nil), @@ -123,11 +123,11 @@ func TestHasRunAsUser(t *testing.T) { var runAsUser int64 = 0 tests := map[string]struct { - container *api.Container + container *v1.Container expect bool }{ "nil sc": { - container: &api.Container{SecurityContext: nil}, + container: &v1.Container{SecurityContext: nil}, }, "nil runAsUser": { container: containerWithUser(nil), @@ -151,11 +151,11 @@ func TestHasRootRunAsUser(t *testing.T) { var root int64 = 0 tests := map[string]struct { - container *api.Container + container *v1.Container expect bool }{ "nil sc": { - container: &api.Container{SecurityContext: nil}, + container: &v1.Container{SecurityContext: nil}, }, "nil runAsuser": { container: containerWithUser(nil), diff --git a/pkg/serviceaccount/BUILD b/pkg/serviceaccount/BUILD index b169ac386f7..81d4f0af9cd 100644 --- a/pkg/serviceaccount/BUILD +++ b/pkg/serviceaccount/BUILD @@ -19,6 +19,7 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/api/validation:go_default_library", "//pkg/auth/authenticator:go_default_library", "//pkg/auth/user:go_default_library", @@ -40,9 +41,9 @@ go_test( srcs = ["jwt_test.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/controller/serviceaccount:go_default_library", "//pkg/serviceaccount:go_default_library", ], diff --git a/pkg/serviceaccount/jwt.go b/pkg/serviceaccount/jwt.go index c9b4b770764..111afe1c5dc 100644 --- a/pkg/serviceaccount/jwt.go +++ b/pkg/serviceaccount/jwt.go @@ -26,7 +26,7 @@ import ( "fmt" "io/ioutil" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/auth/authenticator" "k8s.io/kubernetes/pkg/auth/user" @@ -47,14 +47,14 @@ const ( // ServiceAccountTokenGetter defines functions to retrieve a named service account and secret type ServiceAccountTokenGetter interface { - GetServiceAccount(namespace, name string) (*api.ServiceAccount, error) - GetSecret(namespace, name string) (*api.Secret, error) + GetServiceAccount(namespace, name string) (*v1.ServiceAccount, error) + GetSecret(namespace, name string) (*v1.Secret, error) } type TokenGenerator interface { // GenerateToken generates a token which will identify the given ServiceAccount. // The returned token will be stored in the given (and yet-unpersisted) Secret. - GenerateToken(serviceAccount api.ServiceAccount, secret api.Secret) (string, error) + GenerateToken(serviceAccount v1.ServiceAccount, secret v1.Secret) (string, error) } // ReadPrivateKey is a helper function for reading a private key from a PEM-encoded file @@ -148,7 +148,7 @@ type jwtTokenGenerator struct { privateKey interface{} } -func (j *jwtTokenGenerator) GenerateToken(serviceAccount api.ServiceAccount, secret api.Secret) (string, error) { +func (j *jwtTokenGenerator) GenerateToken(serviceAccount v1.ServiceAccount, secret v1.Secret) (string, error) { var method jwt.SigningMethod switch privateKey := j.privateKey.(type) { case *rsa.PrivateKey: @@ -299,7 +299,7 @@ func (j *jwtTokenAuthenticator) AuthenticateToken(token string) (user.Info, bool glog.V(4).Infof("Could not retrieve token %s/%s for service account %s/%s: %v", namespace, secretName, namespace, serviceAccountName, err) return nil, false, errors.New("Token has been invalidated") } - if bytes.Compare(secret.Data[api.ServiceAccountTokenKey], []byte(token)) != 0 { + if bytes.Compare(secret.Data[v1.ServiceAccountTokenKey], []byte(token)) != 0 { glog.V(4).Infof("Token contents no longer matches %s/%s for service account %s/%s", namespace, secretName, namespace, serviceAccountName) return nil, false, errors.New("Token does not match server's copy") } diff --git a/pkg/serviceaccount/jwt_test.go b/pkg/serviceaccount/jwt_test.go index 3705aee3894..e412a7fb6c9 100644 --- a/pkg/serviceaccount/jwt_test.go +++ b/pkg/serviceaccount/jwt_test.go @@ -22,9 +22,9 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" serviceaccountcontroller "k8s.io/kubernetes/pkg/controller/serviceaccount" "k8s.io/kubernetes/pkg/serviceaccount" ) @@ -164,21 +164,21 @@ func TestTokenGenerateAndValidate(t *testing.T) { expectedUserUID := "12345" // Related API objects - serviceAccount := &api.ServiceAccount{ - ObjectMeta: api.ObjectMeta{ + serviceAccount := &v1.ServiceAccount{ + ObjectMeta: v1.ObjectMeta{ Name: "my-service-account", UID: "12345", Namespace: "test", }, } - rsaSecret := &api.Secret{ - ObjectMeta: api.ObjectMeta{ + rsaSecret := &v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Name: "my-rsa-secret", Namespace: "test", }, } - ecdsaSecret := &api.Secret{ - ObjectMeta: api.ObjectMeta{ + ecdsaSecret := &v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Name: "my-ecdsa-secret", Namespace: "test", }, diff --git a/pkg/serviceaccount/util.go b/pkg/serviceaccount/util.go index 712b086ad48..d8fbc442f32 100644 --- a/pkg/serviceaccount/util.go +++ b/pkg/serviceaccount/util.go @@ -21,6 +21,7 @@ import ( "strings" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/auth/user" ) @@ -84,7 +85,28 @@ func UserInfo(namespace, name, uid string) user.Info { } // IsServiceAccountToken returns true if the secret is a valid api token for the service account -func IsServiceAccountToken(secret *api.Secret, sa *api.ServiceAccount) bool { +func IsServiceAccountToken(secret *v1.Secret, sa *v1.ServiceAccount) bool { + if secret.Type != v1.SecretTypeServiceAccountToken { + return false + } + + name := secret.Annotations[v1.ServiceAccountNameKey] + uid := secret.Annotations[v1.ServiceAccountUIDKey] + if name != sa.Name { + // Name must match + return false + } + if len(uid) > 0 && uid != string(sa.UID) { + // If UID is specified, it must match + return false + } + + return true +} + +// TODO: remove the duplicate code +// InternalIsServiceAccountToken returns true if the secret is a valid api token for the service account +func InternalIsServiceAccountToken(secret *api.Secret, sa *api.ServiceAccount) bool { if secret.Type != api.SecretTypeServiceAccountToken { return false } diff --git a/pkg/storage/BUILD b/pkg/storage/BUILD index de2d97e923a..cccf921b069 100644 --- a/pkg/storage/BUILD +++ b/pkg/storage/BUILD @@ -27,6 +27,7 @@ go_library( "//pkg/api/errors:go_default_library", "//pkg/api/meta:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/api/validation/path:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/conversion:go_default_library", @@ -58,6 +59,7 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/fields:go_default_library", "//pkg/labels:go_default_library", diff --git a/pkg/storage/cacher.go b/pkg/storage/cacher.go index ae64f741dcb..b004b50538c 100644 --- a/pkg/storage/cacher.go +++ b/pkg/storage/cacher.go @@ -28,6 +28,7 @@ import ( "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/conversion" "k8s.io/kubernetes/pkg/runtime" @@ -631,7 +632,7 @@ func newCacherListerWatcher(storage Interface, resourcePrefix string, newListFun } // Implements cache.ListerWatcher interface. -func (lw *cacherListerWatcher) List(options api.ListOptions) (runtime.Object, error) { +func (lw *cacherListerWatcher) List(options v1.ListOptions) (runtime.Object, error) { list := lw.newListFunc() if err := lw.storage.List(context.TODO(), lw.resourcePrefix, "", Everything, list); err != nil { return nil, err @@ -640,7 +641,7 @@ func (lw *cacherListerWatcher) List(options api.ListOptions) (runtime.Object, er } // Implements cache.ListerWatcher interface. -func (lw *cacherListerWatcher) Watch(options api.ListOptions) (watch.Interface, error) { +func (lw *cacherListerWatcher) Watch(options v1.ListOptions) (watch.Interface, error) { return lw.storage.WatchList(context.TODO(), lw.resourcePrefix, options.ResourceVersion, Everything) } diff --git a/pkg/storage/watch_cache_test.go b/pkg/storage/watch_cache_test.go index 8a930ff0876..0a19fa31175 100644 --- a/pkg/storage/watch_cache_test.go +++ b/pkg/storage/watch_cache_test.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/api/v1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/clock" @@ -312,14 +313,14 @@ func TestWaitUntilFreshAndListTimeout(t *testing.T) { } type testLW struct { - ListFunc func(options api.ListOptions) (runtime.Object, error) - WatchFunc func(options api.ListOptions) (watch.Interface, error) + ListFunc func(options v1.ListOptions) (runtime.Object, error) + WatchFunc func(options v1.ListOptions) (watch.Interface, error) } -func (t *testLW) List(options api.ListOptions) (runtime.Object, error) { +func (t *testLW) List(options v1.ListOptions) (runtime.Object, error) { return t.ListFunc(options) } -func (t *testLW) Watch(options api.ListOptions) (watch.Interface, error) { +func (t *testLW) Watch(options v1.ListOptions) (watch.Interface, error) { return t.WatchFunc(options) } @@ -337,12 +338,12 @@ func TestReflectorForWatchCache(t *testing.T) { } lw := &testLW{ - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { fw := watch.NewFake() go fw.Stop() return fw, nil }, - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "10"}}, nil }, } diff --git a/pkg/util/cert/BUILD b/pkg/util/cert/BUILD index bb3e7bc336d..b6e64bbf7f4 100644 --- a/pkg/util/cert/BUILD +++ b/pkg/util/cert/BUILD @@ -19,7 +19,10 @@ go_library( "pem.go", ], tags = ["automanaged"], - deps = ["//pkg/apis/certificates:go_default_library"], + deps = [ + "//pkg/apis/certificates:go_default_library", + "//pkg/apis/certificates/v1alpha1:go_default_library", + ], ) go_test( diff --git a/pkg/util/cert/csr.go b/pkg/util/cert/csr.go index 91cc32f62b0..fb0b1f696c1 100644 --- a/pkg/util/cert/csr.go +++ b/pkg/util/cert/csr.go @@ -26,6 +26,7 @@ import ( "net" "k8s.io/kubernetes/pkg/apis/certificates" + "k8s.io/kubernetes/pkg/apis/certificates/v1alpha1" ) // ParseCSR extracts the CSR from the API object and decodes it. @@ -43,6 +44,21 @@ func ParseCSR(obj *certificates.CertificateSigningRequest) (*x509.CertificateReq return csr, nil } +// ParseCSRV1alpha1 extracts the CSR from the API object and decodes it. +func ParseCSRV1alpha1(obj *v1alpha1.CertificateSigningRequest) (*x509.CertificateRequest, error) { + // extract PEM from request object + pemBytes := obj.Spec.Request + block, _ := pem.Decode(pemBytes) + if block == nil || block.Type != "CERTIFICATE REQUEST" { + return nil, errors.New("PEM block type must be CERTIFICATE REQUEST") + } + csr, err := x509.ParseCertificateRequest(block.Bytes) + if err != nil { + return nil, err + } + return csr, nil +} + // MakeCSR generates a PEM-encoded CSR using the supplied private key, subject, and SANs. // All key types that are implemented via crypto.Signer are supported (This includes *rsa.PrivateKey and *ecdsa.PrivateKey.) func MakeCSR(privateKey interface{}, subject *pkix.Name, dnsSANs []string, ipSANs []net.IP) (csr []byte, err error) { diff --git a/pkg/util/io/BUILD b/pkg/util/io/BUILD index 5c93589a74f..0f4959ddd4c 100644 --- a/pkg/util/io/BUILD +++ b/pkg/util/io/BUILD @@ -19,6 +19,7 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/runtime:go_default_library", "//vendor:github.com/golang/glog", diff --git a/pkg/util/io/io.go b/pkg/util/io/io.go index d7eb6d57f99..07ed9c05b46 100644 --- a/pkg/util/io/io.go +++ b/pkg/util/io/io.go @@ -22,12 +22,13 @@ import ( "os" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "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) { +func LoadPodFromFile(filePath string) (*v1.Pod, error) { if filePath == "" { return nil, fmt.Errorf("file path not specified") } @@ -38,9 +39,9 @@ func LoadPodFromFile(filePath string) (*api.Pod, error) { if len(podDef) == 0 { return nil, fmt.Errorf("file was empty: %s", filePath) } - pod := &api.Pod{} + pod := &v1.Pod{} - codec := api.Codecs.LegacyCodec(registered.GroupOrDie(api.GroupName).GroupVersion) + codec := api.Codecs.LegacyCodec(registered.GroupOrDie(v1.GroupName).GroupVersion) if err := runtime.DecodeInto(codec, podDef, pod); err != nil { return nil, fmt.Errorf("failed decoding file: %v", err) } @@ -48,11 +49,11 @@ func LoadPodFromFile(filePath string) (*api.Pod, error) { } // SavePodToFile will encode and save a pod to a given path & permissions -func SavePodToFile(pod *api.Pod, filePath string, perm os.FileMode) error { +func SavePodToFile(pod *v1.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) + codec := api.Codecs.LegacyCodec(registered.GroupOrDie(v1.GroupName).GroupVersion) data, err := runtime.Encode(codec, pod) if err != nil { return fmt.Errorf("failed encoding pod: %v", err) diff --git a/pkg/util/node/BUILD b/pkg/util/node/BUILD index 25db78b5264..f8821c6794c 100644 --- a/pkg/util/node/BUILD +++ b/pkg/util/node/BUILD @@ -17,7 +17,8 @@ go_library( deps = [ "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/types:go_default_library", "//vendor:github.com/golang/glog", ], @@ -29,7 +30,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", ], ) diff --git a/pkg/util/node/node.go b/pkg/util/node/node.go index 2357a2dde41..47055f7197d 100644 --- a/pkg/util/node/node.go +++ b/pkg/util/node/node.go @@ -27,7 +27,8 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/types" ) @@ -52,7 +53,7 @@ func GetHostname(hostnameOverride string) string { // GetPreferredNodeAddress returns the address of the provided node, using the provided preference order. // If none of the preferred address types are found, an error is returned. -func GetPreferredNodeAddress(node *api.Node, preferredAddressTypes []api.NodeAddressType) (string, error) { +func GetPreferredNodeAddress(node *v1.Node, preferredAddressTypes []v1.NodeAddressType) (string, error) { for _, addressType := range preferredAddressTypes { for _, address := range node.Status.Addresses { if address.Type == addressType { @@ -60,7 +61,7 @@ func GetPreferredNodeAddress(node *api.Node, preferredAddressTypes []api.NodeAdd } } // If hostname was requested and no Hostname address was registered... - if addressType == api.NodeHostName { + if addressType == v1.NodeHostName { // ...fall back to the kubernetes.io/hostname label for compatibility with kubelets before 1.5 if hostname, ok := node.Labels[unversioned.LabelHostname]; ok && len(hostname) > 0 { return hostname, nil @@ -74,7 +75,29 @@ func GetPreferredNodeAddress(node *api.Node, preferredAddressTypes []api.NodeAdd // 1. NodeInternalIP // 2. NodeExternalIP // 3. NodeLegacyHostIP -func GetNodeHostIP(node *api.Node) (net.IP, error) { +func GetNodeHostIP(node *v1.Node) (net.IP, error) { + addresses := node.Status.Addresses + addressMap := make(map[v1.NodeAddressType][]v1.NodeAddress) + for i := range addresses { + addressMap[addresses[i].Type] = append(addressMap[addresses[i].Type], addresses[i]) + } + if addresses, ok := addressMap[v1.NodeInternalIP]; ok { + return net.ParseIP(addresses[0].Address), nil + } + if addresses, ok := addressMap[v1.NodeExternalIP]; ok { + return net.ParseIP(addresses[0].Address), nil + } + if addresses, ok := addressMap[v1.NodeLegacyHostIP]; ok { + return net.ParseIP(addresses[0].Address), nil + } + return nil, fmt.Errorf("host IP unknown; known addresses: %v", addresses) +} + +// InternalGetNodeHostIP returns the provided node's IP, based on the priority: +// 1. NodeInternalIP +// 2. NodeExternalIP +// 3. NodeLegacyHostIP +func InternalGetNodeHostIP(node *api.Node) (net.IP, error) { addresses := node.Status.Addresses addressMap := make(map[api.NodeAddressType][]api.NodeAddress) for i := range addresses { @@ -94,7 +117,7 @@ func GetNodeHostIP(node *api.Node) (net.IP, error) { // Helper function that builds a string identifier that is unique per failure-zone // Returns empty-string for no zone -func GetZoneKey(node *api.Node) string { +func GetZoneKey(node *v1.Node) string { labels := node.Labels if labels == nil { return "" @@ -114,9 +137,9 @@ func GetZoneKey(node *api.Node) string { } // SetNodeCondition updates specific node condition with patch operation. -func SetNodeCondition(c clientset.Interface, node types.NodeName, condition api.NodeCondition) error { - generatePatch := func(condition api.NodeCondition) ([]byte, error) { - raw, err := json.Marshal(&[]api.NodeCondition{condition}) +func SetNodeCondition(c clientset.Interface, node types.NodeName, condition v1.NodeCondition) error { + generatePatch := func(condition v1.NodeCondition) ([]byte, error) { + raw, err := json.Marshal(&[]v1.NodeCondition{condition}) if err != nil { return nil, err } diff --git a/pkg/util/node/node_test.go b/pkg/util/node/node_test.go index 957bf09352e..8629704b497 100644 --- a/pkg/util/node/node_test.go +++ b/pkg/util/node/node_test.go @@ -19,15 +19,15 @@ package node import ( "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" ) func TestGetPreferredAddress(t *testing.T) { testcases := map[string]struct { Labels map[string]string - Addresses []api.NodeAddress - Preferences []api.NodeAddressType + Addresses []v1.NodeAddress + Preferences []v1.NodeAddressType ExpectErr string ExpectAddress string @@ -36,44 +36,44 @@ func TestGetPreferredAddress(t *testing.T) { ExpectErr: "no preferred addresses found; known addresses: []", }, "missing address": { - Addresses: []api.NodeAddress{ - {Type: api.NodeInternalIP, Address: "1.2.3.4"}, + Addresses: []v1.NodeAddress{ + {Type: v1.NodeInternalIP, Address: "1.2.3.4"}, }, - Preferences: []api.NodeAddressType{api.NodeHostName}, + Preferences: []v1.NodeAddressType{v1.NodeHostName}, ExpectErr: "no preferred addresses found; known addresses: [{InternalIP 1.2.3.4}]", }, "found address": { - Addresses: []api.NodeAddress{ - {Type: api.NodeInternalIP, Address: "1.2.3.4"}, - {Type: api.NodeExternalIP, Address: "1.2.3.5"}, - {Type: api.NodeExternalIP, Address: "1.2.3.7"}, + Addresses: []v1.NodeAddress{ + {Type: v1.NodeInternalIP, Address: "1.2.3.4"}, + {Type: v1.NodeExternalIP, Address: "1.2.3.5"}, + {Type: v1.NodeExternalIP, Address: "1.2.3.7"}, }, - Preferences: []api.NodeAddressType{api.NodeHostName, api.NodeExternalIP}, + Preferences: []v1.NodeAddressType{v1.NodeHostName, v1.NodeExternalIP}, ExpectAddress: "1.2.3.5", }, "found hostname address": { Labels: map[string]string{unversioned.LabelHostname: "label-hostname"}, - Addresses: []api.NodeAddress{ - {Type: api.NodeExternalIP, Address: "1.2.3.5"}, - {Type: api.NodeHostName, Address: "status-hostname"}, + Addresses: []v1.NodeAddress{ + {Type: v1.NodeExternalIP, Address: "1.2.3.5"}, + {Type: v1.NodeHostName, Address: "status-hostname"}, }, - Preferences: []api.NodeAddressType{api.NodeHostName, api.NodeExternalIP}, + Preferences: []v1.NodeAddressType{v1.NodeHostName, v1.NodeExternalIP}, ExpectAddress: "status-hostname", }, "found label address": { Labels: map[string]string{unversioned.LabelHostname: "label-hostname"}, - Addresses: []api.NodeAddress{ - {Type: api.NodeExternalIP, Address: "1.2.3.5"}, + Addresses: []v1.NodeAddress{ + {Type: v1.NodeExternalIP, Address: "1.2.3.5"}, }, - Preferences: []api.NodeAddressType{api.NodeHostName, api.NodeExternalIP}, + Preferences: []v1.NodeAddressType{v1.NodeHostName, v1.NodeExternalIP}, ExpectAddress: "label-hostname", }, } for k, tc := range testcases { - node := &api.Node{ - ObjectMeta: api.ObjectMeta{Labels: tc.Labels}, - Status: api.NodeStatus{Addresses: tc.Addresses}, + node := &v1.Node{ + ObjectMeta: v1.ObjectMeta{Labels: tc.Labels}, + Status: v1.NodeStatus{Addresses: tc.Addresses}, } address, err := GetPreferredNodeAddress(node, tc.Preferences) errString := "" diff --git a/pkg/util/pod/BUILD b/pkg/util/pod/BUILD index 147e0ff47ed..bd5a4b0d853 100644 --- a/pkg/util/pod/BUILD +++ b/pkg/util/pod/BUILD @@ -20,7 +20,8 @@ go_library( deps = [ "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/util/errors:go_default_library", "//pkg/util/hash:go_default_library", "//pkg/util/wait:go_default_library", diff --git a/pkg/util/pod/pod.go b/pkg/util/pod/pod.go index a6864e36021..2efe5e35dca 100644 --- a/pkg/util/pod/pod.go +++ b/pkg/util/pod/pod.go @@ -25,13 +25,21 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + "k8s.io/kubernetes/pkg/api/v1" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" 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 { +func GetPodTemplateSpecHash(template v1.PodTemplateSpec) uint32 { + podTemplateSpecHasher := adler32.New() + hashutil.DeepHashObject(podTemplateSpecHasher, template) + return podTemplateSpecHasher.Sum32() +} + +// TODO: remove the duplicate +func GetInternalPodTemplateSpecHash(template api.PodTemplateSpec) uint32 { podTemplateSpecHasher := adler32.New() hashutil.DeepHashObject(podTemplateSpecHasher, template) return podTemplateSpecHasher.Sum32() @@ -39,11 +47,11 @@ func GetPodTemplateSpecHash(template api.PodTemplateSpec) uint32 { // 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 +type updatePodFunc func(pod *v1.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) { +func UpdatePodWithRetries(podClient v1core.PodInterface, pod *v1.Pod, applyUpdate updatePodFunc) (*v1.Pod, bool, error) { var err error var podUpdated bool oldPod := pod @@ -89,8 +97,8 @@ func UpdatePodWithRetries(podClient unversionedcore.PodInterface, pod *api.Pod, } // Filter uses the input function f to filter the given pod list, and return the filtered pods -func Filter(podList *api.PodList, f func(api.Pod) bool) []api.Pod { - pods := make([]api.Pod, 0) +func Filter(podList *v1.PodList, f func(v1.Pod) bool) []v1.Pod { + pods := make([]v1.Pod, 0) for _, p := range podList.Items { if f(p) { pods = append(pods, p) diff --git a/pkg/util/replicaset/BUILD b/pkg/util/replicaset/BUILD index 9bf563be553..6f3266dc964 100644 --- a/pkg/util/replicaset/BUILD +++ b/pkg/util/replicaset/BUILD @@ -15,11 +15,11 @@ go_library( srcs = ["replicaset.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/extensions:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1:go_default_library", "//pkg/labels:go_default_library", "//pkg/util/errors:go_default_library", "//pkg/util/labels:go_default_library", diff --git a/pkg/util/replicaset/replicaset.go b/pkg/util/replicaset/replicaset.go index c11693f5d99..c59bb121bb3 100644 --- a/pkg/util/replicaset/replicaset.go +++ b/pkg/util/replicaset/replicaset.go @@ -21,11 +21,11 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - unversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + unversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1" "k8s.io/kubernetes/pkg/labels" errorsutil "k8s.io/kubernetes/pkg/util/errors" labelsutil "k8s.io/kubernetes/pkg/util/labels" @@ -88,14 +88,14 @@ func UpdateRSWithRetries(rsClient unversionedextensions.ReplicaSetInterface, rs func GetPodTemplateSpecHash(rs *extensions.ReplicaSet) string { meta := rs.Spec.Template.ObjectMeta meta.Labels = labelsutil.CloneAndRemoveLabel(meta.Labels, extensions.DefaultDeploymentUniqueLabelKey) - return fmt.Sprintf("%d", podutil.GetPodTemplateSpecHash(api.PodTemplateSpec{ + return fmt.Sprintf("%d", podutil.GetPodTemplateSpecHash(v1.PodTemplateSpec{ ObjectMeta: meta, Spec: rs.Spec.Template.Spec, })) } // MatchingPodsFunc returns a filter function for pods with matching labels -func MatchingPodsFunc(rs *extensions.ReplicaSet) (func(api.Pod) bool, error) { +func MatchingPodsFunc(rs *extensions.ReplicaSet) (func(v1.Pod) bool, error) { if rs == nil { return nil, nil } @@ -103,7 +103,7 @@ func MatchingPodsFunc(rs *extensions.ReplicaSet) (func(api.Pod) bool, error) { if err != nil { return nil, fmt.Errorf("invalid label selector: %v", err) } - return func(pod api.Pod) bool { + return func(pod v1.Pod) bool { podLabelsSelector := labels.Set(pod.ObjectMeta.Labels) return selector.Matches(podLabelsSelector) }, nil diff --git a/pkg/util/system/BUILD b/pkg/util/system/BUILD index 2a76dea7e76..1b344509b86 100644 --- a/pkg/util/system/BUILD +++ b/pkg/util/system/BUILD @@ -14,7 +14,6 @@ go_library( name = "go_default_library", srcs = ["system_utils.go"], tags = ["automanaged"], - deps = ["//pkg/api:go_default_library"], ) go_test( @@ -22,5 +21,5 @@ go_test( srcs = ["system_utils_test.go"], library = "go_default_library", tags = ["automanaged"], - deps = ["//pkg/api:go_default_library"], + deps = ["//pkg/api/v1:go_default_library"], ) diff --git a/pkg/util/system/system_utils.go b/pkg/util/system/system_utils.go index c4060935e40..a806dac6cb9 100644 --- a/pkg/util/system/system_utils.go +++ b/pkg/util/system/system_utils.go @@ -18,12 +18,10 @@ package system import ( "regexp" - - "k8s.io/kubernetes/pkg/api" ) // TODO: find a better way of figuring out if given node is a registered master. -func IsMasterNode(node *api.Node) bool { +func IsMasterNode(nodeName string) bool { r := regexp.MustCompile("master(-...)?$") - return r.MatchString(node.Name) + return r.MatchString(nodeName) } diff --git a/pkg/util/system/system_utils_test.go b/pkg/util/system/system_utils_test.go index c92c53332c6..69dcc8fd109 100644 --- a/pkg/util/system/system_utils_test.go +++ b/pkg/util/system/system_utils_test.go @@ -19,7 +19,7 @@ package system import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) func TestIsMasterNode(t *testing.T) { @@ -37,8 +37,8 @@ func TestIsMasterNode(t *testing.T) { } for _, tc := range testCases { - node := api.Node{ObjectMeta: api.ObjectMeta{Name: tc.input}} - res := IsMasterNode(&node) + node := v1.Node{ObjectMeta: v1.ObjectMeta{Name: tc.input}} + res := IsMasterNode(node.Name) if res != tc.result { t.Errorf("case \"%s\": expected %t, got %t", tc.input, tc.result, res) } diff --git a/pkg/volume/BUILD b/pkg/volume/BUILD index 6afd210bad1..b291ee63641 100644 --- a/pkg/volume/BUILD +++ b/pkg/volume/BUILD @@ -26,10 +26,10 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/resource:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/fields:go_default_library", "//pkg/types:go_default_library", @@ -59,6 +59,7 @@ go_test( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/watch:go_default_library", ], ) diff --git a/pkg/volume/aws_ebs/BUILD b/pkg/volume/aws_ebs/BUILD index 128ca48cb59..0387503de6e 100644 --- a/pkg/volume/aws_ebs/BUILD +++ b/pkg/volume/aws_ebs/BUILD @@ -20,8 +20,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/cloudprovider/providers/aws:go_default_library", "//pkg/types:go_default_library", @@ -43,8 +43,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/cloudprovider/providers/aws:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", diff --git a/pkg/volume/aws_ebs/attacher_test.go b/pkg/volume/aws_ebs/attacher_test.go index 161a9b6861a..f86638eba61 100644 --- a/pkg/volume/aws_ebs/attacher_test.go +++ b/pkg/volume/aws_ebs/attacher_test.go @@ -20,7 +20,7 @@ import ( "errors" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider/providers/aws" "k8s.io/kubernetes/pkg/volume" volumetest "k8s.io/kubernetes/pkg/volume/testing" @@ -191,9 +191,9 @@ func newDetacher(testcase *testcase) *awsElasticBlockStoreDetacher { func createVolSpec(name aws.KubernetesVolumeID, readOnly bool) *volume.Spec { return &volume.Spec{ - Volume: &api.Volume{ - VolumeSource: api.VolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{ + Volume: &v1.Volume{ + VolumeSource: v1.VolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: string(name), ReadOnly: readOnly, }, @@ -204,10 +204,10 @@ func createVolSpec(name aws.KubernetesVolumeID, readOnly bool) *volume.Spec { func createPVSpec(name aws.KubernetesVolumeID, readOnly bool) *volume.Spec { return &volume.Spec{ - PersistentVolume: &api.PersistentVolume{ - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{ + PersistentVolume: &v1.PersistentVolume{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: string(name), ReadOnly: readOnly, }, diff --git a/pkg/volume/aws_ebs/aws_ebs.go b/pkg/volume/aws_ebs/aws_ebs.go index fbc88791bfa..7fe7b0338e5 100644 --- a/pkg/volume/aws_ebs/aws_ebs.go +++ b/pkg/volume/aws_ebs/aws_ebs.go @@ -25,8 +25,8 @@ import ( "strings" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider/providers/aws" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" @@ -85,13 +85,13 @@ func (plugin *awsElasticBlockStorePlugin) RequiresRemount() bool { return false } -func (plugin *awsElasticBlockStorePlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, +func (plugin *awsElasticBlockStorePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, } } -func (plugin *awsElasticBlockStorePlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *awsElasticBlockStorePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { // Inject real implementations here, test through the internal function. return plugin.newMounterInternal(spec, pod.UID, &AWSDiskUtil{}, plugin.host.GetMounter()) } @@ -176,7 +176,7 @@ func (plugin *awsElasticBlockStorePlugin) newProvisionerInternal(options volume. } func getVolumeSource( - spec *volume.Spec) (*api.AWSElasticBlockStoreVolumeSource, bool, error) { + spec *volume.Spec) (*v1.AWSElasticBlockStoreVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.AWSElasticBlockStore != nil { return spec.Volume.AWSElasticBlockStore, spec.Volume.AWSElasticBlockStore.ReadOnly, nil } else if spec.PersistentVolume != nil && @@ -220,10 +220,10 @@ func (plugin *awsElasticBlockStorePlugin) ConstructVolumeSpec(volName, mountPath glog.V(4).Infof("Convert aws volume name from %q to %q ", volumeID, sourceName) } - awsVolume := &api.Volume{ + awsVolume := &v1.Volume{ Name: volName, - VolumeSource: api.VolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{ + VolumeSource: v1.VolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: sourceName, }, }, @@ -444,29 +444,29 @@ type awsElasticBlockStoreProvisioner struct { var _ volume.Provisioner = &awsElasticBlockStoreProvisioner{} -func (c *awsElasticBlockStoreProvisioner) Provision() (*api.PersistentVolume, error) { +func (c *awsElasticBlockStoreProvisioner) Provision() (*v1.PersistentVolume, error) { volumeID, sizeGB, labels, err := c.manager.CreateVolume(c) if err != nil { glog.Errorf("Provision failed: %v", err) return nil, err } - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: c.options.PVName, Labels: map[string]string{}, Annotations: map[string]string{ "kubernetes.io/createdby": "aws-ebs-dynamic-provisioner", }, }, - Spec: api.PersistentVolumeSpec{ + Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: c.options.PersistentVolumeReclaimPolicy, AccessModes: c.options.PVC.Spec.AccessModes, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: string(volumeID), FSType: "ext4", Partition: 0, diff --git a/pkg/volume/aws_ebs/aws_ebs_test.go b/pkg/volume/aws_ebs/aws_ebs_test.go index 96873799902..3d936b3e8fe 100644 --- a/pkg/volume/aws_ebs/aws_ebs_test.go +++ b/pkg/volume/aws_ebs/aws_ebs_test.go @@ -22,8 +22,8 @@ import ( "path" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/cloudprovider/providers/aws" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" @@ -48,10 +48,10 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/aws-ebs" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{}}}}) { t.Errorf("Expected true") } - if !plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{}}}}}) { + if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{}}}}}) { t.Errorf("Expected true") } } @@ -70,15 +70,15 @@ func TestGetAccessModes(t *testing.T) { t.Errorf("Can't find the plugin by name") } - if !contains(plug.GetAccessModes(), api.ReadWriteOnce) { - t.Errorf("Expected to support AccessModeTypes: %s", api.ReadWriteOnce) + if !contains(plug.GetAccessModes(), v1.ReadWriteOnce) { + t.Errorf("Expected to support AccessModeTypes: %s", v1.ReadWriteOnce) } - if contains(plug.GetAccessModes(), api.ReadOnlyMany) { - t.Errorf("Expected not to support AccessModeTypes: %s", api.ReadOnlyMany) + if contains(plug.GetAccessModes(), v1.ReadOnlyMany) { + t.Errorf("Expected not to support AccessModeTypes: %s", v1.ReadOnlyMany) } } -func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { +func contains(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true @@ -118,10 +118,10 @@ func TestPlugin(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{ + VolumeSource: v1.VolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: "pd", FSType: "ext4", }, @@ -181,8 +181,8 @@ func TestPlugin(t *testing.T) { // Test Provisioner options := volume.VolumeOptions{ - PVC: volumetest.CreateTestPVC("100Mi", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}), - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete, + PVC: volumetest.CreateTestPVC("100Mi", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}), + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, } provisioner, err := plug.(*awsElasticBlockStorePlugin).newProvisionerInternal(options, &fakePDManager{}) persistentSpec, err := provisioner.Provision() @@ -193,7 +193,7 @@ func TestPlugin(t *testing.T) { if persistentSpec.Spec.PersistentVolumeSource.AWSElasticBlockStore.VolumeID != "test-aws-volume-name" { t.Errorf("Provision() returned unexpected volume ID: %s", persistentSpec.Spec.PersistentVolumeSource.AWSElasticBlockStore.VolumeID) } - cap := persistentSpec.Spec.Capacity[api.ResourceStorage] + cap := persistentSpec.Spec.Capacity[v1.ResourceStorage] size := cap.Value() if size != 100*1024*1024*1024 { t.Errorf("Provision() returned unexpected volume size: %v", size) @@ -215,30 +215,30 @@ func TestPlugin(t *testing.T) { } func TestPersistentClaimReadOnlyFlag(t *testing.T) { - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{}, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, + Status: v1.PersistentVolumeClaimStatus{ + Phase: v1.ClaimBound, }, } @@ -255,7 +255,7 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { @@ -276,10 +276,10 @@ func TestMounterAndUnmounterTypeAssert(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{ + VolumeSource: v1.VolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: "pd", FSType: "ext4", }, diff --git a/pkg/volume/aws_ebs/aws_util.go b/pkg/volume/aws_ebs/aws_util.go index 74c0e38f44f..72fac0635bf 100644 --- a/pkg/volume/aws_ebs/aws_util.go +++ b/pkg/volume/aws_ebs/aws_util.go @@ -23,7 +23,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/cloudprovider/providers/aws" "k8s.io/kubernetes/pkg/volume" @@ -80,7 +80,7 @@ func (util *AWSDiskUtil) CreateVolume(c *awsElasticBlockStoreProvisioner) (aws.K } tags["Name"] = volume.GenerateVolumeName(c.options.ClusterName, c.options.PVName, 255) // AWS tags can have 255 characters - capacity := c.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] + capacity := c.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] requestBytes := capacity.Value() // AWS works with gigabytes, convert to GiB with rounding up requestGB := int(volume.RoundUpSize(requestBytes, 1024*1024*1024)) diff --git a/pkg/volume/azure_dd/BUILD b/pkg/volume/azure_dd/BUILD index 60a0e513ac0..ecdbda4ed85 100644 --- a/pkg/volume/azure_dd/BUILD +++ b/pkg/volume/azure_dd/BUILD @@ -20,8 +20,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/cloudprovider/providers/azure:go_default_library", "//pkg/types:go_default_library", @@ -46,7 +46,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", "//pkg/util/mount:go_default_library", diff --git a/pkg/volume/azure_dd/azure_dd.go b/pkg/volume/azure_dd/azure_dd.go index a7f97ca59e6..1f4c1b584d8 100644 --- a/pkg/volume/azure_dd/azure_dd.go +++ b/pkg/volume/azure_dd/azure_dd.go @@ -25,7 +25,7 @@ import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/cloudprovider/providers/azure" "k8s.io/kubernetes/pkg/types" @@ -102,13 +102,13 @@ func (plugin *azureDataDiskPlugin) RequiresRemount() bool { return false } -func (plugin *azureDataDiskPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, +func (plugin *azureDataDiskPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, } } -func (plugin *azureDataDiskPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *azureDataDiskPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { return plugin.newMounterInternal(spec, pod.UID, plugin.host.GetMounter()) } @@ -123,7 +123,7 @@ func (plugin *azureDataDiskPlugin) newMounterInternal(spec *volume.Spec, podUID if azure.FSType != nil { fsType = *azure.FSType } - cachingMode := api.AzureDataDiskCachingNone + cachingMode := v1.AzureDataDiskCachingNone if azure.CachingMode != nil { cachingMode = *azure.CachingMode } @@ -170,10 +170,10 @@ func (plugin *azureDataDiskPlugin) ConstructVolumeSpec(volName, mountPath string if err != nil { return nil, err } - azVolume := &api.Volume{ + azVolume := &v1.Volume{ Name: volName, - VolumeSource: api.VolumeSource{ - AzureDisk: &api.AzureDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + AzureDisk: &v1.AzureDiskVolumeSource{ DiskName: sourceName, }, }, @@ -191,7 +191,7 @@ type azureDisk struct { podUID types.UID diskName string diskUri string - cachingMode api.AzureDataDiskCachingMode + cachingMode v1.AzureDataDiskCachingMode mounter mount.Interface plugin *azureDataDiskPlugin volume.MetricsNil @@ -359,7 +359,7 @@ func (c *azureDiskUnmounter) TearDownAt(dir string) error { return nil } -func getVolumeSource(spec *volume.Spec) (*api.AzureDiskVolumeSource, error) { +func getVolumeSource(spec *volume.Spec) (*v1.AzureDiskVolumeSource, error) { if spec.Volume != nil && spec.Volume.AzureDisk != nil { return spec.Volume.AzureDisk, nil } diff --git a/pkg/volume/azure_dd/azure_dd_test.go b/pkg/volume/azure_dd/azure_dd_test.go index f6d871e87cb..f0ece6bb8ff 100644 --- a/pkg/volume/azure_dd/azure_dd_test.go +++ b/pkg/volume/azure_dd/azure_dd_test.go @@ -24,7 +24,7 @@ import ( "github.com/Azure/azure-sdk-for-go/arm/compute" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -48,11 +48,11 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != azureDataDiskPluginName { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{AzureDisk: &api.AzureDiskVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{AzureDisk: &v1.AzureDiskVolumeSource{}}}}) { t.Errorf("Expected true") } - if !plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{AzureDisk: &api.AzureDiskVolumeSource{}}}}}) { + if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{AzureDisk: &v1.AzureDiskVolumeSource{}}}}}) { t.Errorf("Expected true") } } @@ -114,11 +114,11 @@ func TestPlugin(t *testing.T) { } fs := "ext4" ro := false - caching := api.AzureDataDiskCachingNone - spec := &api.Volume{ + caching := v1.AzureDataDiskCachingNone + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - AzureDisk: &api.AzureDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + AzureDisk: &v1.AzureDiskVolumeSource{ DiskName: fakeDiskName, DataDiskURI: fakeDiskUri, FSType: &fs, diff --git a/pkg/volume/azure_dd/azure_provision.go b/pkg/volume/azure_dd/azure_provision.go index 333e3950ef0..5c9b1353c45 100644 --- a/pkg/volume/azure_dd/azure_provision.go +++ b/pkg/volume/azure_dd/azure_provision.go @@ -21,8 +21,8 @@ import ( "strings" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" utilstrings "k8s.io/kubernetes/pkg/util/strings" "k8s.io/kubernetes/pkg/volume" ) @@ -104,11 +104,11 @@ type azureDiskProvisioner struct { var _ volume.Provisioner = &azureDiskProvisioner{} -func (a *azureDiskProvisioner) Provision() (*api.PersistentVolume, error) { +func (a *azureDiskProvisioner) Provision() (*v1.PersistentVolume, error) { var sku, location, account string name := volume.GenerateVolumeName(a.options.ClusterName, a.options.PVName, 255) - capacity := a.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] + capacity := a.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] requestBytes := capacity.Value() requestGB := int(volume.RoundUpSize(requestBytes, 1024*1024*1024)) @@ -136,22 +136,22 @@ func (a *azureDiskProvisioner) Provision() (*api.PersistentVolume, error) { return nil, err } - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: a.options.PVName, Labels: map[string]string{}, Annotations: map[string]string{ "kubernetes.io/createdby": "azure-disk-dynamic-provisioner", }, }, - Spec: api.PersistentVolumeSpec{ + Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: a.options.PersistentVolumeReclaimPolicy, AccessModes: a.options.PVC.Spec.AccessModes, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - AzureDisk: &api.AzureDiskVolumeSource{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + AzureDisk: &v1.AzureDiskVolumeSource{ DiskName: diskName, DataDiskURI: diskUri, }, diff --git a/pkg/volume/azure_file/BUILD b/pkg/volume/azure_file/BUILD index 57a854f9148..a503e9dca27 100644 --- a/pkg/volume/azure_file/BUILD +++ b/pkg/volume/azure_file/BUILD @@ -19,7 +19,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/strings:go_default_library", @@ -34,8 +34,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/volume:go_default_library", diff --git a/pkg/volume/azure_file/azure_file.go b/pkg/volume/azure_file/azure_file.go index 058b364bdf4..272fa90579c 100644 --- a/pkg/volume/azure_file/azure_file.go +++ b/pkg/volume/azure_file/azure_file.go @@ -20,7 +20,7 @@ import ( "fmt" "os" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" kstrings "k8s.io/kubernetes/pkg/util/strings" @@ -77,19 +77,19 @@ func (plugin *azureFilePlugin) RequiresRemount() bool { return false } -func (plugin *azureFilePlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, +func (plugin *azureFilePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, } } -func (plugin *azureFilePlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *azureFilePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { return plugin.newMounterInternal(spec, pod, &azureSvc{}, plugin.host.GetMounter()) } -func (plugin *azureFilePlugin) newMounterInternal(spec *volume.Spec, pod *api.Pod, util azureUtil, mounter mount.Interface) (volume.Mounter, error) { +func (plugin *azureFilePlugin) newMounterInternal(spec *volume.Spec, pod *v1.Pod, util azureUtil, mounter mount.Interface) (volume.Mounter, error) { source, readOnly, err := getVolumeSource(spec) if err != nil { return nil, err @@ -118,17 +118,17 @@ func (plugin *azureFilePlugin) newUnmounterInternal(volName string, podUID types return &azureFileUnmounter{&azureFile{ volName: volName, mounter: mounter, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{UID: podUID}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: podUID}}, plugin: plugin, MetricsProvider: volume.NewMetricsStatFS(getPath(podUID, volName, plugin.host)), }}, nil } func (plugin *azureFilePlugin) ConstructVolumeSpec(volName, mountPath string) (*volume.Spec, error) { - azureVolume := &api.Volume{ + azureVolume := &v1.Volume{ Name: volName, - VolumeSource: api.VolumeSource{ - AzureFile: &api.AzureFileVolumeSource{ + VolumeSource: v1.VolumeSource{ + AzureFile: &v1.AzureFileVolumeSource{ SecretName: volName, ShareName: volName, }, @@ -140,7 +140,7 @@ func (plugin *azureFilePlugin) ConstructVolumeSpec(volName, mountPath string) (* // azureFile volumes represent mount of an AzureFile share. type azureFile struct { volName string - pod *api.Pod + pod *v1.Pod mounter mount.Interface plugin *azureFilePlugin volume.MetricsProvider @@ -268,7 +268,7 @@ func (c *azureFileUnmounter) TearDownAt(dir string) error { } func getVolumeSource( - spec *volume.Spec) (*api.AzureFileVolumeSource, bool, error) { + spec *volume.Spec) (*v1.AzureFileVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.AzureFile != nil { return spec.Volume.AzureFile, spec.Volume.AzureFile.ReadOnly, nil } else if spec.PersistentVolume != nil && diff --git a/pkg/volume/azure_file/azure_file_test.go b/pkg/volume/azure_file/azure_file_test.go index cfa582e7197..dc6f0d55d71 100644 --- a/pkg/volume/azure_file/azure_file_test.go +++ b/pkg/volume/azure_file/azure_file_test.go @@ -22,8 +22,8 @@ import ( "path" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/volume" @@ -46,10 +46,10 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/azure-file" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{AzureFile: &api.AzureFileVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{AzureFile: &v1.AzureFileVolumeSource{}}}}) { t.Errorf("Expected true") } - if !plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{AzureFile: &api.AzureFileVolumeSource{}}}}}) { + if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{AzureFile: &v1.AzureFileVolumeSource{}}}}}) { t.Errorf("Expected true") } } @@ -67,12 +67,12 @@ func TestGetAccessModes(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - if !contains(plug.GetAccessModes(), api.ReadWriteOnce) || !contains(plug.GetAccessModes(), api.ReadOnlyMany) || !contains(plug.GetAccessModes(), api.ReadWriteMany) { - t.Errorf("Expected three AccessModeTypes: %s, %s, and %s", api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany) + if !contains(plug.GetAccessModes(), v1.ReadWriteOnce) || !contains(plug.GetAccessModes(), v1.ReadOnlyMany) || !contains(plug.GetAccessModes(), v1.ReadWriteMany) { + t.Errorf("Expected three AccessModeTypes: %s, %s, and %s", v1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadWriteMany) } } -func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { +func contains(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true @@ -94,17 +94,17 @@ func TestPlugin(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - AzureFile: &api.AzureFileVolumeSource{ + VolumeSource: v1.VolumeSource{ + AzureFile: &v1.AzureFileVolumeSource{ SecretName: "secret", ShareName: "share", }, }, } fake := &mount.FakeMounter{} - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, err := plug.(*azureFilePlugin).newMounterInternal(volume.NewSpecFromVolume(spec), pod, &fakeAzureSvc{}, fake) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) @@ -155,30 +155,30 @@ func TestPlugin(t *testing.T) { } func TestPersistentClaimReadOnlyFlag(t *testing.T) { - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - AzureFile: &api.AzureFileVolumeSource{}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + AzureFile: &v1.AzureFileVolumeSource{}, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, + Status: v1.PersistentVolumeClaimStatus{ + Phase: v1.ClaimBound, }, } @@ -190,7 +190,7 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { @@ -217,17 +217,17 @@ func TestMounterAndUnmounterTypeAssert(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - AzureFile: &api.AzureFileVolumeSource{ + VolumeSource: v1.VolumeSource{ + AzureFile: &v1.AzureFileVolumeSource{ SecretName: "secret", ShareName: "share", }, }, } fake := &mount.FakeMounter{} - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, err := plug.(*azureFilePlugin).newMounterInternal(volume.NewSpecFromVolume(spec), pod, &fakeAzureSvc{}, fake) if _, ok := mounter.(volume.Unmounter); ok { t.Errorf("Volume Mounter can be type-assert to Unmounter") diff --git a/pkg/volume/cephfs/BUILD b/pkg/volume/cephfs/BUILD index d2357b8c070..794e46b3ecd 100644 --- a/pkg/volume/cephfs/BUILD +++ b/pkg/volume/cephfs/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/strings:go_default_library", @@ -33,7 +33,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/testing:go_default_library", diff --git a/pkg/volume/cephfs/cephfs.go b/pkg/volume/cephfs/cephfs.go index 442ed8c07e6..b7243f669cc 100644 --- a/pkg/volume/cephfs/cephfs.go +++ b/pkg/volume/cephfs/cephfs.go @@ -22,7 +22,7 @@ import ( "strings" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utilstrings "k8s.io/kubernetes/pkg/util/strings" @@ -70,15 +70,15 @@ func (plugin *cephfsPlugin) RequiresRemount() bool { return false } -func (plugin *cephfsPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, +func (plugin *cephfsPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, } } -func (plugin *cephfsPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *cephfsPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { cephvs, _, err := getVolumeSource(spec) if err != nil { return nil, err @@ -155,10 +155,10 @@ func (plugin *cephfsPlugin) newUnmounterInternal(volName string, podUID types.UI } func (plugin *cephfsPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - cephfsVolume := &api.Volume{ + cephfsVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - CephFS: &api.CephFSVolumeSource{ + VolumeSource: v1.VolumeSource{ + CephFS: &v1.CephFSVolumeSource{ Monitors: []string{}, Path: volumeName, }, @@ -312,7 +312,7 @@ func (cephfsVolume *cephfs) execMount(mountpoint string) error { return nil } -func getVolumeSource(spec *volume.Spec) (*api.CephFSVolumeSource, bool, error) { +func getVolumeSource(spec *volume.Spec) (*v1.CephFSVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.CephFS != nil { return spec.Volume.CephFS, spec.Volume.CephFS.ReadOnly, nil } else if spec.PersistentVolume != nil && diff --git a/pkg/volume/cephfs/cephfs_test.go b/pkg/volume/cephfs/cephfs_test.go index 8bf7ee2e8eb..0023f4d8543 100644 --- a/pkg/volume/cephfs/cephfs_test.go +++ b/pkg/volume/cephfs/cephfs_test.go @@ -21,7 +21,7 @@ import ( "path" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -44,10 +44,10 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/cephfs" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) { + if plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{}}}) { t.Errorf("Expected false") } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{CephFS: &api.CephFSVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{CephFS: &v1.CephFSVolumeSource{}}}}) { t.Errorf("Expected true") } } @@ -64,10 +64,10 @@ func TestPlugin(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - CephFS: &api.CephFSVolumeSource{ + VolumeSource: v1.VolumeSource{ + CephFS: &v1.CephFSVolumeSource{ Monitors: []string{"a", "b"}, User: "user", SecretRef: nil, diff --git a/pkg/volume/cinder/BUILD b/pkg/volume/cinder/BUILD index 20f34fdfb26..6a5dda70d65 100644 --- a/pkg/volume/cinder/BUILD +++ b/pkg/volume/cinder/BUILD @@ -20,8 +20,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/cloudprovider/providers/openstack:go_default_library", "//pkg/cloudprovider/providers/rackspace:go_default_library", @@ -45,7 +45,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", diff --git a/pkg/volume/cinder/attacher_test.go b/pkg/volume/cinder/attacher_test.go index b7a129cb67a..25617b7f2ce 100644 --- a/pkg/volume/cinder/attacher_test.go +++ b/pkg/volume/cinder/attacher_test.go @@ -20,7 +20,7 @@ import ( "errors" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/volume" volumetest "k8s.io/kubernetes/pkg/volume/testing" @@ -241,9 +241,9 @@ func newDetacher(testcase *testcase) *cinderDiskDetacher { func createVolSpec(name string, readOnly bool) *volume.Spec { return &volume.Spec{ - Volume: &api.Volume{ - VolumeSource: api.VolumeSource{ - Cinder: &api.CinderVolumeSource{ + Volume: &v1.Volume{ + VolumeSource: v1.VolumeSource{ + Cinder: &v1.CinderVolumeSource{ VolumeID: name, ReadOnly: readOnly, }, @@ -254,10 +254,10 @@ func createVolSpec(name string, readOnly bool) *volume.Spec { func createPVSpec(name string, readOnly bool) *volume.Spec { return &volume.Spec{ - PersistentVolume: &api.PersistentVolume{ - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - Cinder: &api.CinderVolumeSource{ + PersistentVolume: &v1.PersistentVolume{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + Cinder: &v1.CinderVolumeSource{ VolumeID: name, ReadOnly: readOnly, }, @@ -430,8 +430,8 @@ type instances struct { instanceID string } -func (instances *instances) NodeAddresses(name types.NodeName) ([]api.NodeAddress, error) { - return []api.NodeAddress{}, errors.New("Not implemented") +func (instances *instances) NodeAddresses(name types.NodeName) ([]v1.NodeAddress, error) { + return []v1.NodeAddress{}, errors.New("Not implemented") } func (instances *instances) ExternalID(name types.NodeName) (string, error) { diff --git a/pkg/volume/cinder/cinder.go b/pkg/volume/cinder/cinder.go index 41a4b146edd..2d17f427037 100644 --- a/pkg/volume/cinder/cinder.go +++ b/pkg/volume/cinder/cinder.go @@ -23,8 +23,8 @@ import ( "path" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/cloudprovider/providers/openstack" "k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace" @@ -97,13 +97,13 @@ func (plugin *cinderPlugin) RequiresRemount() bool { return false } -func (plugin *cinderPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, +func (plugin *cinderPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, } } -func (plugin *cinderPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *cinderPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { return plugin.newMounterInternal(spec, pod.UID, &CinderDiskUtil{}, plugin.host.GetMounter()) } @@ -211,10 +211,10 @@ func (plugin *cinderPlugin) ConstructVolumeSpec(volumeName, mountPath string) (* return nil, err } glog.V(4).Infof("Found volume %s mounted to %s", sourceName, mountPath) - cinderVolume := &api.Volume{ + cinderVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - Cinder: &api.CinderVolumeSource{ + VolumeSource: v1.VolumeSource{ + Cinder: &v1.CinderVolumeSource{ VolumeID: sourceName, }, }, @@ -464,28 +464,28 @@ type cinderVolumeProvisioner struct { var _ volume.Provisioner = &cinderVolumeProvisioner{} -func (c *cinderVolumeProvisioner) Provision() (*api.PersistentVolume, error) { +func (c *cinderVolumeProvisioner) Provision() (*v1.PersistentVolume, error) { volumeID, sizeGB, err := c.manager.CreateVolume(c) if err != nil { return nil, err } - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: c.options.PVName, Labels: map[string]string{}, Annotations: map[string]string{ "kubernetes.io/createdby": "cinder-dynamic-provisioner", }, }, - Spec: api.PersistentVolumeSpec{ + Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: c.options.PersistentVolumeReclaimPolicy, AccessModes: c.options.PVC.Spec.AccessModes, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - Cinder: &api.CinderVolumeSource{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + Cinder: &v1.CinderVolumeSource{ VolumeID: volumeID, FSType: "ext4", ReadOnly: false, @@ -500,7 +500,7 @@ func (c *cinderVolumeProvisioner) Provision() (*api.PersistentVolume, error) { return pv, nil } -func getVolumeSource(spec *volume.Spec) (*api.CinderVolumeSource, bool, error) { +func getVolumeSource(spec *volume.Spec) (*v1.CinderVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.Cinder != nil { return spec.Volume.Cinder, spec.Volume.Cinder.ReadOnly, nil } else if spec.PersistentVolume != nil && diff --git a/pkg/volume/cinder/cinder_test.go b/pkg/volume/cinder/cinder_test.go index a371392f22e..1f01c23b4d7 100644 --- a/pkg/volume/cinder/cinder_test.go +++ b/pkg/volume/cinder/cinder_test.go @@ -23,7 +23,7 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -47,11 +47,11 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/cinder" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{Cinder: &api.CinderVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{Cinder: &v1.CinderVolumeSource{}}}}) { t.Errorf("Expected true") } - if !plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{Cinder: &api.CinderVolumeSource{}}}}}) { + if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{Cinder: &v1.CinderVolumeSource{}}}}}) { t.Errorf("Expected true") } } @@ -140,10 +140,10 @@ func TestPlugin(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - Cinder: &api.CinderVolumeSource{ + VolumeSource: v1.VolumeSource{ + Cinder: &v1.CinderVolumeSource{ VolumeID: "pd", FSType: "ext4", }, @@ -199,8 +199,8 @@ func TestPlugin(t *testing.T) { // Test Provisioner options := volume.VolumeOptions{ - PVC: volumetest.CreateTestPVC("100Mi", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}), - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete, + PVC: volumetest.CreateTestPVC("100Mi", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}), + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, } provisioner, err := plug.(*cinderPlugin).newProvisionerInternal(options, &fakePDManager{0}) persistentSpec, err := provisioner.Provision() @@ -211,7 +211,7 @@ func TestPlugin(t *testing.T) { if persistentSpec.Spec.PersistentVolumeSource.Cinder.VolumeID != "test-volume-name" { t.Errorf("Provision() returned unexpected volume ID: %s", persistentSpec.Spec.PersistentVolumeSource.Cinder.VolumeID) } - cap := persistentSpec.Spec.Capacity[api.ResourceStorage] + cap := persistentSpec.Spec.Capacity[v1.ResourceStorage] size := cap.Value() if size != 1024*1024*1024 { t.Errorf("Provision() returned unexpected volume size: %v", size) diff --git a/pkg/volume/cinder/cinder_util.go b/pkg/volume/cinder/cinder_util.go index 934006aa723..1a70109902c 100644 --- a/pkg/volume/cinder/cinder_util.go +++ b/pkg/volume/cinder/cinder_util.go @@ -24,7 +24,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/volume" ) @@ -140,7 +140,7 @@ func (util *CinderDiskUtil) CreateVolume(c *cinderVolumeProvisioner) (volumeID s return "", 0, err } - capacity := c.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] + capacity := c.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] volSizeBytes := capacity.Value() // Cinder works with gigabytes, convert to GiB with rounding up volSizeGB := int(volume.RoundUpSize(volSizeBytes, 1024*1024*1024)) diff --git a/pkg/volume/configmap/BUILD b/pkg/volume/configmap/BUILD index 0b2e87d1170..3d9e748256d 100644 --- a/pkg/volume/configmap/BUILD +++ b/pkg/volume/configmap/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/io:go_default_library", "//pkg/util/mount:go_default_library", @@ -35,9 +35,9 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/types:go_default_library", "//pkg/volume:go_default_library", "//pkg/volume/empty_dir:go_default_library", diff --git a/pkg/volume/configmap/configmap.go b/pkg/volume/configmap/configmap.go index 25347f9c701..9c3e5e20054 100644 --- a/pkg/volume/configmap/configmap.go +++ b/pkg/volume/configmap/configmap.go @@ -20,7 +20,7 @@ import ( "fmt" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" ioutil "k8s.io/kubernetes/pkg/util/io" "k8s.io/kubernetes/pkg/util/mount" @@ -74,7 +74,7 @@ func (plugin *configMapPlugin) RequiresRemount() bool { return true } -func (plugin *configMapPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *configMapPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { return &configMapVolumeMounter{ configMapVolume: &configMapVolume{spec.Name(), pod.UID, plugin, plugin.host.GetMounter(), plugin.host.GetWriter(), volume.MetricsNil{}}, source: *spec.Volume.ConfigMap, @@ -87,10 +87,10 @@ func (plugin *configMapPlugin) NewUnmounter(volName string, podUID types.UID) (v } func (plugin *configMapPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - configMapVolume := &api.Volume{ + configMapVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - ConfigMap: &api.ConfigMapVolumeSource{}, + VolumeSource: v1.VolumeSource{ + ConfigMap: &v1.ConfigMapVolumeSource{}, }, } return volume.NewSpecFromVolume(configMapVolume), nil @@ -116,8 +116,8 @@ func (sv *configMapVolume) GetPath() string { type configMapVolumeMounter struct { *configMapVolume - source api.ConfigMapVolumeSource - pod api.Pod + source v1.ConfigMapVolumeSource + pod v1.Pod opts *volume.VolumeOptions } @@ -137,7 +137,7 @@ func wrappedVolumeSpec() volume.Spec { // This should be on a tmpfs instead of the local disk; the problem is // charging the memory for the tmpfs to the right cgroup. We should make // this a tmpfs when we can do the accounting correctly. - Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, + Volume: &v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}}, } } @@ -209,7 +209,7 @@ func (b *configMapVolumeMounter) SetUpAt(dir string, fsGroup *int64) error { return nil } -func makePayload(mappings []api.KeyToPath, configMap *api.ConfigMap, defaultMode *int32) (map[string]volumeutil.FileProjection, error) { +func makePayload(mappings []v1.KeyToPath, configMap *v1.ConfigMap, defaultMode *int32) (map[string]volumeutil.FileProjection, error) { if defaultMode == nil { return nil, fmt.Errorf("No defaultMode used, not even the default value for it") } @@ -245,7 +245,7 @@ func makePayload(mappings []api.KeyToPath, configMap *api.ConfigMap, defaultMode return payload, nil } -func totalBytes(configMap *api.ConfigMap) int { +func totalBytes(configMap *v1.ConfigMap) int { totalSize := 0 for _, value := range configMap.Data { totalSize += len(value) @@ -276,9 +276,9 @@ func (c *configMapVolumeUnmounter) TearDownAt(dir string) error { return wrapped.TearDownAt(dir) } -func getVolumeSource(spec *volume.Spec) (*api.ConfigMapVolumeSource, bool) { +func getVolumeSource(spec *volume.Spec) (*v1.ConfigMapVolumeSource, bool) { var readOnly bool - var volumeSource *api.ConfigMapVolumeSource + var volumeSource *v1.ConfigMapVolumeSource if spec.Volume != nil && spec.Volume.ConfigMap != nil { volumeSource = spec.Volume.ConfigMap diff --git a/pkg/volume/configmap/configmap_test.go b/pkg/volume/configmap/configmap_test.go index f7081b426e8..7b6f5f6ec72 100644 --- a/pkg/volume/configmap/configmap_test.go +++ b/pkg/volume/configmap/configmap_test.go @@ -25,9 +25,9 @@ import ( "strings" "testing" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/empty_dir" @@ -39,15 +39,15 @@ func TestMakePayload(t *testing.T) { caseMappingMode := int32(0400) cases := []struct { name string - mappings []api.KeyToPath - configMap *api.ConfigMap + mappings []v1.KeyToPath + configMap *v1.ConfigMap mode int32 payload map[string]util.FileProjection success bool }{ { name: "no overrides", - configMap: &api.ConfigMap{ + configMap: &v1.ConfigMap{ Data: map[string]string{ "foo": "foo", "bar": "bar", @@ -62,13 +62,13 @@ func TestMakePayload(t *testing.T) { }, { name: "basic 1", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/foo.txt", }, }, - configMap: &api.ConfigMap{ + configMap: &v1.ConfigMap{ Data: map[string]string{ "foo": "foo", "bar": "bar", @@ -82,13 +82,13 @@ func TestMakePayload(t *testing.T) { }, { name: "subdirs", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/1/2/3/foo.txt", }, }, - configMap: &api.ConfigMap{ + configMap: &v1.ConfigMap{ Data: map[string]string{ "foo": "foo", "bar": "bar", @@ -102,13 +102,13 @@ func TestMakePayload(t *testing.T) { }, { name: "subdirs 2", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/1/2/3/foo.txt", }, }, - configMap: &api.ConfigMap{ + configMap: &v1.ConfigMap{ Data: map[string]string{ "foo": "foo", "bar": "bar", @@ -122,7 +122,7 @@ func TestMakePayload(t *testing.T) { }, { name: "subdirs 3", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/1/2/3/foo.txt", @@ -132,7 +132,7 @@ func TestMakePayload(t *testing.T) { Path: "another/path/to/the/esteemed/bar.bin", }, }, - configMap: &api.ConfigMap{ + configMap: &v1.ConfigMap{ Data: map[string]string{ "foo": "foo", "bar": "bar", @@ -147,13 +147,13 @@ func TestMakePayload(t *testing.T) { }, { name: "non existent key", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "zab", Path: "path/to/foo.txt", }, }, - configMap: &api.ConfigMap{ + configMap: &v1.ConfigMap{ Data: map[string]string{ "foo": "foo", "bar": "bar", @@ -164,7 +164,7 @@ func TestMakePayload(t *testing.T) { }, { name: "mapping with Mode", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "foo.txt", @@ -176,7 +176,7 @@ func TestMakePayload(t *testing.T) { Mode: &caseMappingMode, }, }, - configMap: &api.ConfigMap{ + configMap: &v1.ConfigMap{ Data: map[string]string{ "foo": "foo", "bar": "bar", @@ -191,7 +191,7 @@ func TestMakePayload(t *testing.T) { }, { name: "mapping with defaultMode", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "foo.txt", @@ -201,7 +201,7 @@ func TestMakePayload(t *testing.T) { Path: "bar.bin", }, }, - configMap: &api.ConfigMap{ + configMap: &v1.ConfigMap{ Data: map[string]string{ "foo": "foo", "bar": "bar", @@ -260,7 +260,7 @@ func TestCanSupport(t *testing.T) { if plugin.GetPluginName() != configMapPluginName { t.Errorf("Wrong name: %s", plugin.GetPluginName()) } - if !plugin.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{ConfigMap: &api.ConfigMapVolumeSource{LocalObjectReference: api.LocalObjectReference{Name: ""}}}}}) { + if !plugin.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{ConfigMap: &v1.ConfigMapVolumeSource{LocalObjectReference: v1.LocalObjectReference{Name: ""}}}}}) { t.Errorf("Expected true") } if plugin.CanSupport(&volume.Spec{}) { @@ -290,7 +290,7 @@ func TestPlugin(t *testing.T) { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) @@ -354,7 +354,7 @@ func TestPluginReboot(t *testing.T) { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) @@ -387,12 +387,12 @@ func TestPluginReboot(t *testing.T) { doTestCleanAndTeardown(plugin, testPodUID, testVolumeName, volumePath, t) } -func volumeSpec(volumeName, configMapName string, defaultMode int32) *api.Volume { - return &api.Volume{ +func volumeSpec(volumeName, configMapName string, defaultMode int32) *v1.Volume { + return &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - ConfigMap: &api.ConfigMapVolumeSource{ - LocalObjectReference: api.LocalObjectReference{ + VolumeSource: v1.VolumeSource{ + ConfigMap: &v1.ConfigMapVolumeSource{ + LocalObjectReference: v1.LocalObjectReference{ Name: configMapName, }, DefaultMode: &defaultMode, @@ -401,9 +401,9 @@ func volumeSpec(volumeName, configMapName string, defaultMode int32) *api.Volume } } -func configMap(namespace, name string) api.ConfigMap { - return api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ +func configMap(namespace, name string) v1.ConfigMap { + return v1.ConfigMap{ + ObjectMeta: v1.ObjectMeta{ Namespace: namespace, Name: name, }, @@ -415,7 +415,7 @@ func configMap(namespace, name string) api.ConfigMap { } } -func doTestConfigMapDataInVolume(volumePath string, configMap api.ConfigMap, t *testing.T) { +func doTestConfigMapDataInVolume(volumePath string, configMap v1.ConfigMap, t *testing.T) { for key, value := range configMap.Data { configMapDataHostPath := path.Join(volumePath, key) if _, err := os.Stat(configMapDataHostPath); err != nil { diff --git a/pkg/volume/downwardapi/BUILD b/pkg/volume/downwardapi/BUILD index 765dcaf70d0..bef04f30266 100644 --- a/pkg/volume/downwardapi/BUILD +++ b/pkg/volume/downwardapi/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["downwardapi.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/fieldpath:go_default_library", "//pkg/types:go_default_library", "//pkg/util/errors:go_default_library", @@ -32,9 +32,9 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/fieldpath:go_default_library", "//pkg/types:go_default_library", "//pkg/util/testing:go_default_library", diff --git a/pkg/volume/downwardapi/downwardapi.go b/pkg/volume/downwardapi/downwardapi.go index ec41ee20a56..19ed4eb3c9d 100644 --- a/pkg/volume/downwardapi/downwardapi.go +++ b/pkg/volume/downwardapi/downwardapi.go @@ -22,7 +22,7 @@ import ( "sort" "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/fieldpath" "k8s.io/kubernetes/pkg/types" utilerrors "k8s.io/kubernetes/pkg/util/errors" @@ -51,7 +51,7 @@ var _ volume.VolumePlugin = &downwardAPIPlugin{} func wrappedVolumeSpec() volume.Spec { return volume.Spec{ - Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{Medium: api.StorageMediumMemory}}}, + Volume: &v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{Medium: v1.StorageMediumMemory}}}, } } @@ -82,7 +82,7 @@ func (plugin *downwardAPIPlugin) RequiresRemount() bool { return true } -func (plugin *downwardAPIPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *downwardAPIPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { v := &downwardAPIVolume{ volName: spec.Name(), items: spec.Volume.DownwardAPI.Items, @@ -108,10 +108,10 @@ func (plugin *downwardAPIPlugin) NewUnmounter(volName string, podUID types.UID) } func (plugin *downwardAPIPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - downwardAPIVolume := &api.Volume{ + downwardAPIVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{}, + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{}, }, } return volume.NewSpecFromVolume(downwardAPIVolume), nil @@ -120,9 +120,9 @@ func (plugin *downwardAPIPlugin) ConstructVolumeSpec(volumeName, mountPath strin // downwardAPIVolume retrieves downward API data and placing them into the volume on the host. type downwardAPIVolume struct { volName string - items []api.DownwardAPIVolumeFile - pod *api.Pod - podUID types.UID // TODO: remove this redundancy as soon NewUnmounter func will have *api.POD and not only types.UID + items []v1.DownwardAPIVolumeFile + pod *v1.Pod + podUID types.UID // TODO: remove this redundancy as soon NewUnmounter func will have *v1.POD and not only types.UID plugin *downwardAPIPlugin volume.MetricsNil } @@ -131,7 +131,7 @@ type downwardAPIVolume struct { // and dumps it in files type downwardAPIVolumeMounter struct { *downwardAPIVolume - source api.DownwardAPIVolumeSource + source v1.DownwardAPIVolumeSource opts *volume.VolumeOptions } @@ -286,9 +286,9 @@ func (b *downwardAPIVolumeMounter) getMetaDir() string { return path.Join(b.plugin.host.GetPodPluginDir(b.podUID, utilstrings.EscapeQualifiedNameForDisk(downwardAPIPluginName)), b.volName) } -func getVolumeSource(spec *volume.Spec) (*api.DownwardAPIVolumeSource, bool) { +func getVolumeSource(spec *volume.Spec) (*v1.DownwardAPIVolumeSource, bool) { var readOnly bool - var volumeSource *api.DownwardAPIVolumeSource + var volumeSource *v1.DownwardAPIVolumeSource if spec.Volume != nil && spec.Volume.DownwardAPI != nil { volumeSource = spec.Volume.DownwardAPI diff --git a/pkg/volume/downwardapi/downwardapi_test.go b/pkg/volume/downwardapi/downwardapi_test.go index 25d67db1ae6..06541e7cb9b 100644 --- a/pkg/volume/downwardapi/downwardapi_test.go +++ b/pkg/volume/downwardapi/downwardapi_test.go @@ -23,9 +23,9 @@ import ( "path" "testing" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/fieldpath" "k8s.io/kubernetes/pkg/types" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -90,8 +90,8 @@ func TestLabels(t *testing.T) { "key1": "value1", "key2": "value2"} - clientset := fake.NewSimpleClientset(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + clientset := fake.NewSimpleClientset(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: testName, Namespace: testNamespace, Labels: labels, @@ -104,20 +104,20 @@ func TestLabels(t *testing.T) { pluginMgr.InitPlugins(ProbeVolumePlugins(), host) plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName) defaultMode := int32(0644) - volumeSpec := &api.Volume{ + volumeSpec := &v1.Volume{ Name: testVolumeName, - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{ + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{ DefaultMode: &defaultMode, - Items: []api.DownwardAPIVolumeFile{ - {Path: "labels", FieldRef: &api.ObjectFieldSelector{ + Items: []v1.DownwardAPIVolumeFile{ + {Path: "labels", FieldRef: &v1.ObjectFieldSelector{ FieldPath: "metadata.labels"}}}}, }, } if err != nil { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Labels: labels}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: testPodUID, Labels: labels}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { @@ -170,19 +170,19 @@ func TestAnnotations(t *testing.T) { "a2": "value2"} defaultMode := int32(0644) - volumeSpec := &api.Volume{ + volumeSpec := &v1.Volume{ Name: testVolumeName, - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{ + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{ DefaultMode: &defaultMode, - Items: []api.DownwardAPIVolumeFile{ - {Path: "annotations", FieldRef: &api.ObjectFieldSelector{ + Items: []v1.DownwardAPIVolumeFile{ + {Path: "annotations", FieldRef: &v1.ObjectFieldSelector{ FieldPath: "metadata.annotations"}}}}, }, } - clientset := fake.NewSimpleClientset(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + clientset := fake.NewSimpleClientset(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: testName, Namespace: testNamespace, Annotations: annotations, @@ -197,7 +197,7 @@ func TestAnnotations(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Annotations: annotations}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: testPodUID, Annotations: annotations}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) @@ -235,19 +235,19 @@ func TestName(t *testing.T) { ) defaultMode := int32(0644) - volumeSpec := &api.Volume{ + volumeSpec := &v1.Volume{ Name: testVolumeName, - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{ + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{ DefaultMode: &defaultMode, - Items: []api.DownwardAPIVolumeFile{ - {Path: "name_file_name", FieldRef: &api.ObjectFieldSelector{ + Items: []v1.DownwardAPIVolumeFile{ + {Path: "name_file_name", FieldRef: &v1.ObjectFieldSelector{ FieldPath: "metadata.name"}}}}, }, } - clientset := fake.NewSimpleClientset(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + clientset := fake.NewSimpleClientset(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: testName, Namespace: testNamespace, }, @@ -261,7 +261,7 @@ func TestName(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Name: testName}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: testPodUID, Name: testName}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) @@ -300,19 +300,19 @@ func TestNamespace(t *testing.T) { ) defaultMode := int32(0644) - volumeSpec := &api.Volume{ + volumeSpec := &v1.Volume{ Name: testVolumeName, - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{ + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{ DefaultMode: &defaultMode, - Items: []api.DownwardAPIVolumeFile{ - {Path: "namespace_file_name", FieldRef: &api.ObjectFieldSelector{ + Items: []v1.DownwardAPIVolumeFile{ + {Path: "namespace_file_name", FieldRef: &v1.ObjectFieldSelector{ FieldPath: "metadata.namespace"}}}}, }, } - clientset := fake.NewSimpleClientset(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + clientset := fake.NewSimpleClientset(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: testName, Namespace: testNamespace, }, @@ -326,7 +326,7 @@ func TestNamespace(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Namespace: testNamespace}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: testPodUID, Namespace: testNamespace}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) @@ -367,8 +367,8 @@ func TestWriteTwiceNoUpdate(t *testing.T) { "key1": "value1", "key2": "value2"} - clientset := fake.NewSimpleClientset(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + clientset := fake.NewSimpleClientset(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: testName, Namespace: testNamespace, Labels: labels, @@ -380,20 +380,20 @@ func TestWriteTwiceNoUpdate(t *testing.T) { pluginMgr.InitPlugins(ProbeVolumePlugins(), host) plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName) defaultMode := int32(0644) - volumeSpec := &api.Volume{ + volumeSpec := &v1.Volume{ Name: testVolumeName, - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{ + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{ DefaultMode: &defaultMode, - Items: []api.DownwardAPIVolumeFile{ - {Path: "labels", FieldRef: &api.ObjectFieldSelector{ + Items: []v1.DownwardAPIVolumeFile{ + {Path: "labels", FieldRef: &v1.ObjectFieldSelector{ FieldPath: "metadata.labels"}}}}, }, } if err != nil { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Labels: labels}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: testPodUID, Labels: labels}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { @@ -455,8 +455,8 @@ func TestWriteTwiceWithUpdate(t *testing.T) { "key1": "value1", "key2": "value2"} - clientset := fake.NewSimpleClientset(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + clientset := fake.NewSimpleClientset(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: testName, Namespace: testNamespace, Labels: labels, @@ -468,20 +468,20 @@ func TestWriteTwiceWithUpdate(t *testing.T) { pluginMgr.InitPlugins(ProbeVolumePlugins(), host) plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName) defaultMode := int32(0644) - volumeSpec := &api.Volume{ + volumeSpec := &v1.Volume{ Name: testVolumeName, - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{ + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{ DefaultMode: &defaultMode, - Items: []api.DownwardAPIVolumeFile{ - {Path: "labels", FieldRef: &api.ObjectFieldSelector{ + Items: []v1.DownwardAPIVolumeFile{ + {Path: "labels", FieldRef: &v1.ObjectFieldSelector{ FieldPath: "metadata.labels"}}}}, }, } if err != nil { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Labels: labels}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: testPodUID, Labels: labels}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { @@ -562,8 +562,8 @@ func TestWriteWithUnixPath(t *testing.T) { "a1": "value1", "a2": "value2"} - clientset := fake.NewSimpleClientset(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + clientset := fake.NewSimpleClientset(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: testName, Namespace: testNamespace, Labels: labels, @@ -576,22 +576,22 @@ func TestWriteWithUnixPath(t *testing.T) { pluginMgr.InitPlugins(ProbeVolumePlugins(), host) plugin, err := pluginMgr.FindPluginByName(downwardAPIPluginName) defaultMode := int32(0644) - volumeSpec := &api.Volume{ + volumeSpec := &v1.Volume{ Name: testVolumeName, - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{ + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{ DefaultMode: &defaultMode, - Items: []api.DownwardAPIVolumeFile{ - {Path: "this/is/mine/labels", FieldRef: &api.ObjectFieldSelector{ + Items: []v1.DownwardAPIVolumeFile{ + {Path: "this/is/mine/labels", FieldRef: &v1.ObjectFieldSelector{ FieldPath: "metadata.labels"}}, - {Path: "this/is/yours/annotations", FieldRef: &api.ObjectFieldSelector{ + {Path: "this/is/yours/annotations", FieldRef: &v1.ObjectFieldSelector{ FieldPath: "metadata.annotations"}}, }}}, } if err != nil { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Labels: labels, Annotations: annotations}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: testPodUID, Labels: labels, Annotations: annotations}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { @@ -640,8 +640,8 @@ func TestWriteWithUnixPathBadPath(t *testing.T) { "key2": "value2", } - clientset := fake.NewSimpleClientset(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + clientset := fake.NewSimpleClientset(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: testName, Namespace: testNamespace, Labels: labels, @@ -658,15 +658,15 @@ func TestWriteWithUnixPathBadPath(t *testing.T) { } defaultMode := int32(0644) - volumeSpec := &api.Volume{ + volumeSpec := &v1.Volume{ Name: testVolumeName, - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{ + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{ DefaultMode: &defaultMode, - Items: []api.DownwardAPIVolumeFile{ + Items: []v1.DownwardAPIVolumeFile{ { Path: "this//labels", - FieldRef: &api.ObjectFieldSelector{ + FieldRef: &v1.ObjectFieldSelector{ FieldPath: "metadata.labels", }, }, @@ -675,7 +675,7 @@ func TestWriteWithUnixPathBadPath(t *testing.T) { }, } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Labels: labels}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: testPodUID, Labels: labels}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Fatalf("Failed to make a new Mounter: %v", err) @@ -710,19 +710,19 @@ func TestDefaultMode(t *testing.T) { ) defaultMode := int32(0644) - volumeSpec := &api.Volume{ + volumeSpec := &v1.Volume{ Name: testVolumeName, - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{ + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{ DefaultMode: &defaultMode, - Items: []api.DownwardAPIVolumeFile{ - {Path: "name_file_name", FieldRef: &api.ObjectFieldSelector{ + Items: []v1.DownwardAPIVolumeFile{ + {Path: "name_file_name", FieldRef: &v1.ObjectFieldSelector{ FieldPath: "metadata.name"}}}}, }, } - clientset := fake.NewSimpleClientset(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + clientset := fake.NewSimpleClientset(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: testName, Namespace: testNamespace, }, @@ -736,7 +736,7 @@ func TestDefaultMode(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Name: testName}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: testPodUID, Name: testName}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) @@ -776,14 +776,14 @@ func TestItemMode(t *testing.T) { defaultMode := int32(0644) itemMode := int32(0400) - volumeSpec := &api.Volume{ + volumeSpec := &v1.Volume{ Name: testVolumeName, - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{ + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{ DefaultMode: &defaultMode, - Items: []api.DownwardAPIVolumeFile{ + Items: []v1.DownwardAPIVolumeFile{ { - Path: "name_file_name", FieldRef: &api.ObjectFieldSelector{FieldPath: "metadata.name"}, + Path: "name_file_name", FieldRef: &v1.ObjectFieldSelector{FieldPath: "metadata.name"}, Mode: &itemMode, }, }, @@ -791,8 +791,8 @@ func TestItemMode(t *testing.T) { }, } - clientset := fake.NewSimpleClientset(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + clientset := fake.NewSimpleClientset(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: testName, Namespace: testNamespace, }, @@ -806,7 +806,7 @@ func TestItemMode(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID, Name: testName}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: testPodUID, Name: testName}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) diff --git a/pkg/volume/empty_dir/BUILD b/pkg/volume/empty_dir/BUILD index 8b6df93f068..16175ff7ddc 100644 --- a/pkg/volume/empty_dir/BUILD +++ b/pkg/volume/empty_dir/BUILD @@ -19,7 +19,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/strings:go_default_library", @@ -35,7 +35,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/testing:go_default_library", diff --git a/pkg/volume/empty_dir/empty_dir.go b/pkg/volume/empty_dir/empty_dir.go index 56ff708ad76..4be2eb551a9 100644 --- a/pkg/volume/empty_dir/empty_dir.go +++ b/pkg/volume/empty_dir/empty_dir.go @@ -22,7 +22,7 @@ import ( "path" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/util/strings" @@ -89,12 +89,12 @@ func (plugin *emptyDirPlugin) RequiresRemount() bool { return false } -func (plugin *emptyDirPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *emptyDirPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { return plugin.newMounterInternal(spec, pod, plugin.host.GetMounter(), &realMountDetector{plugin.host.GetMounter()}, opts) } -func (plugin *emptyDirPlugin) newMounterInternal(spec *volume.Spec, pod *api.Pod, mounter mount.Interface, mountDetector mountDetector, opts volume.VolumeOptions) (volume.Mounter, error) { - medium := api.StorageMediumDefault +func (plugin *emptyDirPlugin) newMounterInternal(spec *volume.Spec, pod *v1.Pod, mounter mount.Interface, mountDetector mountDetector, opts volume.VolumeOptions) (volume.Mounter, error) { + medium := v1.StorageMediumDefault if spec.Volume.EmptyDir != nil { // Support a non-specified source as EmptyDir. medium = spec.Volume.EmptyDir.Medium } @@ -116,9 +116,9 @@ func (plugin *emptyDirPlugin) NewUnmounter(volName string, podUID types.UID) (vo func (plugin *emptyDirPlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface, mountDetector mountDetector) (volume.Unmounter, error) { ed := &emptyDir{ - pod: &api.Pod{ObjectMeta: api.ObjectMeta{UID: podUID}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: podUID}}, volName: volName, - medium: api.StorageMediumDefault, // might be changed later + medium: v1.StorageMediumDefault, // might be changed later mounter: mounter, mountDetector: mountDetector, plugin: plugin, @@ -128,10 +128,10 @@ func (plugin *emptyDirPlugin) newUnmounterInternal(volName string, podUID types. } func (plugin *emptyDirPlugin) ConstructVolumeSpec(volName, mountPath string) (*volume.Spec, error) { - emptyDirVolume := &api.Volume{ + emptyDirVolume := &v1.Volume{ Name: volName, - VolumeSource: api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + VolumeSource: v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }, } return volume.NewSpecFromVolume(emptyDirVolume), nil @@ -157,9 +157,9 @@ const ( // EmptyDir volumes are temporary directories exposed to the pod. // These do not persist beyond the lifetime of a pod. type emptyDir struct { - pod *api.Pod + pod *v1.Pod volName string - medium api.StorageMedium + medium v1.StorageMedium mounter mount.Interface mountDetector mountDetector plugin *emptyDirPlugin @@ -200,17 +200,17 @@ func (ed *emptyDir) SetUpAt(dir string, fsGroup *int64) error { // medium is memory, and a mountpoint is present, then the volume is // ready. if volumeutil.IsReady(ed.getMetaDir()) { - if ed.medium == api.StorageMediumMemory && !notMnt { + if ed.medium == v1.StorageMediumMemory && !notMnt { return nil - } else if ed.medium == api.StorageMediumDefault { + } else if ed.medium == v1.StorageMediumDefault { return nil } } switch ed.medium { - case api.StorageMediumDefault: + case v1.StorageMediumDefault: err = ed.setupDir(dir) - case api.StorageMediumMemory: + case v1.StorageMediumMemory: err = ed.setupTmpfs(dir) default: err = fmt.Errorf("unknown storage medium %q", ed.medium) @@ -305,7 +305,7 @@ func (ed *emptyDir) TearDownAt(dir string) error { return err } if isMnt && medium == mediumMemory { - ed.medium = api.StorageMediumMemory + ed.medium = v1.StorageMediumMemory return ed.teardownTmpfs(dir) } // assume StorageMediumDefault @@ -341,9 +341,9 @@ func (ed *emptyDir) getMetaDir() string { return path.Join(ed.plugin.host.GetPodPluginDir(ed.pod.UID, strings.EscapeQualifiedNameForDisk(emptyDirPluginName)), ed.volName) } -func getVolumeSource(spec *volume.Spec) (*api.EmptyDirVolumeSource, bool) { +func getVolumeSource(spec *volume.Spec) (*v1.EmptyDirVolumeSource, bool) { var readOnly bool - var volumeSource *api.EmptyDirVolumeSource + var volumeSource *v1.EmptyDirVolumeSource if spec.Volume != nil && spec.Volume.EmptyDir != nil { volumeSource = spec.Volume.EmptyDir diff --git a/pkg/volume/empty_dir/empty_dir_test.go b/pkg/volume/empty_dir/empty_dir_test.go index b1e79f709a5..f071205c997 100644 --- a/pkg/volume/empty_dir/empty_dir_test.go +++ b/pkg/volume/empty_dir/empty_dir_test.go @@ -23,7 +23,7 @@ import ( "path" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -55,10 +55,10 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/empty-dir" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}}}) { t.Errorf("Expected true") } - if plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) { + if plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{}}}) { t.Errorf("Expected false") } } @@ -74,13 +74,13 @@ func (fake *fakeMountDetector) GetMountMedium(path string) (storageMedium, bool, func TestPluginEmptyRootContext(t *testing.T) { doTestPlugin(t, pluginTestConfig{ - medium: api.StorageMediumDefault, + medium: v1.StorageMediumDefault, expectedSetupMounts: 0, expectedTeardownMounts: 0}) } type pluginTestConfig struct { - medium api.StorageMedium + medium v1.StorageMedium idempotent bool expectedSetupMounts int shouldBeMountedBeforeTeardown bool @@ -101,14 +101,14 @@ func doTestPlugin(t *testing.T, config pluginTestConfig) { plug = makePluginUnderTest(t, "kubernetes.io/empty-dir", basePath) volumeName = "test-volume" - spec = &api.Volume{ + spec = &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{Medium: config.medium}}, + VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{Medium: config.medium}}, } physicalMounter = mount.FakeMounter{} mountDetector = fakeMountDetector{} - pod = &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod = &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} ) if config.idempotent { @@ -171,7 +171,7 @@ func doTestPlugin(t *testing.T, config pluginTestConfig) { // Make an unmounter for the volume teardownMedium := mediumUnknown - if config.medium == api.StorageMediumMemory { + if config.medium == v1.StorageMediumMemory { teardownMedium = mediumMemory } unmounterMountDetector := &fakeMountDetector{medium: teardownMedium, isMount: config.shouldBeMountedBeforeTeardown} @@ -211,10 +211,10 @@ func TestPluginBackCompat(t *testing.T) { plug := makePluginUnderTest(t, "kubernetes.io/empty-dir", basePath) - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, err := plug.NewMounter(volume.NewSpecFromVolume(spec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) @@ -240,10 +240,10 @@ func TestMetrics(t *testing.T) { plug := makePluginUnderTest(t, "kubernetes.io/empty-dir", tmpDir) - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, err := plug.NewMounter(volume.NewSpecFromVolume(spec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) diff --git a/pkg/volume/fc/BUILD b/pkg/volume/fc/BUILD index ea7235f849f..0d61e00c320 100644 --- a/pkg/volume/fc/BUILD +++ b/pkg/volume/fc/BUILD @@ -20,7 +20,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", "//pkg/util/mount:go_default_library", @@ -39,8 +39,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/testing:go_default_library", diff --git a/pkg/volume/fc/fc.go b/pkg/volume/fc/fc.go index 281a580be0b..84a1a7487ea 100644 --- a/pkg/volume/fc/fc.go +++ b/pkg/volume/fc/fc.go @@ -21,7 +21,7 @@ import ( "strconv" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/mount" @@ -77,14 +77,14 @@ func (plugin *fcPlugin) RequiresRemount() bool { return false } -func (plugin *fcPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, +func (plugin *fcPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, } } -func (plugin *fcPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *fcPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { // Inject real implementations here, test through the internal function. return plugin.newMounterInternal(spec, pod.UID, &FCUtil{}, plugin.host.GetMounter()) } @@ -142,10 +142,10 @@ func (plugin *fcPlugin) execCommand(command string, args []string) ([]byte, erro } func (plugin *fcPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - fcVolume := &api.Volume{ + fcVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - FC: &api.FCVolumeSource{}, + VolumeSource: v1.VolumeSource{ + FC: &v1.FCVolumeSource{}, }, } return volume.NewSpecFromVolume(fcVolume), nil @@ -225,7 +225,7 @@ func (c *fcDiskUnmounter) TearDownAt(dir string) error { return diskTearDown(c.manager, *c, dir, c.mounter) } -func getVolumeSource(spec *volume.Spec) (*api.FCVolumeSource, bool, error) { +func getVolumeSource(spec *volume.Spec) (*v1.FCVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.FC != nil { return spec.Volume.FC, spec.Volume.FC.ReadOnly, nil } else if spec.PersistentVolume != nil && diff --git a/pkg/volume/fc/fc_test.go b/pkg/volume/fc/fc_test.go index a78b704324c..bc21e95eb5c 100644 --- a/pkg/volume/fc/fc_test.go +++ b/pkg/volume/fc/fc_test.go @@ -21,8 +21,8 @@ import ( "os" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -47,7 +47,7 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/fc" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) { + if plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{}}}) { t.Errorf("Expected false") } } @@ -66,12 +66,12 @@ func TestGetAccessModes(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - if !contains(plug.GetAccessModes(), api.ReadWriteOnce) || !contains(plug.GetAccessModes(), api.ReadOnlyMany) { - t.Errorf("Expected two AccessModeTypes: %s and %s", api.ReadWriteOnce, api.ReadOnlyMany) + if !contains(plug.GetAccessModes(), v1.ReadWriteOnce) || !contains(plug.GetAccessModes(), v1.ReadOnlyMany) { + t.Errorf("Expected two AccessModeTypes: %s and %s", v1.ReadWriteOnce, v1.ReadOnlyMany) } } -func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { +func contains(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true @@ -200,10 +200,10 @@ func doTestPlugin(t *testing.T, spec *volume.Spec) { func TestPluginVolume(t *testing.T) { lun := int32(0) - vol := &api.Volume{ + vol := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - FC: &api.FCVolumeSource{ + VolumeSource: v1.VolumeSource{ + FC: &v1.FCVolumeSource{ TargetWWNs: []string{"some_wwn"}, FSType: "ext4", Lun: &lun, @@ -215,13 +215,13 @@ func TestPluginVolume(t *testing.T) { func TestPluginPersistentVolume(t *testing.T) { lun := int32(0) - vol := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + vol := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "vol1", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - FC: &api.FCVolumeSource{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + FC: &v1.FCVolumeSource{ TargetWWNs: []string{"some_wwn"}, FSType: "ext4", Lun: &lun, @@ -240,34 +240,34 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { defer os.RemoveAll(tmpDir) lun := int32(0) - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - FC: &api.FCVolumeSource{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + FC: &v1.FCVolumeSource{ TargetWWNs: []string{"some_wwn"}, FSType: "ext4", Lun: &lun, }, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, + Status: v1.PersistentVolumeClaimStatus{ + Phase: v1.ClaimBound, }, } @@ -279,7 +279,7 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { diff --git a/pkg/volume/flexvolume/BUILD b/pkg/volume/flexvolume/BUILD index 4cbcdbbcfd7..aeddbf65e8e 100644 --- a/pkg/volume/flexvolume/BUILD +++ b/pkg/volume/flexvolume/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", "//pkg/util/mount:go_default_library", @@ -34,7 +34,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", "//pkg/util/mount:go_default_library", diff --git a/pkg/volume/flexvolume/flexvolume.go b/pkg/volume/flexvolume/flexvolume.go index 1596cbb98d9..73a84ebf77d 100644 --- a/pkg/volume/flexvolume/flexvolume.go +++ b/pkg/volume/flexvolume/flexvolume.go @@ -25,7 +25,7 @@ import ( "strings" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/mount" @@ -97,15 +97,15 @@ func (plugin *flexVolumePlugin) RequiresRemount() bool { } // GetAccessModes gets the allowed access modes for this plugin. -func (plugin *flexVolumePlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, +func (plugin *flexVolumePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, } } // NewMounter is the mounter routine to build the volume. -func (plugin *flexVolumePlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *flexVolumePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { fv, _, err := getVolumeSource(spec) if err != nil { return nil, err @@ -131,7 +131,7 @@ func (plugin *flexVolumePlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ vo } // newMounterInternal is the internal mounter routine to build the volume. -func (plugin *flexVolumePlugin) newMounterInternal(spec *volume.Spec, pod *api.Pod, manager flexVolumeManager, mounter mount.Interface, runner exec.Interface, secrets map[string]string) (volume.Mounter, error) { +func (plugin *flexVolumePlugin) newMounterInternal(spec *volume.Spec, pod *v1.Pod, manager flexVolumeManager, mounter mount.Interface, runner exec.Interface, secrets map[string]string) (volume.Mounter, error) { source, _, err := getVolumeSource(spec) if err != nil { return nil, err @@ -180,10 +180,10 @@ func (plugin *flexVolumePlugin) newUnmounterInternal(volName string, podUID type } func (plugin *flexVolumePlugin) ConstructVolumeSpec(volumeName, sourceName string) (*volume.Spec, error) { - flexVolume := &api.Volume{ + flexVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - FlexVolume: &api.FlexVolumeSource{ + VolumeSource: v1.VolumeSource{ + FlexVolume: &v1.FlexVolumeSource{ Driver: sourceName, }, }, @@ -420,7 +420,7 @@ func (f *flexVolumeUnmounter) TearDownAt(dir string) error { return nil } -func getVolumeSource(spec *volume.Spec) (*api.FlexVolumeSource, bool, error) { +func getVolumeSource(spec *volume.Spec) (*v1.FlexVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.FlexVolume != nil { return spec.Volume.FlexVolume, spec.Volume.FlexVolume.ReadOnly, nil } else if spec.PersistentVolume != nil && diff --git a/pkg/volume/flexvolume/flexvolume_test.go b/pkg/volume/flexvolume/flexvolume_test.go index 392b129b025..318a9f9e3a1 100644 --- a/pkg/volume/flexvolume/flexvolume_test.go +++ b/pkg/volume/flexvolume/flexvolume_test.go @@ -25,7 +25,7 @@ import ( "testing" "text/template" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/mount" @@ -190,13 +190,13 @@ func TestCanSupport(t *testing.T) { if plugin.GetPluginName() != "kubernetes.io/fakeAttacher" { t.Errorf("Wrong name: %s", plugin.GetPluginName()) } - if !plugin.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{FlexVolume: &api.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher"}}}}) { + if !plugin.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{FlexVolume: &v1.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher"}}}}) { t.Errorf("Expected true") } - if !plugin.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{FlexVolume: &api.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher"}}}}}) { + if !plugin.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{FlexVolume: &v1.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher"}}}}}) { t.Errorf("Expected true") } - if plugin.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) { + if plugin.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{}}}) { t.Errorf("Expected false") } } @@ -216,12 +216,12 @@ func TestGetAccessModes(t *testing.T) { if err != nil { t.Fatalf("Can't find the plugin by name") } - if !contains(plugin.GetAccessModes(), api.ReadWriteOnce) || !contains(plugin.GetAccessModes(), api.ReadOnlyMany) { - t.Errorf("Expected two AccessModeTypes: %s and %s", api.ReadWriteOnce, api.ReadOnlyMany) + if !contains(plugin.GetAccessModes(), v1.ReadWriteOnce) || !contains(plugin.GetAccessModes(), v1.ReadOnlyMany) { + t.Errorf("Expected two AccessModeTypes: %s and %s", v1.ReadWriteOnce, v1.ReadOnlyMany) } } -func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { +func contains(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true @@ -239,7 +239,7 @@ func doTestPluginAttachDetach(t *testing.T, spec *volume.Spec, tmpDir string) { t.Errorf("Can't find the plugin by name") } fake := &mount.FakeMounter{} - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} secretMap := make(map[string]string) secretMap["flexsecret"] = base64.StdEncoding.EncodeToString([]byte("foo")) mounter, err := plugin.(*flexVolumePlugin).newMounterInternal(spec, pod, &flexVolumeUtil{}, fake, exec.New(), secretMap) @@ -320,7 +320,7 @@ func doTestPluginMountUnmount(t *testing.T, spec *volume.Spec, tmpDir string) { t.Errorf("Can't find the plugin by name") } fake := &mount.FakeMounter{} - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} // Use nil secret to test for nil secret case. mounter, err := plugin.(*flexVolumePlugin).newMounterInternal(spec, pod, &flexVolumeUtil{}, fake, exec.New(), nil) volumePath := mounter.GetPath() @@ -374,9 +374,9 @@ func TestPluginVolumeAttacher(t *testing.T) { } defer os.RemoveAll(tmpDir) - vol := &api.Volume{ + vol := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{FlexVolume: &api.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher", ReadOnly: false}}, + VolumeSource: v1.VolumeSource{FlexVolume: &v1.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher", ReadOnly: false}}, } doTestPluginAttachDetach(t, volume.NewSpecFromVolume(vol), tmpDir) } @@ -388,9 +388,9 @@ func TestPluginVolumeMounter(t *testing.T) { } defer os.RemoveAll(tmpDir) - vol := &api.Volume{ + vol := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{FlexVolume: &api.FlexVolumeSource{Driver: "kubernetes.io/fakeMounter", ReadOnly: false}}, + VolumeSource: v1.VolumeSource{FlexVolume: &v1.FlexVolumeSource{Driver: "kubernetes.io/fakeMounter", ReadOnly: false}}, } doTestPluginMountUnmount(t, volume.NewSpecFromVolume(vol), tmpDir) } @@ -402,13 +402,13 @@ func TestPluginPersistentVolume(t *testing.T) { } defer os.RemoveAll(tmpDir) - vol := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + vol := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "vol1", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - FlexVolume: &api.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher", ReadOnly: false}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + FlexVolume: &v1.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher", ReadOnly: false}, }, }, } diff --git a/pkg/volume/flocker/BUILD b/pkg/volume/flocker/BUILD index 08369ac7144..909d1996fbd 100644 --- a/pkg/volume/flocker/BUILD +++ b/pkg/volume/flocker/BUILD @@ -20,8 +20,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/env:go_default_library", "//pkg/util/mount:go_default_library", @@ -43,8 +43,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/testing:go_default_library", diff --git a/pkg/volume/flocker/flocker.go b/pkg/volume/flocker/flocker.go index 6d2d7d8fec5..528fdb4eb5b 100644 --- a/pkg/volume/flocker/flocker.go +++ b/pkg/volume/flocker/flocker.go @@ -23,7 +23,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/env" "k8s.io/kubernetes/pkg/util/mount" @@ -49,7 +49,7 @@ type flockerVolume struct { datasetName string // dataset uuid datasetUUID string - //pod *api.Pod + //pod *v1.Pod flockerClient flockerApi.Clientable manager volumeManager plugin *flockerPlugin @@ -111,13 +111,13 @@ func (p *flockerPlugin) RequiresRemount() bool { return false } -func (plugin *flockerPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, +func (plugin *flockerPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, } } -func (p *flockerPlugin) getFlockerVolumeSource(spec *volume.Spec) (*api.FlockerVolumeSource, bool) { +func (p *flockerPlugin) getFlockerVolumeSource(spec *volume.Spec) (*v1.FlockerVolumeSource, bool) { // AFAIK this will always be r/w, but perhaps for the future it will be needed readOnly := false @@ -127,7 +127,7 @@ func (p *flockerPlugin) getFlockerVolumeSource(spec *volume.Spec) (*api.FlockerV return spec.PersistentVolume.Spec.Flocker, readOnly } -func (plugin *flockerPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *flockerPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { // Inject real implementations here, test through the internal function. return plugin.newMounterInternal(spec, pod.UID, &FlockerUtil{}, plugin.host.GetMounter()) } @@ -172,10 +172,10 @@ func (p *flockerPlugin) newUnmounterInternal(volName string, podUID types.UID, m } func (p *flockerPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - flockerVolume := &api.Volume{ + flockerVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - Flocker: &api.FlockerVolumeSource{ + VolumeSource: v1.VolumeSource{ + Flocker: &v1.FlockerVolumeSource{ DatasetName: volumeName, }, }, @@ -392,7 +392,7 @@ func (b *flockerVolumeMounter) updateDatasetPrimary(datasetUUID string, primaryU } -func getVolumeSource(spec *volume.Spec) (*api.FlockerVolumeSource, bool, error) { +func getVolumeSource(spec *volume.Spec) (*v1.FlockerVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.Flocker != nil { return spec.Volume.Flocker, spec.ReadOnly, nil } else if spec.PersistentVolume != nil && diff --git a/pkg/volume/flocker/flocker_test.go b/pkg/volume/flocker/flocker_test.go index 03e10c2ae59..694ecca9096 100644 --- a/pkg/volume/flocker/flocker_test.go +++ b/pkg/volume/flocker/flocker_test.go @@ -21,7 +21,7 @@ import ( "os" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -144,10 +144,10 @@ func TestPlugin(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - Flocker: &api.FlockerVolumeSource{ + VolumeSource: v1.VolumeSource{ + Flocker: &v1.FlockerVolumeSource{ DatasetUUID: "uuid1", }, }, @@ -181,24 +181,24 @@ func TestCanSupport(t *testing.T) { specs := map[*volume.Spec]bool{ &volume.Spec{ - Volume: &api.Volume{ - VolumeSource: api.VolumeSource{ - Flocker: &api.FlockerVolumeSource{}, + Volume: &v1.Volume{ + VolumeSource: v1.VolumeSource{ + Flocker: &v1.FlockerVolumeSource{}, }, }, }: true, &volume.Spec{ - PersistentVolume: &api.PersistentVolume{ - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - Flocker: &api.FlockerVolumeSource{}, + PersistentVolume: &v1.PersistentVolume{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + Flocker: &v1.FlockerVolumeSource{}, }, }, }, }: true, &volume.Spec{ - Volume: &api.Volume{ - VolumeSource: api.VolumeSource{}, + Volume: &v1.Volume{ + VolumeSource: v1.VolumeSource{}, }, }: false, } @@ -215,9 +215,9 @@ func TestGetFlockerVolumeSource(t *testing.T) { p := flockerPlugin{} spec := &volume.Spec{ - Volume: &api.Volume{ - VolumeSource: api.VolumeSource{ - Flocker: &api.FlockerVolumeSource{}, + Volume: &v1.Volume{ + VolumeSource: v1.VolumeSource{ + Flocker: &v1.FlockerVolumeSource{}, }, }, } @@ -226,10 +226,10 @@ func TestGetFlockerVolumeSource(t *testing.T) { assert.Equal(spec.Volume.Flocker, vs) spec = &volume.Spec{ - PersistentVolume: &api.PersistentVolume{ - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - Flocker: &api.FlockerVolumeSource{}, + PersistentVolume: &v1.PersistentVolume{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + Flocker: &v1.FlockerVolumeSource{}, }, }, }, @@ -247,16 +247,16 @@ func TestNewMounterDatasetName(t *testing.T) { assert.NoError(err) spec := &volume.Spec{ - Volume: &api.Volume{ - VolumeSource: api.VolumeSource{ - Flocker: &api.FlockerVolumeSource{ + Volume: &v1.Volume{ + VolumeSource: v1.VolumeSource{ + Flocker: &v1.FlockerVolumeSource{ DatasetName: "something", }, }, }, } - _, err = plug.NewMounter(spec, &api.Pod{}, volume.VolumeOptions{}) + _, err = plug.NewMounter(spec, &v1.Pod{}, volume.VolumeOptions{}) assert.NoError(err) } @@ -268,16 +268,16 @@ func TestNewMounterDatasetUUID(t *testing.T) { assert.NoError(err) spec := &volume.Spec{ - Volume: &api.Volume{ - VolumeSource: api.VolumeSource{ - Flocker: &api.FlockerVolumeSource{ + Volume: &v1.Volume{ + VolumeSource: v1.VolumeSource{ + Flocker: &v1.FlockerVolumeSource{ DatasetUUID: "uuid1", }, }, }, } - mounter, err := plug.NewMounter(spec, &api.Pod{}, volume.VolumeOptions{}) + mounter, err := plug.NewMounter(spec, &v1.Pod{}, volume.VolumeOptions{}) assert.NoError(err) assert.NotNil(mounter, "got a nil mounter") @@ -349,7 +349,7 @@ func TestSetUpAtInternal(t *testing.T) { plug, err := plugMgr.FindPluginByName(flockerPluginName) assert.NoError(err) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} b := flockerVolumeMounter{flockerVolume: &flockerVolume{pod: pod, plugin: plug.(*flockerPlugin)}} b.client = newMockFlockerClient("dataset-id", "primary-uid", mockPath) diff --git a/pkg/volume/flocker/flocker_util.go b/pkg/volume/flocker/flocker_util.go index 6b4ddde1d3a..6b3d891e94c 100644 --- a/pkg/volume/flocker/flocker_util.go +++ b/pkg/volume/flocker/flocker_util.go @@ -20,7 +20,7 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/rand" "k8s.io/kubernetes/pkg/volume" @@ -71,7 +71,7 @@ func (util *FlockerUtil) CreateVolume(c *flockerVolumeProvisioner) (datasetUUID node := nodes[rand.Intn(len(nodes))] glog.V(2).Infof("selected flocker node with UUID '%s' to provision dataset", node.UUID) - capacity := c.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] + capacity := c.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] requestBytes := capacity.Value() volumeSizeGB = int(volume.RoundUpSize(requestBytes, 1024*1024*1024)) diff --git a/pkg/volume/flocker/flocker_util_test.go b/pkg/volume/flocker/flocker_util_test.go index 4d7b499ce8f..d10c1c148d2 100644 --- a/pkg/volume/flocker/flocker_util_test.go +++ b/pkg/volume/flocker/flocker_util_test.go @@ -20,7 +20,7 @@ import ( "fmt" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/volume" volumetest "k8s.io/kubernetes/pkg/volume/testing" @@ -31,10 +31,10 @@ func TestFlockerUtil_CreateVolume(t *testing.T) { assert := assert.New(t) // test CreateVolume happy path - pvc := volumetest.CreateTestPVC("3Gi", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}) + pvc := volumetest.CreateTestPVC("3Gi", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}) options := volume.VolumeOptions{ PVC: pvc, - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete, + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, } fakeFlockerClient := newFakeFlockerClient() diff --git a/pkg/volume/flocker/flocker_volume.go b/pkg/volume/flocker/flocker_volume.go index 051cc501231..112eeaaf6d8 100644 --- a/pkg/volume/flocker/flocker_volume.go +++ b/pkg/volume/flocker/flocker_volume.go @@ -19,8 +19,8 @@ package flocker import ( "fmt" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/volume" ) @@ -52,7 +52,7 @@ type flockerVolumeProvisioner struct { var _ volume.Provisioner = &flockerVolumeProvisioner{} -func (c *flockerVolumeProvisioner) Provision() (*api.PersistentVolume, error) { +func (c *flockerVolumeProvisioner) Provision() (*v1.PersistentVolume, error) { if len(c.options.Parameters) > 0 { return nil, fmt.Errorf("Provisioning failed: Specified at least one unsupported parameter") @@ -67,22 +67,22 @@ func (c *flockerVolumeProvisioner) Provision() (*api.PersistentVolume, error) { return nil, err } - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: c.options.PVName, Labels: map[string]string{}, Annotations: map[string]string{ "kubernetes.io/createdby": "flocker-dynamic-provisioner", }, }, - Spec: api.PersistentVolumeSpec{ + Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: c.options.PersistentVolumeReclaimPolicy, AccessModes: c.options.PVC.Spec.AccessModes, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - Flocker: &api.FlockerVolumeSource{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + Flocker: &v1.FlockerVolumeSource{ DatasetUUID: datasetUUID, }, }, diff --git a/pkg/volume/flocker/flocker_volume_test.go b/pkg/volume/flocker/flocker_volume_test.go index f8cec25a49a..938ac8047b9 100644 --- a/pkg/volume/flocker/flocker_volume_test.go +++ b/pkg/volume/flocker/flocker_volume_test.go @@ -20,8 +20,8 @@ import ( "fmt" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" utiltesting "k8s.io/kubernetes/pkg/util/testing" "k8s.io/kubernetes/pkg/volume" volumetest "k8s.io/kubernetes/pkg/volume/testing" @@ -47,10 +47,10 @@ func newTestableProvisioner(assert *assert.Assertions, options volume.VolumeOpti func TestProvision(t *testing.T) { assert := assert.New(t) - pvc := volumetest.CreateTestPVC("3Gi", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}) + pvc := volumetest.CreateTestPVC("3Gi", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}) options := volume.VolumeOptions{ PVC: pvc, - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete, + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, } provisioner := newTestableProvisioner(assert, options) @@ -58,7 +58,7 @@ func TestProvision(t *testing.T) { persistentSpec, err := provisioner.Provision() assert.NoError(err, "Provision() failed: ", err) - cap := persistentSpec.Spec.Capacity[api.ResourceStorage] + cap := persistentSpec.Spec.Capacity[v1.ResourceStorage] assert.Equal(int64(3*1024*1024*1024), cap.Value()) @@ -75,7 +75,7 @@ func TestProvision(t *testing.T) { // parameters are not supported options = volume.VolumeOptions{ PVC: pvc, - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete, + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, Parameters: map[string]string{ "not-supported-params": "test123", }, @@ -89,7 +89,7 @@ func TestProvision(t *testing.T) { pvc.Spec.Selector = &unversioned.LabelSelector{MatchLabels: map[string]string{"key": "value"}} options = volume.VolumeOptions{ PVC: pvc, - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete, + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, } provisioner = newTestableProvisioner(assert, options) diff --git a/pkg/volume/gce_pd/BUILD b/pkg/volume/gce_pd/BUILD index 88ded890fbc..77f25094dc1 100644 --- a/pkg/volume/gce_pd/BUILD +++ b/pkg/volume/gce_pd/BUILD @@ -20,8 +20,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/cloudprovider/providers/gce:go_default_library", "//pkg/types:go_default_library", @@ -44,8 +44,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/testing:go_default_library", diff --git a/pkg/volume/gce_pd/attacher_test.go b/pkg/volume/gce_pd/attacher_test.go index 8a18bf7c50e..4e2d87a30c8 100644 --- a/pkg/volume/gce_pd/attacher_test.go +++ b/pkg/volume/gce_pd/attacher_test.go @@ -21,7 +21,7 @@ import ( "fmt" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/volume" volumetest "k8s.io/kubernetes/pkg/volume/testing" @@ -224,9 +224,9 @@ func newDetacher(testcase *testcase) *gcePersistentDiskDetacher { func createVolSpec(name string, readOnly bool) *volume.Spec { return &volume.Spec{ - Volume: &api.Volume{ - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + Volume: &v1.Volume{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: name, ReadOnly: readOnly, }, @@ -237,10 +237,10 @@ func createVolSpec(name string, readOnly bool) *volume.Spec { func createPVSpec(name string, readOnly bool) *volume.Spec { return &volume.Spec{ - PersistentVolume: &api.PersistentVolume{ - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + PersistentVolume: &v1.PersistentVolume{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: name, ReadOnly: readOnly, }, diff --git a/pkg/volume/gce_pd/gce_pd.go b/pkg/volume/gce_pd/gce_pd.go index b9fca2c2659..7a1d741147d 100644 --- a/pkg/volume/gce_pd/gce_pd.go +++ b/pkg/volume/gce_pd/gce_pd.go @@ -23,8 +23,8 @@ import ( "strconv" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/util/strings" @@ -80,20 +80,20 @@ func (plugin *gcePersistentDiskPlugin) RequiresRemount() bool { return false } -func (plugin *gcePersistentDiskPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, +func (plugin *gcePersistentDiskPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, } } -func (plugin *gcePersistentDiskPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *gcePersistentDiskPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { // Inject real implementations here, test through the internal function. return plugin.newMounterInternal(spec, pod.UID, &GCEDiskUtil{}, plugin.host.GetMounter()) } func getVolumeSource( - spec *volume.Spec) (*api.GCEPersistentDiskVolumeSource, bool, error) { + spec *volume.Spec) (*v1.GCEPersistentDiskVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.GCEPersistentDisk != nil { return spec.Volume.GCEPersistentDisk, spec.Volume.GCEPersistentDisk.ReadOnly, nil } else if spec.PersistentVolume != nil && @@ -186,10 +186,10 @@ func (plugin *gcePersistentDiskPlugin) ConstructVolumeSpec(volumeName, mountPath if err != nil { return nil, err } - gceVolume := &api.Volume{ + gceVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: sourceName, }, }, @@ -381,28 +381,28 @@ type gcePersistentDiskProvisioner struct { var _ volume.Provisioner = &gcePersistentDiskProvisioner{} -func (c *gcePersistentDiskProvisioner) Provision() (*api.PersistentVolume, error) { +func (c *gcePersistentDiskProvisioner) Provision() (*v1.PersistentVolume, error) { volumeID, sizeGB, labels, err := c.manager.CreateVolume(c) if err != nil { return nil, err } - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: c.options.PVName, Labels: map[string]string{}, Annotations: map[string]string{ "kubernetes.io/createdby": "gce-pd-dynamic-provisioner", }, }, - Spec: api.PersistentVolumeSpec{ + Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: c.options.PersistentVolumeReclaimPolicy, AccessModes: c.options.PVC.Spec.AccessModes, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: volumeID, Partition: 0, ReadOnly: false, diff --git a/pkg/volume/gce_pd/gce_pd_test.go b/pkg/volume/gce_pd/gce_pd_test.go index c8e9b51ad59..4340393a622 100644 --- a/pkg/volume/gce_pd/gce_pd_test.go +++ b/pkg/volume/gce_pd/gce_pd_test.go @@ -22,8 +22,8 @@ import ( "path" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -47,10 +47,10 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/gce-pd" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}}}}) { t.Errorf("Expected true") } - if !plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}}}}}) { + if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}}}}}) { t.Errorf("Expected true") } } @@ -68,12 +68,12 @@ func TestGetAccessModes(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - if !contains(plug.GetAccessModes(), api.ReadWriteOnce) || !contains(plug.GetAccessModes(), api.ReadOnlyMany) { - t.Errorf("Expected two AccessModeTypes: %s and %s", api.ReadWriteOnce, api.ReadOnlyMany) + if !contains(plug.GetAccessModes(), v1.ReadWriteOnce) || !contains(plug.GetAccessModes(), v1.ReadOnlyMany) { + t.Errorf("Expected two AccessModeTypes: %s and %s", v1.ReadWriteOnce, v1.ReadOnlyMany) } } -func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { +func contains(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true @@ -111,10 +111,10 @@ func TestPlugin(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "pd", FSType: "ext4", }, @@ -174,8 +174,8 @@ func TestPlugin(t *testing.T) { // Test Provisioner options := volume.VolumeOptions{ - PVC: volumetest.CreateTestPVC("100Mi", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}), - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete, + PVC: volumetest.CreateTestPVC("100Mi", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}), + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, } provisioner, err := plug.(*gcePersistentDiskPlugin).newProvisionerInternal(options, &fakePDManager{}) persistentSpec, err := provisioner.Provision() @@ -186,7 +186,7 @@ func TestPlugin(t *testing.T) { if persistentSpec.Spec.PersistentVolumeSource.GCEPersistentDisk.PDName != "test-gce-volume-name" { t.Errorf("Provision() returned unexpected volume ID: %s", persistentSpec.Spec.PersistentVolumeSource.GCEPersistentDisk.PDName) } - cap := persistentSpec.Spec.Capacity[api.ResourceStorage] + cap := persistentSpec.Spec.Capacity[v1.ResourceStorage] size := cap.Value() if size != 100*1024*1024*1024 { t.Errorf("Provision() returned unexpected volume size: %v", size) @@ -208,30 +208,30 @@ func TestPlugin(t *testing.T) { } func TestPersistentClaimReadOnlyFlag(t *testing.T) { - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{}, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, + Status: v1.PersistentVolumeClaimStatus{ + Phase: v1.ClaimBound, }, } @@ -248,7 +248,7 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { diff --git a/pkg/volume/gce_pd/gce_util.go b/pkg/volume/gce_pd/gce_util.go index ff5a60d793c..8676f24915b 100644 --- a/pkg/volume/gce_pd/gce_util.go +++ b/pkg/volume/gce_pd/gce_util.go @@ -24,7 +24,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" gcecloud "k8s.io/kubernetes/pkg/cloudprovider/providers/gce" "k8s.io/kubernetes/pkg/util/exec" @@ -78,7 +78,7 @@ func (gceutil *GCEDiskUtil) CreateVolume(c *gcePersistentDiskProvisioner) (strin } name := volume.GenerateVolumeName(c.options.ClusterName, c.options.PVName, 63) // GCE PD name can have up to 63 characters - capacity := c.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] + capacity := c.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] requestBytes := capacity.Value() // GCE works with gigabytes, convert to GiB with rounding up requestGB := volume.RoundUpSize(requestBytes, 1024*1024*1024) diff --git a/pkg/volume/git_repo/BUILD b/pkg/volume/git_repo/BUILD index f9c36f406c1..ee5bb19b836 100644 --- a/pkg/volume/git_repo/BUILD +++ b/pkg/volume/git_repo/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", "//pkg/util/strings:go_default_library", @@ -33,7 +33,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", "//pkg/volume:go_default_library", diff --git a/pkg/volume/git_repo/git_repo.go b/pkg/volume/git_repo/git_repo.go index 3b6e59a9e53..c301fefcfe6 100644 --- a/pkg/volume/git_repo/git_repo.go +++ b/pkg/volume/git_repo/git_repo.go @@ -22,7 +22,7 @@ import ( "path" "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" utilstrings "k8s.io/kubernetes/pkg/util/strings" @@ -43,7 +43,7 @@ var _ volume.VolumePlugin = &gitRepoPlugin{} func wrappedVolumeSpec() volume.Spec { return volume.Spec{ - Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, + Volume: &v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}}, } } @@ -81,7 +81,7 @@ func (plugin *gitRepoPlugin) RequiresRemount() bool { return false } -func (plugin *gitRepoPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *gitRepoPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { return &gitRepoVolumeMounter{ gitRepoVolume: &gitRepoVolume{ volName: spec.Name(), @@ -108,10 +108,10 @@ func (plugin *gitRepoPlugin) NewUnmounter(volName string, podUID types.UID) (vol } func (plugin *gitRepoPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - gitVolume := &api.Volume{ + gitVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - GitRepo: &api.GitRepoVolumeSource{}, + VolumeSource: v1.VolumeSource{ + GitRepo: &v1.GitRepoVolumeSource{}, }, } return volume.NewSpecFromVolume(gitVolume), nil @@ -137,7 +137,7 @@ func (gr *gitRepoVolume) GetPath() string { type gitRepoVolumeMounter struct { *gitRepoVolume - pod api.Pod + pod v1.Pod source string revision string target string @@ -263,9 +263,9 @@ func (c *gitRepoVolumeUnmounter) TearDownAt(dir string) error { return wrapped.TearDownAt(dir) } -func getVolumeSource(spec *volume.Spec) (*api.GitRepoVolumeSource, bool) { +func getVolumeSource(spec *volume.Spec) (*v1.GitRepoVolumeSource, bool) { var readOnly bool - var volumeSource *api.GitRepoVolumeSource + var volumeSource *v1.GitRepoVolumeSource if spec.Volume != nil && spec.Volume.GitRepo != nil { volumeSource = spec.Volume.GitRepo diff --git a/pkg/volume/git_repo/git_repo_test.go b/pkg/volume/git_repo/git_repo_test.go index 77630039495..e17b5514123 100644 --- a/pkg/volume/git_repo/git_repo_test.go +++ b/pkg/volume/git_repo/git_repo_test.go @@ -25,7 +25,7 @@ import ( "strings" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/volume" @@ -54,7 +54,7 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/git-repo" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{GitRepo: &api.GitRepoVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{GitRepo: &v1.GitRepoVolumeSource{}}}}) { t.Errorf("Expected true") } } @@ -73,16 +73,16 @@ func TestPlugin(t *testing.T) { scenarios := []struct { name string - vol *api.Volume + vol *v1.Volume expecteds []expectedCommand isExpectedFailure bool }{ { name: "target-dir", - vol: &api.Volume{ + vol: &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - GitRepo: &api.GitRepoVolumeSource{ + VolumeSource: v1.VolumeSource{ + GitRepo: &v1.GitRepoVolumeSource{ Repository: gitUrl, Revision: revision, Directory: "target_dir", @@ -107,10 +107,10 @@ func TestPlugin(t *testing.T) { }, { name: "target-dir-no-revision", - vol: &api.Volume{ + vol: &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - GitRepo: &api.GitRepoVolumeSource{ + VolumeSource: v1.VolumeSource{ + GitRepo: &v1.GitRepoVolumeSource{ Repository: gitUrl, Directory: "target_dir", }, @@ -126,10 +126,10 @@ func TestPlugin(t *testing.T) { }, { name: "only-git-clone", - vol: &api.Volume{ + vol: &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - GitRepo: &api.GitRepoVolumeSource{ + VolumeSource: v1.VolumeSource{ + GitRepo: &v1.GitRepoVolumeSource{ Repository: gitUrl, }, }, @@ -144,10 +144,10 @@ func TestPlugin(t *testing.T) { }, { name: "no-target-dir", - vol: &api.Volume{ + vol: &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - GitRepo: &api.GitRepoVolumeSource{ + VolumeSource: v1.VolumeSource{ + GitRepo: &v1.GitRepoVolumeSource{ Repository: gitUrl, Revision: revision, Directory: "", @@ -172,10 +172,10 @@ func TestPlugin(t *testing.T) { }, { name: "current-dir", - vol: &api.Volume{ + vol: &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - GitRepo: &api.GitRepoVolumeSource{ + VolumeSource: v1.VolumeSource{ + GitRepo: &v1.GitRepoVolumeSource{ Repository: gitUrl, Revision: revision, Directory: ".", @@ -214,7 +214,7 @@ func TestPlugin(t *testing.T) { func doTestPlugin(scenario struct { name string - vol *api.Volume + vol *v1.Volume expecteds []expectedCommand isExpectedFailure bool }, t *testing.T) []error { @@ -231,7 +231,7 @@ func doTestPlugin(scenario struct { fmt.Errorf("Can't find the plugin by name")) return allErrs } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, err := plug.NewMounter(volume.NewSpecFromVolume(scenario.vol), pod, volume.VolumeOptions{}) if err != nil { @@ -311,7 +311,7 @@ func doTestPlugin(scenario struct { func doTestSetUp(scenario struct { name string - vol *api.Volume + vol *v1.Volume expecteds []expectedCommand isExpectedFailure bool }, mounter volume.Mounter) []error { diff --git a/pkg/volume/glusterfs/BUILD b/pkg/volume/glusterfs/BUILD index 0250fb8dc36..b4843ed01bc 100644 --- a/pkg/volume/glusterfs/BUILD +++ b/pkg/volume/glusterfs/BUILD @@ -19,10 +19,10 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/resource:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", "//pkg/util/mount:go_default_library", @@ -41,8 +41,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/client/testing/core:go_default_library", "//pkg/runtime:go_default_library", "//pkg/types:go_default_library", diff --git a/pkg/volume/glusterfs/glusterfs.go b/pkg/volume/glusterfs/glusterfs.go index bb2f49eb3d1..533e2643680 100644 --- a/pkg/volume/glusterfs/glusterfs.go +++ b/pkg/volume/glusterfs/glusterfs.go @@ -20,22 +20,22 @@ import ( "fmt" "os" "path" + "runtime" dstrings "strings" "github.com/golang/glog" gcli "github.com/heketi/heketi/client/api/go-client" gapi "github.com/heketi/heketi/pkg/glusterfs/api" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/util/strings" "k8s.io/kubernetes/pkg/volume" volutil "k8s.io/kubernetes/pkg/volume/util" - "runtime" ) // This is the primary entrypoint for volume plugins. @@ -104,15 +104,15 @@ func (plugin *glusterfsPlugin) RequiresRemount() bool { return false } -func (plugin *glusterfsPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, +func (plugin *glusterfsPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, } } -func (plugin *glusterfsPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *glusterfsPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { source, _ := plugin.getGlusterVolumeSource(spec) ep_name := source.EndpointsName // PVC/POD is in same ns. @@ -126,7 +126,7 @@ func (plugin *glusterfsPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ vol return plugin.newMounterInternal(spec, ep, pod, plugin.host.GetMounter(), exec.New()) } -func (plugin *glusterfsPlugin) getGlusterVolumeSource(spec *volume.Spec) (*api.GlusterfsVolumeSource, bool) { +func (plugin *glusterfsPlugin) getGlusterVolumeSource(spec *volume.Spec) (*v1.GlusterfsVolumeSource, bool) { // Glusterfs volumes used directly in a pod have a ReadOnly flag set by the pod author. // Glusterfs volumes used as a PersistentVolume gets the ReadOnly flag indirectly through the persistent-claim volume used to mount the PV if spec.Volume != nil && spec.Volume.Glusterfs != nil { @@ -136,7 +136,7 @@ func (plugin *glusterfsPlugin) getGlusterVolumeSource(spec *volume.Spec) (*api.G } } -func (plugin *glusterfsPlugin) newMounterInternal(spec *volume.Spec, ep *api.Endpoints, pod *api.Pod, mounter mount.Interface, exe exec.Interface) (volume.Mounter, error) { +func (plugin *glusterfsPlugin) newMounterInternal(spec *volume.Spec, ep *v1.Endpoints, pod *v1.Pod, mounter mount.Interface, exe exec.Interface) (volume.Mounter, error) { source, readOnly := plugin.getGlusterVolumeSource(spec) return &glusterfsMounter{ glusterfs: &glusterfs{ @@ -159,7 +159,7 @@ func (plugin *glusterfsPlugin) newUnmounterInternal(volName string, podUID types return &glusterfsUnmounter{&glusterfs{ volName: volName, mounter: mounter, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{UID: podUID}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: podUID}}, plugin: plugin, }}, nil } @@ -170,10 +170,10 @@ func (plugin *glusterfsPlugin) execCommand(command string, args []string) ([]byt } func (plugin *glusterfsPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - glusterfsVolume := &api.Volume{ + glusterfsVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - Glusterfs: &api.GlusterfsVolumeSource{ + VolumeSource: v1.VolumeSource{ + Glusterfs: &v1.GlusterfsVolumeSource{ EndpointsName: volumeName, Path: volumeName, }, @@ -185,7 +185,7 @@ func (plugin *glusterfsPlugin) ConstructVolumeSpec(volumeName, mountPath string) // Glusterfs volumes represent a bare host file or directory mount of an Glusterfs export. type glusterfs struct { volName string - pod *api.Pod + pod *v1.Pod mounter mount.Interface plugin *glusterfsPlugin volume.MetricsNil @@ -193,7 +193,7 @@ type glusterfs struct { type glusterfsMounter struct { *glusterfs - hosts *api.Endpoints + hosts *v1.Endpoints path string readOnly bool exe exec.Interface @@ -352,7 +352,7 @@ func (b *glusterfsMounter) setUpAtInternal(dir string) error { } func getVolumeSource( - spec *volume.Spec) (*api.GlusterfsVolumeSource, bool, error) { + spec *volume.Spec) (*v1.GlusterfsVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.Glusterfs != nil { return spec.Volume.Glusterfs, spec.Volume.Glusterfs.ReadOnly, nil } else if spec.PersistentVolume != nil && @@ -416,7 +416,7 @@ func (plugin *glusterfsPlugin) newDeleterInternal(spec *volume.Spec) (volume.Del type glusterfsVolumeDeleter struct { *glusterfsMounter provisioningConfig - spec *api.PersistentVolume + spec *v1.PersistentVolume } func (d *glusterfsVolumeDeleter) GetPath() string { @@ -479,7 +479,7 @@ func (d *glusterfsVolumeDeleter) Delete() error { return nil } -func (r *glusterfsVolumeProvisioner) Provision() (*api.PersistentVolume, error) { +func (r *glusterfsVolumeProvisioner) Provision() (*v1.PersistentVolume, error) { var err error if r.options.PVC.Spec.Selector != nil { glog.V(4).Infof("glusterfs: not able to parse your claim Selector") @@ -499,21 +499,21 @@ func (r *glusterfsVolumeProvisioner) Provision() (*api.PersistentVolume, error) glog.Errorf("glusterfs: create volume err: %v.", err) return nil, fmt.Errorf("glusterfs: create volume err: %v.", err) } - pv := new(api.PersistentVolume) + pv := new(v1.PersistentVolume) pv.Spec.PersistentVolumeSource.Glusterfs = glusterfs pv.Spec.PersistentVolumeReclaimPolicy = r.options.PersistentVolumeReclaimPolicy pv.Spec.AccessModes = r.options.PVC.Spec.AccessModes if len(pv.Spec.AccessModes) == 0 { pv.Spec.AccessModes = r.plugin.GetAccessModes() } - pv.Spec.Capacity = api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), + pv.Spec.Capacity = v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), } return pv, nil } -func (p *glusterfsVolumeProvisioner) CreateVolume() (r *api.GlusterfsVolumeSource, size int, err error) { - capacity := p.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] +func (p *glusterfsVolumeProvisioner) CreateVolume() (r *v1.GlusterfsVolumeSource, size int, err error) { + capacity := p.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] volSizeBytes := capacity.Value() sz := int(volume.RoundUpSize(volSizeBytes, 1024*1024*1024)) glog.V(2).Infof("glusterfs: create volume of size: %d bytes and configuration %+v", volSizeBytes, p.provisioningConfig) @@ -573,30 +573,30 @@ func (p *glusterfsVolumeProvisioner) CreateVolume() (r *api.GlusterfsVolumeSourc return nil, 0, fmt.Errorf("failed to create endpoint/service %v", err) } glog.V(3).Infof("glusterfs: dynamic ep %v and svc : %v ", endpoint, service) - return &api.GlusterfsVolumeSource{ + return &v1.GlusterfsVolumeSource{ EndpointsName: endpoint.Name, Path: volume.Name, ReadOnly: false, }, sz, nil } -func (p *glusterfsVolumeProvisioner) createEndpointService(namespace string, epServiceName string, hostips []string, pvcname string) (endpoint *api.Endpoints, service *api.Service, err error) { +func (p *glusterfsVolumeProvisioner) createEndpointService(namespace string, epServiceName string, hostips []string, pvcname string) (endpoint *v1.Endpoints, service *v1.Service, err error) { - addrlist := make([]api.EndpointAddress, len(hostips)) + addrlist := make([]v1.EndpointAddress, len(hostips)) for i, v := range hostips { addrlist[i].IP = v } - endpoint = &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + endpoint = &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Namespace: namespace, Name: epServiceName, Labels: map[string]string{ "gluster.kubernetes.io/provisioned-for-pvc": pvcname, }, }, - Subsets: []api.EndpointSubset{{ + Subsets: []v1.EndpointSubset{{ Addresses: addrlist, - Ports: []api.EndpointPort{{Port: 1, Protocol: "TCP"}}, + Ports: []v1.EndpointPort{{Port: 1, Protocol: "TCP"}}, }}, } _, err = p.plugin.host.GetKubeClient().Core().Endpoints(namespace).Create(endpoint) @@ -608,16 +608,16 @@ func (p *glusterfsVolumeProvisioner) createEndpointService(namespace string, epS glog.Errorf("glusterfs: failed to create endpoint %v", err) return nil, nil, fmt.Errorf("error creating endpoint %v", err) } - service = &api.Service{ - ObjectMeta: api.ObjectMeta{ + service = &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: epServiceName, Namespace: namespace, Labels: map[string]string{ "gluster.kubernetes.io/provisioned-for-pvc": pvcname, }, }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ + Spec: v1.ServiceSpec{ + Ports: []v1.ServicePort{ {Protocol: "TCP", Port: 1}}}} _, err = p.plugin.host.GetKubeClient().Core().Services(namespace).Create(service) if err != nil && errors.IsAlreadyExists(err) { diff --git a/pkg/volume/glusterfs/glusterfs_test.go b/pkg/volume/glusterfs/glusterfs_test.go index 8a90dafc4ba..30dc37f1b47 100644 --- a/pkg/volume/glusterfs/glusterfs_test.go +++ b/pkg/volume/glusterfs/glusterfs_test.go @@ -22,8 +22,8 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/client/testing/core" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/types" @@ -50,10 +50,10 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/glusterfs" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{}}}}) { + if plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{}}}}) { t.Errorf("Expected false") } - if plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) { + if plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{}}}) { t.Errorf("Expected false") } } @@ -72,12 +72,12 @@ func TestGetAccessModes(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - if !contains(plug.GetAccessModes(), api.ReadWriteOnce) || !contains(plug.GetAccessModes(), api.ReadOnlyMany) || !contains(plug.GetAccessModes(), api.ReadWriteMany) { - t.Errorf("Expected three AccessModeTypes: %s, %s, and %s", api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany) + if !contains(plug.GetAccessModes(), v1.ReadWriteOnce) || !contains(plug.GetAccessModes(), v1.ReadOnlyMany) || !contains(plug.GetAccessModes(), v1.ReadWriteMany) { + t.Errorf("Expected three AccessModeTypes: %s, %s, and %s", v1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadWriteMany) } } -func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { +func contains(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true @@ -99,8 +99,8 @@ func doTestPlugin(t *testing.T, spec *volume.Spec) { if err != nil { t.Errorf("Can't find the plugin by name") } - ep := &api.Endpoints{ObjectMeta: api.ObjectMeta{Name: "foo"}, Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}}}}} + ep := &v1.Endpoints{ObjectMeta: v1.ObjectMeta{Name: "foo"}, Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}}}}} var fcmd exec.FakeCmd fcmd = exec.FakeCmd{ CombinedOutputScript: []exec.FakeCombinedOutputAction{ @@ -115,7 +115,7 @@ func doTestPlugin(t *testing.T, spec *volume.Spec) { func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, }, } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, err := plug.(*glusterfsPlugin).newMounterInternal(spec, ep, pod, &mount.FakeMounter{}, &fake) volumePath := mounter.GetPath() if err != nil { @@ -157,21 +157,21 @@ func doTestPlugin(t *testing.T, spec *volume.Spec) { } func TestPluginVolume(t *testing.T) { - vol := &api.Volume{ + vol := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{Glusterfs: &api.GlusterfsVolumeSource{EndpointsName: "ep", Path: "vol", ReadOnly: false}}, + VolumeSource: v1.VolumeSource{Glusterfs: &v1.GlusterfsVolumeSource{EndpointsName: "ep", Path: "vol", ReadOnly: false}}, } doTestPlugin(t, volume.NewSpecFromVolume(vol)) } func TestPluginPersistentVolume(t *testing.T) { - vol := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + vol := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "vol1", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - Glusterfs: &api.GlusterfsVolumeSource{EndpointsName: "ep", Path: "vol", ReadOnly: false}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + Glusterfs: &v1.GlusterfsVolumeSource{EndpointsName: "ep", Path: "vol", ReadOnly: false}, }, }, } @@ -186,41 +186,41 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { } defer os.RemoveAll(tmpDir) - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - Glusterfs: &api.GlusterfsVolumeSource{EndpointsName: "ep", Path: "vol", ReadOnly: false}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + Glusterfs: &v1.GlusterfsVolumeSource{EndpointsName: "ep", Path: "vol", ReadOnly: false}, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, + Status: v1.PersistentVolumeClaimStatus{ + Phase: v1.ClaimBound, }, } - ep := &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + ep := &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Namespace: "nsA", Name: "ep", }, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 80, Protocol: api.ProtocolTCP}}, + Subsets: []v1.EndpointSubset{{ + Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}}, + Ports: []v1.EndpointPort{{Name: "foo", Port: 80, Protocol: v1.ProtocolTCP}}, }}, } @@ -232,7 +232,7 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{Namespace: "nsA", UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{Namespace: "nsA", UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { @@ -241,7 +241,7 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { } func TestParseClassParameters(t *testing.T) { - secret := api.Secret{ + secret := v1.Secret{ Type: "kubernetes.io/glusterfs", Data: map[string][]byte{ "data": []byte("mypassword"), @@ -251,7 +251,7 @@ func TestParseClassParameters(t *testing.T) { tests := []struct { name string parameters map[string]string - secret *api.Secret + secret *v1.Secret expectError bool expectConfig *provisioningConfig }{ diff --git a/pkg/volume/host_path/BUILD b/pkg/volume/host_path/BUILD index f4ec83fad93..ac5ac615655 100644 --- a/pkg/volume/host_path/BUILD +++ b/pkg/volume/host_path/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/conversion:go_default_library", "//pkg/types:go_default_library", "//pkg/util/uuid:go_default_library", @@ -32,9 +32,9 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/types:go_default_library", "//pkg/util:go_default_library", "//pkg/util/uuid:go_default_library", diff --git a/pkg/volume/host_path/host_path.go b/pkg/volume/host_path/host_path.go index cc2c5e1c0f8..42d2e844c2b 100644 --- a/pkg/volume/host_path/host_path.go +++ b/pkg/volume/host_path/host_path.go @@ -21,7 +21,7 @@ import ( "os" "regexp" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/conversion" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/uuid" @@ -83,13 +83,13 @@ func (plugin *hostPathPlugin) RequiresRemount() bool { return false } -func (plugin *hostPathPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, +func (plugin *hostPathPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, } } -func (plugin *hostPathPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *hostPathPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { hostPathVolumeSource, readOnly, err := getVolumeSource(spec) if err != nil { return nil, err @@ -122,10 +122,10 @@ func (plugin *hostPathPlugin) NewProvisioner(options volume.VolumeOptions) (volu } func (plugin *hostPathPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - hostPathVolume := &api.Volume{ + hostPathVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{ + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{ Path: volumeName, }, }, @@ -249,11 +249,11 @@ func (r *hostPathRecycler) Recycle() error { if err != nil { return err } - pod := templateClone.(*api.Pod) + pod := templateClone.(*v1.Pod) // overrides pod.Spec.ActiveDeadlineSeconds = &r.timeout - pod.Spec.Volumes[0].VolumeSource = api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{ + pod.Spec.Volumes[0].VolumeSource = v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{ Path: r.path, }, } @@ -270,25 +270,25 @@ type hostPathProvisioner struct { // Create for hostPath simply creates a local /tmp/hostpath_pv/%s directory as a new PersistentVolume. // This Provisioner is meant for development and testing only and WILL NOT WORK in a multi-node cluster. -func (r *hostPathProvisioner) Provision() (*api.PersistentVolume, error) { +func (r *hostPathProvisioner) Provision() (*v1.PersistentVolume, error) { fullpath := fmt.Sprintf("/tmp/hostpath_pv/%s", uuid.NewUUID()) - capacity := r.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + capacity := r.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: r.options.PVName, Annotations: map[string]string{ "kubernetes.io/createdby": "hostpath-dynamic-provisioner", }, }, - Spec: api.PersistentVolumeSpec{ + Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: r.options.PersistentVolumeReclaimPolicy, AccessModes: r.options.PVC.Spec.AccessModes, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): capacity, + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): capacity, }, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + HostPath: &v1.HostPathVolumeSource{ Path: fullpath, }, }, @@ -326,7 +326,7 @@ func (r *hostPathDeleter) Delete() error { } func getVolumeSource( - spec *volume.Spec) (*api.HostPathVolumeSource, bool, error) { + spec *volume.Spec) (*v1.HostPathVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.HostPath != nil { return spec.Volume.HostPath, spec.ReadOnly, nil } else if spec.PersistentVolume != nil && diff --git a/pkg/volume/host_path/host_path_test.go b/pkg/volume/host_path/host_path_test.go index 342bdcad2a7..4ef7d7ad430 100644 --- a/pkg/volume/host_path/host_path_test.go +++ b/pkg/volume/host_path/host_path_test.go @@ -23,9 +23,9 @@ import ( "os" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/uuid" @@ -44,13 +44,13 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/host-path" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{HostPath: &v1.HostPathVolumeSource{}}}}) { t.Errorf("Expected true") } - if !plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{HostPath: &api.HostPathVolumeSource{}}}}}) { + if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{HostPath: &v1.HostPathVolumeSource{}}}}}) { t.Errorf("Expected true") } - if plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) { + if plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{}}}) { t.Errorf("Expected false") } } @@ -63,8 +63,8 @@ func TestGetAccessModes(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - if len(plug.GetAccessModes()) != 1 || plug.GetAccessModes()[0] != api.ReadWriteOnce { - t.Errorf("Expected %s PersistentVolumeAccessMode", api.ReadWriteOnce) + if len(plug.GetAccessModes()) != 1 || plug.GetAccessModes()[0] != v1.ReadWriteOnce { + t.Errorf("Expected %s PersistentVolumeAccessMode", v1.ReadWriteOnce) } } @@ -73,7 +73,7 @@ func TestRecycler(t *testing.T) { pluginHost := volumetest.NewFakeVolumeHost("/tmp/fake", nil, nil) plugMgr.InitPlugins([]volume.VolumePlugin{&hostPathPlugin{nil, volume.VolumeConfig{}}}, pluginHost) - spec := &volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/foo"}}}}} + spec := &volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{HostPath: &v1.HostPathVolumeSource{Path: "/foo"}}}}} plug, err := plugMgr.FindRecyclablePluginBySpec(spec) if err != nil { t.Errorf("Can't find the plugin by name") @@ -99,7 +99,7 @@ func TestDeleter(t *testing.T) { plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(volume.VolumeConfig{}), volumetest.NewFakeVolumeHost("/tmp/fake", nil, nil)) - spec := &volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{HostPath: &api.HostPathVolumeSource{Path: tempPath}}}}} + spec := &volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{HostPath: &v1.HostPathVolumeSource{Path: tempPath}}}}} plug, err := plugMgr.FindDeletablePluginBySpec(spec) if err != nil { t.Errorf("Can't find the plugin by name") @@ -132,7 +132,7 @@ func TestDeleterTempDir(t *testing.T) { for name, test := range tests { plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(volume.VolumeConfig{}), volumetest.NewFakeVolumeHost("/tmp/fake", nil, nil)) - spec := &volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{HostPath: &api.HostPathVolumeSource{Path: test.path}}}}} + spec := &volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{HostPath: &v1.HostPathVolumeSource{Path: test.path}}}}} plug, _ := plugMgr.FindDeletablePluginBySpec(spec) deleter, _ := plug.NewDeleter(spec) err := deleter.Delete() @@ -153,14 +153,14 @@ func TestProvisioner(t *testing.T) { plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(volume.VolumeConfig{ProvisioningEnabled: true}), volumetest.NewFakeVolumeHost("/tmp/fake", nil, nil)) - spec := &volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{HostPath: &api.HostPathVolumeSource{Path: tempPath}}}}} + spec := &volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{HostPath: &v1.HostPathVolumeSource{Path: tempPath}}}}} plug, err := plugMgr.FindCreatablePluginBySpec(spec) if err != nil { t.Errorf("Can't find the plugin by name") } options := volume.VolumeOptions{ - PVC: volumetest.CreateTestPVC("1Gi", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}), - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete, + PVC: volumetest.CreateTestPVC("1Gi", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}), + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, } creater, err := plug.NewProvisioner(options) if err != nil { @@ -174,15 +174,15 @@ func TestProvisioner(t *testing.T) { t.Errorf("Expected pv.Spec.HostPath.Path to not be empty: %#v", pv) } expectedCapacity := resource.NewQuantity(1*1024*1024*1024, resource.BinarySI) - actualCapacity := pv.Spec.Capacity[api.ResourceStorage] + actualCapacity := pv.Spec.Capacity[v1.ResourceStorage] expectedAmt := expectedCapacity.Value() actualAmt := actualCapacity.Value() if expectedAmt != actualAmt { t.Errorf("Expected capacity %+v but got %+v", expectedAmt, actualAmt) } - if pv.Spec.PersistentVolumeReclaimPolicy != api.PersistentVolumeReclaimDelete { - t.Errorf("Expected reclaim policy %+v but got %+v", api.PersistentVolumeReclaimDelete, pv.Spec.PersistentVolumeReclaimPolicy) + if pv.Spec.PersistentVolumeReclaimPolicy != v1.PersistentVolumeReclaimDelete { + t.Errorf("Expected reclaim policy %+v but got %+v", v1.PersistentVolumeReclaimDelete, pv.Spec.PersistentVolumeReclaimPolicy) } os.RemoveAll(pv.Spec.HostPath.Path) @@ -196,11 +196,11 @@ func TestPlugin(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/vol1"}}, + VolumeSource: v1.VolumeSource{HostPath: &v1.HostPathVolumeSource{Path: "/vol1"}}, } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, err := plug.NewMounter(volume.NewSpecFromVolume(spec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) @@ -232,30 +232,30 @@ func TestPlugin(t *testing.T) { } func TestPersistentClaimReadOnlyFlag(t *testing.T) { - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "foo"}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + HostPath: &v1.HostPathVolumeSource{Path: "foo"}, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, + Status: v1.PersistentVolumeClaimStatus{ + Phase: v1.ClaimBound, }, } @@ -267,7 +267,7 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { diff --git a/pkg/volume/iscsi/BUILD b/pkg/volume/iscsi/BUILD index 73125e2850c..396403043a5 100644 --- a/pkg/volume/iscsi/BUILD +++ b/pkg/volume/iscsi/BUILD @@ -20,7 +20,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", "//pkg/util/mount:go_default_library", @@ -40,8 +40,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/testing:go_default_library", diff --git a/pkg/volume/iscsi/iscsi.go b/pkg/volume/iscsi/iscsi.go index 15f958c1755..51932c303b5 100644 --- a/pkg/volume/iscsi/iscsi.go +++ b/pkg/volume/iscsi/iscsi.go @@ -22,7 +22,7 @@ import ( "strings" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/mount" @@ -82,14 +82,14 @@ func (plugin *iscsiPlugin) RequiresRemount() bool { return false } -func (plugin *iscsiPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, +func (plugin *iscsiPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, } } -func (plugin *iscsiPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *iscsiPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { // Inject real implementations here, test through the internal function. return plugin.newMounterInternal(spec, pod.UID, &ISCSIUtil{}, plugin.host.GetMounter()) } @@ -147,10 +147,10 @@ func (plugin *iscsiPlugin) execCommand(command string, args []string) ([]byte, e } func (plugin *iscsiPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - iscsiVolume := &api.Volume{ + iscsiVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - ISCSI: &api.ISCSIVolumeSource{ + VolumeSource: v1.VolumeSource{ + ISCSI: &v1.ISCSIVolumeSource{ TargetPortal: volumeName, IQN: volumeName, }, @@ -240,7 +240,7 @@ func portalMounter(portal string) string { return portal } -func getVolumeSource(spec *volume.Spec) (*api.ISCSIVolumeSource, bool, error) { +func getVolumeSource(spec *volume.Spec) (*v1.ISCSIVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.ISCSI != nil { return spec.Volume.ISCSI, spec.Volume.ISCSI.ReadOnly, nil } else if spec.PersistentVolume != nil && diff --git a/pkg/volume/iscsi/iscsi_test.go b/pkg/volume/iscsi/iscsi_test.go index 0c17043b9d7..e4ef5688ed7 100644 --- a/pkg/volume/iscsi/iscsi_test.go +++ b/pkg/volume/iscsi/iscsi_test.go @@ -21,8 +21,8 @@ import ( "os" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -47,7 +47,7 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/iscsi" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) { + if plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{}}}) { t.Errorf("Expected false") } } @@ -66,12 +66,12 @@ func TestGetAccessModes(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - if !contains(plug.GetAccessModes(), api.ReadWriteOnce) || !contains(plug.GetAccessModes(), api.ReadOnlyMany) { - t.Errorf("Expected two AccessModeTypes: %s and %s", api.ReadWriteOnce, api.ReadOnlyMany) + if !contains(plug.GetAccessModes(), v1.ReadWriteOnce) || !contains(plug.GetAccessModes(), v1.ReadOnlyMany) { + t.Errorf("Expected two AccessModeTypes: %s and %s", v1.ReadWriteOnce, v1.ReadOnlyMany) } } -func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { +func contains(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true @@ -199,10 +199,10 @@ func doTestPlugin(t *testing.T, spec *volume.Spec) { } func TestPluginVolume(t *testing.T) { - vol := &api.Volume{ + vol := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - ISCSI: &api.ISCSIVolumeSource{ + VolumeSource: v1.VolumeSource{ + ISCSI: &v1.ISCSIVolumeSource{ TargetPortal: "127.0.0.1:3260", IQN: "iqn.2014-12.server:storage.target01", FSType: "ext4", @@ -214,13 +214,13 @@ func TestPluginVolume(t *testing.T) { } func TestPluginPersistentVolume(t *testing.T) { - vol := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + vol := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "vol1", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - ISCSI: &api.ISCSIVolumeSource{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + ISCSI: &v1.ISCSIVolumeSource{ TargetPortal: "127.0.0.1:3260", IQN: "iqn.2014-12.server:storage.target01", FSType: "ext4", @@ -239,35 +239,35 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { } defer os.RemoveAll(tmpDir) - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - ISCSI: &api.ISCSIVolumeSource{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + ISCSI: &v1.ISCSIVolumeSource{ TargetPortal: "127.0.0.1:3260", IQN: "iqn.2014-12.server:storage.target01", FSType: "ext4", Lun: 0, }, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, + Status: v1.PersistentVolumeClaimStatus{ + Phase: v1.ClaimBound, }, } @@ -279,7 +279,7 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { diff --git a/pkg/volume/nfs/BUILD b/pkg/volume/nfs/BUILD index 67e1e5c4525..4bb365a6fcd 100644 --- a/pkg/volume/nfs/BUILD +++ b/pkg/volume/nfs/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/conversion:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", @@ -35,8 +35,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/testing:go_default_library", diff --git a/pkg/volume/nfs/nfs.go b/pkg/volume/nfs/nfs.go index 25d3cb58d76..9afad5b1bfd 100644 --- a/pkg/volume/nfs/nfs.go +++ b/pkg/volume/nfs/nfs.go @@ -22,7 +22,7 @@ import ( "runtime" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/conversion" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" @@ -87,19 +87,19 @@ func (plugin *nfsPlugin) RequiresRemount() bool { return false } -func (plugin *nfsPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, +func (plugin *nfsPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, } } -func (plugin *nfsPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *nfsPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { return plugin.newMounterInternal(spec, pod, plugin.host.GetMounter()) } -func (plugin *nfsPlugin) newMounterInternal(spec *volume.Spec, pod *api.Pod, mounter mount.Interface) (volume.Mounter, error) { +func (plugin *nfsPlugin) newMounterInternal(spec *volume.Spec, pod *v1.Pod, mounter mount.Interface) (volume.Mounter, error) { source, readOnly, err := getVolumeSource(spec) if err != nil { return nil, err @@ -126,7 +126,7 @@ func (plugin *nfsPlugin) newUnmounterInternal(volName string, podUID types.UID, return &nfsUnmounter{&nfs{ volName: volName, mounter: mounter, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{UID: podUID}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: podUID}}, plugin: plugin, }}, nil } @@ -136,10 +136,10 @@ func (plugin *nfsPlugin) NewRecycler(pvName string, spec *volume.Spec, eventReco } func (plugin *nfsPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - nfsVolume := &api.Volume{ + nfsVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - NFS: &api.NFSVolumeSource{ + VolumeSource: v1.VolumeSource{ + NFS: &v1.NFSVolumeSource{ Path: volumeName, }, }, @@ -150,7 +150,7 @@ func (plugin *nfsPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*vol // NFS volumes represent a bare host file or directory mount of an NFS export. type nfs struct { volName string - pod *api.Pod + pod *v1.Pod mounter mount.Interface plugin *nfsPlugin volume.MetricsNil @@ -337,12 +337,12 @@ func (r *nfsRecycler) Recycle() error { if err != nil { return err } - pod := templateClone.(*api.Pod) + pod := templateClone.(*v1.Pod) // overrides pod.Spec.ActiveDeadlineSeconds = &r.timeout pod.GenerateName = "pv-recycler-nfs-" - pod.Spec.Volumes[0].VolumeSource = api.VolumeSource{ - NFS: &api.NFSVolumeSource{ + pod.Spec.Volumes[0].VolumeSource = v1.VolumeSource{ + NFS: &v1.NFSVolumeSource{ Server: r.server, Path: r.path, }, @@ -350,7 +350,7 @@ func (r *nfsRecycler) Recycle() error { return volume.RecycleVolumeByWatchingPodUntilCompletion(r.pvName, pod, r.host.GetKubeClient(), r.eventRecorder) } -func getVolumeSource(spec *volume.Spec) (*api.NFSVolumeSource, bool, error) { +func getVolumeSource(spec *volume.Spec) (*v1.NFSVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.NFS != nil { return spec.Volume.NFS, spec.Volume.NFS.ReadOnly, nil } else if spec.PersistentVolume != nil && diff --git a/pkg/volume/nfs/nfs_test.go b/pkg/volume/nfs/nfs_test.go index 43a3cba2047..5b792c44484 100644 --- a/pkg/volume/nfs/nfs_test.go +++ b/pkg/volume/nfs/nfs_test.go @@ -21,8 +21,8 @@ import ( "os" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -47,13 +47,13 @@ func TestCanSupport(t *testing.T) { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{NFS: &api.NFSVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{NFS: &v1.NFSVolumeSource{}}}}) { t.Errorf("Expected true") } - if !plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{NFS: &api.NFSVolumeSource{}}}}}) { + if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{NFS: &v1.NFSVolumeSource{}}}}}) { t.Errorf("Expected true") } - if plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) { + if plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{}}}) { t.Errorf("Expected false") } } @@ -72,8 +72,8 @@ func TestGetAccessModes(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - if !contains(plug.GetAccessModes(), api.ReadWriteOnce) || !contains(plug.GetAccessModes(), api.ReadOnlyMany) || !contains(plug.GetAccessModes(), api.ReadWriteMany) { - t.Errorf("Expected three AccessModeTypes: %s, %s, and %s", api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany) + if !contains(plug.GetAccessModes(), v1.ReadWriteOnce) || !contains(plug.GetAccessModes(), v1.ReadOnlyMany) || !contains(plug.GetAccessModes(), v1.ReadWriteMany) { + t.Errorf("Expected three AccessModeTypes: %s, %s, and %s", v1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadWriteMany) } } @@ -87,7 +87,7 @@ func TestRecycler(t *testing.T) { plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins([]volume.VolumePlugin{&nfsPlugin{nil, volume.VolumeConfig{}}}, volumetest.NewFakeVolumeHost(tmpDir, nil, nil)) - spec := &volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{NFS: &api.NFSVolumeSource{Path: "/foo"}}}}} + spec := &volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{NFS: &v1.NFSVolumeSource{Path: "/foo"}}}}} plug, err := plugMgr.FindRecyclablePluginBySpec(spec) if err != nil { t.Errorf("Can't find the plugin by name") @@ -116,7 +116,7 @@ func (r *mockRecycler) Recycle() error { return nil } -func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { +func contains(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true @@ -139,7 +139,7 @@ func doTestPlugin(t *testing.T, spec *volume.Spec) { t.Errorf("Can't find the plugin by name") } fake := &mount.FakeMounter{} - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, err := plug.(*nfsPlugin).newMounterInternal(spec, pod, fake) volumePath := mounter.GetPath() if err != nil { @@ -202,21 +202,21 @@ func doTestPlugin(t *testing.T, spec *volume.Spec) { } func TestPluginVolume(t *testing.T) { - vol := &api.Volume{ + vol := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{NFS: &api.NFSVolumeSource{Server: "localhost", Path: "/somepath", ReadOnly: false}}, + VolumeSource: v1.VolumeSource{NFS: &v1.NFSVolumeSource{Server: "localhost", Path: "/somepath", ReadOnly: false}}, } doTestPlugin(t, volume.NewSpecFromVolume(vol)) } func TestPluginPersistentVolume(t *testing.T) { - vol := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + vol := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "vol1", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - NFS: &api.NFSVolumeSource{Server: "localhost", Path: "/somepath", ReadOnly: false}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + NFS: &v1.NFSVolumeSource{Server: "localhost", Path: "/somepath", ReadOnly: false}, }, }, } @@ -231,30 +231,30 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { } defer os.RemoveAll(tmpDir) - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - NFS: &api.NFSVolumeSource{}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + NFS: &v1.NFSVolumeSource{}, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, + Status: v1.PersistentVolumeClaimStatus{ + Phase: v1.ClaimBound, }, } @@ -266,7 +266,7 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { diff --git a/pkg/volume/photon_pd/BUILD b/pkg/volume/photon_pd/BUILD index b9f4dc651c2..29124dc6561 100644 --- a/pkg/volume/photon_pd/BUILD +++ b/pkg/volume/photon_pd/BUILD @@ -19,8 +19,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/cloudprovider/providers/photon:go_default_library", "//pkg/types:go_default_library", @@ -42,7 +42,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider/providers/photon:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", diff --git a/pkg/volume/photon_pd/attacher_test.go b/pkg/volume/photon_pd/attacher_test.go index 357bb174c91..7c175b9b30f 100644 --- a/pkg/volume/photon_pd/attacher_test.go +++ b/pkg/volume/photon_pd/attacher_test.go @@ -20,7 +20,7 @@ import ( "errors" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider/providers/photon" "k8s.io/kubernetes/pkg/volume" volumetest "k8s.io/kubernetes/pkg/volume/testing" @@ -187,9 +187,9 @@ func newDetacher(testcase *testcase) *photonPersistentDiskDetacher { func createVolSpec(name string, readOnly bool) *volume.Spec { return &volume.Spec{ - Volume: &api.Volume{ - VolumeSource: api.VolumeSource{ - PhotonPersistentDisk: &api.PhotonPersistentDiskVolumeSource{ + Volume: &v1.Volume{ + VolumeSource: v1.VolumeSource{ + PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{ PdID: name, }, }, @@ -199,10 +199,10 @@ func createVolSpec(name string, readOnly bool) *volume.Spec { func createPVSpec(name string, readOnly bool) *volume.Spec { return &volume.Spec{ - PersistentVolume: &api.PersistentVolume{ - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - PhotonPersistentDisk: &api.PhotonPersistentDiskVolumeSource{ + PersistentVolume: &v1.PersistentVolume{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{ PdID: name, }, }, diff --git a/pkg/volume/photon_pd/photon_pd.go b/pkg/volume/photon_pd/photon_pd.go index b100080da3c..e15749fbaf9 100644 --- a/pkg/volume/photon_pd/photon_pd.go +++ b/pkg/volume/photon_pd/photon_pd.go @@ -22,8 +22,8 @@ import ( "path" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/mount" @@ -77,7 +77,7 @@ func (plugin *photonPersistentDiskPlugin) RequiresRemount() bool { return false } -func (plugin *photonPersistentDiskPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *photonPersistentDiskPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { return plugin.newMounterInternal(spec, pod.UID, &PhotonDiskUtil{}, plugin.host.GetMounter()) } @@ -120,10 +120,10 @@ func (plugin *photonPersistentDiskPlugin) newUnmounterInternal(volName string, p } func (plugin *photonPersistentDiskPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - photonPersistentDisk := &api.Volume{ + photonPersistentDisk := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - PhotonPersistentDisk: &api.PhotonPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{ PdID: volumeName, }, }, @@ -292,9 +292,9 @@ func (ppd *photonPersistentDisk) GetPath() string { } // TODO: supporting more access mode for PhotonController persistent disk -func (plugin *photonPersistentDiskPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, +func (plugin *photonPersistentDiskPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, } } @@ -346,28 +346,28 @@ func (plugin *photonPersistentDiskPlugin) newProvisionerInternal(options volume. }, nil } -func (p *photonPersistentDiskProvisioner) Provision() (*api.PersistentVolume, error) { +func (p *photonPersistentDiskProvisioner) Provision() (*v1.PersistentVolume, error) { pdID, sizeGB, err := p.manager.CreateVolume(p) if err != nil { return nil, err } - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: p.options.PVName, Labels: map[string]string{}, Annotations: map[string]string{ "kubernetes.io/createdby": "photon-volume-dynamic-provisioner", }, }, - Spec: api.PersistentVolumeSpec{ + Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: p.options.PersistentVolumeReclaimPolicy, AccessModes: p.options.PVC.Spec.AccessModes, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - PhotonPersistentDisk: &api.PhotonPersistentDiskVolumeSource{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{ PdID: pdID, FSType: "ext4", }, @@ -382,7 +382,7 @@ func (p *photonPersistentDiskProvisioner) Provision() (*api.PersistentVolume, er } func getVolumeSource( - spec *volume.Spec) (*api.PhotonPersistentDiskVolumeSource, bool, error) { + spec *volume.Spec) (*v1.PhotonPersistentDiskVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.PhotonPersistentDisk != nil { return spec.Volume.PhotonPersistentDisk, spec.ReadOnly, nil } else if spec.PersistentVolume != nil && diff --git a/pkg/volume/photon_pd/photon_pd_test.go b/pkg/volume/photon_pd/photon_pd_test.go index e6e1be5e3d4..3688ed672e0 100644 --- a/pkg/volume/photon_pd/photon_pd_test.go +++ b/pkg/volume/photon_pd/photon_pd_test.go @@ -22,7 +22,7 @@ import ( "path" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -46,10 +46,10 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/photon-pd" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{PhotonPersistentDisk: &api.PhotonPersistentDiskVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{}}}}) { t.Errorf("Expected true") } - if !plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{PhotonPersistentDisk: &api.PhotonPersistentDiskVolumeSource{}}}}}) { + if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{}}}}}) { t.Errorf("Expected true") } } @@ -68,15 +68,15 @@ func TestGetAccessModes(t *testing.T) { t.Errorf("Can't find the plugin by name") } - if !contains(plug.GetAccessModes(), api.ReadWriteOnce) { - t.Errorf("Expected to support AccessModeTypes: %s", api.ReadWriteOnce) + if !contains(plug.GetAccessModes(), v1.ReadWriteOnce) { + t.Errorf("Expected to support AccessModeTypes: %s", v1.ReadWriteOnce) } - if contains(plug.GetAccessModes(), api.ReadOnlyMany) { - t.Errorf("Expected not to support AccessModeTypes: %s", api.ReadOnlyMany) + if contains(plug.GetAccessModes(), v1.ReadOnlyMany) { + t.Errorf("Expected not to support AccessModeTypes: %s", v1.ReadOnlyMany) } } -func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { +func contains(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true @@ -112,10 +112,10 @@ func TestPlugin(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - PhotonPersistentDisk: &api.PhotonPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{ PdID: "pdid", FSType: "ext4", }, @@ -175,8 +175,8 @@ func TestPlugin(t *testing.T) { // Test Provisioner options := volume.VolumeOptions{ - PVC: volumetest.CreateTestPVC("10Gi", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}), - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete, + PVC: volumetest.CreateTestPVC("10Gi", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}), + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, } provisioner, err := plug.(*photonPersistentDiskPlugin).newProvisionerInternal(options, &fakePDManager{}) persistentSpec, err := provisioner.Provision() @@ -187,7 +187,7 @@ func TestPlugin(t *testing.T) { if persistentSpec.Spec.PersistentVolumeSource.PhotonPersistentDisk.PdID != "test-photon-pd-id" { t.Errorf("Provision() returned unexpected persistent disk ID: %s", persistentSpec.Spec.PersistentVolumeSource.PhotonPersistentDisk.PdID) } - cap := persistentSpec.Spec.Capacity[api.ResourceStorage] + cap := persistentSpec.Spec.Capacity[v1.ResourceStorage] size := cap.Value() if size != 10*1024*1024*1024 { t.Errorf("Provision() returned unexpected volume size: %v", size) @@ -217,10 +217,10 @@ func TestMounterAndUnmounterTypeAssert(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - PhotonPersistentDisk: &api.PhotonPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + PhotonPersistentDisk: &v1.PhotonPersistentDiskVolumeSource{ PdID: "pdid", FSType: "ext4", }, diff --git a/pkg/volume/photon_pd/photon_util.go b/pkg/volume/photon_pd/photon_util.go index 45b14775533..f3c1936645d 100644 --- a/pkg/volume/photon_pd/photon_util.go +++ b/pkg/volume/photon_pd/photon_util.go @@ -24,7 +24,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/cloudprovider/providers/photon" "k8s.io/kubernetes/pkg/volume" @@ -87,7 +87,7 @@ func (util *PhotonDiskUtil) CreateVolume(p *photonPersistentDiskProvisioner) (pd return "", 0, err } - capacity := p.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] + capacity := p.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] volSizeBytes := capacity.Value() // PhotonController works with GB, convert to GB with rounding up volSizeGB := int(volume.RoundUpSize(volSizeBytes, 1024*1024*1024)) diff --git a/pkg/volume/plugins.go b/pkg/volume/plugins.go index fb217da8418..2ad2ad20fa3 100644 --- a/pkg/volume/plugins.go +++ b/pkg/volume/plugins.go @@ -23,8 +23,8 @@ import ( "sync" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" utilerrors "k8s.io/kubernetes/pkg/util/errors" @@ -40,7 +40,7 @@ type VolumeOptions struct { // many kinds of provisioners. // Reclamation policy for a persistent volume - PersistentVolumeReclaimPolicy api.PersistentVolumeReclaimPolicy + PersistentVolumeReclaimPolicy v1.PersistentVolumeReclaimPolicy // PV.Name of the appropriate PersistentVolume. Used to generate cloud // volume name. PVName string @@ -48,7 +48,7 @@ type VolumeOptions struct { // Provisioners *must* create a PV that would be matched by this PVC, // i.e. with required capacity, accessMode, labels matching PVC.Selector and // so on. - PVC *api.PersistentVolumeClaim + PVC *v1.PersistentVolumeClaim // Unique name of Kubernetes cluster. ClusterName string // Tags to attach to the real volume in the cloud provider - e.g. AWS EBS @@ -90,12 +90,12 @@ type VolumePlugin interface { // NewMounter creates a new volume.Mounter from an API specification. // Ownership of the spec pointer in *not* transferred. - // - spec: The api.Volume spec + // - spec: The v1.Volume spec // - pod: The enclosing pod - NewMounter(spec *Spec, podRef *api.Pod, opts VolumeOptions) (Mounter, error) + NewMounter(spec *Spec, podRef *v1.Pod, opts VolumeOptions) (Mounter, error) // NewUnmounter creates a new volume.Unmounter from recoverable state. - // - name: The volume name, as per the api.Volume spec. + // - name: The volume name, as per the v1.Volume spec. // - podUID: The UID of the enclosing pod NewUnmounter(name string, podUID types.UID) (Unmounter, error) @@ -111,7 +111,7 @@ type VolumePlugin interface { type PersistentVolumePlugin interface { VolumePlugin // GetAccessModes describes the ways a given volume can be accessed/mounted. - GetAccessModes() []api.PersistentVolumeAccessMode + GetAccessModes() []v1.PersistentVolumeAccessMode } // RecyclableVolumePlugin is an extended interface of VolumePlugin and is used @@ -190,7 +190,7 @@ type VolumeHost interface { // the provided spec. This is used to implement volume plugins which // "wrap" other plugins. For example, the "secret" volume is // implemented in terms of the "emptyDir" volume. - NewWrapperMounter(volName string, spec Spec, pod *api.Pod, opts VolumeOptions) (Mounter, error) + NewWrapperMounter(volName string, spec Spec, pod *v1.Pod, opts VolumeOptions) (Mounter, error) // NewWrapperUnmounter finds an appropriate plugin with which to handle // the provided spec. See comments on NewWrapperMounter for more @@ -213,7 +213,7 @@ type VolumeHost interface { GetHostIP() (net.IP, error) // Returns node allocatable - GetNodeAllocatable() (api.ResourceList, error) + GetNodeAllocatable() (v1.ResourceList, error) } // VolumePluginMgr tracks registered plugins. @@ -224,8 +224,8 @@ type VolumePluginMgr struct { // Spec is an internal representation of a volume. All API volume types translate to Spec. type Spec struct { - Volume *api.Volume - PersistentVolume *api.PersistentVolume + Volume *v1.Volume + PersistentVolume *v1.PersistentVolume ReadOnly bool } @@ -269,7 +269,7 @@ type VolumeConfig struct { // which override specific properties of the pod in accordance with that // plugin. See NewPersistentVolumeRecyclerPodTemplate for the properties // that are expected to be overridden. - RecyclerPodTemplate *api.Pod + RecyclerPodTemplate *v1.Pod // RecyclerMinimumTimeout is the minimum amount of time in seconds for the // recycler pod's ActiveDeadlineSeconds attribute. Added to the minimum @@ -296,15 +296,15 @@ type VolumeConfig struct { ProvisioningEnabled bool } -// NewSpecFromVolume creates an Spec from an api.Volume -func NewSpecFromVolume(vs *api.Volume) *Spec { +// NewSpecFromVolume creates an Spec from an v1.Volume +func NewSpecFromVolume(vs *v1.Volume) *Spec { return &Spec{ Volume: vs, } } -// NewSpecFromPersistentVolume creates an Spec from an api.PersistentVolume -func NewSpecFromPersistentVolume(pv *api.PersistentVolume, readOnly bool) *Spec { +// NewSpecFromPersistentVolume creates an Spec from an v1.PersistentVolume +func NewSpecFromPersistentVolume(pv *v1.PersistentVolume, readOnly bool) *Spec { return &Spec{ PersistentVolume: pv, ReadOnly: readOnly, @@ -526,32 +526,32 @@ func (pm *VolumePluginMgr) FindAttachablePluginByName(name string) (AttachableVo // before failing. Recommended. Default is 60 seconds. // // See HostPath and NFS for working recycler examples -func NewPersistentVolumeRecyclerPodTemplate() *api.Pod { +func NewPersistentVolumeRecyclerPodTemplate() *v1.Pod { timeout := int64(60) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "pv-recycler-", - Namespace: api.NamespaceDefault, + Namespace: v1.NamespaceDefault, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ ActiveDeadlineSeconds: &timeout, - RestartPolicy: api.RestartPolicyNever, - Volumes: []api.Volume{ + RestartPolicy: v1.RestartPolicyNever, + Volumes: []v1.Volume{ { Name: "vol", // IMPORTANT! All plugins using this template MUST // override pod.Spec.Volumes[0].VolumeSource Recycler // implementations without a valid VolumeSource will fail. - VolumeSource: api.VolumeSource{}, + VolumeSource: v1.VolumeSource{}, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "pv-recycler", Image: "gcr.io/google_containers/busybox", Command: []string{"/bin/sh"}, Args: []string{"-c", "test -e /scrub && rm -rf /scrub/..?* /scrub/.[!.]* /scrub/* && test -z \"$(ls -A /scrub)\" || exit 1"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "vol", MountPath: "/scrub", diff --git a/pkg/volume/plugins_test.go b/pkg/volume/plugins_test.go index 863087b464d..3523b74c93d 100644 --- a/pkg/volume/plugins_test.go +++ b/pkg/volume/plugins_test.go @@ -19,13 +19,13 @@ package volume import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) func TestSpecSourceConverters(t *testing.T) { - v := &api.Volume{ + v := &v1.Volume{ Name: "foo", - VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}, + VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}, } converted := NewSpecFromVolume(v) @@ -36,10 +36,10 @@ func TestSpecSourceConverters(t *testing.T) { t.Errorf("Expected %v but got %v", v.Name, converted.Name()) } - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{Name: "bar"}, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{}}, + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{Name: "bar"}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{}}, }, } diff --git a/pkg/volume/quobyte/BUILD b/pkg/volume/quobyte/BUILD index 2165dd305ad..b0f6310ef9a 100644 --- a/pkg/volume/quobyte/BUILD +++ b/pkg/volume/quobyte/BUILD @@ -19,8 +19,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", "//pkg/util/mount:go_default_library", @@ -39,8 +39,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/testing:go_default_library", diff --git a/pkg/volume/quobyte/quobyte.go b/pkg/volume/quobyte/quobyte.go index 9552a85468f..47aeb61b143 100644 --- a/pkg/volume/quobyte/quobyte.go +++ b/pkg/volume/quobyte/quobyte.go @@ -24,8 +24,8 @@ import ( "github.com/golang/glog" "github.com/pborman/uuid" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/mount" @@ -117,15 +117,15 @@ func (plugin *quobytePlugin) RequiresRemount() bool { return false } -func (plugin *quobytePlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, +func (plugin *quobytePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, } } -func getVolumeSource(spec *volume.Spec) (*api.QuobyteVolumeSource, bool, error) { +func getVolumeSource(spec *volume.Spec) (*v1.QuobyteVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.Quobyte != nil { return spec.Volume.Quobyte, spec.Volume.Quobyte.ReadOnly, nil } else if spec.PersistentVolume != nil && @@ -137,10 +137,10 @@ func getVolumeSource(spec *volume.Spec) (*api.QuobyteVolumeSource, bool, error) } func (plugin *quobytePlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - quobyteVolume := &api.Volume{ + quobyteVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - Quobyte: &api.QuobyteVolumeSource{ + VolumeSource: v1.VolumeSource{ + Quobyte: &v1.QuobyteVolumeSource{ Volume: volumeName, }, }, @@ -148,11 +148,11 @@ func (plugin *quobytePlugin) ConstructVolumeSpec(volumeName, mountPath string) ( return volume.NewSpecFromVolume(quobyteVolume), nil } -func (plugin *quobytePlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *quobytePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { return plugin.newMounterInternal(spec, pod, plugin.host.GetMounter()) } -func (plugin *quobytePlugin) newMounterInternal(spec *volume.Spec, pod *api.Pod, mounter mount.Interface) (volume.Mounter, error) { +func (plugin *quobytePlugin) newMounterInternal(spec *volume.Spec, pod *v1.Pod, mounter mount.Interface) (volume.Mounter, error) { source, readOnly, err := getVolumeSource(spec) if err != nil { return nil, err @@ -182,7 +182,7 @@ func (plugin *quobytePlugin) newUnmounterInternal(volName string, podUID types.U &quobyte{ volName: volName, mounter: mounter, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{UID: podUID}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: podUID}}, plugin: plugin, }, }, nil @@ -191,7 +191,7 @@ func (plugin *quobytePlugin) newUnmounterInternal(volName string, podUID types.U // Quobyte volumes represent a bare host directory mount of an quobyte export. type quobyte struct { volName string - pod *api.Pod + pod *v1.Pod user string group string volume string @@ -293,7 +293,7 @@ func (unmounter *quobyteUnmounter) TearDownAt(dir string) error { type quobyteVolumeDeleter struct { *quobyteMounter - pv *api.PersistentVolume + pv *v1.PersistentVolume } func (plugin *quobytePlugin) NewDeleter(spec *volume.Spec) (volume.Deleter, error) { @@ -346,7 +346,7 @@ type quobyteVolumeProvisioner struct { options volume.VolumeOptions } -func (provisioner *quobyteVolumeProvisioner) Provision() (*api.PersistentVolume, error) { +func (provisioner *quobyteVolumeProvisioner) Provision() (*v1.PersistentVolume, error) { if provisioner.options.PVC.Spec.Selector != nil { return nil, fmt.Errorf("claim Selector is not supported") } @@ -393,15 +393,15 @@ func (provisioner *quobyteVolumeProvisioner) Provision() (*api.PersistentVolume, if err != nil { return nil, err } - pv := new(api.PersistentVolume) + pv := new(v1.PersistentVolume) pv.Spec.PersistentVolumeSource.Quobyte = vol pv.Spec.PersistentVolumeReclaimPolicy = provisioner.options.PersistentVolumeReclaimPolicy pv.Spec.AccessModes = provisioner.options.PVC.Spec.AccessModes if len(pv.Spec.AccessModes) == 0 { pv.Spec.AccessModes = provisioner.plugin.GetAccessModes() } - pv.Spec.Capacity = api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), + pv.Spec.Capacity = v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), } return pv, nil } diff --git a/pkg/volume/quobyte/quobyte_test.go b/pkg/volume/quobyte/quobyte_test.go index e5d9f2a3848..a4ca6e2961d 100644 --- a/pkg/volume/quobyte/quobyte_test.go +++ b/pkg/volume/quobyte/quobyte_test.go @@ -21,8 +21,8 @@ import ( "os" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -46,10 +46,10 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/quobyte" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{}}}}) { + if plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{}}}}) { t.Errorf("Expected false") } - if plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) { + if plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{}}}) { t.Errorf("Expected false") } } @@ -68,12 +68,12 @@ func TestGetAccessModes(t *testing.T) { if err != nil { t.Errorf("Can't find the plugin by name") } - if !contains(plug.GetAccessModes(), api.ReadWriteOnce) || !contains(plug.GetAccessModes(), api.ReadOnlyMany) || !contains(plug.GetAccessModes(), api.ReadWriteMany) { - t.Errorf("Expected three AccessModeTypes: %s, %s, and %s", api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany) + if !contains(plug.GetAccessModes(), v1.ReadWriteOnce) || !contains(plug.GetAccessModes(), v1.ReadOnlyMany) || !contains(plug.GetAccessModes(), v1.ReadWriteMany) { + t.Errorf("Expected three AccessModeTypes: %s, %s, and %s", v1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadWriteMany) } } -func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool { +func contains(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool { for _, m := range modes { if m == mode { return true @@ -96,7 +96,7 @@ func doTestPlugin(t *testing.T, spec *volume.Spec) { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, err := plug.(*quobytePlugin).newMounterInternal(spec, pod, &mount.FakeMounter{}) volumePath := mounter.GetPath() if err != nil { @@ -126,23 +126,23 @@ func doTestPlugin(t *testing.T, spec *volume.Spec) { } func TestPluginVolume(t *testing.T) { - vol := &api.Volume{ + vol := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - Quobyte: &api.QuobyteVolumeSource{Registry: "reg:7861", Volume: "vol", ReadOnly: false, User: "root", Group: "root"}, + VolumeSource: v1.VolumeSource{ + Quobyte: &v1.QuobyteVolumeSource{Registry: "reg:7861", Volume: "vol", ReadOnly: false, User: "root", Group: "root"}, }, } doTestPlugin(t, volume.NewSpecFromVolume(vol)) } func TestPluginPersistentVolume(t *testing.T) { - vol := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + vol := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "vol1", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - Quobyte: &api.QuobyteVolumeSource{Registry: "reg:7861", Volume: "vol", ReadOnly: false, User: "root", Group: "root"}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + Quobyte: &v1.QuobyteVolumeSource{Registry: "reg:7861", Volume: "vol", ReadOnly: false, User: "root", Group: "root"}, }, }, } @@ -151,30 +151,30 @@ func TestPluginPersistentVolume(t *testing.T) { } func TestPersistentClaimReadOnlyFlag(t *testing.T) { - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - Quobyte: &api.QuobyteVolumeSource{Registry: "reg:7861", Volume: "vol", ReadOnly: false, User: "root", Group: "root"}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + Quobyte: &v1.QuobyteVolumeSource{Registry: "reg:7861", Volume: "vol", ReadOnly: false, User: "root", Group: "root"}, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, + Status: v1.PersistentVolumeClaimStatus{ + Phase: v1.ClaimBound, }, } @@ -191,7 +191,7 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { diff --git a/pkg/volume/quobyte/quobyte_util.go b/pkg/volume/quobyte/quobyte_util.go index 85522724ff9..df7a1236088 100644 --- a/pkg/volume/quobyte/quobyte_util.go +++ b/pkg/volume/quobyte/quobyte_util.go @@ -21,7 +21,7 @@ import ( "path" "strings" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/volume" "github.com/golang/glog" @@ -32,8 +32,8 @@ type quobyteVolumeManager struct { config *quobyteAPIConfig } -func (manager *quobyteVolumeManager) createVolume(provisioner *quobyteVolumeProvisioner) (quobyte *api.QuobyteVolumeSource, size int, err error) { - capacity := provisioner.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] +func (manager *quobyteVolumeManager) createVolume(provisioner *quobyteVolumeProvisioner) (quobyte *v1.QuobyteVolumeSource, size int, err error) { + capacity := provisioner.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] volumeSize := int(volume.RoundUpSize(capacity.Value(), 1024*1024*1024)) // Quobyte has the concept of Volumes which doen't have a specific size (they can grow unlimited) // to simulate a size constraint we could set here a Quota @@ -46,11 +46,11 @@ func (manager *quobyteVolumeManager) createVolume(provisioner *quobyteVolumeProv } if _, err := manager.createQuobyteClient().CreateVolume(volumeRequest); err != nil { - return &api.QuobyteVolumeSource{}, volumeSize, err + return &v1.QuobyteVolumeSource{}, volumeSize, err } glog.V(4).Infof("Created Quobyte volume %s", provisioner.volume) - return &api.QuobyteVolumeSource{ + return &v1.QuobyteVolumeSource{ Registry: provisioner.registry, Volume: provisioner.volume, User: provisioner.user, diff --git a/pkg/volume/rbd/BUILD b/pkg/volume/rbd/BUILD index 033f427cf10..5a175897788 100644 --- a/pkg/volume/rbd/BUILD +++ b/pkg/volume/rbd/BUILD @@ -20,9 +20,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/types:go_default_library", "//pkg/util/exec:go_default_library", "//pkg/util/mount:go_default_library", @@ -41,8 +41,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/testing:go_default_library", diff --git a/pkg/volume/rbd/disk_manager.go b/pkg/volume/rbd/disk_manager.go index 065049bcffb..d5b1cd31a44 100644 --- a/pkg/volume/rbd/disk_manager.go +++ b/pkg/volume/rbd/disk_manager.go @@ -26,7 +26,7 @@ import ( "os" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/volume" ) @@ -39,7 +39,7 @@ type diskManager interface { // Detaches the disk from the kubelet's host machine. DetachDisk(disk rbdUnmounter, mntPath string) error // Creates a rbd image - CreateImage(provisioner *rbdVolumeProvisioner) (r *api.RBDVolumeSource, volumeSizeGB int, err error) + CreateImage(provisioner *rbdVolumeProvisioner) (r *v1.RBDVolumeSource, volumeSizeGB int, err error) // Deletes a rbd image DeleteImage(deleter *rbdVolumeDeleter) error } diff --git a/pkg/volume/rbd/rbd.go b/pkg/volume/rbd/rbd.go index 5674652aabe..84de3578559 100644 --- a/pkg/volume/rbd/rbd.go +++ b/pkg/volume/rbd/rbd.go @@ -21,9 +21,9 @@ import ( dstrings "strings" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/mount" @@ -86,14 +86,14 @@ func (plugin *rbdPlugin) RequiresRemount() bool { return false } -func (plugin *rbdPlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, +func (plugin *rbdPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, } } -func (plugin *rbdPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *rbdPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { var secret string var err error source, _ := plugin.getRBDVolumeSource(spec) @@ -109,7 +109,7 @@ func (plugin *rbdPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.Vo return plugin.newMounterInternal(spec, pod.UID, &RBDUtil{}, plugin.host.GetMounter(), secret) } -func (plugin *rbdPlugin) getRBDVolumeSource(spec *volume.Spec) (*api.RBDVolumeSource, bool) { +func (plugin *rbdPlugin) getRBDVolumeSource(spec *volume.Spec) (*v1.RBDVolumeSource, bool) { // rbd volumes used directly in a pod have a ReadOnly flag set by the pod author. // rbd volumes used as a PersistentVolume gets the ReadOnly flag indirectly through the persistent-claim volume used to mount the PV if spec.Volume != nil && spec.Volume.RBD != nil { @@ -165,10 +165,10 @@ func (plugin *rbdPlugin) newUnmounterInternal(volName string, podUID types.UID, } func (plugin *rbdPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - rbdVolume := &api.Volume{ + rbdVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - RBD: &api.RBDVolumeSource{ + VolumeSource: v1.VolumeSource{ + RBD: &v1.RBDVolumeSource{ CephMonitors: []string{}, }, }, @@ -244,7 +244,7 @@ type rbdVolumeProvisioner struct { options volume.VolumeOptions } -func (r *rbdVolumeProvisioner) Provision() (*api.PersistentVolume, error) { +func (r *rbdVolumeProvisioner) Provision() (*v1.PersistentVolume, error) { if r.options.PVC.Spec.Selector != nil { return nil, fmt.Errorf("claim Selector is not supported") } @@ -311,8 +311,8 @@ func (r *rbdVolumeProvisioner) Provision() (*api.PersistentVolume, error) { return nil, fmt.Errorf("rbd: create volume failed, err: %v", err) } glog.Infof("successfully created rbd image %q", image) - pv := new(api.PersistentVolume) - rbd.SecretRef = new(api.LocalObjectReference) + pv := new(v1.PersistentVolume) + rbd.SecretRef = new(v1.LocalObjectReference) rbd.SecretRef.Name = secretName rbd.RadosUser = r.Id pv.Spec.PersistentVolumeSource.RBD = rbd @@ -321,8 +321,8 @@ func (r *rbdVolumeProvisioner) Provision() (*api.PersistentVolume, error) { if len(pv.Spec.AccessModes) == 0 { pv.Spec.AccessModes = r.plugin.GetAccessModes() } - pv.Spec.Capacity = api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dMi", sizeMB)), + pv.Spec.Capacity = v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dMi", sizeMB)), } return pv, nil } @@ -424,7 +424,7 @@ func (plugin *rbdPlugin) execCommand(command string, args []string) ([]byte, err } func getVolumeSource( - spec *volume.Spec) (*api.RBDVolumeSource, bool, error) { + spec *volume.Spec) (*v1.RBDVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.RBD != nil { return spec.Volume.RBD, spec.Volume.RBD.ReadOnly, nil } else if spec.PersistentVolume != nil && @@ -435,7 +435,7 @@ func getVolumeSource( return nil, false, fmt.Errorf("Spec does not reference a RBD volume type") } -func parsePodSecret(pod *api.Pod, secretName string, kubeClient clientset.Interface) (string, error) { +func parsePodSecret(pod *v1.Pod, secretName string, kubeClient clientset.Interface) (string, error) { secret, err := volutil.GetSecretForPod(pod, secretName, kubeClient) if err != nil { glog.Errorf("failed to get secret from [%q/%q]", pod.Namespace, secretName) diff --git a/pkg/volume/rbd/rbd_test.go b/pkg/volume/rbd/rbd_test.go index dd65022be22..a18f3d32571 100644 --- a/pkg/volume/rbd/rbd_test.go +++ b/pkg/volume/rbd/rbd_test.go @@ -21,8 +21,8 @@ import ( "os" "testing" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -47,7 +47,7 @@ func TestCanSupport(t *testing.T) { if plug.GetPluginName() != "kubernetes.io/rbd" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) { + if plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{}}}) { t.Errorf("Expected false") } } @@ -87,7 +87,7 @@ func (fake *fakeDiskManager) DetachDisk(c rbdUnmounter, mntPath string) error { return nil } -func (fake *fakeDiskManager) CreateImage(provisioner *rbdVolumeProvisioner) (r *api.RBDVolumeSource, volumeSizeGB int, err error) { +func (fake *fakeDiskManager) CreateImage(provisioner *rbdVolumeProvisioner) (r *v1.RBDVolumeSource, volumeSizeGB int, err error) { return nil, 0, fmt.Errorf("not implemented") } @@ -155,10 +155,10 @@ func doTestPlugin(t *testing.T, spec *volume.Spec) { } func TestPluginVolume(t *testing.T) { - vol := &api.Volume{ + vol := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - RBD: &api.RBDVolumeSource{ + VolumeSource: v1.VolumeSource{ + RBD: &v1.RBDVolumeSource{ CephMonitors: []string{"a", "b"}, RBDImage: "bar", FSType: "ext4", @@ -168,13 +168,13 @@ func TestPluginVolume(t *testing.T) { doTestPlugin(t, volume.NewSpecFromVolume(vol)) } func TestPluginPersistentVolume(t *testing.T) { - vol := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + vol := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "vol1", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - RBD: &api.RBDVolumeSource{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + RBD: &v1.RBDVolumeSource{ CephMonitors: []string{"a", "b"}, RBDImage: "bar", FSType: "ext4", @@ -193,34 +193,34 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { } defer os.RemoveAll(tmpDir) - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: "pvA", }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - RBD: &api.RBDVolumeSource{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + RBD: &v1.RBDVolumeSource{ CephMonitors: []string{"a", "b"}, RBDImage: "bar", FSType: "ext4", }, }, - ClaimRef: &api.ObjectReference{ + ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } - claim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + claim := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, + Status: v1.PersistentVolumeClaimStatus{ + Phase: v1.ClaimBound, }, } @@ -232,7 +232,7 @@ func TestPersistentClaimReadOnlyFlag(t *testing.T) { // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { diff --git a/pkg/volume/rbd/rbd_util.go b/pkg/volume/rbd/rbd_util.go index 5eca4c3621c..94d6e668aaa 100644 --- a/pkg/volume/rbd/rbd_util.go +++ b/pkg/volume/rbd/rbd_util.go @@ -34,7 +34,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/util/node" @@ -313,8 +313,8 @@ func (util *RBDUtil) DetachDisk(c rbdUnmounter, mntPath string) error { return nil } -func (util *RBDUtil) CreateImage(p *rbdVolumeProvisioner) (r *api.RBDVolumeSource, size int, err error) { - capacity := p.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] +func (util *RBDUtil) CreateImage(p *rbdVolumeProvisioner) (r *v1.RBDVolumeSource, size int, err error) { + capacity := p.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] volSizeBytes := capacity.Value() // convert to MB that rbd defaults on sz := int(volume.RoundUpSize(volSizeBytes, 1024*1024)) @@ -342,7 +342,7 @@ func (util *RBDUtil) CreateImage(p *rbdVolumeProvisioner) (r *api.RBDVolumeSourc return nil, 0, err } - return &api.RBDVolumeSource{ + return &v1.RBDVolumeSource{ CephMonitors: p.rbdMounter.Mon, RBDImage: p.rbdMounter.Image, RBDPool: p.rbdMounter.Pool, diff --git a/pkg/volume/secret/BUILD b/pkg/volume/secret/BUILD index 9af4233ee10..30e2b4c0319 100644 --- a/pkg/volume/secret/BUILD +++ b/pkg/volume/secret/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/types:go_default_library", "//pkg/util/io:go_default_library", "//pkg/util/mount:go_default_library", @@ -35,9 +35,9 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/fake:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/fake:go_default_library", "//pkg/types:go_default_library", "//pkg/volume:go_default_library", "//pkg/volume/empty_dir:go_default_library", diff --git a/pkg/volume/secret/secret.go b/pkg/volume/secret/secret.go index aed4b9fa77d..73aca3828ee 100644 --- a/pkg/volume/secret/secret.go +++ b/pkg/volume/secret/secret.go @@ -22,7 +22,7 @@ import ( "runtime" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" ioutil "k8s.io/kubernetes/pkg/util/io" "k8s.io/kubernetes/pkg/util/mount" @@ -49,7 +49,7 @@ var _ volume.VolumePlugin = &secretPlugin{} func wrappedVolumeSpec() volume.Spec { return volume.Spec{ - Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{Medium: api.StorageMediumMemory}}}, + Volume: &v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{Medium: v1.StorageMediumMemory}}}, } } @@ -83,7 +83,7 @@ func (plugin *secretPlugin) RequiresRemount() bool { return true } -func (plugin *secretPlugin) NewMounter(spec *volume.Spec, pod *api.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *secretPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { return &secretVolumeMounter{ secretVolume: &secretVolume{ spec.Name(), @@ -113,10 +113,10 @@ func (plugin *secretPlugin) NewUnmounter(volName string, podUID types.UID) (volu } func (plugin *secretPlugin) ConstructVolumeSpec(volName, mountPath string) (*volume.Spec, error) { - secretVolume := &api.Volume{ + secretVolume := &v1.Volume{ Name: volName, - VolumeSource: api.VolumeSource{ - Secret: &api.SecretVolumeSource{ + VolumeSource: v1.VolumeSource{ + Secret: &v1.SecretVolumeSource{ SecretName: volName, }, }, @@ -144,8 +144,8 @@ func (sv *secretVolume) GetPath() string { type secretVolumeMounter struct { *secretVolume - source api.SecretVolumeSource - pod api.Pod + source v1.SecretVolumeSource + pod v1.Pod opts *volume.VolumeOptions } @@ -232,7 +232,7 @@ func (b *secretVolumeMounter) SetUpAt(dir string, fsGroup *int64) error { return nil } -func makePayload(mappings []api.KeyToPath, secret *api.Secret, defaultMode *int32) (map[string]volumeutil.FileProjection, error) { +func makePayload(mappings []v1.KeyToPath, secret *v1.Secret, defaultMode *int32) (map[string]volumeutil.FileProjection, error) { if defaultMode == nil { return nil, fmt.Errorf("No defaultMode used, not even the default value for it") } @@ -267,7 +267,7 @@ func makePayload(mappings []api.KeyToPath, secret *api.Secret, defaultMode *int3 return payload, nil } -func totalSecretBytes(secret *api.Secret) int { +func totalSecretBytes(secret *v1.Secret) int { totalSize := 0 for _, bytes := range secret.Data { totalSize += len(bytes) @@ -303,9 +303,9 @@ func (c *secretVolumeUnmounter) TearDownAt(dir string) error { return wrapped.TearDownAt(dir) } -func getVolumeSource(spec *volume.Spec) (*api.SecretVolumeSource, bool) { +func getVolumeSource(spec *volume.Spec) (*v1.SecretVolumeSource, bool) { var readOnly bool - var volumeSource *api.SecretVolumeSource + var volumeSource *v1.SecretVolumeSource if spec.Volume != nil && spec.Volume.Secret != nil { volumeSource = spec.Volume.Secret diff --git a/pkg/volume/secret/secret_test.go b/pkg/volume/secret/secret_test.go index f76cf41750c..454762114cc 100644 --- a/pkg/volume/secret/secret_test.go +++ b/pkg/volume/secret/secret_test.go @@ -26,9 +26,9 @@ import ( "strings" "testing" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/fake" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/empty_dir" @@ -42,15 +42,15 @@ func TestMakePayload(t *testing.T) { caseMappingMode := int32(0400) cases := []struct { name string - mappings []api.KeyToPath - secret *api.Secret + mappings []v1.KeyToPath + secret *v1.Secret mode int32 payload map[string]util.FileProjection success bool }{ { name: "no overrides", - secret: &api.Secret{ + secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), @@ -65,13 +65,13 @@ func TestMakePayload(t *testing.T) { }, { name: "basic 1", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/foo.txt", }, }, - secret: &api.Secret{ + secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), @@ -85,13 +85,13 @@ func TestMakePayload(t *testing.T) { }, { name: "subdirs", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/1/2/3/foo.txt", }, }, - secret: &api.Secret{ + secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), @@ -105,13 +105,13 @@ func TestMakePayload(t *testing.T) { }, { name: "subdirs 2", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/1/2/3/foo.txt", }, }, - secret: &api.Secret{ + secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), @@ -125,7 +125,7 @@ func TestMakePayload(t *testing.T) { }, { name: "subdirs 3", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/1/2/3/foo.txt", @@ -135,7 +135,7 @@ func TestMakePayload(t *testing.T) { Path: "another/path/to/the/esteemed/bar.bin", }, }, - secret: &api.Secret{ + secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), @@ -150,13 +150,13 @@ func TestMakePayload(t *testing.T) { }, { name: "non existent key", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "zab", Path: "path/to/foo.txt", }, }, - secret: &api.Secret{ + secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), @@ -167,7 +167,7 @@ func TestMakePayload(t *testing.T) { }, { name: "mapping with Mode", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "foo.txt", @@ -179,7 +179,7 @@ func TestMakePayload(t *testing.T) { Mode: &caseMappingMode, }, }, - secret: &api.Secret{ + secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), @@ -194,7 +194,7 @@ func TestMakePayload(t *testing.T) { }, { name: "mapping with defaultMode", - mappings: []api.KeyToPath{ + mappings: []v1.KeyToPath{ { Key: "foo", Path: "foo.txt", @@ -204,7 +204,7 @@ func TestMakePayload(t *testing.T) { Path: "bar.bin", }, }, - secret: &api.Secret{ + secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), @@ -263,7 +263,7 @@ func TestCanSupport(t *testing.T) { if plugin.GetPluginName() != secretPluginName { t.Errorf("Wrong name: %s", plugin.GetPluginName()) } - if !plugin.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{Secret: &api.SecretVolumeSource{SecretName: ""}}}}) { + if !plugin.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{Secret: &v1.SecretVolumeSource{SecretName: ""}}}}) { t.Errorf("Expected true") } if plugin.CanSupport(&volume.Spec{}) { @@ -292,7 +292,7 @@ func TestPlugin(t *testing.T) { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) @@ -365,7 +365,7 @@ func TestPluginReboot(t *testing.T) { t.Errorf("Can't find the plugin by name") } - pod := &api.Pod{ObjectMeta: api.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) @@ -397,11 +397,11 @@ func TestPluginReboot(t *testing.T) { doTestCleanAndTeardown(plugin, testPodUID, testVolumeName, volumePath, t) } -func volumeSpec(volumeName, secretName string, defaultMode int32) *api.Volume { - return &api.Volume{ +func volumeSpec(volumeName, secretName string, defaultMode int32) *v1.Volume { + return &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - Secret: &api.SecretVolumeSource{ + VolumeSource: v1.VolumeSource{ + Secret: &v1.SecretVolumeSource{ SecretName: secretName, DefaultMode: &defaultMode, }, @@ -409,9 +409,9 @@ func volumeSpec(volumeName, secretName string, defaultMode int32) *api.Volume { } } -func secret(namespace, name string) api.Secret { - return api.Secret{ - ObjectMeta: api.ObjectMeta{ +func secret(namespace, name string) v1.Secret { + return v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Namespace: namespace, Name: name, }, @@ -423,7 +423,7 @@ func secret(namespace, name string) api.Secret { } } -func doTestSecretDataInVolume(volumePath string, secret api.Secret, t *testing.T) { +func doTestSecretDataInVolume(volumePath string, secret v1.Secret, t *testing.T) { for key, value := range secret.Data { secretDataHostPath := path.Join(volumePath, key) if _, err := os.Stat(secretDataHostPath); err != nil { diff --git a/pkg/volume/testing/BUILD b/pkg/volume/testing/BUILD index 7a442817d49..247c736ab3c 100644 --- a/pkg/volume/testing/BUILD +++ b/pkg/volume/testing/BUILD @@ -18,9 +18,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/types:go_default_library", "//pkg/util/io:go_default_library", diff --git a/pkg/volume/testing/testing.go b/pkg/volume/testing/testing.go index 005f59dcec7..be74309d30b 100644 --- a/pkg/volume/testing/testing.go +++ b/pkg/volume/testing/testing.go @@ -27,9 +27,9 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/io" @@ -86,7 +86,7 @@ func (f *fakeVolumeHost) GetWriter() io.Writer { return f.writer } -func (f *fakeVolumeHost) NewWrapperMounter(volName string, spec Spec, pod *api.Pod, opts VolumeOptions) (Mounter, error) { +func (f *fakeVolumeHost) NewWrapperMounter(volName string, spec Spec, pod *v1.Pod, opts VolumeOptions) (Mounter, error) { // The name of wrapper volume is set to "wrapped_{wrapped_volume_name}" wrapperVolumeName := "wrapped_" + volName if spec.Volume != nil { @@ -122,8 +122,8 @@ func (f *fakeVolumeHost) GetHostIP() (net.IP, error) { return nil, fmt.Errorf("GetHostIP() not implemented") } -func (f *fakeVolumeHost) GetNodeAllocatable() (api.ResourceList, error) { - return api.ResourceList{}, nil +func (f *fakeVolumeHost) GetNodeAllocatable() (v1.ResourceList, error) { + return v1.ResourceList{}, nil } func ProbeVolumePlugins(config VolumeConfig) []VolumePlugin { @@ -196,7 +196,7 @@ func (plugin *FakeVolumePlugin) RequiresRemount() bool { return false } -func (plugin *FakeVolumePlugin) NewMounter(spec *Spec, pod *api.Pod, opts VolumeOptions) (Mounter, error) { +func (plugin *FakeVolumePlugin) NewMounter(spec *Spec, pod *v1.Pod, opts VolumeOptions) (Mounter, error) { plugin.Lock() defer plugin.Unlock() volume := plugin.getFakeVolume(&plugin.Mounters) @@ -283,8 +283,8 @@ func (plugin *FakeVolumePlugin) NewProvisioner(options VolumeOptions) (Provision return &FakeProvisioner{options, plugin.Host}, nil } -func (plugin *FakeVolumePlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{} +func (plugin *FakeVolumePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{} } func (plugin *FakeVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (*Spec, error) { @@ -473,24 +473,24 @@ type FakeProvisioner struct { Host VolumeHost } -func (fc *FakeProvisioner) Provision() (*api.PersistentVolume, error) { +func (fc *FakeProvisioner) Provision() (*v1.PersistentVolume, error) { fullpath := fmt.Sprintf("/tmp/hostpath_pv/%s", uuid.NewUUID()) - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: fc.Options.PVName, Annotations: map[string]string{ "kubernetes.io/createdby": "fakeplugin-provisioner", }, }, - Spec: api.PersistentVolumeSpec{ + Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: fc.Options.PersistentVolumeReclaimPolicy, AccessModes: fc.Options.PVC.Spec.AccessModes, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): fc.Options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)], + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): fc.Options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)], }, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + HostPath: &v1.HostPathVolumeSource{ Path: fullpath, }, }, @@ -735,17 +735,17 @@ func GetTestVolumePluginMgr( } // CreateTestPVC returns a provisionable PVC for tests -func CreateTestPVC(capacity string, accessModes []api.PersistentVolumeAccessMode) *api.PersistentVolumeClaim { - claim := api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ +func CreateTestPVC(capacity string, accessModes []v1.PersistentVolumeAccessMode) *v1.PersistentVolumeClaim { + claim := v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "dummy", Namespace: "default", }, - Spec: api.PersistentVolumeClaimSpec{ + Spec: v1.PersistentVolumeClaimSpec{ AccessModes: accessModes, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(capacity), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(capacity), }, }, }, diff --git a/pkg/volume/util.go b/pkg/volume/util.go index 04387729333..b9879b92807 100644 --- a/pkg/volume/util.go +++ b/pkg/volume/util.go @@ -20,8 +20,8 @@ import ( "fmt" "reflect" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/watch" @@ -51,13 +51,13 @@ type RecycleEventRecorder func(eventtype, message string) // pod - the pod designed by a volume plugin to recycle the volume. pod.Name // will be overwritten with unique name based on PV.Name. // client - kube client for API operations. -func RecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *api.Pod, kubeClient clientset.Interface, recorder RecycleEventRecorder) error { +func RecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *v1.Pod, kubeClient clientset.Interface, recorder RecycleEventRecorder) error { return internalRecycleVolumeByWatchingPodUntilCompletion(pvName, pod, newRecyclerClient(kubeClient, recorder)) } // same as above func comments, except 'recyclerClient' is a narrower pod API // interface to ease testing -func internalRecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *api.Pod, recyclerClient recyclerClient) error { +func internalRecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *v1.Pod, recyclerClient recyclerClient) error { glog.V(5).Infof("creating recycler pod for volume %s\n", pod.Name) // Generate unique name for the recycler pod - we need to get "already @@ -83,7 +83,7 @@ func internalRecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *api.P return fmt.Errorf("unexpected error creating recycler pod: %+v\n", err) } } - defer func(pod *api.Pod) { + defer func(pod *v1.Pod) { glog.V(2).Infof("deleting recycler pod %s/%s", pod.Namespace, pod.Name) if err := recyclerClient.DeletePod(pod.Name, pod.Namespace); err != nil { glog.Errorf("failed to delete recycler pod %s/%s: %v", pod.Namespace, pod.Name, err) @@ -95,17 +95,17 @@ func internalRecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *api.P for { event := <-podCh switch event.Object.(type) { - case *api.Pod: + case *v1.Pod: // POD changed - pod := event.Object.(*api.Pod) + pod := event.Object.(*v1.Pod) glog.V(4).Infof("recycler pod update received: %s %s/%s %s", event.Type, pod.Namespace, pod.Name, pod.Status.Phase) switch event.Type { case watch.Added, watch.Modified: - if pod.Status.Phase == api.PodSucceeded { + if pod.Status.Phase == v1.PodSucceeded { // Recycle succeeded. return nil } - if pod.Status.Phase == api.PodFailed { + if pod.Status.Phase == v1.PodFailed { if pod.Status.Message != "" { return fmt.Errorf(pod.Status.Message) } else { @@ -120,9 +120,9 @@ func internalRecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *api.P return fmt.Errorf("recycler pod watcher failed") } - case *api.Event: + case *v1.Event: // Event received - podEvent := event.Object.(*api.Event) + podEvent := event.Object.(*v1.Event) glog.V(4).Infof("recycler event received: %s %s/%s %s/%s %s", event.Type, podEvent.Namespace, podEvent.Name, podEvent.InvolvedObject.Namespace, podEvent.InvolvedObject.Name, podEvent.Message) if event.Type == watch.Added { recyclerClient.Event(podEvent.Type, podEvent.Message) @@ -134,8 +134,8 @@ func internalRecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *api.P // recyclerClient abstracts access to a Pod by providing a narrower interface. // This makes it easier to mock a client for testing. type recyclerClient interface { - CreatePod(pod *api.Pod) (*api.Pod, error) - GetPod(name, namespace string) (*api.Pod, error) + CreatePod(pod *v1.Pod) (*v1.Pod, error) + GetPod(name, namespace string) (*v1.Pod, error) DeletePod(name, namespace string) error // WatchPod returns a ListWatch for watching a pod. The stopChannel is used // to close the reflector backing the watch. The caller is responsible for @@ -157,11 +157,11 @@ type realRecyclerClient struct { recorder RecycleEventRecorder } -func (c *realRecyclerClient) CreatePod(pod *api.Pod) (*api.Pod, error) { +func (c *realRecyclerClient) CreatePod(pod *v1.Pod) (*v1.Pod, error) { return c.client.Core().Pods(pod.Namespace).Create(pod) } -func (c *realRecyclerClient) GetPod(name, namespace string) (*api.Pod, error) { +func (c *realRecyclerClient) GetPod(name, namespace string) (*v1.Pod, error) { return c.client.Core().Pods(namespace).Get(name) } @@ -175,8 +175,8 @@ func (c *realRecyclerClient) Event(eventtype, message string) { func (c *realRecyclerClient) WatchPod(name, namespace string, stopChannel chan struct{}) (<-chan watch.Event, error) { podSelector, _ := fields.ParseSelector("metadata.name=" + name) - options := api.ListOptions{ - FieldSelector: podSelector, + options := v1.ListOptions{ + FieldSelector: podSelector.String(), Watch: true, } @@ -186,8 +186,8 @@ func (c *realRecyclerClient) WatchPod(name, namespace string, stopChannel chan s } eventSelector, _ := fields.ParseSelector("involvedObject.name=" + name) - eventWatch, err := c.client.Core().Events(namespace).Watch(api.ListOptions{ - FieldSelector: eventSelector, + eventWatch, err := c.client.Core().Events(namespace).Watch(v1.ListOptions{ + FieldSelector: eventSelector.String(), Watch: true, }) if err != nil { @@ -229,9 +229,9 @@ func (c *realRecyclerClient) WatchPod(name, namespace string, stopChannel chan s // recycle operation. The calculation and return value is either the // minimumTimeout or the timeoutIncrement per Gi of storage size, whichever is // greater. -func CalculateTimeoutForVolume(minimumTimeout, timeoutIncrement int, pv *api.PersistentVolume) int64 { +func CalculateTimeoutForVolume(minimumTimeout, timeoutIncrement int, pv *v1.PersistentVolume) int64 { giQty := resource.MustParse("1Gi") - pvQty := pv.Spec.Capacity[api.ResourceStorage] + pvQty := pv.Spec.Capacity[v1.ResourceStorage] giSize := giQty.Value() pvSize := pvQty.Value() timeout := (pvSize / giSize) * int64(timeoutIncrement) diff --git a/pkg/volume/util/BUILD b/pkg/volume/util/BUILD index 5e82b4ff49a..97203bf3996 100644 --- a/pkg/volume/util/BUILD +++ b/pkg/volume/util/BUILD @@ -23,10 +23,10 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", - "//pkg/apis/storage:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/storage/v1beta1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/util/mount:go_default_library", "//pkg/util/sets:go_default_library", "//vendor:github.com/golang/glog", diff --git a/pkg/volume/util/nestedpendingoperations/BUILD b/pkg/volume/util/nestedpendingoperations/BUILD index b633f98fa5f..92587a9e343 100644 --- a/pkg/volume/util/nestedpendingoperations/BUILD +++ b/pkg/volume/util/nestedpendingoperations/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["nestedpendingoperations.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/util/goroutinemap/exponentialbackoff:go_default_library", "//pkg/util/runtime:go_default_library", "//pkg/volume/util/types:go_default_library", @@ -29,7 +29,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/util/wait:go_default_library", "//pkg/volume/util/types:go_default_library", ], diff --git a/pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go b/pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go index c992f84b051..16600945246 100644 --- a/pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go +++ b/pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go @@ -29,7 +29,7 @@ import ( "sync" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/goroutinemap/exponentialbackoff" k8sRuntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/volume/util/types" @@ -40,7 +40,7 @@ const ( emptyUniquePodName types.UniquePodName = types.UniquePodName("") // emptyUniqueVolumeName is a UniqueVolumeName for empty string - emptyUniqueVolumeName api.UniqueVolumeName = api.UniqueVolumeName("") + emptyUniqueVolumeName v1.UniqueVolumeName = v1.UniqueVolumeName("") ) // NestedPendingOperations defines the supported set of operations. @@ -55,7 +55,7 @@ type NestedPendingOperations interface { // concatenation of volumeName and podName is removed from the list of // executing operations allowing a new operation to be started with the // volumeName without error. - Run(volumeName api.UniqueVolumeName, podName types.UniquePodName, operationFunc func() error) error + Run(volumeName v1.UniqueVolumeName, podName types.UniquePodName, operationFunc func() error) error // Wait blocks until all operations are completed. This is typically // necessary during tests - the test should wait until all operations finish @@ -64,7 +64,7 @@ type NestedPendingOperations interface { // IsOperationPending returns true if an operation for the given volumeName and podName is pending, // otherwise it returns false - IsOperationPending(volumeName api.UniqueVolumeName, podName types.UniquePodName) bool + IsOperationPending(volumeName v1.UniqueVolumeName, podName types.UniquePodName) bool } // NewNestedPendingOperations returns a new instance of NestedPendingOperations. @@ -85,14 +85,14 @@ type nestedPendingOperations struct { } type operation struct { - volumeName api.UniqueVolumeName + volumeName v1.UniqueVolumeName podName types.UniquePodName operationPending bool expBackoff exponentialbackoff.ExponentialBackoff } func (grm *nestedPendingOperations) Run( - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, podName types.UniquePodName, operationFunc func() error) error { grm.lock.Lock() @@ -141,7 +141,7 @@ func (grm *nestedPendingOperations) Run( } func (grm *nestedPendingOperations) IsOperationPending( - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, podName types.UniquePodName) bool { grm.lock.RLock() @@ -156,7 +156,7 @@ func (grm *nestedPendingOperations) IsOperationPending( // This is an internal function and caller should acquire and release the lock func (grm *nestedPendingOperations) isOperationExists( - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, podName types.UniquePodName) (bool, int) { // If volumeName is empty, operation can be executed concurrently @@ -184,7 +184,7 @@ func (grm *nestedPendingOperations) isOperationExists( } func (grm *nestedPendingOperations) getOperation( - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, podName types.UniquePodName) (uint, error) { // Assumes lock has been acquired by caller. @@ -201,7 +201,7 @@ func (grm *nestedPendingOperations) getOperation( func (grm *nestedPendingOperations) deleteOperation( // Assumes lock has been acquired by caller. - volumeName api.UniqueVolumeName, + volumeName v1.UniqueVolumeName, podName types.UniquePodName) { opIndex := -1 @@ -219,7 +219,7 @@ func (grm *nestedPendingOperations) deleteOperation( } func (grm *nestedPendingOperations) operationComplete( - volumeName api.UniqueVolumeName, podName types.UniquePodName, err *error) { + volumeName v1.UniqueVolumeName, podName types.UniquePodName, err *error) { // Defer operations are executed in Last-In is First-Out order. In this case // the lock is acquired first when operationCompletes begins, and is // released when the method finishes, after the lock is released cond is @@ -272,7 +272,7 @@ func (grm *nestedPendingOperations) Wait() { } func getOperationName( - volumeName api.UniqueVolumeName, podName types.UniquePodName) string { + volumeName v1.UniqueVolumeName, podName types.UniquePodName) string { podNameStr := "" if podName != emptyUniquePodName { podNameStr = fmt.Sprintf(" (%q)", podName) diff --git a/pkg/volume/util/nestedpendingoperations/nestedpendingoperations_test.go b/pkg/volume/util/nestedpendingoperations/nestedpendingoperations_test.go index 3181e616960..fb7592c619b 100644 --- a/pkg/volume/util/nestedpendingoperations/nestedpendingoperations_test.go +++ b/pkg/volume/util/nestedpendingoperations/nestedpendingoperations_test.go @@ -21,7 +21,7 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/volume/util/types" ) @@ -46,7 +46,7 @@ const ( func Test_NewGoRoutineMap_Positive_SingleOp(t *testing.T) { // Arrange grm := NewNestedPendingOperations(false /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation := func() error { return nil } // Act @@ -61,8 +61,8 @@ func Test_NewGoRoutineMap_Positive_SingleOp(t *testing.T) { func Test_NewGoRoutineMap_Positive_TwoOps(t *testing.T) { // Arrange grm := NewNestedPendingOperations(false /* exponentialBackOffOnError */) - volume1Name := api.UniqueVolumeName("volume1-name") - volume2Name := api.UniqueVolumeName("volume2-name") + volume1Name := v1.UniqueVolumeName("volume1-name") + volume2Name := v1.UniqueVolumeName("volume2-name") operation := func() error { return nil } // Act @@ -82,7 +82,7 @@ func Test_NewGoRoutineMap_Positive_TwoOps(t *testing.T) { func Test_NewGoRoutineMap_Positive_TwoSubOps(t *testing.T) { // Arrange grm := NewNestedPendingOperations(false /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation1PodName := types.UniquePodName("operation1-podname") operation2PodName := types.UniquePodName("operation2-podname") operation := func() error { return nil } @@ -104,7 +104,7 @@ func Test_NewGoRoutineMap_Positive_TwoSubOps(t *testing.T) { func Test_NewGoRoutineMap_Positive_SingleOpWithExpBackoff(t *testing.T) { // Arrange grm := NewNestedPendingOperations(true /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation := func() error { return nil } // Act @@ -119,7 +119,7 @@ func Test_NewGoRoutineMap_Positive_SingleOpWithExpBackoff(t *testing.T) { func Test_NewGoRoutineMap_Positive_SecondOpAfterFirstCompletes(t *testing.T) { // Arrange grm := NewNestedPendingOperations(false /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation1DoneCh := make(chan interface{}, 0 /* bufferSize */) operation1 := generateCallbackFunc(operation1DoneCh) err1 := grm.Run(volumeName, "" /* operationSubName */, operation1) @@ -151,7 +151,7 @@ func Test_NewGoRoutineMap_Positive_SecondOpAfterFirstCompletes(t *testing.T) { func Test_NewGoRoutineMap_Positive_SecondOpAfterFirstCompletesWithExpBackoff(t *testing.T) { // Arrange grm := NewNestedPendingOperations(true /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation1DoneCh := make(chan interface{}, 0 /* bufferSize */) operation1 := generateCallbackFunc(operation1DoneCh) err1 := grm.Run(volumeName, "" /* operationSubName */, operation1) @@ -183,7 +183,7 @@ func Test_NewGoRoutineMap_Positive_SecondOpAfterFirstCompletesWithExpBackoff(t * func Test_NewGoRoutineMap_Positive_SecondOpAfterFirstPanics(t *testing.T) { // Arrange grm := NewNestedPendingOperations(false /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation1 := generatePanicFunc() err1 := grm.Run(volumeName, "" /* operationSubName */, operation1) if err1 != nil { @@ -213,7 +213,7 @@ func Test_NewGoRoutineMap_Positive_SecondOpAfterFirstPanics(t *testing.T) { func Test_NewGoRoutineMap_Positive_SecondOpAfterFirstPanicsWithExpBackoff(t *testing.T) { // Arrange grm := NewNestedPendingOperations(true /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation1 := generatePanicFunc() err1 := grm.Run(volumeName, "" /* operationSubName */, operation1) if err1 != nil { @@ -243,7 +243,7 @@ func Test_NewGoRoutineMap_Positive_SecondOpAfterFirstPanicsWithExpBackoff(t *tes func Test_NewGoRoutineMap_Negative_SecondOpBeforeFirstCompletes(t *testing.T) { // Arrange grm := NewNestedPendingOperations(false /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation1DoneCh := make(chan interface{}, 0 /* bufferSize */) operation1 := generateWaitFunc(operation1DoneCh) err1 := grm.Run(volumeName, "" /* operationSubName */, operation1) @@ -267,7 +267,7 @@ func Test_NewGoRoutineMap_Negative_SecondOpBeforeFirstCompletes(t *testing.T) { func Test_NewGoRoutineMap_Negative_SecondSubOpBeforeFirstCompletes2(t *testing.T) { // Arrange grm := NewNestedPendingOperations(false /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operationPodName := types.UniquePodName("operation-podname") operation1DoneCh := make(chan interface{}, 0 /* bufferSize */) operation1 := generateWaitFunc(operation1DoneCh) @@ -292,7 +292,7 @@ func Test_NewGoRoutineMap_Negative_SecondSubOpBeforeFirstCompletes2(t *testing.T func Test_NewGoRoutineMap_Negative_SecondSubOpBeforeFirstCompletes(t *testing.T) { // Arrange grm := NewNestedPendingOperations(false /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operationPodName := types.UniquePodName("operation-podname") operation1DoneCh := make(chan interface{}, 0 /* bufferSize */) operation1 := generateWaitFunc(operation1DoneCh) @@ -317,7 +317,7 @@ func Test_NewGoRoutineMap_Negative_SecondSubOpBeforeFirstCompletes(t *testing.T) func Test_NewGoRoutineMap_Negative_SecondOpBeforeFirstCompletesWithExpBackoff(t *testing.T) { // Arrange grm := NewNestedPendingOperations(true /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation1DoneCh := make(chan interface{}, 0 /* bufferSize */) operation1 := generateWaitFunc(operation1DoneCh) err1 := grm.Run(volumeName, "" /* operationSubName */, operation1) @@ -341,7 +341,7 @@ func Test_NewGoRoutineMap_Negative_SecondOpBeforeFirstCompletesWithExpBackoff(t func Test_NewGoRoutineMap_Positive_ThirdOpAfterFirstCompletes(t *testing.T) { // Arrange grm := NewNestedPendingOperations(false /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation1DoneCh := make(chan interface{}, 0 /* bufferSize */) operation1 := generateWaitFunc(operation1DoneCh) err1 := grm.Run(volumeName, "" /* operationSubName */, operation1) @@ -385,7 +385,7 @@ func Test_NewGoRoutineMap_Positive_ThirdOpAfterFirstCompletes(t *testing.T) { func Test_NewGoRoutineMap_Positive_ThirdOpAfterFirstCompletesWithExpBackoff(t *testing.T) { // Arrange grm := NewNestedPendingOperations(true /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation1DoneCh := make(chan interface{}, 0 /* bufferSize */) operation1 := generateWaitFunc(operation1DoneCh) err1 := grm.Run(volumeName, "" /* operationSubName */, operation1) @@ -468,7 +468,7 @@ func Test_NewGoRoutineMap_Positive_Wait(t *testing.T) { // Test that Wait() really blocks until the last operation succeeds // Arrange grm := NewNestedPendingOperations(false /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation1DoneCh := make(chan interface{}, 0 /* bufferSize */) operation1 := generateWaitFunc(operation1DoneCh) err := grm.Run(volumeName, "" /* operationSubName */, operation1) @@ -497,7 +497,7 @@ func Test_NewGoRoutineMap_Positive_WaitWithExpBackoff(t *testing.T) { // Test that Wait() really blocks until the last operation succeeds // Arrange grm := NewNestedPendingOperations(true /* exponentialBackOffOnError */) - volumeName := api.UniqueVolumeName("volume-name") + volumeName := v1.UniqueVolumeName("volume-name") operation1DoneCh := make(chan interface{}, 0 /* bufferSize */) operation1 := generateWaitFunc(operation1DoneCh) err := grm.Run(volumeName, "" /* operationSubName */, operation1) diff --git a/pkg/volume/util/operationexecutor/BUILD b/pkg/volume/util/operationexecutor/BUILD index e708f1b1891..bf78667e35a 100644 --- a/pkg/volume/util/operationexecutor/BUILD +++ b/pkg/volume/util/operationexecutor/BUILD @@ -15,9 +15,9 @@ go_library( srcs = ["operation_executor.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/record:go_default_library", "//pkg/kubelet/events:go_default_library", "//pkg/types:go_default_library", diff --git a/pkg/volume/util/operationexecutor/operation_executor.go b/pkg/volume/util/operationexecutor/operation_executor.go index 15c425cbfd8..96922444fff 100644 --- a/pkg/volume/util/operationexecutor/operation_executor.go +++ b/pkg/volume/util/operationexecutor/operation_executor.go @@ -25,9 +25,9 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/record" kevents "k8s.io/kubernetes/pkg/kubelet/events" "k8s.io/kubernetes/pkg/types" @@ -112,12 +112,12 @@ type OperationExecutor interface { // IsOperationPending returns true if an operation for the given volumeName and podName is pending, // otherwise it returns false - IsOperationPending(volumeName api.UniqueVolumeName, podName volumetypes.UniquePodName) bool + IsOperationPending(volumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName) bool } // NewOperationExecutor returns a new instance of OperationExecutor. func NewOperationExecutor( - kubeClient internalclientset.Interface, + kubeClient clientset.Interface, volumePluginMgr *volume.VolumePluginMgr, recorder record.EventRecorder, checkNodeCapabilitiesBeforeMount bool) OperationExecutor { @@ -136,16 +136,16 @@ func NewOperationExecutor( // state of the world cache after successful mount/unmount. type ActualStateOfWorldMounterUpdater interface { // Marks the specified volume as mounted to the specified pod - MarkVolumeAsMounted(podName volumetypes.UniquePodName, podUID types.UID, volumeName api.UniqueVolumeName, mounter volume.Mounter, outerVolumeSpecName string, volumeGidValue string) error + MarkVolumeAsMounted(podName volumetypes.UniquePodName, podUID types.UID, volumeName v1.UniqueVolumeName, mounter volume.Mounter, outerVolumeSpecName string, volumeGidValue string) error // Marks the specified volume as unmounted from the specified pod - MarkVolumeAsUnmounted(podName volumetypes.UniquePodName, volumeName api.UniqueVolumeName) error + MarkVolumeAsUnmounted(podName volumetypes.UniquePodName, volumeName v1.UniqueVolumeName) error // Marks the specified volume as having been globally mounted. - MarkDeviceAsMounted(volumeName api.UniqueVolumeName) error + MarkDeviceAsMounted(volumeName v1.UniqueVolumeName) error // Marks the specified volume as having its global mount unmounted. - MarkDeviceAsUnmounted(volumeName api.UniqueVolumeName) error + MarkDeviceAsUnmounted(volumeName v1.UniqueVolumeName) error } // ActualStateOfWorldAttacherUpdater defines a set of operations updating the @@ -158,25 +158,25 @@ type ActualStateOfWorldAttacherUpdater interface { // TODO: in the future, we should be able to remove the volumeName // argument to this method -- since it is used only for attachable // volumes. See issue 29695. - MarkVolumeAsAttached(volumeName api.UniqueVolumeName, volumeSpec *volume.Spec, nodeName types.NodeName, devicePath string) error + MarkVolumeAsAttached(volumeName v1.UniqueVolumeName, volumeSpec *volume.Spec, nodeName types.NodeName, devicePath string) error // Marks the specified volume as detached from the specified node - MarkVolumeAsDetached(volumeName api.UniqueVolumeName, nodeName types.NodeName) + MarkVolumeAsDetached(volumeName v1.UniqueVolumeName, nodeName types.NodeName) // Marks desire to detach the specified volume (remove the volume from the node's // volumesToReportedAsAttached list) - RemoveVolumeFromReportAsAttached(volumeName api.UniqueVolumeName, nodeName types.NodeName) error + RemoveVolumeFromReportAsAttached(volumeName v1.UniqueVolumeName, nodeName types.NodeName) error // Unmarks the desire to detach for the specified volume (add the volume back to // the node's volumesToReportedAsAttached list) - AddVolumeToReportAsAttached(volumeName api.UniqueVolumeName, nodeName types.NodeName) + AddVolumeToReportAsAttached(volumeName v1.UniqueVolumeName, nodeName types.NodeName) } // VolumeToAttach represents a volume that should be attached to a node. type VolumeToAttach struct { // VolumeName is the unique identifier for the volume that should be // attached. - VolumeName api.UniqueVolumeName + VolumeName v1.UniqueVolumeName // VolumeSpec is a volume spec containing the specification for the volume // that should be attached. @@ -190,7 +190,7 @@ type VolumeToAttach struct { // volume and are scheduled to the underlying node. The key in the map is // the name of the pod and the value is a pod object containing more // information about the pod. - ScheduledPods []*api.Pod + ScheduledPods []*v1.Pod } // VolumeToMount represents a volume that should be attached to this node and @@ -198,7 +198,7 @@ type VolumeToAttach struct { type VolumeToMount struct { // VolumeName is the unique identifier for the volume that should be // mounted. - VolumeName api.UniqueVolumeName + VolumeName v1.UniqueVolumeName // PodName is the unique identifier for the pod that the volume should be // mounted to after it is attached. @@ -215,7 +215,7 @@ type VolumeToMount struct { OuterVolumeSpecName string // Pod to mount the volume to. Used to create NewMounter. - Pod *api.Pod + Pod *v1.Pod // PluginIsAttachable indicates that the plugin for this volume implements // the volume.Attacher interface @@ -236,7 +236,7 @@ type VolumeToMount struct { // AttachedVolume represents a volume that is attached to a node. type AttachedVolume struct { // VolumeName is the unique identifier for the volume that is attached. - VolumeName api.UniqueVolumeName + VolumeName v1.UniqueVolumeName // VolumeSpec is the volume spec containing the specification for the // volume that is attached. @@ -260,7 +260,7 @@ type MountedVolume struct { PodName volumetypes.UniquePodName // VolumeName is the unique identifier of the volume mounted to the pod. - VolumeName api.UniqueVolumeName + VolumeName v1.UniqueVolumeName // InnerVolumeSpecName is the volume.Spec.Name() of the volume. If the // volume was referenced through a persistent volume claims, this contains @@ -361,7 +361,7 @@ type MountedVolume struct { type operationExecutor struct { // Used to fetch objects from the API server like Node in the // VerifyControllerAttachedVolume operation. - kubeClient internalclientset.Interface + kubeClient clientset.Interface // volumePluginMgr is the volume plugin manager used to create volume // plugin objects. @@ -380,7 +380,7 @@ type operationExecutor struct { checkNodeCapabilitiesBeforeMount bool } -func (oe *operationExecutor) IsOperationPending(volumeName api.UniqueVolumeName, podName volumetypes.UniquePodName) bool { +func (oe *operationExecutor) IsOperationPending(volumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName) bool { return oe.pendingOperations.IsOperationPending(volumeName, podName) } @@ -502,7 +502,7 @@ func (oe *operationExecutor) generateVolumesAreAttachedFunc( volumesPerPlugin := make(map[string][]*volume.Spec) // volumeSpecMap maps from a volume spec to its unique volumeName which will be used // when calling MarkVolumeAsDetached - volumeSpecMap := make(map[*volume.Spec]api.UniqueVolumeName) + volumeSpecMap := make(map[*volume.Spec]v1.UniqueVolumeName) // Iterate each volume spec and put them into a map index by the pluginName for _, volumeAttached := range attachedVolumes { volumePlugin, err := @@ -607,7 +607,7 @@ func (oe *operationExecutor) generateAttachVolumeFunc( volumeToAttach.NodeName, attachErr) for _, pod := range volumeToAttach.ScheduledPods { - oe.recorder.Eventf(pod, api.EventTypeWarning, kevents.FailedMountVolume, err.Error()) + oe.recorder.Eventf(pod, v1.EventTypeWarning, kevents.FailedMountVolume, err.Error()) } return err } @@ -620,7 +620,7 @@ func (oe *operationExecutor) generateAttachVolumeFunc( // Update actual state of world addVolumeNodeErr := actualStateOfWorld.MarkVolumeAsAttached( - api.UniqueVolumeName(""), volumeToAttach.VolumeSpec, volumeToAttach.NodeName, devicePath) + v1.UniqueVolumeName(""), volumeToAttach.VolumeSpec, volumeToAttach.NodeName, devicePath) if addVolumeNodeErr != nil { // On failure, return error. Caller will log and retry. return fmt.Errorf( @@ -857,7 +857,7 @@ func (oe *operationExecutor) generateMountVolumeFunc( volumeToMount.PodName, volumeToMount.Pod.UID, err) - oe.recorder.Eventf(volumeToMount.Pod, api.EventTypeWarning, kevents.FailedMountVolume, err.Error()) + oe.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FailedMountVolume, err.Error()) return err } @@ -887,7 +887,7 @@ func (oe *operationExecutor) generateMountVolumeFunc( if oe.checkNodeCapabilitiesBeforeMount { if canMountErr := volumeMounter.CanMount(); canMountErr != nil { errMsg := fmt.Sprintf("Unable to mount volume %v (spec.Name: %v) on pod %v (UID: %v). Verify that your node machine has the required components before attempting to mount this volume type. %s", volumeToMount.VolumeName, volumeToMount.VolumeSpec.Name(), volumeToMount.Pod.Name, volumeToMount.Pod.UID, canMountErr.Error()) - oe.recorder.Eventf(volumeToMount.Pod, api.EventTypeWarning, kevents.FailedMountVolume, errMsg) + oe.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FailedMountVolume, errMsg) glog.Errorf(errMsg) return fmt.Errorf(errMsg) } @@ -904,7 +904,7 @@ func (oe *operationExecutor) generateMountVolumeFunc( volumeToMount.PodName, volumeToMount.Pod.UID, mountErr) - oe.recorder.Eventf(volumeToMount.Pod, api.EventTypeWarning, kevents.FailedMountVolume, err.Error()) + oe.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FailedMountVolume, err.Error()) return err } @@ -1190,7 +1190,7 @@ func (oe *operationExecutor) generateVerifyControllerAttachedVolumeFunc( for _, attachedVolume := range node.Status.VolumesAttached { if attachedVolume.Name == volumeToMount.VolumeName { addVolumeNodeErr := actualStateOfWorld.MarkVolumeAsAttached( - api.UniqueVolumeName(""), volumeToMount.VolumeSpec, nodeName, attachedVolume.DevicePath) + v1.UniqueVolumeName(""), volumeToMount.VolumeSpec, nodeName, attachedVolume.DevicePath) glog.Infof("Controller successfully attached volume %q (spec.Name: %q) pod %q (UID: %q) devicePath: %q", volumeToMount.VolumeName, volumeToMount.VolumeSpec.Name(), diff --git a/pkg/volume/util/util.go b/pkg/volume/util/util.go index 8b67c5d2f77..cc5c25d41a7 100644 --- a/pkg/volume/util/util.go +++ b/pkg/volume/util/util.go @@ -22,9 +22,9 @@ import ( "path" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/storage" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/util/mount" ) @@ -113,7 +113,7 @@ func PathExists(path string) (bool, error) { } // GetSecretForPod locates secret by name in the pod's namespace and returns secret map -func GetSecretForPod(pod *api.Pod, secretName string, kubeClient clientset.Interface) (map[string]string, error) { +func GetSecretForPod(pod *v1.Pod, secretName string, kubeClient clientset.Interface) (map[string]string, error) { secret := make(map[string]string) if kubeClient == nil { return secret, fmt.Errorf("Cannot get kube client") @@ -138,7 +138,7 @@ func GetSecretForPV(secretNamespace, secretName, volumePluginName string, kubeCl if err != nil { return secret, err } - if secrets.Type != api.SecretType(volumePluginName) { + if secrets.Type != v1.SecretType(volumePluginName) { return secret, fmt.Errorf("Cannot get secret of type %s", volumePluginName) } for name, data := range secrets.Data { @@ -147,7 +147,7 @@ func GetSecretForPV(secretNamespace, secretName, volumePluginName string, kubeCl return secret, nil } -func GetClassForVolume(kubeClient clientset.Interface, pv *api.PersistentVolume) (*storage.StorageClass, error) { +func GetClassForVolume(kubeClient clientset.Interface, pv *v1.PersistentVolume) (*storage.StorageClass, error) { // TODO: replace with a real attribute after beta className, found := pv.Annotations["volume.beta.kubernetes.io/storage-class"] if !found { diff --git a/pkg/volume/util/volumehelper/BUILD b/pkg/volume/util/volumehelper/BUILD index 954c262cbc2..d12ebd25284 100644 --- a/pkg/volume/util/volumehelper/BUILD +++ b/pkg/volume/util/volumehelper/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["volumehelper.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/volume:go_default_library", "//pkg/volume/util/types:go_default_library", ], diff --git a/pkg/volume/util/volumehelper/volumehelper.go b/pkg/volume/util/volumehelper/volumehelper.go index 386daa1f3f6..7c51b7ed538 100644 --- a/pkg/volume/util/volumehelper/volumehelper.go +++ b/pkg/volume/util/volumehelper/volumehelper.go @@ -21,7 +21,7 @@ package volumehelper import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/util/types" ) @@ -38,7 +38,7 @@ const ( ) // GetUniquePodName returns a unique identifier to reference a pod by -func GetUniquePodName(pod *api.Pod) types.UniquePodName { +func GetUniquePodName(pod *v1.Pod) types.UniquePodName { return types.UniquePodName(pod.UID) } @@ -48,15 +48,15 @@ func GetUniquePodName(pod *api.Pod) types.UniquePodName { // The returned name can be used to uniquely reference the volume, for example, // to prevent operations (attach/detach or mount/unmount) from being triggered // on the same volume. -func GetUniqueVolumeName(pluginName, volumeName string) api.UniqueVolumeName { - return api.UniqueVolumeName(fmt.Sprintf("%s/%s", pluginName, volumeName)) +func GetUniqueVolumeName(pluginName, volumeName string) v1.UniqueVolumeName { + return v1.UniqueVolumeName(fmt.Sprintf("%s/%s", pluginName, volumeName)) } // GetUniqueVolumeNameForNonAttachableVolume returns the unique volume name // for a non-attachable volume. func GetUniqueVolumeNameForNonAttachableVolume( - podName types.UniquePodName, volumePlugin volume.VolumePlugin, volumeSpec *volume.Spec) api.UniqueVolumeName { - return api.UniqueVolumeName( + podName types.UniquePodName, volumePlugin volume.VolumePlugin, volumeSpec *volume.Spec) v1.UniqueVolumeName { + return v1.UniqueVolumeName( fmt.Sprintf("%s/%v-%s", volumePlugin.GetPluginName(), podName, volumeSpec.Name())) } @@ -67,7 +67,7 @@ func GetUniqueVolumeNameForNonAttachableVolume( // If the given plugin does not support the volume spec, this returns an error. func GetUniqueVolumeNameFromSpec( volumePlugin volume.VolumePlugin, - volumeSpec *volume.Spec) (api.UniqueVolumeName, error) { + volumeSpec *volume.Spec) (v1.UniqueVolumeName, error) { if volumePlugin == nil { return "", fmt.Errorf( "volumePlugin should not be nil. volumeSpec.Name=%q", diff --git a/pkg/volume/util_test.go b/pkg/volume/util_test.go index 4fd71f373e5..bb8ccfd1308 100644 --- a/pkg/volume/util_test.go +++ b/pkg/volume/util_test.go @@ -24,14 +24,15 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/watch" ) type testcase struct { // Input of the test name string - existingPod *api.Pod - createPod *api.Pod + existingPod *v1.Pod + createPod *v1.Pod // eventSequence is list of events that are simulated during recycling. It // can be either event generated by a recycler pod or a state change of // the pod. (see newPodEvent and newEvent below). @@ -44,7 +45,7 @@ type testcase struct { expectedError string } -func newPodEvent(eventtype watch.EventType, name string, phase api.PodPhase, message string) watch.Event { +func newPodEvent(eventtype watch.EventType, name string, phase v1.PodPhase, message string) watch.Event { return watch.Event{ Type: eventtype, Object: newPod(name, phase, message), @@ -54,9 +55,9 @@ func newPodEvent(eventtype watch.EventType, name string, phase api.PodPhase, mes func newEvent(eventtype, message string) watch.Event { return watch.Event{ Type: watch.Added, - Object: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Namespace: api.NamespaceDefault, + Object: &v1.Event{ + ObjectMeta: v1.ObjectMeta{ + Namespace: v1.NamespaceDefault, }, Reason: "MockEvent", Message: message, @@ -65,13 +66,13 @@ func newEvent(eventtype, message string) watch.Event { } } -func newPod(name string, phase api.PodPhase, message string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Namespace: api.NamespaceDefault, +func newPod(name string, phase v1.PodPhase, message string) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ + Namespace: v1.NamespaceDefault, Name: name, }, - Status: api.PodStatus{ + Status: v1.PodStatus{ Phase: phase, Message: message, }, @@ -83,70 +84,70 @@ func TestRecyclerPod(t *testing.T) { { // Test recycler success with some events name: "RecyclerSuccess", - createPod: newPod("podRecyclerSuccess", api.PodPending, ""), + createPod: newPod("podRecyclerSuccess", v1.PodPending, ""), eventSequence: []watch.Event{ // Pod gets Running and Succeeded - newPodEvent(watch.Added, "podRecyclerSuccess", api.PodPending, ""), - newEvent(api.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerSuccess to 127.0.0.1"), - newEvent(api.EventTypeNormal, "pulling image \"gcr.io/google_containers/busybox\""), - newEvent(api.EventTypeNormal, "Successfully pulled image \"gcr.io/google_containers/busybox\""), - newEvent(api.EventTypeNormal, "Created container with docker id 83d929aeac82"), - newEvent(api.EventTypeNormal, "Started container with docker id 83d929aeac82"), - newPodEvent(watch.Modified, "podRecyclerSuccess", api.PodRunning, ""), - newPodEvent(watch.Modified, "podRecyclerSuccess", api.PodSucceeded, ""), + newPodEvent(watch.Added, "podRecyclerSuccess", v1.PodPending, ""), + newEvent(v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerSuccess to 127.0.0.1"), + newEvent(v1.EventTypeNormal, "pulling image \"gcr.io/google_containers/busybox\""), + newEvent(v1.EventTypeNormal, "Successfully pulled image \"gcr.io/google_containers/busybox\""), + newEvent(v1.EventTypeNormal, "Created container with docker id 83d929aeac82"), + newEvent(v1.EventTypeNormal, "Started container with docker id 83d929aeac82"), + newPodEvent(watch.Modified, "podRecyclerSuccess", v1.PodRunning, ""), + newPodEvent(watch.Modified, "podRecyclerSuccess", v1.PodSucceeded, ""), }, expectedEvents: []mockEvent{ - {api.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerSuccess to 127.0.0.1"}, - {api.EventTypeNormal, "pulling image \"gcr.io/google_containers/busybox\""}, - {api.EventTypeNormal, "Successfully pulled image \"gcr.io/google_containers/busybox\""}, - {api.EventTypeNormal, "Created container with docker id 83d929aeac82"}, - {api.EventTypeNormal, "Started container with docker id 83d929aeac82"}, + {v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerSuccess to 127.0.0.1"}, + {v1.EventTypeNormal, "pulling image \"gcr.io/google_containers/busybox\""}, + {v1.EventTypeNormal, "Successfully pulled image \"gcr.io/google_containers/busybox\""}, + {v1.EventTypeNormal, "Created container with docker id 83d929aeac82"}, + {v1.EventTypeNormal, "Started container with docker id 83d929aeac82"}, }, expectedError: "", }, { // Test recycler failure with some events name: "RecyclerFailure", - createPod: newPod("podRecyclerFailure", api.PodPending, ""), + createPod: newPod("podRecyclerFailure", v1.PodPending, ""), eventSequence: []watch.Event{ // Pod gets Running and Succeeded - newPodEvent(watch.Added, "podRecyclerFailure", api.PodPending, ""), - newEvent(api.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerFailure to 127.0.0.1"), - newEvent(api.EventTypeWarning, "Unable to mount volumes for pod \"recycler-for-podRecyclerFailure_default(3c9809e5-347c-11e6-a79b-3c970e965218)\": timeout expired waiting for volumes to attach/mount"), - newEvent(api.EventTypeWarning, "Error syncing pod, skipping: timeout expired waiting for volumes to attach/mount for pod \"recycler-for-podRecyclerFailure\"/\"default\". list of unattached/unmounted"), - newPodEvent(watch.Modified, "podRecyclerFailure", api.PodRunning, ""), - newPodEvent(watch.Modified, "podRecyclerFailure", api.PodFailed, "Pod was active on the node longer than specified deadline"), + newPodEvent(watch.Added, "podRecyclerFailure", v1.PodPending, ""), + newEvent(v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerFailure to 127.0.0.1"), + newEvent(v1.EventTypeWarning, "Unable to mount volumes for pod \"recycler-for-podRecyclerFailure_default(3c9809e5-347c-11e6-a79b-3c970e965218)\": timeout expired waiting for volumes to attach/mount"), + newEvent(v1.EventTypeWarning, "Error syncing pod, skipping: timeout expired waiting for volumes to attach/mount for pod \"recycler-for-podRecyclerFailure\"/\"default\". list of unattached/unmounted"), + newPodEvent(watch.Modified, "podRecyclerFailure", v1.PodRunning, ""), + newPodEvent(watch.Modified, "podRecyclerFailure", v1.PodFailed, "Pod was active on the node longer than specified deadline"), }, expectedEvents: []mockEvent{ - {api.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerFailure to 127.0.0.1"}, - {api.EventTypeWarning, "Unable to mount volumes for pod \"recycler-for-podRecyclerFailure_default(3c9809e5-347c-11e6-a79b-3c970e965218)\": timeout expired waiting for volumes to attach/mount"}, - {api.EventTypeWarning, "Error syncing pod, skipping: timeout expired waiting for volumes to attach/mount for pod \"recycler-for-podRecyclerFailure\"/\"default\". list of unattached/unmounted"}, + {v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerFailure to 127.0.0.1"}, + {v1.EventTypeWarning, "Unable to mount volumes for pod \"recycler-for-podRecyclerFailure_default(3c9809e5-347c-11e6-a79b-3c970e965218)\": timeout expired waiting for volumes to attach/mount"}, + {v1.EventTypeWarning, "Error syncing pod, skipping: timeout expired waiting for volumes to attach/mount for pod \"recycler-for-podRecyclerFailure\"/\"default\". list of unattached/unmounted"}, }, expectedError: "Pod was active on the node longer than specified deadline", }, { // Recycler pod gets deleted name: "RecyclerDeleted", - createPod: newPod("podRecyclerDeleted", api.PodPending, ""), + createPod: newPod("podRecyclerDeleted", v1.PodPending, ""), eventSequence: []watch.Event{ // Pod gets Running and Succeeded - newPodEvent(watch.Added, "podRecyclerDeleted", api.PodPending, ""), - newEvent(api.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerDeleted to 127.0.0.1"), - newPodEvent(watch.Deleted, "podRecyclerDeleted", api.PodPending, ""), + newPodEvent(watch.Added, "podRecyclerDeleted", v1.PodPending, ""), + newEvent(v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerDeleted to 127.0.0.1"), + newPodEvent(watch.Deleted, "podRecyclerDeleted", v1.PodPending, ""), }, expectedEvents: []mockEvent{ - {api.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerDeleted to 127.0.0.1"}, + {v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerDeleted to 127.0.0.1"}, }, expectedError: "recycler pod was deleted", }, { // Another recycler pod is already running name: "RecyclerRunning", - existingPod: newPod("podOldRecycler", api.PodRunning, ""), - createPod: newPod("podNewRecycler", api.PodFailed, "mock message"), + existingPod: newPod("podOldRecycler", v1.PodRunning, ""), + createPod: newPod("podNewRecycler", v1.PodFailed, "mock message"), eventSequence: []watch.Event{ // Old pod succeeds - newPodEvent(watch.Modified, "podOldRecycler", api.PodSucceeded, ""), + newPodEvent(watch.Modified, "podOldRecycler", v1.PodSucceeded, ""), }, // No error = old pod succeeded. If the new pod was used, there // would be error with "mock message". @@ -155,11 +156,11 @@ func TestRecyclerPod(t *testing.T) { { // Another recycler pod is already running and fails name: "FailedRecyclerRunning", - existingPod: newPod("podOldRecycler", api.PodRunning, ""), - createPod: newPod("podNewRecycler", api.PodFailed, "mock message"), + existingPod: newPod("podOldRecycler", v1.PodRunning, ""), + createPod: newPod("podNewRecycler", v1.PodFailed, "mock message"), eventSequence: []watch.Event{ // Old pod failure - newPodEvent(watch.Modified, "podOldRecycler", api.PodFailed, "Pod was active on the node longer than specified deadline"), + newPodEvent(watch.Modified, "podOldRecycler", v1.PodFailed, "Pod was active on the node longer than specified deadline"), }, // If the new pod was used, there would be error with "mock message". expectedError: "Pod was active on the node longer than specified deadline", @@ -205,7 +206,7 @@ func TestRecyclerPod(t *testing.T) { } type mockRecyclerClient struct { - pod *api.Pod + pod *v1.Pod deletedCalled bool receivedEvents []mockEvent events []watch.Event @@ -215,7 +216,7 @@ type mockEvent struct { eventtype, message string } -func (c *mockRecyclerClient) CreatePod(pod *api.Pod) (*api.Pod, error) { +func (c *mockRecyclerClient) CreatePod(pod *v1.Pod) (*v1.Pod, error) { if c.pod == nil { c.pod = pod return c.pod, nil @@ -224,7 +225,7 @@ func (c *mockRecyclerClient) CreatePod(pod *api.Pod) (*api.Pod, error) { return nil, errors.NewAlreadyExists(api.Resource("pods"), pod.Name) } -func (c *mockRecyclerClient) GetPod(name, namespace string) (*api.Pod, error) { +func (c *mockRecyclerClient) GetPod(name, namespace string) (*v1.Pod, error) { if c.pod != nil { return c.pod, nil } else { @@ -252,10 +253,10 @@ func (c *mockRecyclerClient) Event(eventtype, message string) { } func TestCalculateTimeoutForVolume(t *testing.T) { - pv := &api.PersistentVolume{ - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("500M"), + pv := &v1.PersistentVolume{ + Spec: v1.PersistentVolumeSpec{ + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("500M"), }, }, } @@ -265,13 +266,13 @@ func TestCalculateTimeoutForVolume(t *testing.T) { t.Errorf("Expected 50 for timeout but got %v", timeout) } - pv.Spec.Capacity[api.ResourceStorage] = resource.MustParse("2Gi") + pv.Spec.Capacity[v1.ResourceStorage] = resource.MustParse("2Gi") timeout = CalculateTimeoutForVolume(50, 30, pv) if timeout != 60 { t.Errorf("Expected 60 for timeout but got %v", timeout) } - pv.Spec.Capacity[api.ResourceStorage] = resource.MustParse("150Gi") + pv.Spec.Capacity[v1.ResourceStorage] = resource.MustParse("150Gi") timeout = CalculateTimeoutForVolume(50, 30, pv) if timeout != 4500 { t.Errorf("Expected 4500 for timeout but got %v", timeout) diff --git a/pkg/volume/volume.go b/pkg/volume/volume.go index 83cb1955f01..1d4ea14488d 100644 --- a/pkg/volume/volume.go +++ b/pkg/volume/volume.go @@ -25,8 +25,8 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" ) @@ -149,7 +149,7 @@ type Provisioner interface { // Provision creates the resource by allocating the underlying volume in a // storage system. This method should block until completion and returns // PersistentVolume representing the created storage resource. - Provision() (*api.PersistentVolume, error) + Provision() (*v1.PersistentVolume, error) } // Deleter removes the resource from the underlying storage provider. Calls diff --git a/pkg/volume/vsphere_volume/BUILD b/pkg/volume/vsphere_volume/BUILD index f7bbec8d7ef..8919693939f 100644 --- a/pkg/volume/vsphere_volume/BUILD +++ b/pkg/volume/vsphere_volume/BUILD @@ -19,8 +19,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider:go_default_library", "//pkg/cloudprovider/providers/vsphere:go_default_library", "//pkg/types:go_default_library", @@ -43,7 +43,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider/providers/vsphere:go_default_library", "//pkg/types:go_default_library", "//pkg/util/mount:go_default_library", diff --git a/pkg/volume/vsphere_volume/attacher_test.go b/pkg/volume/vsphere_volume/attacher_test.go index 47c653876bb..4c706e8a773 100644 --- a/pkg/volume/vsphere_volume/attacher_test.go +++ b/pkg/volume/vsphere_volume/attacher_test.go @@ -20,7 +20,7 @@ import ( "errors" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere" "k8s.io/kubernetes/pkg/volume" volumetest "k8s.io/kubernetes/pkg/volume/testing" @@ -187,9 +187,9 @@ func newDetacher(testcase *testcase) *vsphereVMDKDetacher { func createVolSpec(name string) *volume.Spec { return &volume.Spec{ - Volume: &api.Volume{ - VolumeSource: api.VolumeSource{ - VsphereVolume: &api.VsphereVirtualDiskVolumeSource{ + Volume: &v1.Volume{ + VolumeSource: v1.VolumeSource{ + VsphereVolume: &v1.VsphereVirtualDiskVolumeSource{ VolumePath: name, }, }, @@ -199,10 +199,10 @@ func createVolSpec(name string) *volume.Spec { func createPVSpec(name string) *volume.Spec { return &volume.Spec{ - PersistentVolume: &api.PersistentVolume{ - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - VsphereVolume: &api.VsphereVirtualDiskVolumeSource{ + PersistentVolume: &v1.PersistentVolume{ + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + VsphereVolume: &v1.VsphereVirtualDiskVolumeSource{ VolumePath: name, }, }, diff --git a/pkg/volume/vsphere_volume/vsphere_volume.go b/pkg/volume/vsphere_volume/vsphere_volume.go index 218b022780f..06f27dfd70f 100644 --- a/pkg/volume/vsphere_volume/vsphere_volume.go +++ b/pkg/volume/vsphere_volume/vsphere_volume.go @@ -22,8 +22,8 @@ import ( "path" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/mount" @@ -77,7 +77,7 @@ func (plugin *vsphereVolumePlugin) RequiresRemount() bool { return false } -func (plugin *vsphereVolumePlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { +func (plugin *vsphereVolumePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) { return plugin.newMounterInternal(spec, pod.UID, &VsphereDiskUtil{}, plugin.host.GetMounter()) } @@ -119,10 +119,10 @@ func (plugin *vsphereVolumePlugin) newUnmounterInternal(volName string, podUID t } func (plugin *vsphereVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { - vsphereVolume := &api.Volume{ + vsphereVolume := &v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - VsphereVolume: &api.VsphereVirtualDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + VsphereVolume: &v1.VsphereVirtualDiskVolumeSource{ VolumePath: volumeName, }, }, @@ -285,9 +285,9 @@ func (vv *vsphereVolume) GetPath() string { } // vSphere Persistent Volume Plugin -func (plugin *vsphereVolumePlugin) GetAccessModes() []api.PersistentVolumeAccessMode { - return []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, +func (plugin *vsphereVolumePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode { + return []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, } } @@ -341,28 +341,28 @@ func (plugin *vsphereVolumePlugin) newProvisionerInternal(options volume.VolumeO }, nil } -func (v *vsphereVolumeProvisioner) Provision() (*api.PersistentVolume, error) { +func (v *vsphereVolumeProvisioner) Provision() (*v1.PersistentVolume, error) { vmDiskPath, sizeKB, err := v.manager.CreateVolume(v) if err != nil { return nil, err } - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + pv := &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ Name: v.options.PVName, Labels: map[string]string{}, Annotations: map[string]string{ "kubernetes.io/createdby": "vsphere-volume-dynamic-provisioner", }, }, - Spec: api.PersistentVolumeSpec{ + Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: v.options.PersistentVolumeReclaimPolicy, AccessModes: v.options.PVC.Spec.AccessModes, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dKi", sizeKB)), + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dKi", sizeKB)), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - VsphereVolume: &api.VsphereVirtualDiskVolumeSource{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + VsphereVolume: &v1.VsphereVirtualDiskVolumeSource{ VolumePath: vmDiskPath, FSType: "ext4", }, @@ -377,7 +377,7 @@ func (v *vsphereVolumeProvisioner) Provision() (*api.PersistentVolume, error) { } func getVolumeSource( - spec *volume.Spec) (*api.VsphereVirtualDiskVolumeSource, bool, error) { + spec *volume.Spec) (*v1.VsphereVirtualDiskVolumeSource, bool, error) { if spec.Volume != nil && spec.Volume.VsphereVolume != nil { return spec.Volume.VsphereVolume, spec.ReadOnly, nil } else if spec.PersistentVolume != nil && diff --git a/pkg/volume/vsphere_volume/vsphere_volume_test.go b/pkg/volume/vsphere_volume/vsphere_volume_test.go index 83d505fb6aa..4f8d57b9885 100644 --- a/pkg/volume/vsphere_volume/vsphere_volume_test.go +++ b/pkg/volume/vsphere_volume/vsphere_volume_test.go @@ -22,7 +22,7 @@ import ( "path" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/mount" utiltesting "k8s.io/kubernetes/pkg/util/testing" @@ -47,11 +47,11 @@ func TestCanSupport(t *testing.T) { t.Errorf("Wrong name: %s", plug.GetPluginName()) } - if !plug.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{VsphereVolume: &api.VsphereVirtualDiskVolumeSource{}}}}) { + if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{VsphereVolume: &v1.VsphereVirtualDiskVolumeSource{}}}}) { t.Errorf("Expected true") } - if !plug.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{VsphereVolume: &api.VsphereVirtualDiskVolumeSource{}}}}}) { + if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{VsphereVolume: &v1.VsphereVirtualDiskVolumeSource{}}}}}) { t.Errorf("Expected true") } } @@ -90,10 +90,10 @@ func TestPlugin(t *testing.T) { t.Errorf("Can't find the plugin by name") } - spec := &api.Volume{ + spec := &v1.Volume{ Name: "vol1", - VolumeSource: api.VolumeSource{ - VsphereVolume: &api.VsphereVirtualDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + VsphereVolume: &v1.VsphereVirtualDiskVolumeSource{ VolumePath: "[local] test-volume-name.vmdk", FSType: "ext4", }, @@ -142,8 +142,8 @@ func TestPlugin(t *testing.T) { // Test Provisioner options := volume.VolumeOptions{ - PVC: volumetest.CreateTestPVC("100Mi", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}), - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimDelete, + PVC: volumetest.CreateTestPVC("100Mi", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}), + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, } provisioner, err := plug.(*vsphereVolumePlugin).newProvisionerInternal(options, &fakePDManager{}) persistentSpec, err := provisioner.Provision() @@ -155,7 +155,7 @@ func TestPlugin(t *testing.T) { t.Errorf("Provision() returned unexpected path %s", persistentSpec.Spec.PersistentVolumeSource.VsphereVolume.VolumePath) } - cap := persistentSpec.Spec.Capacity[api.ResourceStorage] + cap := persistentSpec.Spec.Capacity[v1.ResourceStorage] size := cap.Value() if size != 100*1024 { t.Errorf("Provision() returned unexpected volume size: %v", size) diff --git a/pkg/volume/vsphere_volume/vsphere_volume_util.go b/pkg/volume/vsphere_volume/vsphere_volume_util.go index dc6c951aaf8..6e32b27f835 100644 --- a/pkg/volume/vsphere_volume/vsphere_volume_util.go +++ b/pkg/volume/vsphere_volume/vsphere_volume_util.go @@ -23,7 +23,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere" "k8s.io/kubernetes/pkg/volume" @@ -58,7 +58,7 @@ func (util *VsphereDiskUtil) CreateVolume(v *vsphereVolumeProvisioner) (vmDiskPa return "", 0, err } - capacity := v.options.PVC.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] + capacity := v.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] volSizeBytes := capacity.Value() // vSphere works with kilobytes, convert to KiB with rounding up volSizeKB := int(volume.RoundUpSize(volSizeBytes, 1024)) diff --git a/plugin/cmd/kube-scheduler/app/BUILD b/plugin/cmd/kube-scheduler/app/BUILD index 98fc091ab8f..82a9e150abc 100644 --- a/plugin/cmd/kube-scheduler/app/BUILD +++ b/plugin/cmd/kube-scheduler/app/BUILD @@ -15,9 +15,9 @@ go_library( srcs = ["server.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/leaderelection:go_default_library", "//pkg/client/leaderelection/resourcelock:go_default_library", "//pkg/client/record:go_default_library", diff --git a/plugin/cmd/kube-scheduler/app/server.go b/plugin/cmd/kube-scheduler/app/server.go index 766d0be2754..60fdabf90e4 100644 --- a/plugin/cmd/kube-scheduler/app/server.go +++ b/plugin/cmd/kube-scheduler/app/server.go @@ -26,9 +26,9 @@ import ( "os" "strconv" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/leaderelection" "k8s.io/kubernetes/pkg/client/leaderelection/resourcelock" "k8s.io/kubernetes/pkg/client/record" @@ -122,9 +122,9 @@ func Run(s *options.SchedulerServer) error { } eventBroadcaster := record.NewBroadcaster() - config.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: s.SchedulerName}) + config.Recorder = eventBroadcaster.NewRecorder(v1.EventSource{Component: s.SchedulerName}) eventBroadcaster.StartLogging(glog.Infof) - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: leaderElectionClient.Core().Events("")}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: leaderElectionClient.Core().Events("")}) sched := scheduler.New(config) @@ -147,7 +147,7 @@ func Run(s *options.SchedulerServer) error { // TODO: enable other lock types rl := resourcelock.EndpointsLock{ - EndpointsMeta: api.ObjectMeta{ + EndpointsMeta: v1.ObjectMeta{ Namespace: "kube-system", Name: "kube-scheduler", }, diff --git a/plugin/pkg/admission/limitranger/admission.go b/plugin/pkg/admission/limitranger/admission.go index 0001fc750f7..0a51d9a7b54 100644 --- a/plugin/pkg/admission/limitranger/admission.go +++ b/plugin/pkg/admission/limitranger/admission.go @@ -68,9 +68,9 @@ type liveLookupEntry struct { } func (l *limitRanger) SetInformerFactory(f informers.SharedInformerFactory) { - limitRangeInformer := f.LimitRanges().Informer() + limitRangeInformer := f.InternalLimitRanges().Informer() l.SetReadyFunc(limitRangeInformer.HasSynced) - l.lister = f.LimitRanges().Lister() + l.lister = f.InternalLimitRanges().Lister() } func (l *limitRanger) Validate() error { diff --git a/plugin/pkg/admission/limitranger/admission_test.go b/plugin/pkg/admission/limitranger/admission_test.go index 693a80c1ba9..e2adf26fb37 100644 --- a/plugin/pkg/admission/limitranger/admission_test.go +++ b/plugin/pkg/admission/limitranger/admission_test.go @@ -588,7 +588,7 @@ func newMockClientForTest(limitRanges []api.LimitRange) *fake.Clientset { // newHandlerForTest returns a handler configured for testing. func newHandlerForTest(c clientset.Interface) (admission.Interface, informers.SharedInformerFactory, error) { - f := informers.NewSharedInformerFactory(c, 5*time.Minute) + f := informers.NewSharedInformerFactory(nil, c, 5*time.Minute) handler, err := NewLimitRanger(c, &DefaultLimitRangerActions{}) if err != nil { return nil, f, err diff --git a/plugin/pkg/admission/namespace/autoprovision/admission.go b/plugin/pkg/admission/namespace/autoprovision/admission.go index f1f3eda1570..67e92560361 100644 --- a/plugin/pkg/admission/namespace/autoprovision/admission.go +++ b/plugin/pkg/admission/namespace/autoprovision/admission.go @@ -88,7 +88,7 @@ func NewProvision(c clientset.Interface) admission.Interface { } func (p *provision) SetInformerFactory(f informers.SharedInformerFactory) { - p.namespaceInformer = f.Namespaces().Informer() + p.namespaceInformer = f.InternalNamespaces().Informer() p.SetReadyFunc(p.namespaceInformer.HasSynced) } diff --git a/plugin/pkg/admission/namespace/autoprovision/admission_test.go b/plugin/pkg/admission/namespace/autoprovision/admission_test.go index 37c502be747..63c1a3115a7 100644 --- a/plugin/pkg/admission/namespace/autoprovision/admission_test.go +++ b/plugin/pkg/admission/namespace/autoprovision/admission_test.go @@ -35,7 +35,7 @@ import ( // newHandlerForTest returns the admission controller configured for testing. func newHandlerForTest(c clientset.Interface) (admission.Interface, informers.SharedInformerFactory, error) { - f := informers.NewSharedInformerFactory(c, 5*time.Minute) + f := informers.NewSharedInformerFactory(nil, c, 5*time.Minute) handler := NewProvision(c) plugins := []admission.Interface{handler} pluginInitializer := admission.NewPluginInitializer(f, nil) diff --git a/plugin/pkg/admission/namespace/exists/admission.go b/plugin/pkg/admission/namespace/exists/admission.go index 292d44f7fc4..41e31c20b59 100644 --- a/plugin/pkg/admission/namespace/exists/admission.go +++ b/plugin/pkg/admission/namespace/exists/admission.go @@ -95,7 +95,7 @@ func NewExists(c clientset.Interface) admission.Interface { } func (e *exists) SetInformerFactory(f informers.SharedInformerFactory) { - e.namespaceInformer = f.Namespaces().Informer() + e.namespaceInformer = f.InternalNamespaces().Informer() e.SetReadyFunc(e.namespaceInformer.HasSynced) } diff --git a/plugin/pkg/admission/namespace/exists/admission_test.go b/plugin/pkg/admission/namespace/exists/admission_test.go index ee2685986ba..f75f690a03b 100644 --- a/plugin/pkg/admission/namespace/exists/admission_test.go +++ b/plugin/pkg/admission/namespace/exists/admission_test.go @@ -34,7 +34,7 @@ import ( // newHandlerForTest returns the admission controller configured for testing. func newHandlerForTest(c clientset.Interface) (admission.Interface, informers.SharedInformerFactory, error) { - f := informers.NewSharedInformerFactory(c, 5*time.Minute) + f := informers.NewSharedInformerFactory(nil, c, 5*time.Minute) handler := NewExists(c) plugins := []admission.Interface{handler} pluginInitializer := admission.NewPluginInitializer(f, nil) diff --git a/plugin/pkg/admission/namespace/lifecycle/admission.go b/plugin/pkg/admission/namespace/lifecycle/admission.go index 98f08100814..2547e36bc72 100644 --- a/plugin/pkg/admission/namespace/lifecycle/admission.go +++ b/plugin/pkg/admission/namespace/lifecycle/admission.go @@ -181,7 +181,7 @@ func newLifecycleWithClock(c clientset.Interface, immortalNamespaces sets.String } func (l *lifecycle) SetInformerFactory(f informers.SharedInformerFactory) { - l.namespaceInformer = f.Namespaces().Informer() + l.namespaceInformer = f.InternalNamespaces().Informer() l.SetReadyFunc(l.namespaceInformer.HasSynced) } diff --git a/plugin/pkg/admission/namespace/lifecycle/admission_test.go b/plugin/pkg/admission/namespace/lifecycle/admission_test.go index 74e7c81c37c..d3f11d0577f 100644 --- a/plugin/pkg/admission/namespace/lifecycle/admission_test.go +++ b/plugin/pkg/admission/namespace/lifecycle/admission_test.go @@ -41,7 +41,7 @@ func newHandlerForTest(c clientset.Interface) (admission.Interface, informers.Sh // newHandlerForTestWithClock returns a configured handler for testing. func newHandlerForTestWithClock(c clientset.Interface, cacheClock clock.Clock) (admission.Interface, informers.SharedInformerFactory, error) { - f := informers.NewSharedInformerFactory(c, 5*time.Minute) + f := informers.NewSharedInformerFactory(nil, c, 5*time.Minute) handler, err := newLifecycleWithClock(c, sets.NewString(api.NamespaceDefault, api.NamespaceSystem), cacheClock) if err != nil { return nil, f, err diff --git a/plugin/pkg/admission/podnodeselector/admission.go b/plugin/pkg/admission/podnodeselector/admission.go index 0201d8f28d4..14be567144b 100644 --- a/plugin/pkg/admission/podnodeselector/admission.go +++ b/plugin/pkg/admission/podnodeselector/admission.go @@ -165,7 +165,7 @@ func NewPodNodeSelector(client clientset.Interface, clusterNodeSelectors map[str } func (p *podNodeSelector) SetInformerFactory(f informers.SharedInformerFactory) { - p.namespaceInformer = f.Namespaces().Informer() + p.namespaceInformer = f.InternalNamespaces().Informer() p.SetReadyFunc(p.namespaceInformer.HasSynced) } diff --git a/plugin/pkg/admission/podnodeselector/admission_test.go b/plugin/pkg/admission/podnodeselector/admission_test.go index dee7fd39533..fa54633b1b4 100644 --- a/plugin/pkg/admission/podnodeselector/admission_test.go +++ b/plugin/pkg/admission/podnodeselector/admission_test.go @@ -178,7 +178,7 @@ func TestHandles(t *testing.T) { // newHandlerForTest returns the admission controller configured for testing. func newHandlerForTest(c clientset.Interface) (*podNodeSelector, informers.SharedInformerFactory, error) { - f := informers.NewSharedInformerFactory(c, 5*time.Minute) + f := informers.NewSharedInformerFactory(nil, c, 5*time.Minute) handler := NewPodNodeSelector(c, nil) plugins := []admission.Interface{handler} pluginInitializer := admission.NewPluginInitializer(f, nil) diff --git a/plugin/pkg/admission/resourcequota/BUILD b/plugin/pkg/admission/resourcequota/BUILD index 356652ec1b7..db1e6c80b64 100644 --- a/plugin/pkg/admission/resourcequota/BUILD +++ b/plugin/pkg/admission/resourcequota/BUILD @@ -23,6 +23,7 @@ go_library( "//pkg/admission:go_default_library", "//pkg/api:go_default_library", "//pkg/api/meta:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", "//pkg/quota:go_default_library", diff --git a/plugin/pkg/admission/resourcequota/admission.go b/plugin/pkg/admission/resourcequota/admission.go index b5c00b81ba9..d6ebfa44b26 100644 --- a/plugin/pkg/admission/resourcequota/admission.go +++ b/plugin/pkg/admission/resourcequota/admission.go @@ -33,7 +33,7 @@ func init() { func(client clientset.Interface, config io.Reader) (admission.Interface, error) { // NOTE: we do not provide informers to the registry because admission level decisions // does not require us to open watches for all items tracked by quota. - registry := install.NewRegistry(client, nil) + registry := install.NewRegistry(nil, nil) return NewResourceQuota(client, registry, 5, make(chan struct{})) }) } diff --git a/plugin/pkg/admission/resourcequota/admission_test.go b/plugin/pkg/admission/resourcequota/admission_test.go index ed8c415a74c..8bf0024c71e 100644 --- a/plugin/pkg/admission/resourcequota/admission_test.go +++ b/plugin/pkg/admission/resourcequota/admission_test.go @@ -126,7 +126,7 @@ func TestAdmissionIgnoresDelete(t *testing.T) { kubeClient := fake.NewSimpleClientset() stopCh := make(chan struct{}) defer close(stopCh) - handler, err := NewResourceQuota(kubeClient, install.NewRegistry(kubeClient, nil), 5, stopCh) + handler, err := NewResourceQuota(kubeClient, install.NewRegistry(nil, nil), 5, stopCh) if err != nil { t.Errorf("Unexpected error %v", err) } @@ -158,7 +158,7 @@ func TestAdmissionIgnoresSubresources(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -201,7 +201,7 @@ func TestAdmitBelowQuotaLimit(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -283,7 +283,7 @@ func TestAdmitHandlesOldObjects(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -379,7 +379,7 @@ func TestAdmitHandlesCreatingUpdates(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -472,7 +472,7 @@ func TestAdmitExceedQuotaLimit(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -515,7 +515,7 @@ func TestAdmitEnforceQuotaConstraints(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -568,7 +568,7 @@ func TestAdmitPodInNamespaceWithoutQuota(t *testing.T) { quotaAccessor.indexer = indexer quotaAccessor.liveLookupCache = liveLookupCache go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -633,7 +633,7 @@ func TestAdmitBelowTerminatingQuotaLimit(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -737,7 +737,7 @@ func TestAdmitBelowBestEffortQuotaLimit(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -828,7 +828,7 @@ func TestAdmitBestEffortQuotaLimitIgnoresBurstable(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -945,7 +945,7 @@ func TestAdmissionSetsMissingNamespace(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) evaluator.(*quotaEvaluator).registry = registry handler := "aAdmission{ @@ -990,7 +990,7 @@ func TestAdmitRejectsNegativeUsage(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -1035,7 +1035,7 @@ func TestAdmitWhenUnrelatedResourceExceedsQuota(t *testing.T) { quotaAccessor, _ := newQuotaAccessor(kubeClient) quotaAccessor.indexer = indexer go quotaAccessor.Run(stopCh) - evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(kubeClient, nil), nil, 5, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, install.NewRegistry(nil, nil), nil, 5, stopCh) handler := "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), diff --git a/plugin/pkg/admission/resourcequota/resource_access.go b/plugin/pkg/admission/resourcequota/resource_access.go index 4322f1b8ddf..cff0f7d67af 100644 --- a/plugin/pkg/admission/resourcequota/resource_access.go +++ b/plugin/pkg/admission/resourcequota/resource_access.go @@ -26,6 +26,7 @@ import ( clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/storage/etcd" @@ -73,11 +74,15 @@ func newQuotaAccessor(client clientset.Interface) (*quotaAccessor, error) { return nil, err } lw := &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return client.Core().ResourceQuotas(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return client.Core().ResourceQuotas(api.NamespaceAll).List(internalOptions) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return client.Core().ResourceQuotas(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return client.Core().ResourceQuotas(api.NamespaceAll).Watch(internalOptions) }, } indexer, reflector := cache.NewNamespaceKeyedIndexerAndReflector(lw, &api.ResourceQuota{}, 0) diff --git a/plugin/pkg/admission/security/podsecuritypolicy/BUILD b/plugin/pkg/admission/security/podsecuritypolicy/BUILD index 29e1f347d8e..7efe3bd77f1 100644 --- a/plugin/pkg/admission/security/podsecuritypolicy/BUILD +++ b/plugin/pkg/admission/security/podsecuritypolicy/BUILD @@ -18,6 +18,7 @@ go_library( "//pkg/admission:go_default_library", "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/extensions:go_default_library", "//pkg/auth/authorizer:go_default_library", "//pkg/auth/user:go_default_library", diff --git a/plugin/pkg/admission/security/podsecuritypolicy/admission.go b/plugin/pkg/admission/security/podsecuritypolicy/admission.go index 287d483e6e5..895e0549d72 100644 --- a/plugin/pkg/admission/security/podsecuritypolicy/admission.go +++ b/plugin/pkg/admission/security/podsecuritypolicy/admission.go @@ -26,6 +26,7 @@ import ( "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/auth/authorizer" "k8s.io/kubernetes/pkg/auth/user" @@ -91,11 +92,15 @@ func NewPlugin(kclient clientset.Interface, strategyFactory psp.StrategyFactory, store := cache.NewStore(cache.MetaNamespaceKeyFunc) reflector := cache.NewReflector( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return kclient.Extensions().PodSecurityPolicies().List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return kclient.Extensions().PodSecurityPolicies().List(internalOptions) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return kclient.Extensions().PodSecurityPolicies().Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return kclient.Extensions().PodSecurityPolicies().Watch(internalOptions) }, }, &extensions.PodSecurityPolicy{}, @@ -228,7 +233,7 @@ func assignSecurityContext(provider psp.Provider, pod *api.Pod, fldPath *field.P // since that is how the sc provider will eventually apply settings in the runtime. // This results in an SC that is based on the Pod's PSC with the set fields from the container // overriding pod level settings. - containerCopy.SecurityContext = sc.DetermineEffectiveSecurityContext(pod, &containerCopy) + containerCopy.SecurityContext = sc.InternalDetermineEffectiveSecurityContext(pod, &containerCopy) sc, scAnnotations, err := provider.CreateContainerSecurityContext(pod, &containerCopy) if err != nil { @@ -249,7 +254,7 @@ func assignSecurityContext(provider psp.Provider, pod *api.Pod, fldPath *field.P // since that is how the sc provider will eventually apply settings in the runtime. // This results in an SC that is based on the Pod's PSC with the set fields from the container // overriding pod level settings. - containerCopy.SecurityContext = sc.DetermineEffectiveSecurityContext(pod, &containerCopy) + containerCopy.SecurityContext = sc.InternalDetermineEffectiveSecurityContext(pod, &containerCopy) sc, scAnnotations, err := provider.CreateContainerSecurityContext(pod, &containerCopy) if err != nil { diff --git a/plugin/pkg/admission/security/podsecuritypolicy/admission_test.go b/plugin/pkg/admission/security/podsecuritypolicy/admission_test.go index ce21dcd6ea1..bf3944f39fc 100644 --- a/plugin/pkg/admission/security/podsecuritypolicy/admission_test.go +++ b/plugin/pkg/admission/security/podsecuritypolicy/admission_test.go @@ -751,7 +751,7 @@ func TestAdmitSELinux(t *testing.T) { func TestAdmitAppArmor(t *testing.T) { createPodWithAppArmor := func(profile string) *kapi.Pod { pod := goodPod() - apparmor.SetProfileName(pod, defaultContainerName, profile) + apparmor.SetProfileNameFromPodAnnotations(pod.Annotations, defaultContainerName, profile) return pod } @@ -822,7 +822,7 @@ func TestAdmitAppArmor(t *testing.T) { testPSPAdmit(k, []*extensions.PodSecurityPolicy{v.psp}, v.pod, v.shouldPass, v.psp.Name, t) if v.shouldPass { - assert.Equal(t, v.expectedProfile, apparmor.GetProfileName(v.pod, defaultContainerName), k) + assert.Equal(t, v.expectedProfile, apparmor.GetProfileNameFromPodAnnotations(v.pod.Annotations, defaultContainerName), k) } } } diff --git a/plugin/pkg/admission/serviceaccount/BUILD b/plugin/pkg/admission/serviceaccount/BUILD index 5046ddc075c..ab6759791fc 100644 --- a/plugin/pkg/admission/serviceaccount/BUILD +++ b/plugin/pkg/admission/serviceaccount/BUILD @@ -22,6 +22,7 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", "//pkg/fields:go_default_library", diff --git a/plugin/pkg/admission/serviceaccount/admission.go b/plugin/pkg/admission/serviceaccount/admission.go index 4a71080067c..96b15e86599 100644 --- a/plugin/pkg/admission/serviceaccount/admission.go +++ b/plugin/pkg/admission/serviceaccount/admission.go @@ -29,6 +29,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/fields" kubelet "k8s.io/kubernetes/pkg/kubelet/types" @@ -91,11 +92,15 @@ type serviceAccount struct { func NewServiceAccount(cl clientset.Interface) *serviceAccount { serviceAccountsIndexer, serviceAccountsReflector := cache.NewNamespaceKeyedIndexerAndReflector( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return cl.Core().ServiceAccounts(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return cl.Core().ServiceAccounts(api.NamespaceAll).List(internalOptions) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return cl.Core().ServiceAccounts(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return cl.Core().ServiceAccounts(api.NamespaceAll).Watch(internalOptions) }, }, &api.ServiceAccount{}, @@ -105,13 +110,17 @@ func NewServiceAccount(cl clientset.Interface) *serviceAccount { tokenSelector := fields.SelectorFromSet(map[string]string{api.SecretTypeField: string(api.SecretTypeServiceAccountToken)}) secretsIndexer, secretsReflector := cache.NewNamespaceKeyedIndexerAndReflector( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - options.FieldSelector = tokenSelector - return cl.Core().Secrets(api.NamespaceAll).List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + internalOptions.FieldSelector = tokenSelector + return cl.Core().Secrets(api.NamespaceAll).List(internalOptions) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - options.FieldSelector = tokenSelector - return cl.Core().Secrets(api.NamespaceAll).Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + internalOptions.FieldSelector = tokenSelector + return cl.Core().Secrets(api.NamespaceAll).Watch(internalOptions) }, }, &api.Secret{}, @@ -304,7 +313,7 @@ func (s *serviceAccount) getServiceAccountTokens(serviceAccount *api.ServiceAcco for _, obj := range index { token := obj.(*api.Secret) - if serviceaccount.IsServiceAccountToken(token, serviceAccount) { + if serviceaccount.InternalIsServiceAccountToken(token, serviceAccount) { tokens = append(tokens, token) } } diff --git a/plugin/pkg/admission/storageclass/default/BUILD b/plugin/pkg/admission/storageclass/default/BUILD index fa8d42b6543..61ba38f3f57 100644 --- a/plugin/pkg/admission/storageclass/default/BUILD +++ b/plugin/pkg/admission/storageclass/default/BUILD @@ -18,6 +18,7 @@ go_library( "//pkg/admission:go_default_library", "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/storage:go_default_library", "//pkg/apis/storage/util:go_default_library", "//pkg/client/cache:go_default_library", diff --git a/plugin/pkg/admission/storageclass/default/admission.go b/plugin/pkg/admission/storageclass/default/admission.go index cbd5850f0e4..92d555a03b9 100644 --- a/plugin/pkg/admission/storageclass/default/admission.go +++ b/plugin/pkg/admission/storageclass/default/admission.go @@ -25,6 +25,7 @@ import ( admission "k8s.io/kubernetes/pkg/admission" api "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/storage" storageutil "k8s.io/kubernetes/pkg/apis/storage/util" "k8s.io/kubernetes/pkg/client/cache" @@ -62,11 +63,15 @@ func newPlugin(kclient clientset.Interface) *claimDefaulterPlugin { store := cache.NewStore(cache.MetaNamespaceKeyFunc) reflector := cache.NewReflector( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return kclient.Storage().StorageClasses().List(options) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return kclient.Storage().StorageClasses().List(internalOptions) }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return kclient.Storage().StorageClasses().Watch(options) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + internalOptions := api.ListOptions{} + v1.Convert_v1_ListOptions_To_api_ListOptions(&options, &internalOptions, nil) + return kclient.Storage().StorageClasses().Watch(internalOptions) }, }, &storage.StorageClass{}, diff --git a/plugin/pkg/auth/authenticator/token/webhook/BUILD b/plugin/pkg/auth/authenticator/token/webhook/BUILD index f86acf2be11..406dd1c899d 100644 --- a/plugin/pkg/auth/authenticator/token/webhook/BUILD +++ b/plugin/pkg/auth/authenticator/token/webhook/BUILD @@ -16,12 +16,11 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api/unversioned:go_default_library", - "//pkg/apis/authentication:go_default_library", "//pkg/apis/authentication/install:go_default_library", "//pkg/apis/authentication/v1beta1:go_default_library", "//pkg/auth/authenticator:go_default_library", "//pkg/auth/user:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/authentication/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/authentication/v1beta1:go_default_library", "//pkg/util/cache:go_default_library", "//plugin/pkg/webhook:go_default_library", ], diff --git a/plugin/pkg/auth/authenticator/token/webhook/webhook.go b/plugin/pkg/auth/authenticator/token/webhook/webhook.go index 86157f0459e..6dbbc60d859 100644 --- a/plugin/pkg/auth/authenticator/token/webhook/webhook.go +++ b/plugin/pkg/auth/authenticator/token/webhook/webhook.go @@ -21,18 +21,17 @@ import ( "time" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/authentication" _ "k8s.io/kubernetes/pkg/apis/authentication/install" - "k8s.io/kubernetes/pkg/apis/authentication/v1beta1" + authentication "k8s.io/kubernetes/pkg/apis/authentication/v1beta1" "k8s.io/kubernetes/pkg/auth/authenticator" "k8s.io/kubernetes/pkg/auth/user" - authenticationclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/authentication/internalversion" + authenticationclient "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/authentication/v1beta1" "k8s.io/kubernetes/pkg/util/cache" "k8s.io/kubernetes/plugin/pkg/webhook" ) var ( - groupVersions = []unversioned.GroupVersion{v1beta1.SchemeGroupVersion} + groupVersions = []unversioned.GroupVersion{authentication.SchemeGroupVersion} ) const retryBackoff = 500 * time.Millisecond diff --git a/plugin/pkg/auth/authorizer/webhook/BUILD b/plugin/pkg/auth/authorizer/webhook/BUILD index 19d6ca05938..bf2c3e84bcb 100644 --- a/plugin/pkg/auth/authorizer/webhook/BUILD +++ b/plugin/pkg/auth/authorizer/webhook/BUILD @@ -16,11 +16,10 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api/unversioned:go_default_library", - "//pkg/apis/authorization:go_default_library", "//pkg/apis/authorization/install:go_default_library", "//pkg/apis/authorization/v1beta1:go_default_library", "//pkg/auth/authorizer:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/authorization/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/authorization/v1beta1:go_default_library", "//pkg/util/cache:go_default_library", "//plugin/pkg/webhook:go_default_library", "//vendor:github.com/golang/glog", diff --git a/plugin/pkg/auth/authorizer/webhook/webhook.go b/plugin/pkg/auth/authorizer/webhook/webhook.go index 96a53a34094..a04202d2ac5 100644 --- a/plugin/pkg/auth/authorizer/webhook/webhook.go +++ b/plugin/pkg/auth/authorizer/webhook/webhook.go @@ -24,10 +24,9 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/authorization" - "k8s.io/kubernetes/pkg/apis/authorization/v1beta1" + authorization "k8s.io/kubernetes/pkg/apis/authorization/v1beta1" "k8s.io/kubernetes/pkg/auth/authorizer" - authorizationclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/authorization/internalversion" + authorizationclient "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/authorization/v1beta1" "k8s.io/kubernetes/pkg/util/cache" "k8s.io/kubernetes/plugin/pkg/webhook" @@ -35,7 +34,7 @@ import ( ) var ( - groupVersions = []unversioned.GroupVersion{v1beta1.SchemeGroupVersion} + groupVersions = []unversioned.GroupVersion{authorization.SchemeGroupVersion} ) const retryBackoff = 500 * time.Millisecond diff --git a/plugin/pkg/scheduler/BUILD b/plugin/pkg/scheduler/BUILD index cdf26bf31e7..cde1f24dfe0 100644 --- a/plugin/pkg/scheduler/BUILD +++ b/plugin/pkg/scheduler/BUILD @@ -20,7 +20,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/util:go_default_library", @@ -49,10 +49,10 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/testapi:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/client/record:go_default_library", "//pkg/labels:go_default_library", diff --git a/plugin/pkg/scheduler/algorithm/BUILD b/plugin/pkg/scheduler/algorithm/BUILD index 99ece95dc10..8eec95dc35c 100644 --- a/plugin/pkg/scheduler/algorithm/BUILD +++ b/plugin/pkg/scheduler/algorithm/BUILD @@ -20,9 +20,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/labels:go_default_library", "//plugin/pkg/scheduler/api:go_default_library", "//plugin/pkg/scheduler/schedulercache:go_default_library", @@ -34,5 +34,5 @@ go_test( srcs = ["scheduler_interface_test.go"], library = "go_default_library", tags = ["automanaged"], - deps = ["//pkg/api:go_default_library"], + deps = ["//pkg/api/v1:go_default_library"], ) diff --git a/plugin/pkg/scheduler/algorithm/listers.go b/plugin/pkg/scheduler/algorithm/listers.go index 343a27c7946..78c2c93d3df 100644 --- a/plugin/pkg/scheduler/algorithm/listers.go +++ b/plugin/pkg/scheduler/algorithm/listers.go @@ -19,39 +19,39 @@ package algorithm import ( "fmt" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/labels" ) // NodeLister interface represents anything that can list nodes for a scheduler. type NodeLister interface { - // We explicitly return []*api.Node, instead of api.NodeList, to avoid + // We explicitly return []*v1.Node, instead of v1.NodeList, to avoid // performing expensive copies that are unneded. - List() ([]*api.Node, error) + List() ([]*v1.Node, error) } // FakeNodeLister implements NodeLister on a []string for test purposes. -type FakeNodeLister []*api.Node +type FakeNodeLister []*v1.Node // List returns nodes as a []string. -func (f FakeNodeLister) List() ([]*api.Node, error) { +func (f FakeNodeLister) List() ([]*v1.Node, error) { return f, nil } // PodLister interface represents anything that can list pods for a scheduler. type PodLister interface { - // We explicitly return []*api.Pod, instead of api.PodList, to avoid + // We explicitly return []*v1.Pod, instead of v1.PodList, to avoid // performing expensive copies that are unneded. - List(labels.Selector) ([]*api.Pod, error) + List(labels.Selector) ([]*v1.Pod, error) } -// FakePodLister implements PodLister on an []api.Pods for test purposes. -type FakePodLister []*api.Pod +// FakePodLister implements PodLister on an []v1.Pods for test purposes. +type FakePodLister []*v1.Pod -// List returns []*api.Pod matching a query. -func (f FakePodLister) List(s labels.Selector) (selected []*api.Pod, err error) { +// List returns []*v1.Pod matching a query. +func (f FakePodLister) List(s labels.Selector) (selected []*v1.Pod, err error) { for _, pod := range f { if s.Matches(labels.Set(pod.Labels)) { selected = append(selected, pod) @@ -63,21 +63,21 @@ func (f FakePodLister) List(s labels.Selector) (selected []*api.Pod, err error) // ServiceLister interface represents anything that can produce a list of services; the list is consumed by a scheduler. type ServiceLister interface { // Lists all the services - List(labels.Selector) ([]*api.Service, error) + List(labels.Selector) ([]*v1.Service, error) // Gets the services for the given pod - GetPodServices(*api.Pod) ([]*api.Service, error) + GetPodServices(*v1.Pod) ([]*v1.Service, error) } -// FakeServiceLister implements ServiceLister on []api.Service for test purposes. -type FakeServiceLister []*api.Service +// FakeServiceLister implements ServiceLister on []v1.Service for test purposes. +type FakeServiceLister []*v1.Service -// List returns api.ServiceList, the list of all services. -func (f FakeServiceLister) List(labels.Selector) ([]*api.Service, error) { +// List returns v1.ServiceList, the list of all services. +func (f FakeServiceLister) List(labels.Selector) ([]*v1.Service, error) { return f, nil } // GetPodServices gets the services that have the selector that match the labels on the given pod. -func (f FakeServiceLister) GetPodServices(pod *api.Pod) (services []*api.Service, err error) { +func (f FakeServiceLister) GetPodServices(pod *v1.Pod) (services []*v1.Service, err error) { var selector labels.Selector for i := range f { @@ -97,34 +97,34 @@ func (f FakeServiceLister) GetPodServices(pod *api.Pod) (services []*api.Service // ControllerLister interface represents anything that can produce a list of ReplicationController; the list is consumed by a scheduler. type ControllerLister interface { // Lists all the replication controllers - List(labels.Selector) ([]*api.ReplicationController, error) + List(labels.Selector) ([]*v1.ReplicationController, error) // Gets the services for the given pod - GetPodControllers(*api.Pod) ([]*api.ReplicationController, error) + GetPodControllers(*v1.Pod) ([]*v1.ReplicationController, error) } -// EmptyControllerLister implements ControllerLister on []api.ReplicationController returning empty data +// EmptyControllerLister implements ControllerLister on []v1.ReplicationController returning empty data type EmptyControllerLister struct{} // List returns nil -func (f EmptyControllerLister) List(labels.Selector) ([]*api.ReplicationController, error) { +func (f EmptyControllerLister) List(labels.Selector) ([]*v1.ReplicationController, error) { return nil, nil } // GetPodControllers returns nil -func (f EmptyControllerLister) GetPodControllers(pod *api.Pod) (controllers []*api.ReplicationController, err error) { +func (f EmptyControllerLister) GetPodControllers(pod *v1.Pod) (controllers []*v1.ReplicationController, err error) { return nil, nil } -// FakeControllerLister implements ControllerLister on []api.ReplicationController for test purposes. -type FakeControllerLister []*api.ReplicationController +// FakeControllerLister implements ControllerLister on []v1.ReplicationController for test purposes. +type FakeControllerLister []*v1.ReplicationController -// List returns []api.ReplicationController, the list of all ReplicationControllers. -func (f FakeControllerLister) List(labels.Selector) ([]*api.ReplicationController, error) { +// List returns []v1.ReplicationController, the list of all ReplicationControllers. +func (f FakeControllerLister) List(labels.Selector) ([]*v1.ReplicationController, error) { return f, nil } // GetPodControllers gets the ReplicationControllers that have the selector that match the labels on the given pod -func (f FakeControllerLister) GetPodControllers(pod *api.Pod) (controllers []*api.ReplicationController, err error) { +func (f FakeControllerLister) GetPodControllers(pod *v1.Pod) (controllers []*v1.ReplicationController, err error) { var selector labels.Selector for i := range f { @@ -147,14 +147,14 @@ func (f FakeControllerLister) GetPodControllers(pod *api.Pod) (controllers []*ap // ReplicaSetLister interface represents anything that can produce a list of ReplicaSet; the list is consumed by a scheduler. type ReplicaSetLister interface { // Gets the replicasets for the given pod - GetPodReplicaSets(*api.Pod) ([]*extensions.ReplicaSet, error) + GetPodReplicaSets(*v1.Pod) ([]*extensions.ReplicaSet, error) } // EmptyReplicaSetLister implements ReplicaSetLister on []extensions.ReplicaSet returning empty data type EmptyReplicaSetLister struct{} // GetPodReplicaSets returns nil -func (f EmptyReplicaSetLister) GetPodReplicaSets(pod *api.Pod) (rss []*extensions.ReplicaSet, err error) { +func (f EmptyReplicaSetLister) GetPodReplicaSets(pod *v1.Pod) (rss []*extensions.ReplicaSet, err error) { return nil, nil } @@ -162,7 +162,7 @@ func (f EmptyReplicaSetLister) GetPodReplicaSets(pod *api.Pod) (rss []*extension type FakeReplicaSetLister []*extensions.ReplicaSet // GetPodReplicaSets gets the ReplicaSets that have the selector that match the labels on the given pod -func (f FakeReplicaSetLister) GetPodReplicaSets(pod *api.Pod) (rss []*extensions.ReplicaSet, err error) { +func (f FakeReplicaSetLister) GetPodReplicaSets(pod *v1.Pod) (rss []*extensions.ReplicaSet, err error) { var selector labels.Selector for _, rs := range f { diff --git a/plugin/pkg/scheduler/algorithm/predicates/BUILD b/plugin/pkg/scheduler/algorithm/predicates/BUILD index fca4d360940..a6d223eb230 100644 --- a/plugin/pkg/scheduler/algorithm/predicates/BUILD +++ b/plugin/pkg/scheduler/algorithm/predicates/BUILD @@ -20,8 +20,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/kubelet/qos:go_default_library", "//pkg/labels:go_default_library", @@ -46,8 +46,8 @@ go_test( "skip", ], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/labels:go_default_library", "//pkg/util/codeinspector:go_default_library", "//plugin/pkg/scheduler/algorithm:go_default_library", diff --git a/plugin/pkg/scheduler/algorithm/predicates/error.go b/plugin/pkg/scheduler/algorithm/predicates/error.go index a71cdb9aae7..61bb249bb9e 100644 --- a/plugin/pkg/scheduler/algorithm/predicates/error.go +++ b/plugin/pkg/scheduler/algorithm/predicates/error.go @@ -19,7 +19,7 @@ package predicates import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) var ( @@ -46,13 +46,13 @@ var ( // hit and caused the unfitting failure. type InsufficientResourceError struct { // resourceName is the name of the resource that is insufficient - ResourceName api.ResourceName + ResourceName v1.ResourceName requested int64 used int64 capacity int64 } -func NewInsufficientResourceError(resourceName api.ResourceName, requested, used, capacity int64) *InsufficientResourceError { +func NewInsufficientResourceError(resourceName v1.ResourceName, requested, used, capacity int64) *InsufficientResourceError { return &InsufficientResourceError{ ResourceName: resourceName, requested: requested, diff --git a/plugin/pkg/scheduler/algorithm/predicates/metadata.go b/plugin/pkg/scheduler/algorithm/predicates/metadata.go index 7c04d80a4fc..e407ac98af0 100644 --- a/plugin/pkg/scheduler/algorithm/predicates/metadata.go +++ b/plugin/pkg/scheduler/algorithm/predicates/metadata.go @@ -18,7 +18,7 @@ package predicates import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) @@ -35,7 +35,7 @@ func NewPredicateMetadataFactory(podLister algorithm.PodLister) algorithm.Metada } // GetMetadata returns the predicateMetadata used which will be used by various predicates. -func (pfactory *PredicateMetadataFactory) GetMetadata(pod *api.Pod, nodeNameToInfoMap map[string]*schedulercache.NodeInfo) interface{} { +func (pfactory *PredicateMetadataFactory) GetMetadata(pod *v1.Pod, nodeNameToInfoMap map[string]*schedulercache.NodeInfo) interface{} { // If we cannot compute metadata, just return nil if pod == nil { return nil diff --git a/plugin/pkg/scheduler/algorithm/predicates/predicates.go b/plugin/pkg/scheduler/algorithm/predicates/predicates.go index e57afcceba0..7665bcc5572 100644 --- a/plugin/pkg/scheduler/algorithm/predicates/predicates.go +++ b/plugin/pkg/scheduler/algorithm/predicates/predicates.go @@ -24,8 +24,8 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/kubelet/qos" "k8s.io/kubernetes/pkg/labels" @@ -50,15 +50,15 @@ func RegisterPredicatePrecomputation(predicateName string, precomp PredicateMeta // Other types for predicate functions... type NodeInfo interface { - GetNodeInfo(nodeID string) (*api.Node, error) + GetNodeInfo(nodeID string) (*v1.Node, error) } type PersistentVolumeInfo interface { - GetPersistentVolumeInfo(pvID string) (*api.PersistentVolume, error) + GetPersistentVolumeInfo(pvID string) (*v1.PersistentVolume, error) } type PersistentVolumeClaimInfo interface { - GetPersistentVolumeClaimInfo(namespace string, name string) (*api.PersistentVolumeClaim, error) + GetPersistentVolumeClaimInfo(namespace string, name string) (*v1.PersistentVolumeClaim, error) } // CachedPersistentVolumeClaimInfo implements PersistentVolumeClaimInfo @@ -67,7 +67,7 @@ type CachedPersistentVolumeClaimInfo struct { } // GetPersistentVolumeClaimInfo fetches the claim in specified namespace with specified name -func (c *CachedPersistentVolumeClaimInfo) GetPersistentVolumeClaimInfo(namespace string, name string) (*api.PersistentVolumeClaim, error) { +func (c *CachedPersistentVolumeClaimInfo) GetPersistentVolumeClaimInfo(namespace string, name string) (*v1.PersistentVolumeClaim, error) { return c.PersistentVolumeClaims(namespace).Get(name) } @@ -76,8 +76,8 @@ type CachedNodeInfo struct { } // GetNodeInfo returns cached data for the node 'id'. -func (c *CachedNodeInfo) GetNodeInfo(id string) (*api.Node, error) { - node, exists, err := c.Get(&api.Node{ObjectMeta: api.ObjectMeta{Name: id}}) +func (c *CachedNodeInfo) GetNodeInfo(id string) (*v1.Node, error) { + node, exists, err := c.Get(&v1.Node{ObjectMeta: v1.ObjectMeta{Name: id}}) if err != nil { return nil, fmt.Errorf("error retrieving node '%v' from cache: %v", id, err) @@ -87,27 +87,27 @@ func (c *CachedNodeInfo) GetNodeInfo(id string) (*api.Node, error) { return nil, fmt.Errorf("node '%v' not found", id) } - return node.(*api.Node), nil + return node.(*v1.Node), nil } // Note that predicateMetdata and matchingPodAntiAffinityTerm need to be declared in the same file // due to the way declarations are processed in predicate declaration unit tests. type matchingPodAntiAffinityTerm struct { - term *api.PodAffinityTerm - node *api.Node + term *v1.PodAffinityTerm + node *v1.Node } type predicateMetadata struct { - pod *api.Pod + pod *v1.Pod podBestEffort bool podRequest *schedulercache.Resource podPorts map[int]bool matchingAntiAffinityTerms []matchingPodAntiAffinityTerm - serviceAffinityMatchingPodList []*api.Pod - serviceAffinityMatchingPodServices []*api.Service + serviceAffinityMatchingPodList []*v1.Pod + serviceAffinityMatchingPodServices []*v1.Service } -func isVolumeConflict(volume api.Volume, pod *api.Pod) bool { +func isVolumeConflict(volume v1.Volume, pod *v1.Pod) bool { // fast path if there is no conflict checking targets. if volume.GCEPersistentDisk == nil && volume.AWSElasticBlockStore == nil && volume.RBD == nil { return false @@ -151,7 +151,7 @@ func isVolumeConflict(volume api.Volume, pod *api.Pod) bool { // - AWS EBS forbids any two pods mounting the same volume ID // - Ceph RBD forbids if any two pods share at least same monitor, and match pool and image. // TODO: migrate this into some per-volume specific code? -func NoDiskConflict(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func NoDiskConflict(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { for _, v := range pod.Spec.Volumes { for _, ev := range nodeInfo.Pods() { if isVolumeConflict(v, ev) { @@ -172,8 +172,8 @@ type MaxPDVolumeCountChecker struct { // VolumeFilter contains information on how to filter PD Volumes when checking PD Volume caps type VolumeFilter struct { // Filter normal volumes - FilterVolume func(vol *api.Volume) (id string, relevant bool) - FilterPersistentVolume func(pv *api.PersistentVolume) (id string, relevant bool) + FilterVolume func(vol *v1.Volume) (id string, relevant bool) + FilterPersistentVolume func(pv *v1.PersistentVolume) (id string, relevant bool) } // NewMaxPDVolumeCountPredicate creates a predicate which evaluates whether a pod can fit based on the @@ -194,7 +194,7 @@ func NewMaxPDVolumeCountPredicate(filter VolumeFilter, maxVolumes int, pvInfo Pe return c.predicate } -func (c *MaxPDVolumeCountChecker) filterVolumes(volumes []api.Volume, namespace string, filteredVolumes map[string]bool) error { +func (c *MaxPDVolumeCountChecker) filterVolumes(volumes []v1.Volume, namespace string, filteredVolumes map[string]bool) error { for _, vol := range volumes { if id, ok := c.filter.FilterVolume(&vol); ok { filteredVolumes[id] = true @@ -248,7 +248,7 @@ func (c *MaxPDVolumeCountChecker) filterVolumes(volumes []api.Volume, namespace return nil } -func (c *MaxPDVolumeCountChecker) predicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func (c *MaxPDVolumeCountChecker) predicate(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { // If a pod doesn't have any volume attached to it, the predicate will always be true. // Thus we make a fast path for it, to avoid unnecessary computations in this case. if len(pod.Spec.Volumes) == 0 { @@ -293,14 +293,14 @@ func (c *MaxPDVolumeCountChecker) predicate(pod *api.Pod, meta interface{}, node // EBSVolumeFilter is a VolumeFilter for filtering AWS ElasticBlockStore Volumes var EBSVolumeFilter VolumeFilter = VolumeFilter{ - FilterVolume: func(vol *api.Volume) (string, bool) { + FilterVolume: func(vol *v1.Volume) (string, bool) { if vol.AWSElasticBlockStore != nil { return vol.AWSElasticBlockStore.VolumeID, true } return "", false }, - FilterPersistentVolume: func(pv *api.PersistentVolume) (string, bool) { + FilterPersistentVolume: func(pv *v1.PersistentVolume) (string, bool) { if pv.Spec.AWSElasticBlockStore != nil { return pv.Spec.AWSElasticBlockStore.VolumeID, true } @@ -310,14 +310,14 @@ var EBSVolumeFilter VolumeFilter = VolumeFilter{ // GCEPDVolumeFilter is a VolumeFilter for filtering GCE PersistentDisk Volumes var GCEPDVolumeFilter VolumeFilter = VolumeFilter{ - FilterVolume: func(vol *api.Volume) (string, bool) { + FilterVolume: func(vol *v1.Volume) (string, bool) { if vol.GCEPersistentDisk != nil { return vol.GCEPersistentDisk.PDName, true } return "", false }, - FilterPersistentVolume: func(pv *api.PersistentVolume) (string, bool) { + FilterPersistentVolume: func(pv *v1.PersistentVolume) (string, bool) { if pv.Spec.GCEPersistentDisk != nil { return pv.Spec.GCEPersistentDisk.PDName, true } @@ -352,7 +352,7 @@ func NewVolumeZonePredicate(pvInfo PersistentVolumeInfo, pvcInfo PersistentVolum return c.predicate } -func (c *VolumeZoneChecker) predicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func (c *VolumeZoneChecker) predicate(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { // If a pod doesn't have any volume attached to it, the predicate will always be true. // Thus we make a fast path for it, to avoid unnecessary computations in this case. if len(pod.Spec.Volumes) == 0 { @@ -427,22 +427,22 @@ func (c *VolumeZoneChecker) predicate(pod *api.Pod, meta interface{}, nodeInfo * return true, nil, nil } -func GetResourceRequest(pod *api.Pod) *schedulercache.Resource { +func GetResourceRequest(pod *v1.Pod) *schedulercache.Resource { result := schedulercache.Resource{} for _, container := range pod.Spec.Containers { for rName, rQuantity := range container.Resources.Requests { switch rName { - case api.ResourceMemory: + case v1.ResourceMemory: result.Memory += rQuantity.Value() - case api.ResourceCPU: + case v1.ResourceCPU: result.MilliCPU += rQuantity.MilliValue() - case api.ResourceNvidiaGPU: + case v1.ResourceNvidiaGPU: result.NvidiaGPU += rQuantity.Value() default: - if api.IsOpaqueIntResourceName(rName) { + if v1.IsOpaqueIntResourceName(rName) { // Lazily allocate this map only if required. if result.OpaqueIntResources == nil { - result.OpaqueIntResources = map[api.ResourceName]int64{} + result.OpaqueIntResources = map[v1.ResourceName]int64{} } result.OpaqueIntResources[rName] += rQuantity.Value() } @@ -453,23 +453,23 @@ func GetResourceRequest(pod *api.Pod) *schedulercache.Resource { for _, container := range pod.Spec.InitContainers { for rName, rQuantity := range container.Resources.Requests { switch rName { - case api.ResourceMemory: + case v1.ResourceMemory: if mem := rQuantity.Value(); mem > result.Memory { result.Memory = mem } - case api.ResourceCPU: + case v1.ResourceCPU: if cpu := rQuantity.MilliValue(); cpu > result.MilliCPU { result.MilliCPU = cpu } - case api.ResourceNvidiaGPU: + case v1.ResourceNvidiaGPU: if gpu := rQuantity.Value(); gpu > result.NvidiaGPU { result.NvidiaGPU = gpu } default: - if api.IsOpaqueIntResourceName(rName) { + if v1.IsOpaqueIntResourceName(rName) { // Lazily allocate this map only if required. if result.OpaqueIntResources == nil { - result.OpaqueIntResources = map[api.ResourceName]int64{} + result.OpaqueIntResources = map[v1.ResourceName]int64{} } value := rQuantity.Value() if value > result.OpaqueIntResources[rName] { @@ -482,11 +482,11 @@ func GetResourceRequest(pod *api.Pod) *schedulercache.Resource { return &result } -func podName(pod *api.Pod) string { +func podName(pod *v1.Pod) string { return pod.Namespace + "/" + pod.Name } -func PodFitsResources(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func PodFitsResources(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { node := nodeInfo.Node() if node == nil { return false, nil, fmt.Errorf("node not found") @@ -495,7 +495,7 @@ func PodFitsResources(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.N var predicateFails []algorithm.PredicateFailureReason allowedPodNumber := nodeInfo.AllowedPodNumber() if len(nodeInfo.Pods())+1 > allowedPodNumber { - predicateFails = append(predicateFails, NewInsufficientResourceError(api.ResourcePods, 1, int64(len(nodeInfo.Pods())), int64(allowedPodNumber))) + predicateFails = append(predicateFails, NewInsufficientResourceError(v1.ResourcePods, 1, int64(len(nodeInfo.Pods())), int64(allowedPodNumber))) } var podRequest *schedulercache.Resource @@ -511,13 +511,13 @@ func PodFitsResources(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.N allocatable := nodeInfo.AllocatableResource() if allocatable.MilliCPU < podRequest.MilliCPU+nodeInfo.RequestedResource().MilliCPU { - predicateFails = append(predicateFails, NewInsufficientResourceError(api.ResourceCPU, podRequest.MilliCPU, nodeInfo.RequestedResource().MilliCPU, allocatable.MilliCPU)) + predicateFails = append(predicateFails, NewInsufficientResourceError(v1.ResourceCPU, podRequest.MilliCPU, nodeInfo.RequestedResource().MilliCPU, allocatable.MilliCPU)) } if allocatable.Memory < podRequest.Memory+nodeInfo.RequestedResource().Memory { - predicateFails = append(predicateFails, NewInsufficientResourceError(api.ResourceMemory, podRequest.Memory, nodeInfo.RequestedResource().Memory, allocatable.Memory)) + predicateFails = append(predicateFails, NewInsufficientResourceError(v1.ResourceMemory, podRequest.Memory, nodeInfo.RequestedResource().Memory, allocatable.Memory)) } if allocatable.NvidiaGPU < podRequest.NvidiaGPU+nodeInfo.RequestedResource().NvidiaGPU { - predicateFails = append(predicateFails, NewInsufficientResourceError(api.ResourceNvidiaGPU, podRequest.NvidiaGPU, nodeInfo.RequestedResource().NvidiaGPU, allocatable.NvidiaGPU)) + predicateFails = append(predicateFails, NewInsufficientResourceError(v1.ResourceNvidiaGPU, podRequest.NvidiaGPU, nodeInfo.RequestedResource().NvidiaGPU, allocatable.NvidiaGPU)) } for rName, rQuant := range podRequest.OpaqueIntResources { if allocatable.OpaqueIntResources[rName] < rQuant+nodeInfo.RequestedResource().OpaqueIntResources[rName] { @@ -536,9 +536,9 @@ func PodFitsResources(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.N // nodeMatchesNodeSelectorTerms checks if a node's labels satisfy a list of node selector terms, // terms are ORed, and an empty list of terms will match nothing. -func nodeMatchesNodeSelectorTerms(node *api.Node, nodeSelectorTerms []api.NodeSelectorTerm) bool { +func nodeMatchesNodeSelectorTerms(node *v1.Node, nodeSelectorTerms []v1.NodeSelectorTerm) bool { for _, req := range nodeSelectorTerms { - nodeSelector, err := api.NodeSelectorRequirementsAsSelector(req.MatchExpressions) + nodeSelector, err := v1.NodeSelectorRequirementsAsSelector(req.MatchExpressions) if err != nil { glog.V(10).Infof("Failed to parse MatchExpressions: %+v, regarding as not match.", req.MatchExpressions) return false @@ -551,7 +551,7 @@ func nodeMatchesNodeSelectorTerms(node *api.Node, nodeSelectorTerms []api.NodeSe } // The pod can only schedule onto nodes that satisfy requirements in both NodeAffinity and nodeSelector. -func podMatchesNodeLabels(pod *api.Pod, node *api.Node) bool { +func podMatchesNodeLabels(pod *v1.Pod, node *v1.Node) bool { // Check if node.Labels match pod.Spec.NodeSelector. if len(pod.Spec.NodeSelector) > 0 { selector := labels.SelectorFromSet(pod.Spec.NodeSelector) @@ -562,7 +562,7 @@ func podMatchesNodeLabels(pod *api.Pod, node *api.Node) bool { // Parse required node affinity scheduling requirements // and check if the current node match the requirements. - affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations) + affinity, err := v1.GetAffinityFromPodAnnotations(pod.Annotations) if err != nil { glog.V(10).Infof("Failed to get Affinity from Pod %+v, err: %+v", podName(pod), err) return false @@ -603,7 +603,7 @@ func podMatchesNodeLabels(pod *api.Pod, node *api.Node) bool { return nodeAffinityMatches } -func PodSelectorMatches(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func PodSelectorMatches(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { node := nodeInfo.Node() if node == nil { return false, nil, fmt.Errorf("node not found") @@ -614,7 +614,7 @@ func PodSelectorMatches(pod *api.Pod, meta interface{}, nodeInfo *schedulercache return false, []algorithm.PredicateFailureReason{ErrNodeSelectorNotMatch}, nil } -func PodFitsHost(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func PodFitsHost(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { if len(pod.Spec.NodeName) == 0 { return true, nil, nil } @@ -653,7 +653,7 @@ func NewNodeLabelPredicate(labels []string, presence bool) algorithm.FitPredicat // Alternately, eliminating nodes that have a certain label, regardless of value, is also useful // A node may have a label with "retiring" as key and the date as the value // and it may be desirable to avoid scheduling new pods on this node -func (n *NodeLabelChecker) CheckNodeLabelPresence(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func (n *NodeLabelChecker) CheckNodeLabelPresence(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { node := nodeInfo.Node() if node == nil { return false, nil, fmt.Errorf("node not found") @@ -732,9 +732,9 @@ func NewServiceAffinityPredicate(podLister algorithm.PodLister, serviceLister al // // WARNING: This Predicate is NOT guaranteed to work if some of the predicateMetadata data isn't precomputed... // For that reason it is not exported, i.e. it is highly coupled to the implementation of the FitPredicate construction. -func (s *ServiceAffinity) checkServiceAffinity(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { - var services []*api.Service - var pods []*api.Pod +func (s *ServiceAffinity) checkServiceAffinity(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { + var services []*v1.Service + var pods []*v1.Pod if pm, ok := meta.(*predicateMetadata); ok && (pm.serviceAffinityMatchingPodList != nil || pm.serviceAffinityMatchingPodServices != nil) { services = pm.serviceAffinityMatchingPodServices pods = pm.serviceAffinityMatchingPodList @@ -769,7 +769,7 @@ func (s *ServiceAffinity) checkServiceAffinity(pod *api.Pod, meta interface{}, n return false, []algorithm.PredicateFailureReason{ErrServiceAffinityViolated}, nil } -func PodFitsHostPorts(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func PodFitsHostPorts(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { var wantPorts map[int]bool if predicateMeta, ok := meta.(*predicateMetadata); ok { wantPorts = predicateMeta.podPorts @@ -791,7 +791,7 @@ func PodFitsHostPorts(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.N return true, nil, nil } -func GetUsedPorts(pods ...*api.Pod) map[int]bool { +func GetUsedPorts(pods ...*v1.Pod) map[int]bool { ports := make(map[int]bool) for _, pod := range pods { for j := range pod.Spec.Containers { @@ -821,7 +821,7 @@ func haveSame(a1, a2 []string) bool { return false } -func GeneralPredicates(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func GeneralPredicates(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { var predicateFails []algorithm.PredicateFailureReason fit, reasons, err := PodFitsResources(pod, meta, nodeInfo) if err != nil { @@ -873,7 +873,7 @@ func NewPodAffinityPredicate(info NodeInfo, podLister algorithm.PodLister, failu return checker.InterPodAffinityMatches } -func (c *PodAffinityChecker) InterPodAffinityMatches(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func (c *PodAffinityChecker) InterPodAffinityMatches(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { node := nodeInfo.Node() if node == nil { return false, nil, fmt.Errorf("node not found") @@ -883,7 +883,7 @@ func (c *PodAffinityChecker) InterPodAffinityMatches(pod *api.Pod, meta interfac } // Now check if requirements will be satisfied on this node. - affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations) + affinity, err := v1.GetAffinityFromPodAnnotations(pod.Annotations) if err != nil { return false, nil, err } @@ -907,7 +907,7 @@ func (c *PodAffinityChecker) InterPodAffinityMatches(pod *api.Pod, meta interfac // First return value indicates whether a matching pod exists on a node that matches the topology key, // while the second return value indicates whether a matching pod exists anywhere. // TODO: Do we really need any pod matching, or all pods matching? I think the latter. -func (c *PodAffinityChecker) anyPodMatchesPodAffinityTerm(pod *api.Pod, allPods []*api.Pod, node *api.Node, term *api.PodAffinityTerm) (bool, bool, error) { +func (c *PodAffinityChecker) anyPodMatchesPodAffinityTerm(pod *v1.Pod, allPods []*v1.Pod, node *v1.Node, term *v1.PodAffinityTerm) (bool, bool, error) { matchingPodExists := false for _, existingPod := range allPods { match, err := priorityutil.PodMatchesTermsNamespaceAndSelector(existingPod, pod, term) @@ -928,7 +928,7 @@ func (c *PodAffinityChecker) anyPodMatchesPodAffinityTerm(pod *api.Pod, allPods return false, matchingPodExists, nil } -func getPodAffinityTerms(podAffinity *api.PodAffinity) (terms []api.PodAffinityTerm) { +func getPodAffinityTerms(podAffinity *v1.PodAffinity) (terms []v1.PodAffinityTerm) { if podAffinity != nil { if len(podAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 { terms = podAffinity.RequiredDuringSchedulingIgnoredDuringExecution @@ -941,7 +941,7 @@ func getPodAffinityTerms(podAffinity *api.PodAffinity) (terms []api.PodAffinityT return terms } -func getPodAntiAffinityTerms(podAntiAffinity *api.PodAntiAffinity) (terms []api.PodAffinityTerm) { +func getPodAntiAffinityTerms(podAntiAffinity *v1.PodAntiAffinity) (terms []v1.PodAffinityTerm) { if podAntiAffinity != nil { if len(podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 { terms = podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution @@ -954,7 +954,7 @@ func getPodAntiAffinityTerms(podAntiAffinity *api.PodAntiAffinity) (terms []api. return terms } -func getMatchingAntiAffinityTerms(pod *api.Pod, nodeInfoMap map[string]*schedulercache.NodeInfo) ([]matchingPodAntiAffinityTerm, error) { +func getMatchingAntiAffinityTerms(pod *v1.Pod, nodeInfoMap map[string]*schedulercache.NodeInfo) ([]matchingPodAntiAffinityTerm, error) { allNodeNames := make([]string, 0, len(nodeInfoMap)) for name := range nodeInfoMap { allNodeNames = append(allNodeNames, name) @@ -985,7 +985,7 @@ func getMatchingAntiAffinityTerms(pod *api.Pod, nodeInfoMap map[string]*schedule } var nodeResult []matchingPodAntiAffinityTerm for _, existingPod := range nodeInfo.PodsWithAffinity() { - affinity, err := api.GetAffinityFromPodAnnotations(existingPod.Annotations) + affinity, err := v1.GetAffinityFromPodAnnotations(existingPod.Annotations) if err != nil { catchError(err) return @@ -1012,10 +1012,10 @@ func getMatchingAntiAffinityTerms(pod *api.Pod, nodeInfoMap map[string]*schedule return result, firstError } -func (c *PodAffinityChecker) getMatchingAntiAffinityTerms(pod *api.Pod, allPods []*api.Pod) ([]matchingPodAntiAffinityTerm, error) { +func (c *PodAffinityChecker) getMatchingAntiAffinityTerms(pod *v1.Pod, allPods []*v1.Pod) ([]matchingPodAntiAffinityTerm, error) { var result []matchingPodAntiAffinityTerm for _, existingPod := range allPods { - affinity, err := api.GetAffinityFromPodAnnotations(existingPod.Annotations) + affinity, err := v1.GetAffinityFromPodAnnotations(existingPod.Annotations) if err != nil { return nil, err } @@ -1040,7 +1040,7 @@ func (c *PodAffinityChecker) getMatchingAntiAffinityTerms(pod *api.Pod, allPods // Checks if scheduling the pod onto this node would break any anti-affinity // rules indicated by the existing pods. -func (c *PodAffinityChecker) satisfiesExistingPodsAntiAffinity(pod *api.Pod, meta interface{}, node *api.Node) bool { +func (c *PodAffinityChecker) satisfiesExistingPodsAntiAffinity(pod *v1.Pod, meta interface{}, node *v1.Node) bool { var matchingTerms []matchingPodAntiAffinityTerm if predicateMeta, ok := meta.(*predicateMetadata); ok { matchingTerms = predicateMeta.matchingAntiAffinityTerms @@ -1072,7 +1072,7 @@ func (c *PodAffinityChecker) satisfiesExistingPodsAntiAffinity(pod *api.Pod, met } // Checks if scheduling the pod onto this node would break any rules of this pod. -func (c *PodAffinityChecker) satisfiesPodsAffinityAntiAffinity(pod *api.Pod, node *api.Node, affinity *api.Affinity) bool { +func (c *PodAffinityChecker) satisfiesPodsAffinityAntiAffinity(pod *v1.Pod, node *v1.Node, affinity *v1.Affinity) bool { allPods, err := c.podLister.List(labels.Everything()) if err != nil { return false @@ -1118,18 +1118,18 @@ func (c *PodAffinityChecker) satisfiesPodsAffinityAntiAffinity(pod *api.Pod, nod return true } -func PodToleratesNodeTaints(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func PodToleratesNodeTaints(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { node := nodeInfo.Node() if node == nil { return false, nil, fmt.Errorf("node not found") } - taints, err := api.GetTaintsFromNodeAnnotations(node.Annotations) + taints, err := v1.GetTaintsFromNodeAnnotations(node.Annotations) if err != nil { return false, nil, err } - tolerations, err := api.GetTolerationsFromPodAnnotations(pod.Annotations) + tolerations, err := v1.GetTolerationsFromPodAnnotations(pod.Annotations) if err != nil { return false, nil, err } @@ -1140,7 +1140,7 @@ func PodToleratesNodeTaints(pod *api.Pod, meta interface{}, nodeInfo *schedulerc return false, []algorithm.PredicateFailureReason{ErrTaintsTolerationsNotMatch}, nil } -func tolerationsToleratesTaints(tolerations []api.Toleration, taints []api.Taint) bool { +func tolerationsToleratesTaints(tolerations []v1.Toleration, taints []v1.Taint) bool { // If the taint list is nil/empty, it is tolerated by all tolerations by default. if len(taints) == 0 { return true @@ -1154,11 +1154,11 @@ func tolerationsToleratesTaints(tolerations []api.Toleration, taints []api.Taint for i := range taints { taint := &taints[i] // skip taints that have effect PreferNoSchedule, since it is for priorities - if taint.Effect == api.TaintEffectPreferNoSchedule { + if taint.Effect == v1.TaintEffectPreferNoSchedule { continue } - if !api.TaintToleratedByTolerations(taint, tolerations) { + if !v1.TaintToleratedByTolerations(taint, tolerations) { return false } } @@ -1167,13 +1167,13 @@ func tolerationsToleratesTaints(tolerations []api.Toleration, taints []api.Taint } // Determine if a pod is scheduled with best-effort QoS -func isPodBestEffort(pod *api.Pod) bool { +func isPodBestEffort(pod *v1.Pod) bool { return qos.GetPodQOS(pod) == qos.BestEffort } // CheckNodeMemoryPressurePredicate checks if a pod can be scheduled on a node // reporting memory pressure condition. -func CheckNodeMemoryPressurePredicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func CheckNodeMemoryPressurePredicate(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { node := nodeInfo.Node() if node == nil { return false, nil, fmt.Errorf("node not found") @@ -1194,7 +1194,7 @@ func CheckNodeMemoryPressurePredicate(pod *api.Pod, meta interface{}, nodeInfo * // is node under pressure? for _, cond := range node.Status.Conditions { - if cond.Type == api.NodeMemoryPressure && cond.Status == api.ConditionTrue { + if cond.Type == v1.NodeMemoryPressure && cond.Status == v1.ConditionTrue { return false, []algorithm.PredicateFailureReason{ErrNodeUnderMemoryPressure}, nil } } @@ -1204,7 +1204,7 @@ func CheckNodeMemoryPressurePredicate(pod *api.Pod, meta interface{}, nodeInfo * // CheckNodeDiskPressurePredicate checks if a pod can be scheduled on a node // reporting disk pressure condition. -func CheckNodeDiskPressurePredicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func CheckNodeDiskPressurePredicate(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { node := nodeInfo.Node() if node == nil { return false, nil, fmt.Errorf("node not found") @@ -1212,7 +1212,7 @@ func CheckNodeDiskPressurePredicate(pod *api.Pod, meta interface{}, nodeInfo *sc // is node under pressure? for _, cond := range node.Status.Conditions { - if cond.Type == api.NodeDiskPressure && cond.Status == api.ConditionTrue { + if cond.Type == v1.NodeDiskPressure && cond.Status == v1.ConditionTrue { return false, []algorithm.PredicateFailureReason{ErrNodeUnderDiskPressure}, nil } } diff --git a/plugin/pkg/scheduler/algorithm/predicates/predicates_test.go b/plugin/pkg/scheduler/algorithm/predicates/predicates_test.go index 931c59229fa..9932d6cd437 100644 --- a/plugin/pkg/scheduler/algorithm/predicates/predicates_test.go +++ b/plugin/pkg/scheduler/algorithm/predicates/predicates_test.go @@ -26,24 +26,24 @@ import ( "k8s.io/gengo/parser" "k8s.io/gengo/types" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/codeinspector" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" priorityutil "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) -type FakeNodeInfo api.Node +type FakeNodeInfo v1.Node -func (n FakeNodeInfo) GetNodeInfo(nodeName string) (*api.Node, error) { - node := api.Node(n) +func (n FakeNodeInfo) GetNodeInfo(nodeName string) (*v1.Node, error) { + node := v1.Node(n) return &node, nil } -type FakeNodeListInfo []api.Node +type FakeNodeListInfo []v1.Node -func (nodes FakeNodeListInfo) GetNodeInfo(nodeName string) (*api.Node, error) { +func (nodes FakeNodeListInfo) GetNodeInfo(nodeName string) (*v1.Node, error) { for _, node := range nodes { if node.Name == nodeName { return &node, nil @@ -52,9 +52,9 @@ func (nodes FakeNodeListInfo) GetNodeInfo(nodeName string) (*api.Node, error) { return nil, fmt.Errorf("Unable to find node: %s", nodeName) } -type FakePersistentVolumeClaimInfo []api.PersistentVolumeClaim +type FakePersistentVolumeClaimInfo []v1.PersistentVolumeClaim -func (pvcs FakePersistentVolumeClaimInfo) GetPersistentVolumeClaimInfo(namespace string, pvcID string) (*api.PersistentVolumeClaim, error) { +func (pvcs FakePersistentVolumeClaimInfo) GetPersistentVolumeClaimInfo(namespace string, pvcID string) (*v1.PersistentVolumeClaim, error) { for _, pvc := range pvcs { if pvc.Name == pvcID && pvc.Namespace == namespace { return &pvc, nil @@ -63,9 +63,9 @@ func (pvcs FakePersistentVolumeClaimInfo) GetPersistentVolumeClaimInfo(namespace return nil, fmt.Errorf("Unable to find persistent volume claim: %s/%s", namespace, pvcID) } -type FakePersistentVolumeInfo []api.PersistentVolume +type FakePersistentVolumeInfo []v1.PersistentVolume -func (pvs FakePersistentVolumeInfo) GetPersistentVolumeInfo(pvID string) (*api.PersistentVolume, error) { +func (pvs FakePersistentVolumeInfo) GetPersistentVolumeInfo(pvID string) (*v1.PersistentVolume, error) { for _, pv := range pvs { if pv.Name == pvID { return &pv, nil @@ -75,66 +75,66 @@ func (pvs FakePersistentVolumeInfo) GetPersistentVolumeInfo(pvID string) (*api.P } var ( - opaqueResourceA = api.OpaqueIntResourceName("AAA") - opaqueResourceB = api.OpaqueIntResourceName("BBB") + opaqueResourceA = v1.OpaqueIntResourceName("AAA") + opaqueResourceB = v1.OpaqueIntResourceName("BBB") ) -func makeResources(milliCPU, memory, nvidiaGPUs, pods, opaqueA int64) api.NodeResources { - return api.NodeResources{ - Capacity: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(milliCPU, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(memory, resource.BinarySI), - api.ResourcePods: *resource.NewQuantity(pods, resource.DecimalSI), - api.ResourceNvidiaGPU: *resource.NewQuantity(nvidiaGPUs, resource.DecimalSI), - opaqueResourceA: *resource.NewQuantity(opaqueA, resource.DecimalSI), +func makeResources(milliCPU, memory, nvidiaGPUs, pods, opaqueA int64) v1.NodeResources { + return v1.NodeResources{ + Capacity: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(milliCPU, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(memory, resource.BinarySI), + v1.ResourcePods: *resource.NewQuantity(pods, resource.DecimalSI), + v1.ResourceNvidiaGPU: *resource.NewQuantity(nvidiaGPUs, resource.DecimalSI), + opaqueResourceA: *resource.NewQuantity(opaqueA, resource.DecimalSI), }, } } -func makeAllocatableResources(milliCPU, memory, nvidiaGPUs, pods, opaqueA int64) api.ResourceList { - return api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(milliCPU, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(memory, resource.BinarySI), - api.ResourcePods: *resource.NewQuantity(pods, resource.DecimalSI), - api.ResourceNvidiaGPU: *resource.NewQuantity(nvidiaGPUs, resource.DecimalSI), - opaqueResourceA: *resource.NewQuantity(opaqueA, resource.DecimalSI), +func makeAllocatableResources(milliCPU, memory, nvidiaGPUs, pods, opaqueA int64) v1.ResourceList { + return v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(milliCPU, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(memory, resource.BinarySI), + v1.ResourcePods: *resource.NewQuantity(pods, resource.DecimalSI), + v1.ResourceNvidiaGPU: *resource.NewQuantity(nvidiaGPUs, resource.DecimalSI), + opaqueResourceA: *resource.NewQuantity(opaqueA, resource.DecimalSI), } } -func newResourcePod(usage ...schedulercache.Resource) *api.Pod { - containers := []api.Container{} +func newResourcePod(usage ...schedulercache.Resource) *v1.Pod { + containers := []v1.Container{} for _, req := range usage { - containers = append(containers, api.Container{ - Resources: api.ResourceRequirements{Requests: req.ResourceList()}, + containers = append(containers, v1.Container{ + Resources: v1.ResourceRequirements{Requests: req.ResourceList()}, }) } - return &api.Pod{ - Spec: api.PodSpec{ + return &v1.Pod{ + Spec: v1.PodSpec{ Containers: containers, }, } } -func newResourceInitPod(pod *api.Pod, usage ...schedulercache.Resource) *api.Pod { +func newResourceInitPod(pod *v1.Pod, usage ...schedulercache.Resource) *v1.Pod { pod.Spec.InitContainers = newResourcePod(usage...).Spec.Containers return pod } -func PredicateMetadata(p *api.Pod, nodeInfo map[string]*schedulercache.NodeInfo) interface{} { +func PredicateMetadata(p *v1.Pod, nodeInfo map[string]*schedulercache.NodeInfo) interface{} { pm := PredicateMetadataFactory{algorithm.FakePodLister{p}} return pm.GetMetadata(p, nodeInfo) } func TestPodFitsResources(t *testing.T) { enoughPodsTests := []struct { - pod *api.Pod + pod *v1.Pod nodeInfo *schedulercache.NodeInfo fits bool test string reasons []algorithm.PredicateFailureReason }{ { - pod: &api.Pod{}, + pod: &v1.Pod{}, nodeInfo: schedulercache.NewNodeInfo( newResourcePod(schedulercache.Resource{MilliCPU: 10, Memory: 20})), fits: true, @@ -147,8 +147,8 @@ func TestPodFitsResources(t *testing.T) { fits: false, test: "too many resources fails", reasons: []algorithm.PredicateFailureReason{ - NewInsufficientResourceError(api.ResourceCPU, 1, 10, 10), - NewInsufficientResourceError(api.ResourceMemory, 1, 20, 20), + NewInsufficientResourceError(v1.ResourceCPU, 1, 10, 10), + NewInsufficientResourceError(v1.ResourceMemory, 1, 20, 20), }, }, { @@ -157,7 +157,7 @@ func TestPodFitsResources(t *testing.T) { newResourcePod(schedulercache.Resource{MilliCPU: 8, Memory: 19})), fits: false, test: "too many resources fails due to init container cpu", - reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(api.ResourceCPU, 3, 8, 10)}, + reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(v1.ResourceCPU, 3, 8, 10)}, }, { pod: newResourceInitPod(newResourcePod(schedulercache.Resource{MilliCPU: 1, Memory: 1}), schedulercache.Resource{MilliCPU: 3, Memory: 1}, schedulercache.Resource{MilliCPU: 2, Memory: 1}), @@ -165,7 +165,7 @@ func TestPodFitsResources(t *testing.T) { newResourcePod(schedulercache.Resource{MilliCPU: 8, Memory: 19})), fits: false, test: "too many resources fails due to highest init container cpu", - reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(api.ResourceCPU, 3, 8, 10)}, + reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(v1.ResourceCPU, 3, 8, 10)}, }, { pod: newResourceInitPod(newResourcePod(schedulercache.Resource{MilliCPU: 1, Memory: 1}), schedulercache.Resource{MilliCPU: 1, Memory: 3}), @@ -173,7 +173,7 @@ func TestPodFitsResources(t *testing.T) { newResourcePod(schedulercache.Resource{MilliCPU: 9, Memory: 19})), fits: false, test: "too many resources fails due to init container memory", - reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(api.ResourceMemory, 3, 19, 20)}, + reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(v1.ResourceMemory, 3, 19, 20)}, }, { pod: newResourceInitPod(newResourcePod(schedulercache.Resource{MilliCPU: 1, Memory: 1}), schedulercache.Resource{MilliCPU: 1, Memory: 3}, schedulercache.Resource{MilliCPU: 1, Memory: 2}), @@ -181,7 +181,7 @@ func TestPodFitsResources(t *testing.T) { newResourcePod(schedulercache.Resource{MilliCPU: 9, Memory: 19})), fits: false, test: "too many resources fails due to highest init container memory", - reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(api.ResourceMemory, 3, 19, 20)}, + reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(v1.ResourceMemory, 3, 19, 20)}, }, { pod: newResourceInitPod(newResourcePod(schedulercache.Resource{MilliCPU: 1, Memory: 1}), schedulercache.Resource{MilliCPU: 1, Memory: 1}), @@ -210,7 +210,7 @@ func TestPodFitsResources(t *testing.T) { newResourcePod(schedulercache.Resource{MilliCPU: 9, Memory: 5})), fits: false, test: "one resource memory fits", - reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(api.ResourceCPU, 2, 9, 10)}, + reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(v1.ResourceCPU, 2, 9, 10)}, }, { pod: newResourcePod(schedulercache.Resource{MilliCPU: 1, Memory: 2}), @@ -218,7 +218,7 @@ func TestPodFitsResources(t *testing.T) { newResourcePod(schedulercache.Resource{MilliCPU: 5, Memory: 19})), fits: false, test: "one resource cpu fits", - reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(api.ResourceMemory, 2, 19, 20)}, + reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(v1.ResourceMemory, 2, 19, 20)}, }, { pod: newResourcePod(schedulercache.Resource{MilliCPU: 5, Memory: 1}), @@ -235,85 +235,85 @@ func TestPodFitsResources(t *testing.T) { test: "equal edge case for init container", }, { - pod: newResourcePod(schedulercache.Resource{OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 1}}), + pod: newResourcePod(schedulercache.Resource{OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 1}}), nodeInfo: schedulercache.NewNodeInfo(newResourcePod(schedulercache.Resource{})), fits: true, test: "opaque resource fits", }, { - pod: newResourceInitPod(newResourcePod(schedulercache.Resource{}), schedulercache.Resource{OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 1}}), + pod: newResourceInitPod(newResourcePod(schedulercache.Resource{}), schedulercache.Resource{OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 1}}), nodeInfo: schedulercache.NewNodeInfo(newResourcePod(schedulercache.Resource{})), fits: true, test: "opaque resource fits for init container", }, { pod: newResourcePod( - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 10}}), + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 10}}), nodeInfo: schedulercache.NewNodeInfo( - newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 0}})), + newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 0}})), fits: false, test: "opaque resource capacity enforced", reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(opaqueResourceA, 10, 0, 5)}, }, { pod: newResourceInitPod(newResourcePod(schedulercache.Resource{}), - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 10}}), + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 10}}), nodeInfo: schedulercache.NewNodeInfo( - newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 0}})), + newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 0}})), fits: false, test: "opaque resource capacity enforced for init container", reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(opaqueResourceA, 10, 0, 5)}, }, { pod: newResourcePod( - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 1}}), + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 1}}), nodeInfo: schedulercache.NewNodeInfo( - newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 5}})), + newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 5}})), fits: false, test: "opaque resource allocatable enforced", reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(opaqueResourceA, 1, 5, 5)}, }, { pod: newResourceInitPod(newResourcePod(schedulercache.Resource{}), - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 1}}), + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 1}}), nodeInfo: schedulercache.NewNodeInfo( - newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 5}})), + newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 5}})), fits: false, test: "opaque resource allocatable enforced for init container", reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(opaqueResourceA, 1, 5, 5)}, }, { pod: newResourcePod( - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 3}}, - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 3}}), + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 3}}, + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 3}}), nodeInfo: schedulercache.NewNodeInfo( - newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 2}})), + newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 2}})), fits: false, test: "opaque resource allocatable enforced for multiple containers", reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(opaqueResourceA, 6, 2, 5)}, }, { pod: newResourceInitPod(newResourcePod(schedulercache.Resource{}), - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 3}}, - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 3}}), + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 3}}, + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 3}}), nodeInfo: schedulercache.NewNodeInfo( - newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 2}})), + newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 2}})), fits: true, test: "opaque resource allocatable admits multiple init containers", }, { pod: newResourceInitPod(newResourcePod(schedulercache.Resource{}), - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 6}}, - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 3}}), + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 6}}, + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 3}}), nodeInfo: schedulercache.NewNodeInfo( - newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceA: 2}})), + newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceA: 2}})), fits: false, test: "opaque resource allocatable enforced for multiple init containers", reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(opaqueResourceA, 6, 2, 5)}, }, { pod: newResourcePod( - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceB: 1}}), + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceB: 1}}), nodeInfo: schedulercache.NewNodeInfo( newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0})), fits: false, @@ -322,7 +322,7 @@ func TestPodFitsResources(t *testing.T) { }, { pod: newResourceInitPod(newResourcePod(schedulercache.Resource{}), - schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[api.ResourceName]int64{opaqueResourceB: 1}}), + schedulercache.Resource{MilliCPU: 1, Memory: 1, OpaqueIntResources: map[v1.ResourceName]int64{opaqueResourceB: 1}}), nodeInfo: schedulercache.NewNodeInfo( newResourcePod(schedulercache.Resource{MilliCPU: 0, Memory: 0})), fits: false, @@ -332,7 +332,7 @@ func TestPodFitsResources(t *testing.T) { } for _, test := range enoughPodsTests { - node := api.Node{Status: api.NodeStatus{Capacity: makeResources(10, 20, 0, 32, 5).Capacity, Allocatable: makeAllocatableResources(10, 20, 0, 32, 5)}} + node := v1.Node{Status: v1.NodeStatus{Capacity: makeResources(10, 20, 0, 32, 5).Capacity, Allocatable: makeAllocatableResources(10, 20, 0, 32, 5)}} test.nodeInfo.SetNode(&node) fits, reasons, err := PodFitsResources(test.pod, PredicateMetadata(test.pod, nil), test.nodeInfo) if err != nil { @@ -347,19 +347,19 @@ func TestPodFitsResources(t *testing.T) { } notEnoughPodsTests := []struct { - pod *api.Pod + pod *v1.Pod nodeInfo *schedulercache.NodeInfo fits bool test string reasons []algorithm.PredicateFailureReason }{ { - pod: &api.Pod{}, + pod: &v1.Pod{}, nodeInfo: schedulercache.NewNodeInfo( newResourcePod(schedulercache.Resource{MilliCPU: 10, Memory: 20})), fits: false, test: "even without specified resources predicate fails when there's no space for additional pod", - reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(api.ResourcePods, 1, 1, 1)}, + reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(v1.ResourcePods, 1, 1, 1)}, }, { pod: newResourcePod(schedulercache.Resource{MilliCPU: 1, Memory: 1}), @@ -367,7 +367,7 @@ func TestPodFitsResources(t *testing.T) { newResourcePod(schedulercache.Resource{MilliCPU: 5, Memory: 5})), fits: false, test: "even if both resources fit predicate fails when there's no space for additional pod", - reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(api.ResourcePods, 1, 1, 1)}, + reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(v1.ResourcePods, 1, 1, 1)}, }, { pod: newResourcePod(schedulercache.Resource{MilliCPU: 5, Memory: 1}), @@ -375,7 +375,7 @@ func TestPodFitsResources(t *testing.T) { newResourcePod(schedulercache.Resource{MilliCPU: 5, Memory: 19})), fits: false, test: "even for equal edge case predicate fails when there's no space for additional pod", - reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(api.ResourcePods, 1, 1, 1)}, + reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(v1.ResourcePods, 1, 1, 1)}, }, { pod: newResourceInitPod(newResourcePod(schedulercache.Resource{MilliCPU: 5, Memory: 1}), schedulercache.Resource{MilliCPU: 5, Memory: 1}), @@ -383,11 +383,11 @@ func TestPodFitsResources(t *testing.T) { newResourcePod(schedulercache.Resource{MilliCPU: 5, Memory: 19})), fits: false, test: "even for equal edge case predicate fails when there's no space for additional pod due to init container", - reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(api.ResourcePods, 1, 1, 1)}, + reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(v1.ResourcePods, 1, 1, 1)}, }, } for _, test := range notEnoughPodsTests { - node := api.Node{Status: api.NodeStatus{Capacity: api.ResourceList{}, Allocatable: makeAllocatableResources(10, 20, 0, 1, 0)}} + node := v1.Node{Status: v1.NodeStatus{Capacity: v1.ResourceList{}, Allocatable: makeAllocatableResources(10, 20, 0, 1, 0)}} test.nodeInfo.SetNode(&node) fits, reasons, err := PodFitsResources(test.pod, PredicateMetadata(test.pod, nil), test.nodeInfo) if err != nil { @@ -404,25 +404,25 @@ func TestPodFitsResources(t *testing.T) { func TestPodFitsHost(t *testing.T) { tests := []struct { - pod *api.Pod - node *api.Node + pod *v1.Pod + node *v1.Node fits bool test string }{ { - pod: &api.Pod{}, - node: &api.Node{}, + pod: &v1.Pod{}, + node: &v1.Node{}, fits: true, test: "no host specified", }, { - pod: &api.Pod{ - Spec: api.PodSpec{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ NodeName: "foo", }, }, - node: &api.Node{ - ObjectMeta: api.ObjectMeta{ + node: &v1.Node{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", }, }, @@ -430,13 +430,13 @@ func TestPodFitsHost(t *testing.T) { test: "host matches", }, { - pod: &api.Pod{ - Spec: api.PodSpec{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ NodeName: "bar", }, }, - node: &api.Node{ - ObjectMeta: api.ObjectMeta{ + node: &v1.Node{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", }, }, @@ -462,15 +462,15 @@ func TestPodFitsHost(t *testing.T) { } } -func newPod(host string, hostPorts ...int) *api.Pod { - networkPorts := []api.ContainerPort{} +func newPod(host string, hostPorts ...int) *v1.Pod { + networkPorts := []v1.ContainerPort{} for _, port := range hostPorts { - networkPorts = append(networkPorts, api.ContainerPort{HostPort: int32(port)}) + networkPorts = append(networkPorts, v1.ContainerPort{HostPort: int32(port)}) } - return &api.Pod{ - Spec: api.PodSpec{ + return &v1.Pod{ + Spec: v1.PodSpec{ NodeName: host, - Containers: []api.Container{ + Containers: []v1.Container{ { Ports: networkPorts, }, @@ -481,13 +481,13 @@ func newPod(host string, hostPorts ...int) *api.Pod { func TestPodFitsHostPorts(t *testing.T) { tests := []struct { - pod *api.Pod + pod *v1.Pod nodeInfo *schedulercache.NodeInfo fits bool test string }{ { - pod: &api.Pod{}, + pod: &v1.Pod{}, nodeInfo: schedulercache.NewNodeInfo(), fits: true, test: "nothing running", @@ -539,25 +539,25 @@ func TestPodFitsHostPorts(t *testing.T) { func TestGetUsedPorts(t *testing.T) { tests := []struct { - pods []*api.Pod + pods []*v1.Pod ports map[int]bool }{ { - []*api.Pod{ + []*v1.Pod{ newPod("m1", 9090), }, map[int]bool{9090: true}, }, { - []*api.Pod{ + []*v1.Pod{ newPod("m1", 9090), newPod("m1", 9091), }, map[int]bool{9090: true, 9091: true}, }, { - []*api.Pod{ + []*v1.Pod{ newPod("m1", 9090), newPod("m2", 9091), }, @@ -574,22 +574,22 @@ func TestGetUsedPorts(t *testing.T) { } func TestDiskConflicts(t *testing.T) { - volState := api.PodSpec{ - Volumes: []api.Volume{ + volState := v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "foo", }, }, }, }, } - volState2 := api.PodSpec{ - Volumes: []api.Volume{ + volState2 := v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + VolumeSource: v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: "bar", }, }, @@ -597,15 +597,15 @@ func TestDiskConflicts(t *testing.T) { }, } tests := []struct { - pod *api.Pod + pod *v1.Pod nodeInfo *schedulercache.NodeInfo isOk bool test string }{ - {&api.Pod{}, schedulercache.NewNodeInfo(), true, "nothing"}, - {&api.Pod{}, schedulercache.NewNodeInfo(&api.Pod{Spec: volState}), true, "one state"}, - {&api.Pod{Spec: volState}, schedulercache.NewNodeInfo(&api.Pod{Spec: volState}), false, "same state"}, - {&api.Pod{Spec: volState2}, schedulercache.NewNodeInfo(&api.Pod{Spec: volState}), true, "different state"}, + {&v1.Pod{}, schedulercache.NewNodeInfo(), true, "nothing"}, + {&v1.Pod{}, schedulercache.NewNodeInfo(&v1.Pod{Spec: volState}), true, "one state"}, + {&v1.Pod{Spec: volState}, schedulercache.NewNodeInfo(&v1.Pod{Spec: volState}), false, "same state"}, + {&v1.Pod{Spec: volState2}, schedulercache.NewNodeInfo(&v1.Pod{Spec: volState}), true, "different state"}, } expectedFailureReasons := []algorithm.PredicateFailureReason{ErrDiskConflict} @@ -627,22 +627,22 @@ func TestDiskConflicts(t *testing.T) { } func TestAWSDiskConflicts(t *testing.T) { - volState := api.PodSpec{ - Volumes: []api.Volume{ + volState := v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{ + VolumeSource: v1.VolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: "foo", }, }, }, }, } - volState2 := api.PodSpec{ - Volumes: []api.Volume{ + volState2 := v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{ + VolumeSource: v1.VolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: "bar", }, }, @@ -650,15 +650,15 @@ func TestAWSDiskConflicts(t *testing.T) { }, } tests := []struct { - pod *api.Pod + pod *v1.Pod nodeInfo *schedulercache.NodeInfo isOk bool test string }{ - {&api.Pod{}, schedulercache.NewNodeInfo(), true, "nothing"}, - {&api.Pod{}, schedulercache.NewNodeInfo(&api.Pod{Spec: volState}), true, "one state"}, - {&api.Pod{Spec: volState}, schedulercache.NewNodeInfo(&api.Pod{Spec: volState}), false, "same state"}, - {&api.Pod{Spec: volState2}, schedulercache.NewNodeInfo(&api.Pod{Spec: volState}), true, "different state"}, + {&v1.Pod{}, schedulercache.NewNodeInfo(), true, "nothing"}, + {&v1.Pod{}, schedulercache.NewNodeInfo(&v1.Pod{Spec: volState}), true, "one state"}, + {&v1.Pod{Spec: volState}, schedulercache.NewNodeInfo(&v1.Pod{Spec: volState}), false, "same state"}, + {&v1.Pod{Spec: volState2}, schedulercache.NewNodeInfo(&v1.Pod{Spec: volState}), true, "different state"}, } expectedFailureReasons := []algorithm.PredicateFailureReason{ErrDiskConflict} @@ -680,11 +680,11 @@ func TestAWSDiskConflicts(t *testing.T) { } func TestRBDDiskConflicts(t *testing.T) { - volState := api.PodSpec{ - Volumes: []api.Volume{ + volState := v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - RBD: &api.RBDVolumeSource{ + VolumeSource: v1.VolumeSource{ + RBD: &v1.RBDVolumeSource{ CephMonitors: []string{"a", "b"}, RBDPool: "foo", RBDImage: "bar", @@ -694,11 +694,11 @@ func TestRBDDiskConflicts(t *testing.T) { }, }, } - volState2 := api.PodSpec{ - Volumes: []api.Volume{ + volState2 := v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - RBD: &api.RBDVolumeSource{ + VolumeSource: v1.VolumeSource{ + RBD: &v1.RBDVolumeSource{ CephMonitors: []string{"c", "d"}, RBDPool: "foo", RBDImage: "bar", @@ -709,15 +709,15 @@ func TestRBDDiskConflicts(t *testing.T) { }, } tests := []struct { - pod *api.Pod + pod *v1.Pod nodeInfo *schedulercache.NodeInfo isOk bool test string }{ - {&api.Pod{}, schedulercache.NewNodeInfo(), true, "nothing"}, - {&api.Pod{}, schedulercache.NewNodeInfo(&api.Pod{Spec: volState}), true, "one state"}, - {&api.Pod{Spec: volState}, schedulercache.NewNodeInfo(&api.Pod{Spec: volState}), false, "same state"}, - {&api.Pod{Spec: volState2}, schedulercache.NewNodeInfo(&api.Pod{Spec: volState}), true, "different state"}, + {&v1.Pod{}, schedulercache.NewNodeInfo(), true, "nothing"}, + {&v1.Pod{}, schedulercache.NewNodeInfo(&v1.Pod{Spec: volState}), true, "one state"}, + {&v1.Pod{Spec: volState}, schedulercache.NewNodeInfo(&v1.Pod{Spec: volState}), false, "same state"}, + {&v1.Pod{Spec: volState2}, schedulercache.NewNodeInfo(&v1.Pod{Spec: volState}), true, "different state"}, } expectedFailureReasons := []algorithm.PredicateFailureReason{ErrDiskConflict} @@ -740,19 +740,19 @@ func TestRBDDiskConflicts(t *testing.T) { func TestPodFitsSelector(t *testing.T) { tests := []struct { - pod *api.Pod + pod *v1.Pod labels map[string]string fits bool test string }{ { - pod: &api.Pod{}, + pod: &v1.Pod{}, fits: true, test: "no selector", }, { - pod: &api.Pod{ - Spec: api.PodSpec{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ NodeSelector: map[string]string{ "foo": "bar", }, @@ -762,8 +762,8 @@ func TestPodFitsSelector(t *testing.T) { test: "missing labels", }, { - pod: &api.Pod{ - Spec: api.PodSpec{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ NodeSelector: map[string]string{ "foo": "bar", }, @@ -776,8 +776,8 @@ func TestPodFitsSelector(t *testing.T) { test: "same labels", }, { - pod: &api.Pod{ - Spec: api.PodSpec{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ NodeSelector: map[string]string{ "foo": "bar", }, @@ -791,8 +791,8 @@ func TestPodFitsSelector(t *testing.T) { test: "node labels are superset", }, { - pod: &api.Pod{ - Spec: api.PodSpec{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ NodeSelector: map[string]string{ "foo": "bar", "baz": "blah", @@ -806,10 +806,10 @@ func TestPodFitsSelector(t *testing.T) { test: "node labels are subset", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -829,10 +829,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with matchExpressions using In operator that matches the existing node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -853,10 +853,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with matchExpressions using Gt operator that matches the existing node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -876,10 +876,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with matchExpressions using NotIn operator that matches the existing node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -898,10 +898,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with matchExpressions using Exists operator that matches the existing node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -921,10 +921,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with affinity that don't match node's labels won't schedule onto the node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": null }}}`, @@ -938,10 +938,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with a nil []NodeSelectorTerm in affinity, can't match the node's labels and won't schedule onto the node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [] }}}`, @@ -955,10 +955,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with an empty []NodeSelectorTerm in affinity, can't match the node's labels and won't schedule onto the node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{}, {}] }}}`, @@ -972,10 +972,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with invalid NodeSelectTerms in affinity will match no objects and won't schedule onto the node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{"matchExpressions": [{}]}] }}}`, @@ -989,8 +989,8 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with empty MatchExpressions is not a valid value will match no objects and won't schedule onto the node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ "some-key": "some-value", }, @@ -1003,10 +1003,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with no Affinity will schedule onto a node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": null }}`, }, @@ -1019,10 +1019,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with Affinity but nil NodeSelector will schedule onto a node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -1045,10 +1045,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with multiple matchExpressions ANDed that matches the existing node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -1071,10 +1071,10 @@ func TestPodFitsSelector(t *testing.T) { test: "Pod with multiple matchExpressions ANDed that doesn't match the existing node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [ { @@ -1104,10 +1104,10 @@ func TestPodFitsSelector(t *testing.T) { }, // TODO: Uncomment this test when implement RequiredDuringSchedulingRequiredDuringExecution // { - // pod: &api.Pod{ - // ObjectMeta: api.ObjectMeta{ + // pod: &v1.Pod{ + // ObjectMeta: v1.ObjectMeta{ // Annotations: map[string]string{ - // api.AffinityAnnotationKey: ` + // v1.AffinityAnnotationKey: ` // {"nodeAffinity": { // "requiredDuringSchedulingRequiredDuringExecution": { // "nodeSelectorTerms": [{ @@ -1139,10 +1139,10 @@ func TestPodFitsSelector(t *testing.T) { // "requiredDuringSchedulingIgnoredDuringExecution indicated that don't match node's labels and won't schedule onto the node", // }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -1153,7 +1153,7 @@ func TestPodFitsSelector(t *testing.T) { }}}`, }, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeSelector: map[string]string{ "foo": "bar", }, @@ -1167,10 +1167,10 @@ func TestPodFitsSelector(t *testing.T) { "both are satisfied, will schedule onto the node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -1181,7 +1181,7 @@ func TestPodFitsSelector(t *testing.T) { }}}`, }, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeSelector: map[string]string{ "foo": "bar", }, @@ -1198,7 +1198,7 @@ func TestPodFitsSelector(t *testing.T) { expectedFailureReasons := []algorithm.PredicateFailureReason{ErrNodeSelectorNotMatch} for _, test := range tests { - node := api.Node{ObjectMeta: api.ObjectMeta{Labels: test.labels}} + node := v1.Node{ObjectMeta: v1.ObjectMeta{Labels: test.labels}} nodeInfo := schedulercache.NewNodeInfo() nodeInfo.SetNode(&node) @@ -1218,7 +1218,7 @@ func TestPodFitsSelector(t *testing.T) { func TestNodeLabelPresence(t *testing.T) { label := map[string]string{"foo": "bar", "bar": "foo"} tests := []struct { - pod *api.Pod + pod *v1.Pod labels []string presence bool fits bool @@ -1264,7 +1264,7 @@ func TestNodeLabelPresence(t *testing.T) { expectedFailureReasons := []algorithm.PredicateFailureReason{ErrNodeLabelPresenceViolated} for _, test := range tests { - node := api.Node{ObjectMeta: api.ObjectMeta{Labels: label}} + node := v1.Node{ObjectMeta: v1.ObjectMeta{Labels: label}} nodeInfo := schedulercache.NewNodeInfo() nodeInfo.SetNode(&node) @@ -1300,109 +1300,109 @@ func TestServiceAffinity(t *testing.T) { "region": "r2", "zone": "z22", } - node1 := api.Node{ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labels1}} - node2 := api.Node{ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labels2}} - node3 := api.Node{ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labels3}} - node4 := api.Node{ObjectMeta: api.ObjectMeta{Name: "machine4", Labels: labels4}} - node5 := api.Node{ObjectMeta: api.ObjectMeta{Name: "machine5", Labels: labels4}} + node1 := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labels1}} + node2 := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labels2}} + node3 := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labels3}} + node4 := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "machine4", Labels: labels4}} + node5 := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "machine5", Labels: labels4}} tests := []struct { - pod *api.Pod - pods []*api.Pod - services []*api.Service - node *api.Node + pod *v1.Pod + pods []*v1.Pod + services []*v1.Service + node *v1.Node labels []string fits bool test string }{ { - pod: new(api.Pod), + pod: new(v1.Pod), node: &node1, fits: true, labels: []string{"region"}, test: "nothing scheduled", }, { - pod: &api.Pod{Spec: api.PodSpec{NodeSelector: map[string]string{"region": "r1"}}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeSelector: map[string]string{"region": "r1"}}}, node: &node1, fits: true, labels: []string{"region"}, test: "pod with region label match", }, { - pod: &api.Pod{Spec: api.PodSpec{NodeSelector: map[string]string{"region": "r2"}}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeSelector: map[string]string{"region": "r2"}}}, node: &node1, fits: false, labels: []string{"region"}, test: "pod with region label mismatch", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: selector}}, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: selector}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: selector}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: selector}}}, node: &node1, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: selector}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}}}, fits: true, labels: []string{"region"}, test: "service pod on same node", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: selector}}, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: selector}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: selector}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: selector}}}, node: &node1, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: selector}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}}}, fits: true, labels: []string{"region"}, test: "service pod on different node, region match", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: selector}}, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine3"}, ObjectMeta: api.ObjectMeta{Labels: selector}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: selector}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: v1.ObjectMeta{Labels: selector}}}, node: &node1, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: selector}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}}}, fits: false, labels: []string{"region"}, test: "service pod on different node, region mismatch", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: selector, Namespace: "ns1"}}, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine3"}, ObjectMeta: api.ObjectMeta{Labels: selector, Namespace: "ns1"}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: selector, Namespace: "ns1"}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: v1.ObjectMeta{Labels: selector, Namespace: "ns1"}}}, node: &node1, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: selector}, ObjectMeta: api.ObjectMeta{Namespace: "ns2"}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}, ObjectMeta: v1.ObjectMeta{Namespace: "ns2"}}}, fits: true, labels: []string{"region"}, test: "service in different namespace, region mismatch", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: selector, Namespace: "ns1"}}, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine3"}, ObjectMeta: api.ObjectMeta{Labels: selector, Namespace: "ns2"}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: selector, Namespace: "ns1"}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: v1.ObjectMeta{Labels: selector, Namespace: "ns2"}}}, node: &node1, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: selector}, ObjectMeta: api.ObjectMeta{Namespace: "ns1"}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}, ObjectMeta: v1.ObjectMeta{Namespace: "ns1"}}}, fits: true, labels: []string{"region"}, test: "pod in different namespace, region mismatch", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: selector, Namespace: "ns1"}}, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine3"}, ObjectMeta: api.ObjectMeta{Labels: selector, Namespace: "ns1"}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: selector, Namespace: "ns1"}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: v1.ObjectMeta{Labels: selector, Namespace: "ns1"}}}, node: &node1, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: selector}, ObjectMeta: api.ObjectMeta{Namespace: "ns1"}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}, ObjectMeta: v1.ObjectMeta{Namespace: "ns1"}}}, fits: false, labels: []string{"region"}, test: "service and pod in same namespace, region mismatch", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: selector}}, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: selector}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: selector}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: selector}}}, node: &node1, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: selector}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}}}, fits: false, labels: []string{"region", "zone"}, test: "service pod on different node, multiple labels, not all match", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: selector}}, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine5"}, ObjectMeta: api.ObjectMeta{Labels: selector}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: selector}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine5"}, ObjectMeta: v1.ObjectMeta{Labels: selector}}}, node: &node4, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: selector}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}}}, fits: true, labels: []string{"region", "zone"}, test: "service pod on different node, multiple labels, all match", @@ -1411,7 +1411,7 @@ func TestServiceAffinity(t *testing.T) { expectedFailureReasons := []algorithm.PredicateFailureReason{ErrServiceAffinityViolated} for _, test := range tests { testIt := func(skipPrecompute bool) { - nodes := []api.Node{node1, node2, node3, node4, node5} + nodes := []v1.Node{node1, node2, node3, node4, node5} nodeInfo := schedulercache.NewNodeInfo() nodeInfo.SetNode(test.node) nodeInfoMap := map[string]*schedulercache.NodeInfo{test.node.Name: nodeInfo} @@ -1445,23 +1445,23 @@ func TestServiceAffinity(t *testing.T) { } func TestEBSVolumeCountConflicts(t *testing.T) { - oneVolPod := &api.Pod{ - Spec: api.PodSpec{ - Volumes: []api.Volume{ + oneVolPod := &v1.Pod{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{VolumeID: "ovp"}, + VolumeSource: v1.VolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{VolumeID: "ovp"}, }, }, }, }, } - ebsPVCPod := &api.Pod{ - Spec: api.PodSpec{ - Volumes: []api.Volume{ + ebsPVCPod := &v1.Pod{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ + VolumeSource: v1.VolumeSource{ + PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: "someEBSVol", }, }, @@ -1469,19 +1469,19 @@ func TestEBSVolumeCountConflicts(t *testing.T) { }, }, } - splitPVCPod := &api.Pod{ - Spec: api.PodSpec{ - Volumes: []api.Volume{ + splitPVCPod := &v1.Pod{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ + VolumeSource: v1.VolumeSource{ + PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: "someNonEBSVol", }, }, }, { - VolumeSource: api.VolumeSource{ - PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ + VolumeSource: v1.VolumeSource{ + PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: "someEBSVol", }, }, @@ -1489,55 +1489,55 @@ func TestEBSVolumeCountConflicts(t *testing.T) { }, }, } - twoVolPod := &api.Pod{ - Spec: api.PodSpec{ - Volumes: []api.Volume{ + twoVolPod := &v1.Pod{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{VolumeID: "tvp1"}, + VolumeSource: v1.VolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{VolumeID: "tvp1"}, }, }, { - VolumeSource: api.VolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{VolumeID: "tvp2"}, + VolumeSource: v1.VolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{VolumeID: "tvp2"}, }, }, }, }, } - splitVolsPod := &api.Pod{ - Spec: api.PodSpec{ - Volumes: []api.Volume{ + splitVolsPod := &v1.Pod{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{}, + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{}, }, }, { - VolumeSource: api.VolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{VolumeID: "svp"}, + VolumeSource: v1.VolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{VolumeID: "svp"}, }, }, }, }, } - nonApplicablePod := &api.Pod{ - Spec: api.PodSpec{ - Volumes: []api.Volume{ + nonApplicablePod := &v1.Pod{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{}, + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{}, }, }, }, }, } - deletedPVCPod := &api.Pod{ - Spec: api.PodSpec{ - Volumes: []api.Volume{ + deletedPVCPod := &v1.Pod{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ + VolumeSource: v1.VolumeSource{ + PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: "deletedPVC", }, }, @@ -1545,12 +1545,12 @@ func TestEBSVolumeCountConflicts(t *testing.T) { }, }, } - deletedPVPod := &api.Pod{ - Spec: api.PodSpec{ - Volumes: []api.Volume{ + deletedPVPod := &v1.Pod{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { - VolumeSource: api.VolumeSource{ - PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ + VolumeSource: v1.VolumeSource{ + PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: "pvcWithDeletedPV", }, }, @@ -1558,104 +1558,104 @@ func TestEBSVolumeCountConflicts(t *testing.T) { }, }, } - emptyPod := &api.Pod{ - Spec: api.PodSpec{}, + emptyPod := &v1.Pod{ + Spec: v1.PodSpec{}, } tests := []struct { - newPod *api.Pod - existingPods []*api.Pod + newPod *v1.Pod + existingPods []*v1.Pod maxVols int fits bool test string }{ { newPod: oneVolPod, - existingPods: []*api.Pod{twoVolPod, oneVolPod}, + existingPods: []*v1.Pod{twoVolPod, oneVolPod}, maxVols: 4, fits: true, test: "fits when node capacity >= new pod's EBS volumes", }, { newPod: twoVolPod, - existingPods: []*api.Pod{oneVolPod}, + existingPods: []*v1.Pod{oneVolPod}, maxVols: 2, fits: false, test: "doesn't fit when node capacity < new pod's EBS volumes", }, { newPod: splitVolsPod, - existingPods: []*api.Pod{twoVolPod}, + existingPods: []*v1.Pod{twoVolPod}, maxVols: 3, fits: true, test: "new pod's count ignores non-EBS volumes", }, { newPod: twoVolPod, - existingPods: []*api.Pod{splitVolsPod, nonApplicablePod, emptyPod}, + existingPods: []*v1.Pod{splitVolsPod, nonApplicablePod, emptyPod}, maxVols: 3, fits: true, test: "existing pods' counts ignore non-EBS volumes", }, { newPod: ebsPVCPod, - existingPods: []*api.Pod{splitVolsPod, nonApplicablePod, emptyPod}, + existingPods: []*v1.Pod{splitVolsPod, nonApplicablePod, emptyPod}, maxVols: 3, fits: true, test: "new pod's count considers PVCs backed by EBS volumes", }, { newPod: splitPVCPod, - existingPods: []*api.Pod{splitVolsPod, oneVolPod}, + existingPods: []*v1.Pod{splitVolsPod, oneVolPod}, maxVols: 3, fits: true, test: "new pod's count ignores PVCs not backed by EBS volumes", }, { newPod: twoVolPod, - existingPods: []*api.Pod{oneVolPod, ebsPVCPod}, + existingPods: []*v1.Pod{oneVolPod, ebsPVCPod}, maxVols: 3, fits: false, test: "existing pods' counts considers PVCs backed by EBS volumes", }, { newPod: twoVolPod, - existingPods: []*api.Pod{oneVolPod, twoVolPod, ebsPVCPod}, + existingPods: []*v1.Pod{oneVolPod, twoVolPod, ebsPVCPod}, maxVols: 4, fits: true, test: "already-mounted EBS volumes are always ok to allow", }, { newPod: splitVolsPod, - existingPods: []*api.Pod{oneVolPod, oneVolPod, ebsPVCPod}, + existingPods: []*v1.Pod{oneVolPod, oneVolPod, ebsPVCPod}, maxVols: 3, fits: true, test: "the same EBS volumes are not counted multiple times", }, { newPod: ebsPVCPod, - existingPods: []*api.Pod{oneVolPod, deletedPVCPod}, + existingPods: []*v1.Pod{oneVolPod, deletedPVCPod}, maxVols: 2, fits: false, test: "pod with missing PVC is counted towards the PV limit", }, { newPod: ebsPVCPod, - existingPods: []*api.Pod{oneVolPod, deletedPVCPod}, + existingPods: []*v1.Pod{oneVolPod, deletedPVCPod}, maxVols: 3, fits: true, test: "pod with missing PVC is counted towards the PV limit", }, { newPod: ebsPVCPod, - existingPods: []*api.Pod{oneVolPod, deletedPVPod}, + existingPods: []*v1.Pod{oneVolPod, deletedPVPod}, maxVols: 2, fits: false, test: "pod with missing PV is counted towards the PV limit", }, { newPod: ebsPVCPod, - existingPods: []*api.Pod{oneVolPod, deletedPVPod}, + existingPods: []*v1.Pod{oneVolPod, deletedPVPod}, maxVols: 3, fits: true, test: "pod with missing PV is counted towards the PV limit", @@ -1664,44 +1664,44 @@ func TestEBSVolumeCountConflicts(t *testing.T) { pvInfo := FakePersistentVolumeInfo{ { - ObjectMeta: api.ObjectMeta{Name: "someEBSVol"}, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{VolumeID: "ebsVol"}, + ObjectMeta: v1.ObjectMeta{Name: "someEBSVol"}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{VolumeID: "ebsVol"}, }, }, }, { - ObjectMeta: api.ObjectMeta{Name: "someNonEBSVol"}, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{}, + ObjectMeta: v1.ObjectMeta{Name: "someNonEBSVol"}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{}, }, }, } pvcInfo := FakePersistentVolumeClaimInfo{ { - ObjectMeta: api.ObjectMeta{Name: "someEBSVol"}, - Spec: api.PersistentVolumeClaimSpec{VolumeName: "someEBSVol"}, + ObjectMeta: v1.ObjectMeta{Name: "someEBSVol"}, + Spec: v1.PersistentVolumeClaimSpec{VolumeName: "someEBSVol"}, }, { - ObjectMeta: api.ObjectMeta{Name: "someNonEBSVol"}, - Spec: api.PersistentVolumeClaimSpec{VolumeName: "someNonEBSVol"}, + ObjectMeta: v1.ObjectMeta{Name: "someNonEBSVol"}, + Spec: v1.PersistentVolumeClaimSpec{VolumeName: "someNonEBSVol"}, }, { - ObjectMeta: api.ObjectMeta{Name: "pvcWithDeletedPV"}, - Spec: api.PersistentVolumeClaimSpec{VolumeName: "pvcWithDeletedPV"}, + ObjectMeta: v1.ObjectMeta{Name: "pvcWithDeletedPV"}, + Spec: v1.PersistentVolumeClaimSpec{VolumeName: "pvcWithDeletedPV"}, }, } filter := VolumeFilter{ - FilterVolume: func(vol *api.Volume) (string, bool) { + FilterVolume: func(vol *v1.Volume) (string, bool) { if vol.AWSElasticBlockStore != nil { return vol.AWSElasticBlockStore.VolumeID, true } return "", false }, - FilterPersistentVolume: func(pv *api.PersistentVolume) (string, bool) { + FilterPersistentVolume: func(pv *v1.PersistentVolume) (string, bool) { if pv.Spec.AWSElasticBlockStore != nil { return pv.Spec.AWSElasticBlockStore.VolumeID, true } @@ -1803,14 +1803,14 @@ func TestPredicatesRegistered(t *testing.T) { } } -func newPodWithPort(hostPorts ...int) *api.Pod { - networkPorts := []api.ContainerPort{} +func newPodWithPort(hostPorts ...int) *v1.Pod { + networkPorts := []v1.ContainerPort{} for _, port := range hostPorts { - networkPorts = append(networkPorts, api.ContainerPort{HostPort: int32(port)}) + networkPorts = append(networkPorts, v1.ContainerPort{HostPort: int32(port)}) } - return &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + return &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Ports: networkPorts, }, @@ -1821,21 +1821,21 @@ func newPodWithPort(hostPorts ...int) *api.Pod { func TestRunGeneralPredicates(t *testing.T) { resourceTests := []struct { - pod *api.Pod + pod *v1.Pod nodeInfo *schedulercache.NodeInfo - node *api.Node + node *v1.Node fits bool test string wErr error reasons []algorithm.PredicateFailureReason }{ { - pod: &api.Pod{}, + pod: &v1.Pod{}, nodeInfo: schedulercache.NewNodeInfo( newResourcePod(schedulercache.Resource{MilliCPU: 9, Memory: 19})), - node: &api.Node{ - ObjectMeta: api.ObjectMeta{Name: "machine1"}, - Status: api.NodeStatus{Capacity: makeResources(10, 20, 0, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 0, 32, 0)}, + node: &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: "machine1"}, + Status: v1.NodeStatus{Capacity: makeResources(10, 20, 0, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 0, 32, 0)}, }, fits: true, wErr: nil, @@ -1845,23 +1845,23 @@ func TestRunGeneralPredicates(t *testing.T) { pod: newResourcePod(schedulercache.Resource{MilliCPU: 8, Memory: 10}), nodeInfo: schedulercache.NewNodeInfo( newResourcePod(schedulercache.Resource{MilliCPU: 5, Memory: 19})), - node: &api.Node{ - ObjectMeta: api.ObjectMeta{Name: "machine1"}, - Status: api.NodeStatus{Capacity: makeResources(10, 20, 0, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 0, 32, 0)}, + node: &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: "machine1"}, + Status: v1.NodeStatus{Capacity: makeResources(10, 20, 0, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 0, 32, 0)}, }, fits: false, wErr: nil, reasons: []algorithm.PredicateFailureReason{ - NewInsufficientResourceError(api.ResourceCPU, 8, 5, 10), - NewInsufficientResourceError(api.ResourceMemory, 10, 19, 20), + NewInsufficientResourceError(v1.ResourceCPU, 8, 5, 10), + NewInsufficientResourceError(v1.ResourceMemory, 10, 19, 20), }, test: "not enough cpu and memory resource", }, { - pod: &api.Pod{}, + pod: &v1.Pod{}, nodeInfo: schedulercache.NewNodeInfo( newResourcePod(schedulercache.Resource{MilliCPU: 9, Memory: 19})), - node: &api.Node{Status: api.NodeStatus{Capacity: makeResources(10, 20, 1, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 1, 32, 0)}}, + node: &v1.Node{Status: v1.NodeStatus{Capacity: makeResources(10, 20, 1, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 1, 32, 0)}}, fits: true, wErr: nil, test: "no resources/port/host requested always fits on GPU machine", @@ -1870,31 +1870,31 @@ func TestRunGeneralPredicates(t *testing.T) { pod: newResourcePod(schedulercache.Resource{MilliCPU: 3, Memory: 1, NvidiaGPU: 1}), nodeInfo: schedulercache.NewNodeInfo( newResourcePod(schedulercache.Resource{MilliCPU: 5, Memory: 10, NvidiaGPU: 1})), - node: &api.Node{Status: api.NodeStatus{Capacity: makeResources(10, 20, 1, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 1, 32, 0)}}, + node: &v1.Node{Status: v1.NodeStatus{Capacity: makeResources(10, 20, 1, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 1, 32, 0)}}, fits: false, wErr: nil, - reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(api.ResourceNvidiaGPU, 1, 1, 1)}, + reasons: []algorithm.PredicateFailureReason{NewInsufficientResourceError(v1.ResourceNvidiaGPU, 1, 1, 1)}, test: "not enough GPU resource", }, { pod: newResourcePod(schedulercache.Resource{MilliCPU: 3, Memory: 1, NvidiaGPU: 1}), nodeInfo: schedulercache.NewNodeInfo( newResourcePod(schedulercache.Resource{MilliCPU: 5, Memory: 10, NvidiaGPU: 0})), - node: &api.Node{Status: api.NodeStatus{Capacity: makeResources(10, 20, 1, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 1, 32, 0)}}, + node: &v1.Node{Status: v1.NodeStatus{Capacity: makeResources(10, 20, 1, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 1, 32, 0)}}, fits: true, wErr: nil, test: "enough GPU resource", }, { - pod: &api.Pod{ - Spec: api.PodSpec{ + pod: &v1.Pod{ + Spec: v1.PodSpec{ NodeName: "machine2", }, }, nodeInfo: schedulercache.NewNodeInfo(), - node: &api.Node{ - ObjectMeta: api.ObjectMeta{Name: "machine1"}, - Status: api.NodeStatus{Capacity: makeResources(10, 20, 0, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 0, 32, 0)}, + node: &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: "machine1"}, + Status: v1.NodeStatus{Capacity: makeResources(10, 20, 0, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 0, 32, 0)}, }, fits: false, wErr: nil, @@ -1904,9 +1904,9 @@ func TestRunGeneralPredicates(t *testing.T) { { pod: newPodWithPort(123), nodeInfo: schedulercache.NewNodeInfo(newPodWithPort(123)), - node: &api.Node{ - ObjectMeta: api.ObjectMeta{Name: "machine1"}, - Status: api.NodeStatus{Capacity: makeResources(10, 20, 0, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 0, 32, 0)}, + node: &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: "machine1"}, + Status: v1.NodeStatus{Capacity: makeResources(10, 20, 0, 32, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 0, 32, 0)}, }, fits: false, wErr: nil, @@ -1936,26 +1936,26 @@ func TestInterPodAffinity(t *testing.T) { "zone": "z11", } podLabel2 := map[string]string{"security": "S1"} - node1 := api.Node{ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labels1}} + node1 := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labels1}} tests := []struct { - pod *api.Pod - pods []*api.Pod - node *api.Node + pod *v1.Pod + pods []*v1.Pod + node *v1.Node fits bool test string }{ { - pod: new(api.Pod), + pod: new(v1.Pod), node: &node1, fits: true, test: "A pod that has no required pod affinity scheduling rules can schedule onto a node with no existing pods", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel2, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -1971,17 +1971,17 @@ func TestInterPodAffinity(t *testing.T) { }, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabel}}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel}}}, node: &node1, fits: true, test: "satisfies with requiredDuringSchedulingIgnoredDuringExecution in PodAffinity using In operator that matches the existing pod", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel2, Annotations: map[string]string{ - api.AffinityAnnotationKey: `{"podAffinity": { + v1.AffinityAnnotationKey: `{"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { "matchExpressions": [{ @@ -1996,17 +1996,17 @@ func TestInterPodAffinity(t *testing.T) { }, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabel}}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel}}}, node: &node1, fits: true, test: "satisfies the pod with requiredDuringSchedulingIgnoredDuringExecution in PodAffinity using not in operator in labelSelector that matches the existing pod", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel2, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2022,17 +2022,17 @@ func TestInterPodAffinity(t *testing.T) { }, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabel, Namespace: "ns"}}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel, Namespace: "ns"}}}, node: &node1, fits: false, test: "Does not satisfy the PodAffinity with labelSelector because of diff Namespace", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2047,17 +2047,17 @@ func TestInterPodAffinity(t *testing.T) { }, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabel}}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel}}}, node: &node1, fits: false, test: "Doesn't satisfy the PodAffinity because of unmatching labelSelector with the existing pod", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel2, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [ { @@ -2090,17 +2090,17 @@ func TestInterPodAffinity(t *testing.T) { }, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabel}}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel}}}, node: &node1, fits: true, test: "satisfies the PodAffinity with different label Operators in multiple RequiredDuringSchedulingIgnoredDuringExecution ", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel2, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [ { @@ -2133,17 +2133,17 @@ func TestInterPodAffinity(t *testing.T) { }, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabel}}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel}}}, node: &node1, fits: false, test: "The labelSelector requirements(items of matchExpressions) are ANDed, the pod cannot schedule onto the node because one of the matchExpression item don't match.", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel2, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2171,18 +2171,18 @@ func TestInterPodAffinity(t *testing.T) { }, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabel}}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel}}}, node: &node1, fits: true, test: "satisfies the PodAffinity and PodAntiAffinity with the existing pod", }, // TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution. //{ - // pod: &api.Pod{ - // ObjectMeta: api.ObjectMeta{ + // pod: &v1.Pod{ + // ObjectMeta: v1.ObjectMeta{ // Labels: podLabel2, // Annotations: map[string]string{ - // api.AffinityAnnotationKey: ` + // v1.AffinityAnnotationKey: ` // {"podAffinity": { // "requiredDuringSchedulingRequiredDuringExecution": [ // { @@ -2215,17 +2215,17 @@ func TestInterPodAffinity(t *testing.T) { // }, // }, // }, - // pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podlabel}}}, + // pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podlabel}}}, // node: &node1, // fits: true, // test: "satisfies the PodAffinity with different Label Operators in multiple RequiredDuringSchedulingRequiredDuringExecution ", //}, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel2, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2253,10 +2253,10 @@ func TestInterPodAffinity(t *testing.T) { }, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, - ObjectMeta: api.ObjectMeta{Labels: podLabel, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, + ObjectMeta: v1.ObjectMeta{Labels: podLabel, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"PodAntiAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2276,11 +2276,11 @@ func TestInterPodAffinity(t *testing.T) { test: "satisfies the PodAffinity and PodAntiAffinity and PodAntiAffinity symmetry with the existing pod", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel2, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2308,17 +2308,17 @@ func TestInterPodAffinity(t *testing.T) { }, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabel}}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel}}}, node: &node1, fits: false, test: "satisfies the PodAffinity but doesn't satisfies the PodAntiAffinity with the existing pod", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2346,10 +2346,10 @@ func TestInterPodAffinity(t *testing.T) { }, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, - ObjectMeta: api.ObjectMeta{Labels: podLabel, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, + ObjectMeta: v1.ObjectMeta{Labels: podLabel, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"PodAntiAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2369,11 +2369,11 @@ func TestInterPodAffinity(t *testing.T) { test: "satisfies the PodAffinity and PodAntiAffinity but doesn't satisfies PodAntiAffinity symmetry with the existing pod", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2389,21 +2389,21 @@ func TestInterPodAffinity(t *testing.T) { }, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabel}}}, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel}}}, node: &node1, fits: false, test: "pod matches its own Label in PodAffinity and that matches the existing pod Labels", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, - ObjectMeta: api.ObjectMeta{Labels: podLabel, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, + ObjectMeta: v1.ObjectMeta{Labels: podLabel, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"PodAntiAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2423,15 +2423,15 @@ func TestInterPodAffinity(t *testing.T) { test: "verify that PodAntiAffinity from existing pod is respected when pod has no AntiAffinity constraints. doesn't satisfy PodAntiAffinity symmetry with the existing pod", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabel, }, }, - pods: []*api.Pod{{Spec: api.PodSpec{NodeName: "machine1"}, - ObjectMeta: api.ObjectMeta{Labels: podLabel, + pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, + ObjectMeta: v1.ObjectMeta{Labels: podLabel, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"PodAntiAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2455,7 +2455,7 @@ func TestInterPodAffinity(t *testing.T) { for _, test := range tests { node := test.node - var podsOnNode []*api.Pod + var podsOnNode []*v1.Pod for _, pod := range test.pods { if pod.Spec.NodeName == node.Name { podsOnNode = append(podsOnNode, pod) @@ -2465,7 +2465,7 @@ func TestInterPodAffinity(t *testing.T) { fit := PodAffinityChecker{ info: FakeNodeInfo(*node), podLister: algorithm.FakePodLister(test.pods), - failureDomains: priorityutil.Topologies{DefaultKeys: strings.Split(api.DefaultFailureDomains, ",")}, + failureDomains: priorityutil.Topologies{DefaultKeys: strings.Split(v1.DefaultFailureDomains, ",")}, } nodeInfo := schedulercache.NewNodeInfo(podsOnNode...) nodeInfo.SetNode(test.node) @@ -2498,17 +2498,17 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { "region": "India", } tests := []struct { - pod *api.Pod - pods []*api.Pod - nodes []api.Node + pod *v1.Pod + pods []*v1.Pod + nodes []v1.Node fits map[string]bool test string }{ { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2524,13 +2524,13 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { }, }, }, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelA}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelA}}, }, - nodes: []api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgChinaAzAz1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelRgIndia}}, + nodes: []v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgChinaAzAz1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelRgIndia}}, }, fits: map[string]bool{ "machine1": true, @@ -2540,10 +2540,10 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { test: "A pod can be scheduled onto all the nodes that have the same topology key & label value with one of them has an existing pod that match the affinity rules", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { @@ -2572,13 +2572,13 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { }, }, }, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "nodeA"}, ObjectMeta: api.ObjectMeta{Labels: map[string]string{"foo": "abc"}}}, - {Spec: api.PodSpec{NodeName: "nodeB"}, ObjectMeta: api.ObjectMeta{Labels: map[string]string{"foo": "def"}}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "nodeA"}, ObjectMeta: v1.ObjectMeta{Labels: map[string]string{"foo": "abc"}}}, + {Spec: v1.PodSpec{NodeName: "nodeB"}, ObjectMeta: v1.ObjectMeta{Labels: map[string]string{"foo": "def"}}}, }, - nodes: []api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "nodeA", Labels: map[string]string{"region": "r1", "hostname": "h1"}}}, - {ObjectMeta: api.ObjectMeta{Name: "nodeB", Labels: map[string]string{"region": "r1", "hostname": "h2"}}}, + nodes: []v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "nodeA", Labels: map[string]string{"region": "r1", "hostname": "h1"}}}, + {ObjectMeta: v1.ObjectMeta{Name: "nodeB", Labels: map[string]string{"region": "r1", "hostname": "h2"}}}, }, fits: map[string]bool{ "nodeA": false, @@ -2587,13 +2587,13 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { test: "NodeA and nodeB have same topologyKey and label value. NodeA does not satisfy node affinity rule, but has an existing pod that match the inter pod affinity rule. The pod can be scheduled onto nodeB.", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{ "foo": "bar", }, Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ "labelSelector": { @@ -2609,10 +2609,10 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { }, }, }, - pods: []*api.Pod{}, - nodes: []api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "nodeA", Labels: map[string]string{"zone": "az1", "hostname": "h1"}}}, - {ObjectMeta: api.ObjectMeta{Name: "nodeB", Labels: map[string]string{"zone": "az2", "hostname": "h2"}}}, + pods: []*v1.Pod{}, + nodes: []v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "nodeA", Labels: map[string]string{"zone": "az1", "hostname": "h1"}}}, + {ObjectMeta: v1.ObjectMeta{Name: "nodeB", Labels: map[string]string{"zone": "az2", "hostname": "h2"}}}, }, fits: map[string]bool{ "nodeA": true, @@ -2622,10 +2622,10 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { "should not be blocked from being scheduled onto any node, even there's no existing pod that match the rule anywhere.", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` { "podAntiAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ @@ -2643,12 +2643,12 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { }, }, }, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "nodeA"}, ObjectMeta: api.ObjectMeta{Labels: map[string]string{"foo": "abc"}}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "nodeA"}, ObjectMeta: v1.ObjectMeta{Labels: map[string]string{"foo": "abc"}}}, }, - nodes: []api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "nodeA", Labels: map[string]string{"region": "r1", "hostname": "nodeA"}}}, - {ObjectMeta: api.ObjectMeta{Name: "nodeB", Labels: map[string]string{"region": "r1", "hostname": "nodeB"}}}, + nodes: []v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "nodeA", Labels: map[string]string{"region": "r1", "hostname": "nodeA"}}}, + {ObjectMeta: v1.ObjectMeta{Name: "nodeB", Labels: map[string]string{"region": "r1", "hostname": "nodeB"}}}, }, fits: map[string]bool{ "nodeA": false, @@ -2657,10 +2657,10 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { test: "NodeA and nodeB have same topologyKey and label value. NodeA has an existing pod that match the inter pod affinity rule. The pod can not be scheduled onto nodeA and nodeB.", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` { "podAntiAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [{ @@ -2678,13 +2678,13 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { }, }, }, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "nodeA"}, ObjectMeta: api.ObjectMeta{Labels: map[string]string{"foo": "abc"}}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "nodeA"}, ObjectMeta: v1.ObjectMeta{Labels: map[string]string{"foo": "abc"}}}, }, - nodes: []api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "nodeA", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "nodeB", Labels: labelRgChinaAzAz1}}, - {ObjectMeta: api.ObjectMeta{Name: "nodeC", Labels: labelRgIndia}}, + nodes: []v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "nodeA", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "nodeB", Labels: labelRgChinaAzAz1}}, + {ObjectMeta: v1.ObjectMeta{Name: "nodeC", Labels: labelRgIndia}}, }, fits: map[string]bool{ "nodeA": false, @@ -2700,7 +2700,7 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { for _, test := range tests { nodeListInfo := FakeNodeListInfo(test.nodes) for _, node := range test.nodes { - var podsOnNode []*api.Pod + var podsOnNode []*v1.Pod for _, pod := range test.pods { if pod.Spec.NodeName == node.Name { podsOnNode = append(podsOnNode, pod) @@ -2710,7 +2710,7 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { testFit := PodAffinityChecker{ info: nodeListInfo, podLister: algorithm.FakePodLister(test.pods), - failureDomains: priorityutil.Topologies{DefaultKeys: strings.Split(api.DefaultFailureDomains, ",")}, + failureDomains: priorityutil.Topologies{DefaultKeys: strings.Split(v1.DefaultFailureDomains, ",")}, } nodeInfo := schedulercache.NewNodeInfo(podsOnNode...) nodeInfo.SetNode(&node) @@ -2722,7 +2722,7 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { if !fits && !reflect.DeepEqual(reasons, affinityExpectedFailureReasons) { t.Errorf("%s: unexpected failure reasons: %v", test.test, reasons) } - affinity, err := api.GetAffinityFromPodAnnotations(test.pod.ObjectMeta.Annotations) + affinity, err := v1.GetAffinityFromPodAnnotations(test.pod.ObjectMeta.Annotations) if err != nil { t.Errorf("%s: unexpected error: %v", test.test, err) } @@ -2749,21 +2749,21 @@ func TestInterPodAffinityWithMultipleNodes(t *testing.T) { func TestPodToleratesTaints(t *testing.T) { podTolerateTaintsTests := []struct { - pod *api.Pod - node api.Node + pod *v1.Pod + node v1.Node fits bool test string }{ { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod0", }, }, - node: api.Node{ - ObjectMeta: api.ObjectMeta{ + node: v1.Node{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.TaintsAnnotationKey: ` + v1.TaintsAnnotationKey: ` [{ "key": "dedicated", "value": "user1", @@ -2776,11 +2776,11 @@ func TestPodToleratesTaints(t *testing.T) { test: "a pod having no tolerations can't be scheduled onto a node with nonempty taints", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", Annotations: map[string]string{ - api.TolerationsAnnotationKey: ` + v1.TolerationsAnnotationKey: ` [{ "key": "dedicated", "value": "user1", @@ -2788,14 +2788,14 @@ func TestPodToleratesTaints(t *testing.T) { }]`, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{{Image: "pod1:V1"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Image: "pod1:V1"}}, }, }, - node: api.Node{ - ObjectMeta: api.ObjectMeta{ + node: v1.Node{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.TaintsAnnotationKey: ` + v1.TaintsAnnotationKey: ` [{ "key": "dedicated", "value": "user1", @@ -2808,11 +2808,11 @@ func TestPodToleratesTaints(t *testing.T) { test: "a pod which can be scheduled on a dedicated node assigned to user1 with effect NoSchedule", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod2", Annotations: map[string]string{ - api.TolerationsAnnotationKey: ` + v1.TolerationsAnnotationKey: ` [{ "key": "dedicated", "operator": "Equal", @@ -2821,14 +2821,14 @@ func TestPodToleratesTaints(t *testing.T) { }]`, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{{Image: "pod2:V1"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Image: "pod2:V1"}}, }, }, - node: api.Node{ - ObjectMeta: api.ObjectMeta{ + node: v1.Node{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.TaintsAnnotationKey: ` + v1.TaintsAnnotationKey: ` [{ "key": "dedicated", "value": "user1", @@ -2841,11 +2841,11 @@ func TestPodToleratesTaints(t *testing.T) { test: "a pod which can't be scheduled on a dedicated node assigned to user2 with effect NoSchedule", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod2", Annotations: map[string]string{ - api.TolerationsAnnotationKey: ` + v1.TolerationsAnnotationKey: ` [{ "key": "foo", "operator": "Exists", @@ -2853,14 +2853,14 @@ func TestPodToleratesTaints(t *testing.T) { }]`, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{{Image: "pod2:V1"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Image: "pod2:V1"}}, }, }, - node: api.Node{ - ObjectMeta: api.ObjectMeta{ + node: v1.Node{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.TaintsAnnotationKey: ` + v1.TaintsAnnotationKey: ` [{ "key": "foo", "value": "bar", @@ -2873,11 +2873,11 @@ func TestPodToleratesTaints(t *testing.T) { test: "a pod can be scheduled onto the node, with a toleration uses operator Exists that tolerates the taints on the node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod2", Annotations: map[string]string{ - api.TolerationsAnnotationKey: ` + v1.TolerationsAnnotationKey: ` [{ "key": "dedicated", "operator": "Equal", @@ -2890,14 +2890,14 @@ func TestPodToleratesTaints(t *testing.T) { }]`, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{{Image: "pod2:V1"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Image: "pod2:V1"}}, }, }, - node: api.Node{ - ObjectMeta: api.ObjectMeta{ + node: v1.Node{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.TaintsAnnotationKey: ` + v1.TaintsAnnotationKey: ` [{ "key": "dedicated", "value": "user2", @@ -2914,11 +2914,11 @@ func TestPodToleratesTaints(t *testing.T) { test: "a pod has multiple tolerations, node has multiple taints, all the taints are tolerated, pod can be scheduled onto the node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod2", Annotations: map[string]string{ - api.TolerationsAnnotationKey: ` + v1.TolerationsAnnotationKey: ` [{ "key": "foo", "operator": "Equal", @@ -2927,14 +2927,14 @@ func TestPodToleratesTaints(t *testing.T) { }]`, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{{Image: "pod2:V1"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Image: "pod2:V1"}}, }, }, - node: api.Node{ - ObjectMeta: api.ObjectMeta{ + node: v1.Node{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.TaintsAnnotationKey: ` + v1.TaintsAnnotationKey: ` [{ "key": "foo", "value": "bar", @@ -2948,11 +2948,11 @@ func TestPodToleratesTaints(t *testing.T) { "can't be scheduled onto the node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod2", Annotations: map[string]string{ - api.TolerationsAnnotationKey: ` + v1.TolerationsAnnotationKey: ` [{ "key": "foo", "operator": "Equal", @@ -2960,14 +2960,14 @@ func TestPodToleratesTaints(t *testing.T) { }]`, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{{Image: "pod2:V1"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Image: "pod2:V1"}}, }, }, - node: api.Node{ - ObjectMeta: api.ObjectMeta{ + node: v1.Node{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.TaintsAnnotationKey: ` + v1.TaintsAnnotationKey: ` [{ "key": "foo", "value": "bar", @@ -2981,11 +2981,11 @@ func TestPodToleratesTaints(t *testing.T) { "and the effect of taint is NoSchedule. Pod can be scheduled onto the node", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod2", Annotations: map[string]string{ - api.TolerationsAnnotationKey: ` + v1.TolerationsAnnotationKey: ` [{ "key": "dedicated", "operator": "Equal", @@ -2994,14 +2994,14 @@ func TestPodToleratesTaints(t *testing.T) { }]`, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{{Image: "pod2:V1"}}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Image: "pod2:V1"}}, }, }, - node: api.Node{ - ObjectMeta: api.ObjectMeta{ + node: v1.Node{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.TaintsAnnotationKey: ` + v1.TaintsAnnotationKey: ` [{ "key": "dedicated", "value": "user1", @@ -3033,7 +3033,7 @@ func TestPodToleratesTaints(t *testing.T) { } } -func makeEmptyNodeInfo(node *api.Node) *schedulercache.NodeInfo { +func makeEmptyNodeInfo(node *v1.Node) *schedulercache.NodeInfo { nodeInfo := schedulercache.NewNodeInfo() nodeInfo.SetNode(node) return nodeInfo @@ -3041,30 +3041,30 @@ func makeEmptyNodeInfo(node *api.Node) *schedulercache.NodeInfo { func TestPodSchedulesOnNodeWithMemoryPressureCondition(t *testing.T) { // specify best-effort pod - bestEffortPod := &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + bestEffortPod := &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "container", Image: "image", ImagePullPolicy: "Always", // no requirements -> best effort pod - Resources: api.ResourceRequirements{}, + Resources: v1.ResourceRequirements{}, }, }, }, } // specify non-best-effort pod - nonBestEffortPod := &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + nonBestEffortPod := &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "container", Image: "image", ImagePullPolicy: "Always", // at least one requirement -> burstable pod - Resources: api.ResourceRequirements{ + Resources: v1.ResourceRequirements{ Requests: makeAllocatableResources(100, 100, 100, 100, 0), }, }, @@ -3073,9 +3073,9 @@ func TestPodSchedulesOnNodeWithMemoryPressureCondition(t *testing.T) { } // specify a node with no memory pressure condition on - noMemoryPressureNode := &api.Node{ - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + noMemoryPressureNode := &v1.Node{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { Type: "Ready", Status: "True", @@ -3085,9 +3085,9 @@ func TestPodSchedulesOnNodeWithMemoryPressureCondition(t *testing.T) { } // specify a node with memory pressure condition on - memoryPressureNode := &api.Node{ - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + memoryPressureNode := &v1.Node{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { Type: "MemoryPressure", Status: "True", @@ -3097,7 +3097,7 @@ func TestPodSchedulesOnNodeWithMemoryPressureCondition(t *testing.T) { } tests := []struct { - pod *api.Pod + pod *v1.Pod nodeInfo *schedulercache.NodeInfo fits bool name string @@ -3144,9 +3144,9 @@ func TestPodSchedulesOnNodeWithMemoryPressureCondition(t *testing.T) { } func TestPodSchedulesOnNodeWithDiskPressureCondition(t *testing.T) { - pod := &api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{ + pod := &v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "container", Image: "image", @@ -3157,9 +3157,9 @@ func TestPodSchedulesOnNodeWithDiskPressureCondition(t *testing.T) { } // specify a node with no disk pressure condition on - noPressureNode := &api.Node{ - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + noPressureNode := &v1.Node{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { Type: "Ready", Status: "True", @@ -3169,9 +3169,9 @@ func TestPodSchedulesOnNodeWithDiskPressureCondition(t *testing.T) { } // specify a node with pressure condition on - pressureNode := &api.Node{ - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ + pressureNode := &v1.Node{ + Status: v1.NodeStatus{ + Conditions: []v1.NodeCondition{ { Type: "DiskPressure", Status: "True", @@ -3181,7 +3181,7 @@ func TestPodSchedulesOnNodeWithDiskPressureCondition(t *testing.T) { } tests := []struct { - pod *api.Pod + pod *v1.Pod nodeInfo *schedulercache.NodeInfo fits bool name string diff --git a/plugin/pkg/scheduler/algorithm/predicates/utils.go b/plugin/pkg/scheduler/algorithm/predicates/utils.go index e5a1faeec25..46e7597c392 100644 --- a/plugin/pkg/scheduler/algorithm/predicates/utils.go +++ b/plugin/pkg/scheduler/algorithm/predicates/utils.go @@ -16,8 +16,10 @@ limitations under the License. package predicates -import "k8s.io/kubernetes/pkg/labels" -import "k8s.io/kubernetes/pkg/api" +import ( + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/labels" +) // FindLabelsInSet gets as many key/value pairs as possible out of a label set. func FindLabelsInSet(labelsToKeep []string, selector labels.Set) map[string]string { @@ -45,8 +47,8 @@ func AddUnsetLabelsToMap(aL map[string]string, labelsToAdd []string, labelSet la } // FilterPodsByNamespace filters pods outside a namespace from the given list. -func FilterPodsByNamespace(pods []*api.Pod, ns string) []*api.Pod { - filtered := []*api.Pod{} +func FilterPodsByNamespace(pods []*v1.Pod, ns string) []*v1.Pod { + filtered := []*v1.Pod{} for _, nsPod := range pods { if nsPod.Namespace == ns { filtered = append(filtered, nsPod) diff --git a/plugin/pkg/scheduler/algorithm/predicates/utils_test.go b/plugin/pkg/scheduler/algorithm/predicates/utils_test.go index 32729304cfd..1e1125a6fd3 100644 --- a/plugin/pkg/scheduler/algorithm/predicates/utils_test.go +++ b/plugin/pkg/scheduler/algorithm/predicates/utils_test.go @@ -19,7 +19,7 @@ package predicates import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" ) @@ -30,9 +30,9 @@ func ExampleFindLabelsInSet() { labelSubset["label2"] = "value2" // Lets make believe that these pods are on the cluster. // Utility functions will inspect their labels, filter them, and so on. - nsPods := []*api.Pod{ + nsPods := []*v1.Pod{ { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "pod1", Namespace: "ns1", Labels: map[string]string{ @@ -43,14 +43,14 @@ func ExampleFindLabelsInSet() { }, }, // first pod which will be used via the utilities { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "pod2", Namespace: "ns1", }, }, { - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "pod3ThatWeWontSee", }, }, diff --git a/plugin/pkg/scheduler/algorithm/priorities/BUILD b/plugin/pkg/scheduler/algorithm/priorities/BUILD index 879e1e3f496..fb6f1cd2f1b 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/BUILD +++ b/plugin/pkg/scheduler/algorithm/priorities/BUILD @@ -28,9 +28,9 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/labels:go_default_library", "//pkg/util/node:go_default_library", "//pkg/util/workqueue:go_default_library", @@ -64,10 +64,10 @@ go_test( "skip", ], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/util/codeinspector:go_default_library", "//plugin/pkg/scheduler/algorithm:go_default_library", "//plugin/pkg/scheduler/algorithm/priorities/util:go_default_library", diff --git a/plugin/pkg/scheduler/algorithm/priorities/balanced_resource_allocation.go b/plugin/pkg/scheduler/algorithm/priorities/balanced_resource_allocation.go index fedc16463c6..002c184cadf 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/balanced_resource_allocation.go +++ b/plugin/pkg/scheduler/algorithm/priorities/balanced_resource_allocation.go @@ -20,7 +20,7 @@ import ( "fmt" "math" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" priorityutil "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" @@ -37,7 +37,7 @@ const ( // Also used in most/least_requested nad metadata. // TODO: despaghettify it -func getNonZeroRequests(pod *api.Pod) *schedulercache.Resource { +func getNonZeroRequests(pod *v1.Pod) *schedulercache.Resource { result := &schedulercache.Resource{} for i := range pod.Spec.Containers { container := &pod.Spec.Containers[i] @@ -48,7 +48,7 @@ func getNonZeroRequests(pod *api.Pod) *schedulercache.Resource { return result } -func calculateBalancedResourceAllocation(pod *api.Pod, podRequests *schedulercache.Resource, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func calculateBalancedResourceAllocation(pod *v1.Pod, podRequests *schedulercache.Resource, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { node := nodeInfo.Node() if node == nil { return schedulerapi.HostPriority{}, fmt.Errorf("node not found") @@ -104,7 +104,7 @@ func fractionOfCapacity(requested, capacity int64) float64 { // close the two metrics are to each other. // Detail: score = 10 - abs(cpuFraction-memoryFraction)*10. The algorithm is partly inspired by: // "Wei Huang et al. An Energy Efficient Virtual Machine Placement Algorithm with Balanced Resource Utilization" -func BalancedResourceAllocationMap(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func BalancedResourceAllocationMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { var nonZeroRequest *schedulercache.Resource if priorityMeta, ok := meta.(*priorityMetadata); ok { nonZeroRequest = priorityMeta.nonZeroRequest diff --git a/plugin/pkg/scheduler/algorithm/priorities/balanced_resource_allocation_test.go b/plugin/pkg/scheduler/algorithm/priorities/balanced_resource_allocation_test.go index 4003ded9a8e..607668ae6b2 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/balanced_resource_allocation_test.go +++ b/plugin/pkg/scheduler/algorithm/priorities/balanced_resource_allocation_test.go @@ -20,8 +20,8 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) @@ -35,29 +35,29 @@ func TestBalancedResourceAllocation(t *testing.T) { "bar": "foo", "baz": "blah", } - machine1Spec := api.PodSpec{ + machine1Spec := v1.PodSpec{ NodeName: "machine1", } - machine2Spec := api.PodSpec{ + machine2Spec := v1.PodSpec{ NodeName: "machine2", } - noResources := api.PodSpec{ - Containers: []api.Container{}, + noResources := v1.PodSpec{ + Containers: []v1.Container{}, } - cpuOnly := api.PodSpec{ + cpuOnly := v1.PodSpec{ NodeName: "machine1", - Containers: []api.Container{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("1000m"), "memory": resource.MustParse("0"), }, }, }, { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("2000m"), "memory": resource.MustParse("0"), }, @@ -67,20 +67,20 @@ func TestBalancedResourceAllocation(t *testing.T) { } cpuOnly2 := cpuOnly cpuOnly2.NodeName = "machine2" - cpuAndMemory := api.PodSpec{ + cpuAndMemory := v1.PodSpec{ NodeName: "machine2", - Containers: []api.Container{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("1000m"), "memory": resource.MustParse("2000"), }, }, }, { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("2000m"), "memory": resource.MustParse("3000"), }, @@ -89,9 +89,9 @@ func TestBalancedResourceAllocation(t *testing.T) { }, } tests := []struct { - pod *api.Pod - pods []*api.Pod - nodes []*api.Node + pod *v1.Pod + pods []*v1.Pod + nodes []*v1.Node expectedList schedulerapi.HostPriorityList test string }{ @@ -107,8 +107,8 @@ func TestBalancedResourceAllocation(t *testing.T) { Memory Fraction: 0 / 10000 = 0% Node2 Score: 10 - (0-0)*10 = 10 */ - pod: &api.Pod{Spec: noResources}, - nodes: []*api.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, + pod: &v1.Pod{Spec: noResources}, + nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}}, test: "nothing scheduled, nothing requested", }, @@ -124,8 +124,8 @@ func TestBalancedResourceAllocation(t *testing.T) { Memory Fraction: 5000/10000 = 50% Node2 Score: 10 - (0.5-0.5)*10 = 10 */ - pod: &api.Pod{Spec: cpuAndMemory}, - nodes: []*api.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 6000, 10000)}, + pod: &v1.Pod{Spec: cpuAndMemory}, + nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 6000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 7}, {Host: "machine2", Score: 10}}, test: "nothing scheduled, resources requested, differently sized machines", }, @@ -141,15 +141,15 @@ func TestBalancedResourceAllocation(t *testing.T) { Memory Fraction: 0 / 10000 = 0% Node2 Score: 10 - (0-0)*10 = 10 */ - pod: &api.Pod{Spec: noResources}, - nodes: []*api.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, + pod: &v1.Pod{Spec: noResources}, + nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}}, test: "no resources requested, pods scheduled", - pods: []*api.Pod{ - {Spec: machine1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: machine1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: machine2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: machine2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: machine1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: machine1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: machine2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: machine2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, }, { @@ -164,15 +164,15 @@ func TestBalancedResourceAllocation(t *testing.T) { Memory Fraction: 5000 / 20000 = 25% Node2 Score: 10 - (0.6-0.25)*10 = 6 */ - pod: &api.Pod{Spec: noResources}, - nodes: []*api.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, + pod: &v1.Pod{Spec: noResources}, + nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 4}, {Host: "machine2", Score: 6}}, test: "no resources requested, pods scheduled with resources", - pods: []*api.Pod{ - {Spec: cpuOnly, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: cpuOnly, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: cpuOnly2, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: cpuAndMemory, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: cpuOnly, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: cpuOnly, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: cpuOnly2, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: cpuAndMemory, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, }, { @@ -187,11 +187,11 @@ func TestBalancedResourceAllocation(t *testing.T) { Memory Fraction: 10000 / 20000 = 50% Node2 Score: 10 - (0.6-0.5)*10 = 9 */ - pod: &api.Pod{Spec: cpuAndMemory}, - nodes: []*api.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, + pod: &v1.Pod{Spec: cpuAndMemory}, + nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 6}, {Host: "machine2", Score: 9}}, test: "resources requested, pods scheduled with resources", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, @@ -208,11 +208,11 @@ func TestBalancedResourceAllocation(t *testing.T) { Memory Fraction: 10000 / 50000 = 20% Node2 Score: 10 - (0.6-0.2)*10 = 6 */ - pod: &api.Pod{Spec: cpuAndMemory}, - nodes: []*api.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 50000)}, + pod: &v1.Pod{Spec: cpuAndMemory}, + nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 50000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 6}, {Host: "machine2", Score: 6}}, test: "resources requested, pods scheduled with resources, differently sized machines", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, @@ -229,21 +229,21 @@ func TestBalancedResourceAllocation(t *testing.T) { Memory Fraction 5000 / 10000 = 50% Node2 Score: 0 */ - pod: &api.Pod{Spec: cpuOnly}, - nodes: []*api.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, + pod: &v1.Pod{Spec: cpuOnly}, + nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}}, test: "requested resources exceed node capacity", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, }, { - pod: &api.Pod{Spec: noResources}, - nodes: []*api.Node{makeNode("machine1", 0, 0), makeNode("machine2", 0, 0)}, + pod: &v1.Pod{Spec: noResources}, + nodes: []*v1.Node{makeNode("machine1", 0, 0), makeNode("machine2", 0, 0)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}}, test: "zero node resources, pods scheduled with resources", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, diff --git a/plugin/pkg/scheduler/algorithm/priorities/image_locality.go b/plugin/pkg/scheduler/algorithm/priorities/image_locality.go index 0bdd3ba3980..c83373484af 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/image_locality.go +++ b/plugin/pkg/scheduler/algorithm/priorities/image_locality.go @@ -19,7 +19,7 @@ package priorities import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) @@ -29,7 +29,7 @@ import ( // based on the total size of those images. // - If none of the images are present, this node will be given the lowest priority. // - If some of the images are present on a node, the larger their sizes' sum, the higher the node's priority. -func ImageLocalityPriorityMap(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func ImageLocalityPriorityMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { node := nodeInfo.Node() if node == nil { return schedulerapi.HostPriority{}, fmt.Errorf("node not found") @@ -66,7 +66,7 @@ func calculateScoreFromSize(sumSize int64) int { } // checkContainerImageOnNode checks if a container image is present on a node and returns its size. -func checkContainerImageOnNode(node *api.Node, container *api.Container) int64 { +func checkContainerImageOnNode(node *v1.Node, container *v1.Container) int64 { for _, image := range node.Status.Images { for _, name := range image.Names { if container.Image == name { diff --git a/plugin/pkg/scheduler/algorithm/priorities/image_locality_test.go b/plugin/pkg/scheduler/algorithm/priorities/image_locality_test.go index 0921e70ab92..0612a2e45f4 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/image_locality_test.go +++ b/plugin/pkg/scheduler/algorithm/priorities/image_locality_test.go @@ -21,14 +21,14 @@ import ( "sort" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) func TestImageLocalityPriority(t *testing.T) { - test_40_250 := api.PodSpec{ - Containers: []api.Container{ + test_40_250 := v1.PodSpec{ + Containers: []v1.Container{ { Image: "gcr.io/40", }, @@ -38,8 +38,8 @@ func TestImageLocalityPriority(t *testing.T) { }, } - test_40_140 := api.PodSpec{ - Containers: []api.Container{ + test_40_140 := v1.PodSpec{ + Containers: []v1.Container{ { Image: "gcr.io/40", }, @@ -49,8 +49,8 @@ func TestImageLocalityPriority(t *testing.T) { }, } - test_min_max := api.PodSpec{ - Containers: []api.Container{ + test_min_max := v1.PodSpec{ + Containers: []v1.Container{ { Image: "gcr.io/10", }, @@ -60,8 +60,8 @@ func TestImageLocalityPriority(t *testing.T) { }, } - node_40_140_2000 := api.NodeStatus{ - Images: []api.ContainerImage{ + node_40_140_2000 := v1.NodeStatus{ + Images: []v1.ContainerImage{ { Names: []string{ "gcr.io/40", @@ -86,8 +86,8 @@ func TestImageLocalityPriority(t *testing.T) { }, } - node_250_10 := api.NodeStatus{ - Images: []api.ContainerImage{ + node_250_10 := v1.NodeStatus{ + Images: []v1.ContainerImage{ { Names: []string{ "gcr.io/250", @@ -105,9 +105,9 @@ func TestImageLocalityPriority(t *testing.T) { } tests := []struct { - pod *api.Pod - pods []*api.Pod - nodes []*api.Node + pod *v1.Pod + pods []*v1.Pod + nodes []*v1.Node expectedList schedulerapi.HostPriorityList test string }{ @@ -121,8 +121,8 @@ func TestImageLocalityPriority(t *testing.T) { // Node2 // Image: gcr.io/250 250MB // Score: (250M-23M)/97.7M + 1 = 3 - pod: &api.Pod{Spec: test_40_250}, - nodes: []*api.Node{makeImageNode("machine1", node_40_140_2000), makeImageNode("machine2", node_250_10)}, + pod: &v1.Pod{Spec: test_40_250}, + nodes: []*v1.Node{makeImageNode("machine1", node_40_140_2000), makeImageNode("machine2", node_250_10)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 1}, {Host: "machine2", Score: 3}}, test: "two images spread on two nodes, prefer the larger image one", }, @@ -136,8 +136,8 @@ func TestImageLocalityPriority(t *testing.T) { // Node2 // Image: not present // Score: 0 - pod: &api.Pod{Spec: test_40_140}, - nodes: []*api.Node{makeImageNode("machine1", node_40_140_2000), makeImageNode("machine2", node_250_10)}, + pod: &v1.Pod{Spec: test_40_140}, + nodes: []*v1.Node{makeImageNode("machine1", node_40_140_2000), makeImageNode("machine2", node_250_10)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 2}, {Host: "machine2", Score: 0}}, test: "two images on one node, prefer this node", }, @@ -151,8 +151,8 @@ func TestImageLocalityPriority(t *testing.T) { // Node2 // Image: gcr.io/10 10MB // Score: 10 < min score = 0 - pod: &api.Pod{Spec: test_min_max}, - nodes: []*api.Node{makeImageNode("machine1", node_40_140_2000), makeImageNode("machine2", node_250_10)}, + pod: &v1.Pod{Spec: test_min_max}, + nodes: []*v1.Node{makeImageNode("machine1", node_40_140_2000), makeImageNode("machine2", node_250_10)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 0}}, test: "if exceed limit, use limit", }, @@ -174,9 +174,9 @@ func TestImageLocalityPriority(t *testing.T) { } } -func makeImageNode(node string, status api.NodeStatus) *api.Node { - return &api.Node{ - ObjectMeta: api.ObjectMeta{Name: node}, +func makeImageNode(node string, status v1.NodeStatus) *v1.Node { + return &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: node}, Status: status, } } diff --git a/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity.go b/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity.go index 394eb27239e..5f73183709d 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity.go +++ b/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity.go @@ -20,7 +20,7 @@ import ( "sync" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/workqueue" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates" @@ -57,7 +57,7 @@ type podAffinityPriorityMap struct { sync.Mutex // nodes contain all nodes that should be considered - nodes []*api.Node + nodes []*v1.Node // counts store the mapping from node name to so-far computed score of // the node. counts map[string]float64 @@ -67,7 +67,7 @@ type podAffinityPriorityMap struct { firstError error } -func newPodAffinityPriorityMap(nodes []*api.Node, failureDomains priorityutil.Topologies) *podAffinityPriorityMap { +func newPodAffinityPriorityMap(nodes []*v1.Node, failureDomains priorityutil.Topologies) *podAffinityPriorityMap { return &podAffinityPriorityMap{ nodes: nodes, counts: make(map[string]float64, len(nodes)), @@ -83,7 +83,7 @@ func (p *podAffinityPriorityMap) setError(err error) { } } -func (p *podAffinityPriorityMap) processTerm(term *api.PodAffinityTerm, podDefiningAffinityTerm, podToCheck *api.Pod, fixedNode *api.Node, weight float64) { +func (p *podAffinityPriorityMap) processTerm(term *v1.PodAffinityTerm, podDefiningAffinityTerm, podToCheck *v1.Pod, fixedNode *v1.Node, weight float64) { match, err := priorityutil.PodMatchesTermsNamespaceAndSelector(podToCheck, podDefiningAffinityTerm, term) if err != nil { p.setError(err) @@ -102,7 +102,7 @@ func (p *podAffinityPriorityMap) processTerm(term *api.PodAffinityTerm, podDefin } } -func (p *podAffinityPriorityMap) processTerms(terms []api.WeightedPodAffinityTerm, podDefiningAffinityTerm, podToCheck *api.Pod, fixedNode *api.Node, multiplier int) { +func (p *podAffinityPriorityMap) processTerms(terms []v1.WeightedPodAffinityTerm, podDefiningAffinityTerm, podToCheck *v1.Pod, fixedNode *v1.Node, multiplier int) { for i := range terms { term := &terms[i] p.processTerm(&term.PodAffinityTerm, podDefiningAffinityTerm, podToCheck, fixedNode, float64(term.Weight*int32(multiplier))) @@ -114,8 +114,8 @@ func (p *podAffinityPriorityMap) processTerms(terms []api.WeightedPodAffinityTer // that node; the node(s) with the highest sum are the most preferred. // Symmetry need to be considered for preferredDuringSchedulingIgnoredDuringExecution from podAffinity & podAntiAffinity, // symmetry need to be considered for hard requirements from podAffinity -func (ipa *InterPodAffinity) CalculateInterPodAffinityPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { - affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations) +func (ipa *InterPodAffinity) CalculateInterPodAffinityPriority(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*v1.Node) (schedulerapi.HostPriorityList, error) { + affinity, err := v1.GetAffinityFromPodAnnotations(pod.Annotations) if err != nil { return nil, err } @@ -134,12 +134,12 @@ func (ipa *InterPodAffinity) CalculateInterPodAffinityPriority(pod *api.Pod, nod // the node. pm := newPodAffinityPriorityMap(nodes, ipa.failureDomains) - processPod := func(existingPod *api.Pod) error { + processPod := func(existingPod *v1.Pod) error { existingPodNode, err := ipa.info.GetNodeInfo(existingPod.Spec.NodeName) if err != nil { return err } - existingPodAffinity, err := api.GetAffinityFromPodAnnotations(existingPod.Annotations) + existingPodAffinity, err := v1.GetAffinityFromPodAnnotations(existingPod.Annotations) if err != nil { return err } diff --git a/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity_test.go b/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity_test.go index 98ba9ffd013..1e4dd8586e0 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity_test.go +++ b/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity_test.go @@ -22,17 +22,17 @@ import ( "strings" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" priorityutil "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) -type FakeNodeListInfo []*api.Node +type FakeNodeListInfo []*v1.Node -func (nodes FakeNodeListInfo) GetNodeInfo(nodeName string) (*api.Node, error) { +func (nodes FakeNodeListInfo) GetNodeInfo(nodeName string) (*v1.Node, error) { for _, node := range nodes { if node.Name == nodeName { return node, nil @@ -66,7 +66,7 @@ func TestInterPodAffinityPriority(t *testing.T) { } // considered only preferredDuringSchedulingIgnoredDuringExecution in pod affinity stayWithS1InRegion := map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "preferredDuringSchedulingIgnoredDuringExecution": [{ "weight": 5, @@ -85,7 +85,7 @@ func TestInterPodAffinityPriority(t *testing.T) { }}`, } stayWithS2InRegion := map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "preferredDuringSchedulingIgnoredDuringExecution": [{ "weight": 6, @@ -104,7 +104,7 @@ func TestInterPodAffinityPriority(t *testing.T) { }}`, } affinity3 := map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "preferredDuringSchedulingIgnoredDuringExecution": [ { @@ -144,7 +144,7 @@ func TestInterPodAffinityPriority(t *testing.T) { }}`, } hardAffinity := map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [ { @@ -174,7 +174,7 @@ func TestInterPodAffinityPriority(t *testing.T) { }}`, } awayFromS1InAz := map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAntiAffinity": { "preferredDuringSchedulingIgnoredDuringExecution": [{ "weight": 5, @@ -194,7 +194,7 @@ func TestInterPodAffinityPriority(t *testing.T) { } // to stay away from security S2 in any az. awayFromS2InAz := map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAntiAffinity": { "preferredDuringSchedulingIgnoredDuringExecution": [{ "weight": 5, @@ -214,7 +214,7 @@ func TestInterPodAffinityPriority(t *testing.T) { } // to stay with security S1 in same region, stay away from security S2 in any az. stayWithS1InRegionAwayFromS2InAz := map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "preferredDuringSchedulingIgnoredDuringExecution": [{ "weight": 8, @@ -250,18 +250,18 @@ func TestInterPodAffinityPriority(t *testing.T) { } tests := []struct { - pod *api.Pod - pods []*api.Pod - nodes []*api.Node + pod *v1.Pod + pods []*v1.Pod + nodes []*v1.Node expectedList schedulerapi.HostPriorityList test string }{ { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: map[string]string{}}}, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: map[string]string{}}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}, {Host: "machine3", Score: 0}}, test: "all machines are same priority as Affinity is nil", @@ -270,16 +270,16 @@ func TestInterPodAffinityPriority(t *testing.T) { // the node(machine3) that don't have the label {"region": "whatever the value is"} (mismatch the topology key) but that have existing pods that match the labelSelector get low score // the node(machine2) that have the label {"region": "China"} (match the topology key) but that have existing pods that mismatch the labelSelector get low score { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS1InRegion}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, - {Spec: api.PodSpec{NodeName: "machine3"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS1InRegion}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, + {Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 0}, {Host: "machine3", Score: 0}}, test: "Affinity: pod that matches topology key & pods in nodes will get high score comparing to others" + @@ -290,14 +290,14 @@ func TestInterPodAffinityPriority(t *testing.T) { // the node3(machine3) that have the label {"region": "India"}, match the topology key but have a different label value, don't have existing pods that match the labelSelector, // get a low score. { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Annotations: stayWithS1InRegion}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Annotations: stayWithS1InRegion}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgChinaAzAz1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelRgIndia}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgChinaAzAz1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelRgIndia}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}, {Host: "machine3", Score: 0}}, test: "All the nodes that have the same topology key & label value with one of them has an existing pod that match the affinity rules, have the same score", @@ -307,37 +307,37 @@ func TestInterPodAffinityPriority(t *testing.T) { // Then, nodes in regionChina get higher score than nodes in regionIndia, and all the nodes in regionChina should get a same score(high score), // while all the nodes in regionIndia should get another same score(low score). { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS2InRegion}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, - {Spec: api.PodSpec{NodeName: "machine3"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, - {Spec: api.PodSpec{NodeName: "machine4"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, - {Spec: api.PodSpec{NodeName: "machine5"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS2InRegion}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, + {Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, + {Spec: v1.PodSpec{NodeName: "machine4"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, + {Spec: v1.PodSpec{NodeName: "machine5"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine4", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine5", Labels: labelRgIndia}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine4", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine5", Labels: labelRgIndia}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 5}, {Host: "machine3", Score: 10}, {Host: "machine4", Score: 10}, {Host: "machine5", Score: 5}}, test: "Affinity: nodes in one region has more matching pods comparing to other reqion, so the region which has more macthes will get high score", }, // Test with the different operators and values for pod affinity scheduling preference, including some match failures. { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: affinity3}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, - {Spec: api.PodSpec{NodeName: "machine3"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: affinity3}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, + {Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 2}, {Host: "machine2", Score: 10}, {Host: "machine3", Score: 0}}, test: "Affinity: different Label operators and values for pod affinity scheduling preference, including some match failures ", @@ -345,29 +345,29 @@ func TestInterPodAffinityPriority(t *testing.T) { // Test the symmetry cases for affinity, the difference between affinity and symmetry is not the pod wants to run together with some existing pods, // but the existing pods have the inter pod affinity preference while the pod to schedule satisfy the preference. { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS1InRegion}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2, Annotations: stayWithS2InRegion}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS1InRegion}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2, Annotations: stayWithS2InRegion}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 10}, {Host: "machine3", Score: 0}}, test: "Affinity symmetry: considred only the preferredDuringSchedulingIgnoredDuringExecution in pod affinity symmetry", }, { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: hardAffinity}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2, Annotations: hardAffinity}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: hardAffinity}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2, Annotations: hardAffinity}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}, {Host: "machine3", Score: 0}}, test: "Affinity symmetry: considred RequiredDuringSchedulingIgnoredDuringExecution in pod affinity symmetry", @@ -380,69 +380,69 @@ func TestInterPodAffinityPriority(t *testing.T) { // there are 2 nodes, say node1 and node2, both nodes have pods that match the labelSelector and have topology-key in node.Labels. // But there are more pods on node1 that match the preference than node2. Then, node1 get a lower score than node2. { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: awayFromS1InAz}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: awayFromS1InAz}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelAzAz1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgChina}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelAzAz1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgChina}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 10}}, test: "Anti Affinity: pod that doesnot match existing pods in node will get high score ", }, { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: awayFromS1InAz}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: awayFromS1InAz}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelAzAz1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgChina}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelAzAz1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgChina}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 10}}, test: "Anti Affinity: pod that does not matches topology key & matches the pods in nodes will get higher score comparing to others ", }, { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: awayFromS1InAz}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: awayFromS1InAz}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelAzAz1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelAzAz1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 10}}, test: "Anti Affinity: one node has more matching pods comparing to other node, so the node which has more unmacthes will get high score", }, // Test the symmetry cases for anti affinity { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: awayFromS2InAz}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2, Annotations: awayFromS1InAz}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: awayFromS2InAz}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2, Annotations: awayFromS1InAz}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelAzAz1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelAzAz2}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelAzAz1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelAzAz2}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 10}}, test: "Anti Affinity symmetry: the existing pods in node which has anti affinity match will get high score", }, // Test both affinity and anti-affinity { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS1InRegionAwayFromS2InAz}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS1InRegionAwayFromS2InAz}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelAzAz1}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelAzAz1}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 0}}, test: "Affinity and Anti Affinity: considered only preferredDuringSchedulingIgnoredDuringExecution in both pod affinity & anti affinity", @@ -452,22 +452,22 @@ func TestInterPodAffinityPriority(t *testing.T) { // so that all the pods of a RC/service can stay in a same region but trying to separate with each other // machine-1,machine-3,machine-4 are in ChinaRegion others machin-2,machine-5 are in IndiaRegion { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS1InRegionAwayFromS2InAz}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine3"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine3"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine4"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine5"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS1InRegionAwayFromS2InAz}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine4"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine5"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChinaAzAz1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine4", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine5", Labels: labelRgIndia}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChinaAzAz1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine4", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine5", Labels: labelRgIndia}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 4}, {Host: "machine3", Score: 10}, {Host: "machine4", Score: 10}, {Host: "machine5", Score: 4}}, test: "Affinity and Anti Affinity: considering both affinity and anti-affinity, the pod to schedule and existing pods have the same labels", @@ -478,18 +478,18 @@ func TestInterPodAffinityPriority(t *testing.T) { // for Affinity symmetry, the weights are: 0, 0, 8, 0 // for Anti Affinity symmetry, the weights are: 0, 0, 0, -5 { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS1InRegionAwayFromS2InAz}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS1}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabelSecurityS2}}, - {Spec: api.PodSpec{NodeName: "machine3"}, ObjectMeta: api.ObjectMeta{Annotations: stayWithS1InRegionAwayFromS2InAz}}, - {Spec: api.PodSpec{NodeName: "machine4"}, ObjectMeta: api.ObjectMeta{Annotations: awayFromS1InAz}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1, Annotations: stayWithS1InRegionAwayFromS2InAz}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS1}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabelSecurityS2}}, + {Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: v1.ObjectMeta{Annotations: stayWithS1InRegionAwayFromS2InAz}}, + {Spec: v1.PodSpec{NodeName: "machine4"}, ObjectMeta: v1.ObjectMeta{Annotations: awayFromS1InAz}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelAzAz1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelRgIndia}}, - {ObjectMeta: api.ObjectMeta{Name: "machine4", Labels: labelAzAz2}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelAzAz1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelRgIndia}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine4", Labels: labelAzAz2}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 0}, {Host: "machine3", Score: 10}, {Host: "machine4", Score: 0}}, test: "Affinity and Anti Affinity and symmetry: considered only preferredDuringSchedulingIgnoredDuringExecution in both pod affinity & anti affinity & symmetry", @@ -501,8 +501,8 @@ func TestInterPodAffinityPriority(t *testing.T) { info: FakeNodeListInfo(test.nodes), nodeLister: algorithm.FakeNodeLister(test.nodes), podLister: algorithm.FakePodLister(test.pods), - hardPodAffinityWeight: api.DefaultHardPodAffinitySymmetricWeight, - failureDomains: priorityutil.Topologies{DefaultKeys: strings.Split(api.DefaultFailureDomains, ",")}, + hardPodAffinityWeight: v1.DefaultHardPodAffinitySymmetricWeight, + failureDomains: priorityutil.Topologies{DefaultKeys: strings.Split(v1.DefaultFailureDomains, ",")}, } list, err := interPodAffinity.CalculateInterPodAffinityPriority(test.pod, nodeNameToInfo, test.nodes) if err != nil { @@ -528,7 +528,7 @@ func TestHardPodAffinitySymmetricWeight(t *testing.T) { "az": "az1", } hardPodAffinity := map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": [ { @@ -546,38 +546,38 @@ func TestHardPodAffinitySymmetricWeight(t *testing.T) { }}`, } tests := []struct { - pod *api.Pod - pods []*api.Pod - nodes []*api.Node + pod *v1.Pod + pods []*v1.Pod + nodes []*v1.Node hardPodAffinityWeight int expectedList schedulerapi.HostPriorityList test string }{ { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelServiceS1}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Annotations: hardPodAffinity}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Annotations: hardPodAffinity}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelServiceS1}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Annotations: hardPodAffinity}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Annotations: hardPodAffinity}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, }, - hardPodAffinityWeight: api.DefaultHardPodAffinitySymmetricWeight, + hardPodAffinityWeight: v1.DefaultHardPodAffinitySymmetricWeight, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}, {Host: "machine3", Score: 0}}, test: "Hard Pod Affinity symmetry: hard pod affinity symmetry weights 1 by default, then nodes that match the hard pod affinity symmetry rules, get a high score", }, { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabelServiceS1}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Annotations: hardPodAffinity}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Annotations: hardPodAffinity}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabelServiceS1}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Annotations: hardPodAffinity}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Annotations: hardPodAffinity}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: labelRgChina}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}}, }, hardPodAffinityWeight: 0, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}, {Host: "machine3", Score: 0}}, @@ -613,7 +613,7 @@ func TestSoftPodAntiAffinityWithFailureDomains(t *testing.T) { "security": "S1", } antiAffinity1 := map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"podAntiAffinity": { "preferredDuringSchedulingIgnoredDuringExecution": [{ "weight": 5, @@ -632,36 +632,36 @@ func TestSoftPodAntiAffinityWithFailureDomains(t *testing.T) { }}`, } tests := []struct { - pod *api.Pod - pods []*api.Pod - nodes []*api.Node + pod *v1.Pod + pods []*v1.Pod + nodes []*v1.Node failureDomains priorityutil.Topologies expectedList schedulerapi.HostPriorityList test string }{ { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabel1, Annotations: antiAffinity1}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabel1}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabel1}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabel1, Annotations: antiAffinity1}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel1}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel1}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: LabelZoneFailureDomainAZ1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelAzAZ1}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: LabelZoneFailureDomainAZ1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelAzAZ1}}, }, - failureDomains: priorityutil.Topologies{DefaultKeys: strings.Split(api.DefaultFailureDomains, ",")}, + failureDomains: priorityutil.Topologies{DefaultKeys: strings.Split(v1.DefaultFailureDomains, ",")}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 10}}, test: "Soft Pod Anti Affinity: when the topologyKey is emtpy, match among topologyKeys indicated by failure domains.", }, { - pod: &api.Pod{Spec: api.PodSpec{NodeName: ""}, ObjectMeta: api.ObjectMeta{Labels: podLabel1, Annotations: antiAffinity1}}, - pods: []*api.Pod{ - {Spec: api.PodSpec{NodeName: "machine1"}, ObjectMeta: api.ObjectMeta{Labels: podLabel1}}, - {Spec: api.PodSpec{NodeName: "machine2"}, ObjectMeta: api.ObjectMeta{Labels: podLabel1}}, + pod: &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: v1.ObjectMeta{Labels: podLabel1, Annotations: antiAffinity1}}, + pods: []*v1.Pod{ + {Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel1}}, + {Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: v1.ObjectMeta{Labels: podLabel1}}, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: LabelZoneFailureDomainAZ1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: labelAzAZ1}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: LabelZoneFailureDomainAZ1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: labelAzAZ1}}, }, failureDomains: priorityutil.Topologies{}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}}, @@ -674,7 +674,7 @@ func TestSoftPodAntiAffinityWithFailureDomains(t *testing.T) { info: FakeNodeListInfo(test.nodes), nodeLister: algorithm.FakeNodeLister(test.nodes), podLister: algorithm.FakePodLister(test.pods), - hardPodAffinityWeight: api.DefaultHardPodAffinitySymmetricWeight, + hardPodAffinityWeight: v1.DefaultHardPodAffinitySymmetricWeight, failureDomains: test.failureDomains, } list, err := ipa.CalculateInterPodAffinityPriority(test.pod, nodeNameToInfo, test.nodes) diff --git a/plugin/pkg/scheduler/algorithm/priorities/least_requested.go b/plugin/pkg/scheduler/algorithm/priorities/least_requested.go index 4e8b4289799..5e0f7bcaed1 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/least_requested.go +++ b/plugin/pkg/scheduler/algorithm/priorities/least_requested.go @@ -19,7 +19,7 @@ package priorities import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" @@ -30,7 +30,7 @@ import ( // It calculates the percentage of memory and CPU requested by pods scheduled on the node, and prioritizes // based on the minimum of the average of the fraction of requested to capacity. // Details: cpu((capacity - sum(requested)) * 10 / capacity) + memory((capacity - sum(requested)) * 10 / capacity) / 2 -func LeastRequestedPriorityMap(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func LeastRequestedPriorityMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { var nonZeroRequest *schedulercache.Resource if priorityMeta, ok := meta.(*priorityMetadata); ok { nonZeroRequest = priorityMeta.nonZeroRequest @@ -59,7 +59,7 @@ func calculateUnusedScore(requested int64, capacity int64, node string) int64 { // Calculates host priority based on the amount of unused resources. // 'node' has information about the resources on the node. // 'pods' is a list of pods currently scheduled on the node. -func calculateUnusedPriority(pod *api.Pod, podRequests *schedulercache.Resource, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func calculateUnusedPriority(pod *v1.Pod, podRequests *schedulercache.Resource, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { node := nodeInfo.Node() if node == nil { return schedulerapi.HostPriority{}, fmt.Errorf("node not found") diff --git a/plugin/pkg/scheduler/algorithm/priorities/least_requested_test.go b/plugin/pkg/scheduler/algorithm/priorities/least_requested_test.go index 55ebdb8b94a..f47a76e65d0 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/least_requested_test.go +++ b/plugin/pkg/scheduler/algorithm/priorities/least_requested_test.go @@ -20,8 +20,8 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) @@ -35,29 +35,29 @@ func TestLeastRequested(t *testing.T) { "bar": "foo", "baz": "blah", } - machine1Spec := api.PodSpec{ + machine1Spec := v1.PodSpec{ NodeName: "machine1", } - machine2Spec := api.PodSpec{ + machine2Spec := v1.PodSpec{ NodeName: "machine2", } - noResources := api.PodSpec{ - Containers: []api.Container{}, + noResources := v1.PodSpec{ + Containers: []v1.Container{}, } - cpuOnly := api.PodSpec{ + cpuOnly := v1.PodSpec{ NodeName: "machine1", - Containers: []api.Container{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("1000m"), "memory": resource.MustParse("0"), }, }, }, { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("2000m"), "memory": resource.MustParse("0"), }, @@ -67,20 +67,20 @@ func TestLeastRequested(t *testing.T) { } cpuOnly2 := cpuOnly cpuOnly2.NodeName = "machine2" - cpuAndMemory := api.PodSpec{ + cpuAndMemory := v1.PodSpec{ NodeName: "machine2", - Containers: []api.Container{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("1000m"), "memory": resource.MustParse("2000"), }, }, }, { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("2000m"), "memory": resource.MustParse("3000"), }, @@ -89,9 +89,9 @@ func TestLeastRequested(t *testing.T) { }, } tests := []struct { - pod *api.Pod - pods []*api.Pod - nodes []*api.Node + pod *v1.Pod + pods []*v1.Pod + nodes []*v1.Node expectedList schedulerapi.HostPriorityList test string }{ @@ -107,8 +107,8 @@ func TestLeastRequested(t *testing.T) { Memory Score: ((10000 - 0) *10) / 10000 = 10 Node2 Score: (10 + 10) / 2 = 10 */ - pod: &api.Pod{Spec: noResources}, - nodes: []*api.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, + pod: &v1.Pod{Spec: noResources}, + nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}}, test: "nothing scheduled, nothing requested", }, @@ -124,8 +124,8 @@ func TestLeastRequested(t *testing.T) { Memory Score: ((10000 - 5000) *10) / 10000 = 5 Node2 Score: (5 + 5) / 2 = 5 */ - pod: &api.Pod{Spec: cpuAndMemory}, - nodes: []*api.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 6000, 10000)}, + pod: &v1.Pod{Spec: cpuAndMemory}, + nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 6000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 3}, {Host: "machine2", Score: 5}}, test: "nothing scheduled, resources requested, differently sized machines", }, @@ -141,15 +141,15 @@ func TestLeastRequested(t *testing.T) { Memory Score: ((10000 - 0) *10) / 10000 = 10 Node2 Score: (10 + 10) / 2 = 10 */ - pod: &api.Pod{Spec: noResources}, - nodes: []*api.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, + pod: &v1.Pod{Spec: noResources}, + nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}}, test: "no resources requested, pods scheduled", - pods: []*api.Pod{ - {Spec: machine1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: machine1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: machine2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: machine2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: machine1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: machine1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: machine2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: machine2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, }, { @@ -164,15 +164,15 @@ func TestLeastRequested(t *testing.T) { Memory Score: ((20000 - 5000) *10) / 20000 = 7.5 Node2 Score: (4 + 7.5) / 2 = 5 */ - pod: &api.Pod{Spec: noResources}, - nodes: []*api.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, + pod: &v1.Pod{Spec: noResources}, + nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 7}, {Host: "machine2", Score: 5}}, test: "no resources requested, pods scheduled with resources", - pods: []*api.Pod{ - {Spec: cpuOnly, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: cpuOnly, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: cpuOnly2, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: cpuAndMemory, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: cpuOnly, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: cpuOnly, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: cpuOnly2, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: cpuAndMemory, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, }, { @@ -187,11 +187,11 @@ func TestLeastRequested(t *testing.T) { Memory Score: ((20000 - 10000) *10) / 20000 = 5 Node2 Score: (4 + 5) / 2 = 4 */ - pod: &api.Pod{Spec: cpuAndMemory}, - nodes: []*api.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, + pod: &v1.Pod{Spec: cpuAndMemory}, + nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 5}, {Host: "machine2", Score: 4}}, test: "resources requested, pods scheduled with resources", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, @@ -208,11 +208,11 @@ func TestLeastRequested(t *testing.T) { Memory Score: ((50000 - 10000) *10) / 50000 = 8 Node2 Score: (4 + 8) / 2 = 6 */ - pod: &api.Pod{Spec: cpuAndMemory}, - nodes: []*api.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 50000)}, + pod: &v1.Pod{Spec: cpuAndMemory}, + nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 50000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 5}, {Host: "machine2", Score: 6}}, test: "resources requested, pods scheduled with resources, differently sized machines", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, @@ -229,21 +229,21 @@ func TestLeastRequested(t *testing.T) { Memory Score: ((10000 - 5000) *10) / 10000 = 5 Node2 Score: (0 + 5) / 2 = 2 */ - pod: &api.Pod{Spec: cpuOnly}, - nodes: []*api.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, + pod: &v1.Pod{Spec: cpuOnly}, + nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 5}, {Host: "machine2", Score: 2}}, test: "requested resources exceed node capacity", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, }, { - pod: &api.Pod{Spec: noResources}, - nodes: []*api.Node{makeNode("machine1", 0, 0), makeNode("machine2", 0, 0)}, + pod: &v1.Pod{Spec: noResources}, + nodes: []*v1.Node{makeNode("machine1", 0, 0), makeNode("machine2", 0, 0)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}}, test: "zero node resources, pods scheduled with resources", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, diff --git a/plugin/pkg/scheduler/algorithm/priorities/metadata.go b/plugin/pkg/scheduler/algorithm/priorities/metadata.go index d41b34bfde4..1a83826547d 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/metadata.go +++ b/plugin/pkg/scheduler/algorithm/priorities/metadata.go @@ -17,19 +17,19 @@ limitations under the License. package priorities import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) // priorityMetadata is a type that is passed as metadata for priority functions type priorityMetadata struct { nonZeroRequest *schedulercache.Resource - podTolerations []api.Toleration - affinity *api.Affinity + podTolerations []v1.Toleration + affinity *v1.Affinity } // PriorityMetadata is a MetadataProducer. Node info can be nil. -func PriorityMetadata(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo) interface{} { +func PriorityMetadata(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo) interface{} { // If we cannot compute metadata, just return nil if pod == nil { return nil @@ -38,7 +38,7 @@ func PriorityMetadata(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.No if err != nil { return nil } - affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations) + affinity, err := v1.GetAffinityFromPodAnnotations(pod.Annotations) if err != nil { return nil } diff --git a/plugin/pkg/scheduler/algorithm/priorities/most_requested.go b/plugin/pkg/scheduler/algorithm/priorities/most_requested.go index 426cb6ca449..1492dc57f8a 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/most_requested.go +++ b/plugin/pkg/scheduler/algorithm/priorities/most_requested.go @@ -19,7 +19,7 @@ package priorities import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" @@ -30,7 +30,7 @@ import ( // It calculates the percentage of memory and CPU requested by pods scheduled on the node, and prioritizes // based on the maximum of the average of the fraction of requested to capacity. // Details: (cpu(10 * sum(requested) / capacity) + memory(10 * sum(requested) / capacity)) / 2 -func MostRequestedPriorityMap(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func MostRequestedPriorityMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { var nonZeroRequest *schedulercache.Resource if priorityMeta, ok := meta.(*priorityMetadata); ok { nonZeroRequest = priorityMeta.nonZeroRequest @@ -62,7 +62,7 @@ func calculateUsedScore(requested int64, capacity int64, node string) int64 { // Calculate the resource used on a node. 'node' has information about the resources on the node. // 'pods' is a list of pods currently scheduled on the node. -func calculateUsedPriority(pod *api.Pod, podRequests *schedulercache.Resource, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func calculateUsedPriority(pod *v1.Pod, podRequests *schedulercache.Resource, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { node := nodeInfo.Node() if node == nil { return schedulerapi.HostPriority{}, fmt.Errorf("node not found") diff --git a/plugin/pkg/scheduler/algorithm/priorities/most_requested_test.go b/plugin/pkg/scheduler/algorithm/priorities/most_requested_test.go index a11aaf5e3c5..fef9748a4a6 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/most_requested_test.go +++ b/plugin/pkg/scheduler/algorithm/priorities/most_requested_test.go @@ -20,8 +20,8 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) @@ -35,23 +35,23 @@ func TestMostRequested(t *testing.T) { "bar": "foo", "baz": "blah", } - noResources := api.PodSpec{ - Containers: []api.Container{}, + noResources := v1.PodSpec{ + Containers: []v1.Container{}, } - cpuOnly := api.PodSpec{ + cpuOnly := v1.PodSpec{ NodeName: "machine1", - Containers: []api.Container{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("1000m"), "memory": resource.MustParse("0"), }, }, }, { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("2000m"), "memory": resource.MustParse("0"), }, @@ -61,20 +61,20 @@ func TestMostRequested(t *testing.T) { } cpuOnly2 := cpuOnly cpuOnly2.NodeName = "machine2" - cpuAndMemory := api.PodSpec{ + cpuAndMemory := v1.PodSpec{ NodeName: "machine2", - Containers: []api.Container{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("1000m"), "memory": resource.MustParse("2000"), }, }, }, { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("2000m"), "memory": resource.MustParse("3000"), }, @@ -83,9 +83,9 @@ func TestMostRequested(t *testing.T) { }, } tests := []struct { - pod *api.Pod - pods []*api.Pod - nodes []*api.Node + pod *v1.Pod + pods []*v1.Pod + nodes []*v1.Node expectedList schedulerapi.HostPriorityList test string }{ @@ -101,8 +101,8 @@ func TestMostRequested(t *testing.T) { Memory Score: (0 * 10 / 10000 = 0 Node2 Score: (0 + 0) / 2 = 0 */ - pod: &api.Pod{Spec: noResources}, - nodes: []*api.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, + pod: &v1.Pod{Spec: noResources}, + nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}}, test: "nothing scheduled, nothing requested", }, @@ -118,8 +118,8 @@ func TestMostRequested(t *testing.T) { Memory Score: (5000 * 10 / 10000 = 5 Node2 Score: (5 + 5) / 2 = 5 */ - pod: &api.Pod{Spec: cpuAndMemory}, - nodes: []*api.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 6000, 10000)}, + pod: &v1.Pod{Spec: cpuAndMemory}, + nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 6000, 10000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 6}, {Host: "machine2", Score: 5}}, test: "nothing scheduled, resources requested, differently sized machines", }, @@ -135,15 +135,15 @@ func TestMostRequested(t *testing.T) { Memory Score: (5000 * 10) / 20000 = 2.5 Node2 Score: (6 + 2.5) / 2 = 4 */ - pod: &api.Pod{Spec: noResources}, - nodes: []*api.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, + pod: &v1.Pod{Spec: noResources}, + nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 3}, {Host: "machine2", Score: 4}}, test: "no resources requested, pods scheduled with resources", - pods: []*api.Pod{ - {Spec: cpuOnly, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: cpuOnly, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: cpuOnly2, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: cpuAndMemory, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: cpuOnly, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: cpuOnly, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: cpuOnly2, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: cpuAndMemory, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, }, { @@ -158,11 +158,11 @@ func TestMostRequested(t *testing.T) { Memory Score: (10000 * 10) / 20000 = 5 Node2 Score: (6 + 5) / 2 = 5 */ - pod: &api.Pod{Spec: cpuAndMemory}, - nodes: []*api.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, + pod: &v1.Pod{Spec: cpuAndMemory}, + nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 4}, {Host: "machine2", Score: 5}}, test: "resources requested, pods scheduled with resources", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: cpuOnly}, {Spec: cpuAndMemory}, }, diff --git a/plugin/pkg/scheduler/algorithm/priorities/node_affinity.go b/plugin/pkg/scheduler/algorithm/priorities/node_affinity.go index 861f9e7ca0b..4c9c151d752 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/node_affinity.go +++ b/plugin/pkg/scheduler/algorithm/priorities/node_affinity.go @@ -20,7 +20,7 @@ import ( "fmt" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" @@ -31,19 +31,19 @@ import ( // it will a get an add of preferredSchedulingTerm.Weight. Thus, the more preferredSchedulingTerms // the node satisfies and the more the preferredSchedulingTerm that is satisfied weights, the higher // score the node gets. -func CalculateNodeAffinityPriorityMap(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func CalculateNodeAffinityPriorityMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { node := nodeInfo.Node() if node == nil { return schedulerapi.HostPriority{}, fmt.Errorf("node not found") } - var affinity *api.Affinity + var affinity *v1.Affinity if priorityMeta, ok := meta.(*priorityMetadata); ok { affinity = priorityMeta.affinity } else { // We couldn't parse metadata - fallback to computing it. var err error - affinity, err = api.GetAffinityFromPodAnnotations(pod.Annotations) + affinity, err = v1.GetAffinityFromPodAnnotations(pod.Annotations) if err != nil { return schedulerapi.HostPriority{}, err } @@ -62,7 +62,7 @@ func CalculateNodeAffinityPriorityMap(pod *api.Pod, meta interface{}, nodeInfo * } // TODO: Avoid computing it for all nodes if this becomes a performance problem. - nodeSelector, err := api.NodeSelectorRequirementsAsSelector(preferredSchedulingTerm.Preference.MatchExpressions) + nodeSelector, err := v1.NodeSelectorRequirementsAsSelector(preferredSchedulingTerm.Preference.MatchExpressions) if err != nil { return schedulerapi.HostPriority{}, err } @@ -78,7 +78,7 @@ func CalculateNodeAffinityPriorityMap(pod *api.Pod, meta interface{}, nodeInfo * }, nil } -func CalculateNodeAffinityPriorityReduce(pod *api.Pod, meta interface{}, nodeNameToInfo map[string]*schedulercache.NodeInfo, result schedulerapi.HostPriorityList) error { +func CalculateNodeAffinityPriorityReduce(pod *v1.Pod, meta interface{}, nodeNameToInfo map[string]*schedulercache.NodeInfo, result schedulerapi.HostPriorityList) error { var maxCount int for i := range result { if result[i].Score > maxCount { diff --git a/plugin/pkg/scheduler/algorithm/priorities/node_affinity_test.go b/plugin/pkg/scheduler/algorithm/priorities/node_affinity_test.go index 85c390c903e..64335f37b57 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/node_affinity_test.go +++ b/plugin/pkg/scheduler/algorithm/priorities/node_affinity_test.go @@ -20,7 +20,7 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) @@ -33,7 +33,7 @@ func TestNodeAffinityPriority(t *testing.T) { label5 := map[string]string{"foo": "bar", "key": "value", "az": "az1"} affinity1 := map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": {"preferredDuringSchedulingIgnoredDuringExecution": [ { "weight": 2, @@ -50,7 +50,7 @@ func TestNodeAffinityPriority(t *testing.T) { } affinity2 := map[string]string{ - api.AffinityAnnotationKey: ` + v1.AffinityAnnotationKey: ` {"nodeAffinity": {"preferredDuringSchedulingIgnoredDuringExecution": [ { "weight": 2, @@ -91,63 +91,63 @@ func TestNodeAffinityPriority(t *testing.T) { } tests := []struct { - pod *api.Pod - nodes []*api.Node + pod *v1.Pod + nodes []*v1.Node expectedList schedulerapi.HostPriorityList test string }{ { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{}, }, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: label1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: label2}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: label3}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: label1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: label2}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: label3}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}, {Host: "machine3", Score: 0}}, test: "all machines are same priority as NodeAffinity is nil", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: affinity1, }, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: label4}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: label2}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: label3}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: label4}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: label2}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: label3}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}, {Host: "machine3", Score: 0}}, test: "no machine macthes preferred scheduling requirements in NodeAffinity of pod so all machines' priority is zero", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: affinity1, }, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: label1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: label2}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: label3}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: label1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: label2}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: label3}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 0}, {Host: "machine3", Score: 0}}, test: "only machine1 matches the preferred scheduling requirements of pod", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: affinity2, }, }, - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: label1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine5", Labels: label5}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: label2}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: label1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine5", Labels: label5}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: label2}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 1}, {Host: "machine5", Score: 10}, {Host: "machine2", Score: 3}}, test: "all machines matches the preferred scheduling requirements of pod but with different priorities ", diff --git a/plugin/pkg/scheduler/algorithm/priorities/node_label.go b/plugin/pkg/scheduler/algorithm/priorities/node_label.go index ed177e02e4b..d22c29b505c 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/node_label.go +++ b/plugin/pkg/scheduler/algorithm/priorities/node_label.go @@ -19,7 +19,7 @@ package priorities import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" @@ -42,7 +42,7 @@ func NewNodeLabelPriority(label string, presence bool) (algorithm.PriorityMapFun // CalculateNodeLabelPriority checks whether a particular label exists on a node or not, regardless of its value. // If presence is true, prioritizes nodes that have the specified label, regardless of value. // If presence is false, prioritizes nodes that do not have the specified label. -func (n *NodeLabelPrioritizer) CalculateNodeLabelPriorityMap(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func (n *NodeLabelPrioritizer) CalculateNodeLabelPriorityMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { node := nodeInfo.Node() if node == nil { return schedulerapi.HostPriority{}, fmt.Errorf("node not found") diff --git a/plugin/pkg/scheduler/algorithm/priorities/node_label_test.go b/plugin/pkg/scheduler/algorithm/priorities/node_label_test.go index 826ceb3f818..58913ae4e0a 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/node_label_test.go +++ b/plugin/pkg/scheduler/algorithm/priorities/node_label_test.go @@ -21,7 +21,7 @@ import ( "sort" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) @@ -31,17 +31,17 @@ func TestNewNodeLabelPriority(t *testing.T) { label2 := map[string]string{"bar": "foo"} label3 := map[string]string{"bar": "baz"} tests := []struct { - nodes []*api.Node + nodes []*v1.Node label string presence bool expectedList schedulerapi.HostPriorityList test string }{ { - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: label1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: label2}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: label3}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: label1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: label2}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: label3}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}, {Host: "machine3", Score: 0}}, label: "baz", @@ -49,10 +49,10 @@ func TestNewNodeLabelPriority(t *testing.T) { test: "no match found, presence true", }, { - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: label1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: label2}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: label3}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: label1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: label2}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: label3}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}, {Host: "machine3", Score: 10}}, label: "baz", @@ -60,10 +60,10 @@ func TestNewNodeLabelPriority(t *testing.T) { test: "no match found, presence false", }, { - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: label1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: label2}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: label3}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: label1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: label2}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: label3}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 0}, {Host: "machine3", Score: 0}}, label: "foo", @@ -71,10 +71,10 @@ func TestNewNodeLabelPriority(t *testing.T) { test: "one match found, presence true", }, { - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: label1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: label2}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: label3}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: label1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: label2}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: label3}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 10}, {Host: "machine3", Score: 10}}, label: "foo", @@ -82,10 +82,10 @@ func TestNewNodeLabelPriority(t *testing.T) { test: "one match found, presence false", }, { - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: label1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: label2}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: label3}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: label1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: label2}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: label3}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 10}, {Host: "machine3", Score: 10}}, label: "bar", @@ -93,10 +93,10 @@ func TestNewNodeLabelPriority(t *testing.T) { test: "two matches found, presence true", }, { - nodes: []*api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "machine1", Labels: label1}}, - {ObjectMeta: api.ObjectMeta{Name: "machine2", Labels: label2}}, - {ObjectMeta: api.ObjectMeta{Name: "machine3", Labels: label3}}, + nodes: []*v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "machine1", Labels: label1}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine2", Labels: label2}}, + {ObjectMeta: v1.ObjectMeta{Name: "machine3", Labels: label3}}, }, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 0}, {Host: "machine3", Score: 0}}, label: "bar", diff --git a/plugin/pkg/scheduler/algorithm/priorities/node_prefer_avoid_pods.go b/plugin/pkg/scheduler/algorithm/priorities/node_prefer_avoid_pods.go index d58890e75dd..e65c00d7552 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/node_prefer_avoid_pods.go +++ b/plugin/pkg/scheduler/algorithm/priorities/node_prefer_avoid_pods.go @@ -19,13 +19,13 @@ package priorities import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" priorityutil "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) -func CalculateNodePreferAvoidPodsPriorityMap(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func CalculateNodePreferAvoidPodsPriorityMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { node := nodeInfo.Node() if node == nil { return schedulerapi.HostPriority{}, fmt.Errorf("node not found") @@ -43,7 +43,7 @@ func CalculateNodePreferAvoidPodsPriorityMap(pod *api.Pod, meta interface{}, nod return schedulerapi.HostPriority{Host: node.Name, Score: 10}, nil } - avoids, err := api.GetAvoidPodsFromNodeAnnotations(node.Annotations) + avoids, err := v1.GetAvoidPodsFromNodeAnnotations(node.Annotations) if err != nil { // If we cannot get annotation, assume it's schedulable there. return schedulerapi.HostPriority{Host: node.Name, Score: 10}, nil diff --git a/plugin/pkg/scheduler/algorithm/priorities/node_prefer_avoid_pods_test.go b/plugin/pkg/scheduler/algorithm/priorities/node_prefer_avoid_pods_test.go index 66d00249c76..cdac523984e 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/node_prefer_avoid_pods_test.go +++ b/plugin/pkg/scheduler/algorithm/priorities/node_prefer_avoid_pods_test.go @@ -21,14 +21,14 @@ import ( "sort" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) func TestNodePreferAvoidPriority(t *testing.T) { annotations1 := map[string]string{ - api.PreferAvoidPodsAnnotationKey: ` + v1.PreferAvoidPodsAnnotationKey: ` { "preferAvoidPods": [ { @@ -48,7 +48,7 @@ func TestNodePreferAvoidPriority(t *testing.T) { }`, } annotations2 := map[string]string{ - api.PreferAvoidPodsAnnotationKey: ` + v1.PreferAvoidPodsAnnotationKey: ` { "preferAvoidPods": [ { @@ -67,29 +67,29 @@ func TestNodePreferAvoidPriority(t *testing.T) { ] }`, } - testNodes := []*api.Node{ + testNodes := []*v1.Node{ { - ObjectMeta: api.ObjectMeta{Name: "machine1", Annotations: annotations1}, + ObjectMeta: v1.ObjectMeta{Name: "machine1", Annotations: annotations1}, }, { - ObjectMeta: api.ObjectMeta{Name: "machine2", Annotations: annotations2}, + ObjectMeta: v1.ObjectMeta{Name: "machine2", Annotations: annotations2}, }, { - ObjectMeta: api.ObjectMeta{Name: "machine3"}, + ObjectMeta: v1.ObjectMeta{Name: "machine3"}, }, } trueVar := true tests := []struct { - pod *api.Pod - nodes []*api.Node + pod *v1.Pod + nodes []*v1.Node expectedList schedulerapi.HostPriorityList test string }{ { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", - OwnerReferences: []api.OwnerReference{ + OwnerReferences: []v1.OwnerReference{ {Kind: "ReplicationController", Name: "foo", UID: "abcdef123456", Controller: &trueVar}, }, }, @@ -99,10 +99,10 @@ func TestNodePreferAvoidPriority(t *testing.T) { test: "pod managed by ReplicationController should avoid a node, this node get lowest priority score", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", - OwnerReferences: []api.OwnerReference{ + OwnerReferences: []v1.OwnerReference{ {Kind: "RandomController", Name: "foo", UID: "abcdef123456", Controller: &trueVar}, }, }, @@ -112,10 +112,10 @@ func TestNodePreferAvoidPriority(t *testing.T) { test: "ownership by random controller should be ignored", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", - OwnerReferences: []api.OwnerReference{ + OwnerReferences: []v1.OwnerReference{ {Kind: "ReplicationController", Name: "foo", UID: "abcdef123456"}, }, }, @@ -125,10 +125,10 @@ func TestNodePreferAvoidPriority(t *testing.T) { test: "owner without Controller field set should be ignored", }, { - pod: &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod: &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: "default", - OwnerReferences: []api.OwnerReference{ + OwnerReferences: []v1.OwnerReference{ {Kind: "ReplicaSet", Name: "foo", UID: "qwert12345", Controller: &trueVar}, }, }, diff --git a/plugin/pkg/scheduler/algorithm/priorities/selector_spreading.go b/plugin/pkg/scheduler/algorithm/priorities/selector_spreading.go index da31aa6a541..20d5f4a9ee4 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/selector_spreading.go +++ b/plugin/pkg/scheduler/algorithm/priorities/selector_spreading.go @@ -20,8 +20,8 @@ import ( "sync" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" utilnode "k8s.io/kubernetes/pkg/util/node" "k8s.io/kubernetes/pkg/util/workqueue" @@ -57,7 +57,7 @@ func NewSelectorSpreadPriority( } // Returns selectors of services, RCs and RSs matching the given pod. -func getSelectors(pod *api.Pod, sl algorithm.ServiceLister, cl algorithm.ControllerLister, rsl algorithm.ReplicaSetLister) []labels.Selector { +func getSelectors(pod *v1.Pod, sl algorithm.ServiceLister, cl algorithm.ControllerLister, rsl algorithm.ReplicaSetLister) []labels.Selector { selectors := make([]labels.Selector, 0, 3) if services, err := sl.GetPodServices(pod); err == nil { for _, service := range services { @@ -79,7 +79,7 @@ func getSelectors(pod *api.Pod, sl algorithm.ServiceLister, cl algorithm.Control return selectors } -func (s *SelectorSpread) getSelectors(pod *api.Pod) []labels.Selector { +func (s *SelectorSpread) getSelectors(pod *v1.Pod) []labels.Selector { return getSelectors(pod, s.serviceLister, s.controllerLister, s.replicaSetLister) } @@ -89,7 +89,7 @@ func (s *SelectorSpread) getSelectors(pod *api.Pod) []labels.Selector { // i.e. it pushes the scheduler towards a node where there's the smallest number of // pods which match the same service, RC or RS selectors as the pod being scheduled. // Where zone information is included on the nodes, it favors nodes in zones with fewer existing matching pods. -func (s *SelectorSpread) CalculateSpreadPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { +func (s *SelectorSpread) CalculateSpreadPriority(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*v1.Node) (schedulerapi.HostPriorityList, error) { selectors := s.getSelectors(pod) // Count similar pods by node @@ -199,8 +199,8 @@ func NewServiceAntiAffinityPriority(podLister algorithm.PodLister, serviceLister // CalculateAntiAffinityPriority spreads pods by minimizing the number of pods belonging to the same service // on machines with the same value for a particular label. // The label to be considered is provided to the struct (ServiceAntiAffinity). -func (s *ServiceAntiAffinity) CalculateAntiAffinityPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { - var nsServicePods []*api.Pod +func (s *ServiceAntiAffinity) CalculateAntiAffinityPriority(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*v1.Node) (schedulerapi.HostPriorityList, error) { + var nsServicePods []*v1.Pod if services, err := s.serviceLister.GetPodServices(pod); err == nil && len(services) > 0 { // just use the first service and get the other pods within the service // TODO: a separate predicate can be created that tries to handle all services for the pod diff --git a/plugin/pkg/scheduler/algorithm/priorities/selector_spreading_test.go b/plugin/pkg/scheduler/algorithm/priorities/selector_spreading_test.go index 908398a5750..7d6ebe870ab 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/selector_spreading_test.go +++ b/plugin/pkg/scheduler/algorithm/priorities/selector_spreading_test.go @@ -21,19 +21,19 @@ import ( "sort" "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) -func controllerRef(kind, name, uid string) []api.OwnerReference { +func controllerRef(kind, name, uid string) []v1.OwnerReference { // TODO: When ControllerRef will be implemented uncomment code below. return nil //trueVar := true - //return []api.OwnerReference{ + //return []v1.OwnerReference{ // {Kind: kind, Name: name, UID: types.UID(uid), Controller: &trueVar}, //} } @@ -47,208 +47,208 @@ func TestSelectorSpreadPriority(t *testing.T) { "bar": "foo", "baz": "blah", } - zone1Spec := api.PodSpec{ + zone1Spec := v1.PodSpec{ NodeName: "machine1", } - zone2Spec := api.PodSpec{ + zone2Spec := v1.PodSpec{ NodeName: "machine2", } tests := []struct { - pod *api.Pod - pods []*api.Pod + pod *v1.Pod + pods []*v1.Pod nodes []string - rcs []*api.ReplicationController + rcs []*v1.ReplicationController rss []*extensions.ReplicaSet - services []*api.Service + services []*v1.Service expectedList schedulerapi.HostPriorityList test string }{ { - pod: new(api.Pod), + pod: new(v1.Pod), nodes: []string{"machine1", "machine2"}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}}, test: "nothing scheduled", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{{Spec: zone1Spec}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{{Spec: zone1Spec}}, nodes: []string{"machine1", "machine2"}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}}, test: "no services", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{{Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{{Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}}, nodes: []string{"machine1", "machine2"}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: map[string]string{"key": "value"}}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: map[string]string{"key": "value"}}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}}, test: "different services", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, nodes: []string{"machine1", "machine2"}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 0}}, test: "two pods, one service pod", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: api.NamespaceDefault}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: "ns1"}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: v1.NamespaceDefault}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: "ns1"}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, }, nodes: []string{"machine1", "machine2"}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 0}}, test: "five pods, one service pod in no namespace", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: api.NamespaceDefault}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: "ns1"}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: api.NamespaceDefault}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: v1.NamespaceDefault}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: "ns1"}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: v1.NamespaceDefault}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, }, nodes: []string{"machine1", "machine2"}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}, ObjectMeta: api.ObjectMeta{Namespace: api.NamespaceDefault}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}, ObjectMeta: v1.ObjectMeta{Namespace: v1.NamespaceDefault}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 0}}, test: "four pods, one service pod in default namespace", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: "ns1"}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: api.NamespaceDefault}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: "ns2"}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: "ns1"}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: "ns1"}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: v1.NamespaceDefault}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: "ns2"}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: "ns1"}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, }, nodes: []string{"machine1", "machine2"}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}, ObjectMeta: api.ObjectMeta{Namespace: "ns1"}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}, ObjectMeta: v1.ObjectMeta{Namespace: "ns1"}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 0}}, test: "five pods, one service pod in specific namespace", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, nodes: []string{"machine1", "machine2"}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}}, test: "three pods, two service pods on different machines", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, nodes: []string{"machine1", "machine2"}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 5}, {Host: "machine2", Score: 0}}, test: "four pods, three service pods", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, nodes: []string{"machine1", "machine2"}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: map[string]string{"baz": "blah"}}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: map[string]string{"baz": "blah"}}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 5}}, test: "service with partial pod label matches", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, }, nodes: []string{"machine1", "machine2"}, - rcs: []*api.ReplicationController{{Spec: api.ReplicationControllerSpec{Selector: map[string]string{"foo": "bar"}}}}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: map[string]string{"baz": "blah"}}}}, + rcs: []*v1.ReplicationController{{Spec: v1.ReplicationControllerSpec{Selector: map[string]string{"foo": "bar"}}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: map[string]string{"baz": "blah"}}}}, // "baz=blah" matches both labels1 and labels2, and "foo=bar" matches only labels 1. This means that we assume that we want to // do spreading between all pods. The result should be exactly as above. expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 5}}, test: "service with partial pod label matches with service and replication controller", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, }, nodes: []string{"machine1", "machine2"}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: map[string]string{"baz": "blah"}}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: map[string]string{"baz": "blah"}}}}, rss: []*extensions.ReplicaSet{{Spec: extensions.ReplicaSetSpec{Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}}}}, // We use ReplicaSet, instead of ReplicationController. The result should be exactly as above. expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 5}}, test: "service with partial pod label matches with service and replica set", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: map[string]string{"foo": "bar", "bar": "foo"}, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: map[string]string{"foo": "bar", "bar": "foo"}, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, }, nodes: []string{"machine1", "machine2"}, - rcs: []*api.ReplicationController{{Spec: api.ReplicationControllerSpec{Selector: map[string]string{"foo": "bar"}}}}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: map[string]string{"bar": "foo"}}}}, + rcs: []*v1.ReplicationController{{Spec: v1.ReplicationControllerSpec{Selector: map[string]string{"foo": "bar"}}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: map[string]string{"bar": "foo"}}}}, // Taken together Service and Replication Controller should match all Pods, hence result should be equal to one above. expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 5}}, test: "disjoined service and replication controller should be treated equally", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: map[string]string{"foo": "bar", "bar": "foo"}, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: map[string]string{"foo": "bar", "bar": "foo"}, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, }, nodes: []string{"machine1", "machine2"}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: map[string]string{"bar": "foo"}}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: map[string]string{"bar": "foo"}}}}, rss: []*extensions.ReplicaSet{{Spec: extensions.ReplicaSetSpec{Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}}}}, // We use ReplicaSet, instead of ReplicationController. The result should be exactly as above. expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 5}}, test: "disjoined service and replica set should be treated equally", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, }, nodes: []string{"machine1", "machine2"}, - rcs: []*api.ReplicationController{{Spec: api.ReplicationControllerSpec{Selector: map[string]string{"foo": "bar"}}}}, + rcs: []*v1.ReplicationController{{Spec: v1.ReplicationControllerSpec{Selector: map[string]string{"foo": "bar"}}}}, // Both Nodes have one pod from the given RC, hence both get 0 score. expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}}, test: "Replication controller with partial pod label matches", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, }, nodes: []string{"machine1", "machine2"}, rss: []*extensions.ReplicaSet{{Spec: extensions.ReplicaSetSpec{Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}}}}, @@ -257,23 +257,23 @@ func TestSelectorSpreadPriority(t *testing.T) { test: "Replica set with partial pod label matches", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicationController", "name", "abc123")}}, }, nodes: []string{"machine1", "machine2"}, - rcs: []*api.ReplicationController{{Spec: api.ReplicationControllerSpec{Selector: map[string]string{"baz": "blah"}}}}, + rcs: []*v1.ReplicationController{{Spec: v1.ReplicationControllerSpec{Selector: map[string]string{"baz": "blah"}}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 5}}, test: "Another replication controller with partial pod label matches", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, OwnerReferences: controllerRef("ReplicaSet", "name", "abc123")}}, }, nodes: []string{"machine1", "machine2"}, rss: []*extensions.ReplicaSet{{Spec: extensions.ReplicaSetSpec{Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"baz": "blah"}}}}}, @@ -300,10 +300,10 @@ func TestSelectorSpreadPriority(t *testing.T) { } } -func buildPod(nodeName string, labels map[string]string, ownerRefs []api.OwnerReference) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{Labels: labels, OwnerReferences: ownerRefs}, - Spec: api.PodSpec{NodeName: nodeName}, +func buildPod(nodeName string, labels map[string]string, ownerRefs []v1.OwnerReference) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Labels: labels, OwnerReferences: ownerRefs}, + Spec: v1.PodSpec{NodeName: nodeName}, } } @@ -340,17 +340,17 @@ func TestZoneSelectorSpreadPriority(t *testing.T) { } tests := []struct { - pod *api.Pod - pods []*api.Pod + pod *v1.Pod + pods []*v1.Pod nodes []string - rcs []*api.ReplicationController + rcs []*v1.ReplicationController rss []*extensions.ReplicaSet - services []*api.Service + services []*v1.Service expectedList schedulerapi.HostPriorityList test string }{ { - pod: new(api.Pod), + pod: new(v1.Pod), expectedList: []schedulerapi.HostPriority{ {Host: nodeMachine1Zone1, Score: 10}, {Host: nodeMachine1Zone2, Score: 10}, @@ -363,7 +363,7 @@ func TestZoneSelectorSpreadPriority(t *testing.T) { }, { pod: buildPod("", labels1, nil), - pods: []*api.Pod{buildPod(nodeMachine1Zone1, nil, nil)}, + pods: []*v1.Pod{buildPod(nodeMachine1Zone1, nil, nil)}, expectedList: []schedulerapi.HostPriority{ {Host: nodeMachine1Zone1, Score: 10}, {Host: nodeMachine1Zone2, Score: 10}, @@ -376,8 +376,8 @@ func TestZoneSelectorSpreadPriority(t *testing.T) { }, { pod: buildPod("", labels1, nil), - pods: []*api.Pod{buildPod(nodeMachine1Zone1, labels2, nil)}, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: map[string]string{"key": "value"}}}}, + pods: []*v1.Pod{buildPod(nodeMachine1Zone1, labels2, nil)}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: map[string]string{"key": "value"}}}}, expectedList: []schedulerapi.HostPriority{ {Host: nodeMachine1Zone1, Score: 10}, {Host: nodeMachine1Zone2, Score: 10}, @@ -390,11 +390,11 @@ func TestZoneSelectorSpreadPriority(t *testing.T) { }, { pod: buildPod("", labels1, nil), - pods: []*api.Pod{ + pods: []*v1.Pod{ buildPod(nodeMachine1Zone1, labels2, nil), buildPod(nodeMachine1Zone2, labels1, nil), }, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{ {Host: nodeMachine1Zone1, Score: 10}, {Host: nodeMachine1Zone2, Score: 0}, // Already have pod on machine @@ -407,14 +407,14 @@ func TestZoneSelectorSpreadPriority(t *testing.T) { }, { pod: buildPod("", labels1, nil), - pods: []*api.Pod{ + pods: []*v1.Pod{ buildPod(nodeMachine1Zone1, labels2, nil), buildPod(nodeMachine1Zone2, labels1, nil), buildPod(nodeMachine2Zone2, labels1, nil), buildPod(nodeMachine1Zone3, labels2, nil), buildPod(nodeMachine2Zone3, labels1, nil), }, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{ {Host: nodeMachine1Zone1, Score: 10}, {Host: nodeMachine1Zone2, Score: 0}, // Pod on node @@ -427,13 +427,13 @@ func TestZoneSelectorSpreadPriority(t *testing.T) { }, { pod: buildPod("", labels1, nil), - pods: []*api.Pod{ + pods: []*v1.Pod{ buildPod(nodeMachine1Zone1, labels1, nil), buildPod(nodeMachine1Zone2, labels1, nil), buildPod(nodeMachine2Zone2, labels2, nil), buildPod(nodeMachine1Zone3, labels1, nil), }, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{ {Host: nodeMachine1Zone1, Score: 0}, // Pod on node {Host: nodeMachine1Zone2, Score: 0}, // Pod on node @@ -446,13 +446,13 @@ func TestZoneSelectorSpreadPriority(t *testing.T) { }, { pod: buildPod("", labels1, nil), - pods: []*api.Pod{ + pods: []*v1.Pod{ buildPod(nodeMachine1Zone1, labels1, nil), buildPod(nodeMachine1Zone2, labels1, nil), buildPod(nodeMachine1Zone3, labels1, nil), buildPod(nodeMachine2Zone2, labels2, nil), }, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{ {Host: nodeMachine1Zone1, Score: 0}, // Pod on node {Host: nodeMachine1Zone2, Score: 0}, // Pod on node @@ -465,12 +465,12 @@ func TestZoneSelectorSpreadPriority(t *testing.T) { }, { pod: buildPod("", labels1, controllerRef("ReplicationController", "name", "abc123")), - pods: []*api.Pod{ + pods: []*v1.Pod{ buildPod(nodeMachine1Zone3, labels1, controllerRef("ReplicationController", "name", "abc123")), buildPod(nodeMachine1Zone2, labels1, controllerRef("ReplicationController", "name", "abc123")), buildPod(nodeMachine1Zone3, labels1, controllerRef("ReplicationController", "name", "abc123")), }, - rcs: []*api.ReplicationController{{Spec: api.ReplicationControllerSpec{Selector: labels1}}}, + rcs: []*v1.ReplicationController{{Spec: v1.ReplicationControllerSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{ // Note that because we put two pods on the same node (nodeMachine1Zone3), // the values here are questionable for zone2, in particular for nodeMachine1Zone2. @@ -528,13 +528,13 @@ func TestZoneSpreadPriority(t *testing.T) { nozone := map[string]string{ "name": "value", } - zone0Spec := api.PodSpec{ + zone0Spec := v1.PodSpec{ NodeName: "machine01", } - zone1Spec := api.PodSpec{ + zone1Spec := v1.PodSpec{ NodeName: "machine11", } - zone2Spec := api.PodSpec{ + zone2Spec := v1.PodSpec{ NodeName: "machine21", } labeledNodes := map[string]map[string]string{ @@ -543,15 +543,15 @@ func TestZoneSpreadPriority(t *testing.T) { "machine21": zone2, "machine22": zone2, } tests := []struct { - pod *api.Pod - pods []*api.Pod + pod *v1.Pod + pods []*v1.Pod nodes map[string]map[string]string - services []*api.Service + services []*v1.Service expectedList schedulerapi.HostPriorityList test string }{ { - pod: new(api.Pod), + pod: new(v1.Pod), nodes: labeledNodes, expectedList: []schedulerapi.HostPriority{{Host: "machine11", Score: 10}, {Host: "machine12", Score: 10}, {Host: "machine21", Score: 10}, {Host: "machine22", Score: 10}, @@ -559,8 +559,8 @@ func TestZoneSpreadPriority(t *testing.T) { test: "nothing scheduled", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{{Spec: zone1Spec}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{{Spec: zone1Spec}}, nodes: labeledNodes, expectedList: []schedulerapi.HostPriority{{Host: "machine11", Score: 10}, {Host: "machine12", Score: 10}, {Host: "machine21", Score: 10}, {Host: "machine22", Score: 10}, @@ -568,97 +568,97 @@ func TestZoneSpreadPriority(t *testing.T) { test: "no services", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{{Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{{Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}}, nodes: labeledNodes, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: map[string]string{"key": "value"}}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: map[string]string{"key": "value"}}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine11", Score: 10}, {Host: "machine12", Score: 10}, {Host: "machine21", Score: 10}, {Host: "machine22", Score: 10}, {Host: "machine01", Score: 0}, {Host: "machine02", Score: 0}}, test: "different services", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{ - {Spec: zone0Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: zone0Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, nodes: labeledNodes, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine11", Score: 10}, {Host: "machine12", Score: 10}, {Host: "machine21", Score: 0}, {Host: "machine22", Score: 0}, {Host: "machine01", Score: 0}, {Host: "machine02", Score: 0}}, test: "three pods, one service pod", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, nodes: labeledNodes, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine11", Score: 5}, {Host: "machine12", Score: 5}, {Host: "machine21", Score: 5}, {Host: "machine22", Score: 5}, {Host: "machine01", Score: 0}, {Host: "machine02", Score: 0}}, test: "three pods, two service pods on different machines", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: api.NamespaceDefault}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: api.NamespaceDefault}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1, Namespace: "ns1"}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: v1.NamespaceDefault}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: v1.NamespaceDefault}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1, Namespace: "ns1"}}, }, nodes: labeledNodes, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}, ObjectMeta: api.ObjectMeta{Namespace: api.NamespaceDefault}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}, ObjectMeta: v1.ObjectMeta{Namespace: v1.NamespaceDefault}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine11", Score: 0}, {Host: "machine12", Score: 0}, {Host: "machine21", Score: 10}, {Host: "machine22", Score: 10}, {Host: "machine01", Score: 0}, {Host: "machine02", Score: 0}}, test: "three service label match pods in different namespaces", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, nodes: labeledNodes, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine11", Score: 6}, {Host: "machine12", Score: 6}, {Host: "machine21", Score: 3}, {Host: "machine22", Score: 3}, {Host: "machine01", Score: 0}, {Host: "machine02", Score: 0}}, test: "four pods, three service pods", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{ - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels2}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels2}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, nodes: labeledNodes, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: map[string]string{"baz": "blah"}}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: map[string]string{"baz": "blah"}}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine11", Score: 3}, {Host: "machine12", Score: 3}, {Host: "machine21", Score: 6}, {Host: "machine22", Score: 6}, {Host: "machine01", Score: 0}, {Host: "machine02", Score: 0}}, test: "service with partial pod label matches", }, { - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Labels: labels1}}, - pods: []*api.Pod{ - {Spec: zone0Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone1Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, - {Spec: zone2Spec, ObjectMeta: api.ObjectMeta{Labels: labels1}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + pods: []*v1.Pod{ + {Spec: zone0Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone1Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, + {Spec: zone2Spec, ObjectMeta: v1.ObjectMeta{Labels: labels1}}, }, nodes: labeledNodes, - services: []*api.Service{{Spec: api.ServiceSpec{Selector: labels1}}}, + services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []schedulerapi.HostPriority{{Host: "machine11", Score: 7}, {Host: "machine12", Score: 7}, {Host: "machine21", Score: 5}, {Host: "machine22", Score: 5}, {Host: "machine01", Score: 0}, {Host: "machine02", Score: 0}}, @@ -682,18 +682,18 @@ func TestZoneSpreadPriority(t *testing.T) { } } -func makeLabeledNodeList(nodeMap map[string]map[string]string) []*api.Node { - nodes := make([]*api.Node, 0, len(nodeMap)) +func makeLabeledNodeList(nodeMap map[string]map[string]string) []*v1.Node { + nodes := make([]*v1.Node, 0, len(nodeMap)) for nodeName, labels := range nodeMap { - nodes = append(nodes, &api.Node{ObjectMeta: api.ObjectMeta{Name: nodeName, Labels: labels}}) + nodes = append(nodes, &v1.Node{ObjectMeta: v1.ObjectMeta{Name: nodeName, Labels: labels}}) } return nodes } -func makeNodeList(nodeNames []string) []*api.Node { - nodes := make([]*api.Node, 0, len(nodeNames)) +func makeNodeList(nodeNames []string) []*v1.Node { + nodes := make([]*v1.Node, 0, len(nodeNames)) for _, nodeName := range nodeNames { - nodes = append(nodes, &api.Node{ObjectMeta: api.ObjectMeta{Name: nodeName}}) + nodes = append(nodes, &v1.Node{ObjectMeta: v1.ObjectMeta{Name: nodeName}}) } return nodes } diff --git a/plugin/pkg/scheduler/algorithm/priorities/taint_toleration.go b/plugin/pkg/scheduler/algorithm/priorities/taint_toleration.go index 791a521ce29..d08c12b00f9 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/taint_toleration.go +++ b/plugin/pkg/scheduler/algorithm/priorities/taint_toleration.go @@ -20,21 +20,21 @@ import ( "fmt" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) // CountIntolerableTaintsPreferNoSchedule gives the count of intolerable taints of a pod with effect PreferNoSchedule -func countIntolerableTaintsPreferNoSchedule(taints []api.Taint, tolerations []api.Toleration) (intolerableTaints int) { +func countIntolerableTaintsPreferNoSchedule(taints []v1.Taint, tolerations []v1.Toleration) (intolerableTaints int) { for i := range taints { taint := &taints[i] // check only on taints that have effect PreferNoSchedule - if taint.Effect != api.TaintEffectPreferNoSchedule { + if taint.Effect != v1.TaintEffectPreferNoSchedule { continue } - if !api.TaintToleratedByTolerations(taint, tolerations) { + if !v1.TaintToleratedByTolerations(taint, tolerations) { intolerableTaints++ } } @@ -42,18 +42,18 @@ func countIntolerableTaintsPreferNoSchedule(taints []api.Taint, tolerations []ap } // getAllTolerationEffectPreferNoSchedule gets the list of all Toleration with Effect PreferNoSchedule -func getAllTolerationPreferNoSchedule(tolerations []api.Toleration) (tolerationList []api.Toleration) { +func getAllTolerationPreferNoSchedule(tolerations []v1.Toleration) (tolerationList []v1.Toleration) { for i := range tolerations { toleration := &tolerations[i] - if len(toleration.Effect) == 0 || toleration.Effect == api.TaintEffectPreferNoSchedule { + if len(toleration.Effect) == 0 || toleration.Effect == v1.TaintEffectPreferNoSchedule { tolerationList = append(tolerationList, *toleration) } } return } -func getTolerationListFromPod(pod *api.Pod) ([]api.Toleration, error) { - tolerations, err := api.GetTolerationsFromPodAnnotations(pod.Annotations) +func getTolerationListFromPod(pod *v1.Pod) ([]v1.Toleration, error) { + tolerations, err := v1.GetTolerationsFromPodAnnotations(pod.Annotations) if err != nil { return nil, err } @@ -61,13 +61,13 @@ func getTolerationListFromPod(pod *api.Pod) ([]api.Toleration, error) { } // ComputeTaintTolerationPriority prepares the priority list for all the nodes based on the number of intolerable taints on the node -func ComputeTaintTolerationPriorityMap(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func ComputeTaintTolerationPriorityMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { node := nodeInfo.Node() if node == nil { return schedulerapi.HostPriority{}, fmt.Errorf("node not found") } - var tolerationList []api.Toleration + var tolerationList []v1.Toleration if priorityMeta, ok := meta.(*priorityMetadata); ok { tolerationList = priorityMeta.podTolerations } else { @@ -78,7 +78,7 @@ func ComputeTaintTolerationPriorityMap(pod *api.Pod, meta interface{}, nodeInfo } } - taints, err := api.GetTaintsFromNodeAnnotations(node.Annotations) + taints, err := v1.GetTaintsFromNodeAnnotations(node.Annotations) if err != nil { return schedulerapi.HostPriority{}, err } @@ -88,7 +88,7 @@ func ComputeTaintTolerationPriorityMap(pod *api.Pod, meta interface{}, nodeInfo }, nil } -func ComputeTaintTolerationPriorityReduce(pod *api.Pod, meta interface{}, nodeNameToInfo map[string]*schedulercache.NodeInfo, result schedulerapi.HostPriorityList) error { +func ComputeTaintTolerationPriorityReduce(pod *v1.Pod, meta interface{}, nodeNameToInfo map[string]*schedulercache.NodeInfo, result schedulerapi.HostPriorityList) error { var maxCount int for i := range result { if result[i].Score > maxCount { diff --git a/plugin/pkg/scheduler/algorithm/priorities/taint_toleration_test.go b/plugin/pkg/scheduler/algorithm/priorities/taint_toleration_test.go index 93277ea59b3..c71664a816c 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/taint_toleration_test.go +++ b/plugin/pkg/scheduler/algorithm/priorities/taint_toleration_test.go @@ -21,29 +21,29 @@ import ( "reflect" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) -func nodeWithTaints(nodeName string, taints []api.Taint) *api.Node { +func nodeWithTaints(nodeName string, taints []v1.Taint) *v1.Node { taintsData, _ := json.Marshal(taints) - return &api.Node{ - ObjectMeta: api.ObjectMeta{ + return &v1.Node{ + ObjectMeta: v1.ObjectMeta{ Name: nodeName, Annotations: map[string]string{ - api.TaintsAnnotationKey: string(taintsData), + v1.TaintsAnnotationKey: string(taintsData), }, }, } } -func podWithTolerations(tolerations []api.Toleration) *api.Pod { +func podWithTolerations(tolerations []v1.Toleration) *v1.Pod { tolerationData, _ := json.Marshal(tolerations) - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Annotations: map[string]string{ - api.TolerationsAnnotationKey: string(tolerationData), + v1.TolerationsAnnotationKey: string(tolerationData), }, }, } @@ -55,30 +55,30 @@ func podWithTolerations(tolerations []api.Toleration) *api.Pod { func TestTaintAndToleration(t *testing.T) { tests := []struct { - pod *api.Pod - nodes []*api.Node + pod *v1.Pod + nodes []*v1.Node expectedList schedulerapi.HostPriorityList test string }{ // basic test case { test: "node with taints tolerated by the pod, gets a higher score than those node with intolerable taints", - pod: podWithTolerations([]api.Toleration{{ + pod: podWithTolerations([]v1.Toleration{{ Key: "foo", - Operator: api.TolerationOpEqual, + Operator: v1.TolerationOpEqual, Value: "bar", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }}), - nodes: []*api.Node{ - nodeWithTaints("nodeA", []api.Taint{{ + nodes: []*v1.Node{ + nodeWithTaints("nodeA", []v1.Taint{{ Key: "foo", Value: "bar", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }}), - nodeWithTaints("nodeB", []api.Taint{{ + nodeWithTaints("nodeB", []v1.Taint{{ Key: "foo", Value: "blah", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }}), }, expectedList: []schedulerapi.HostPriority{ @@ -89,37 +89,37 @@ func TestTaintAndToleration(t *testing.T) { // the count of taints that are tolerated by pod, does not matter. { test: "the nodes that all of their taints are tolerated by the pod, get the same score, no matter how many tolerable taints a node has", - pod: podWithTolerations([]api.Toleration{ + pod: podWithTolerations([]v1.Toleration{ { Key: "cpu-type", - Operator: api.TolerationOpEqual, + Operator: v1.TolerationOpEqual, Value: "arm64", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }, { Key: "disk-type", - Operator: api.TolerationOpEqual, + Operator: v1.TolerationOpEqual, Value: "ssd", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }, }), - nodes: []*api.Node{ - nodeWithTaints("nodeA", []api.Taint{}), - nodeWithTaints("nodeB", []api.Taint{ + nodes: []*v1.Node{ + nodeWithTaints("nodeA", []v1.Taint{}), + nodeWithTaints("nodeB", []v1.Taint{ { Key: "cpu-type", Value: "arm64", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }, }), - nodeWithTaints("nodeC", []api.Taint{ + nodeWithTaints("nodeC", []v1.Taint{ { Key: "cpu-type", Value: "arm64", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }, { Key: "disk-type", Value: "ssd", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }, }), }, @@ -132,30 +132,30 @@ func TestTaintAndToleration(t *testing.T) { // the count of taints on a node that are not tolerated by pod, matters. { test: "the more intolerable taints a node has, the lower score it gets.", - pod: podWithTolerations([]api.Toleration{{ + pod: podWithTolerations([]v1.Toleration{{ Key: "foo", - Operator: api.TolerationOpEqual, + Operator: v1.TolerationOpEqual, Value: "bar", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }}), - nodes: []*api.Node{ - nodeWithTaints("nodeA", []api.Taint{}), - nodeWithTaints("nodeB", []api.Taint{ + nodes: []*v1.Node{ + nodeWithTaints("nodeA", []v1.Taint{}), + nodeWithTaints("nodeB", []v1.Taint{ { Key: "cpu-type", Value: "arm64", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }, }), - nodeWithTaints("nodeC", []api.Taint{ + nodeWithTaints("nodeC", []v1.Taint{ { Key: "cpu-type", Value: "arm64", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }, { Key: "disk-type", Value: "ssd", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }, }), }, @@ -168,37 +168,37 @@ func TestTaintAndToleration(t *testing.T) { // taints-tolerations priority only takes care about the taints and tolerations that have effect PreferNoSchedule { test: "only taints and tolerations that have effect PreferNoSchedule are checked by taints-tolerations priority function", - pod: podWithTolerations([]api.Toleration{ + pod: podWithTolerations([]v1.Toleration{ { Key: "cpu-type", - Operator: api.TolerationOpEqual, + Operator: v1.TolerationOpEqual, Value: "arm64", - Effect: api.TaintEffectNoSchedule, + Effect: v1.TaintEffectNoSchedule, }, { Key: "disk-type", - Operator: api.TolerationOpEqual, + Operator: v1.TolerationOpEqual, Value: "ssd", - Effect: api.TaintEffectNoSchedule, + Effect: v1.TaintEffectNoSchedule, }, }), - nodes: []*api.Node{ - nodeWithTaints("nodeA", []api.Taint{}), - nodeWithTaints("nodeB", []api.Taint{ + nodes: []*v1.Node{ + nodeWithTaints("nodeA", []v1.Taint{}), + nodeWithTaints("nodeB", []v1.Taint{ { Key: "cpu-type", Value: "arm64", - Effect: api.TaintEffectNoSchedule, + Effect: v1.TaintEffectNoSchedule, }, }), - nodeWithTaints("nodeC", []api.Taint{ + nodeWithTaints("nodeC", []v1.Taint{ { Key: "cpu-type", Value: "arm64", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }, { Key: "disk-type", Value: "ssd", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, }, }), }, diff --git a/plugin/pkg/scheduler/algorithm/priorities/test_util.go b/plugin/pkg/scheduler/algorithm/priorities/test_util.go index 76fd847aa49..a09a5943485 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/test_util.go +++ b/plugin/pkg/scheduler/algorithm/priorities/test_util.go @@ -17,22 +17,22 @@ limitations under the License. package priorities import ( - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) -func makeNode(node string, milliCPU, memory int64) *api.Node { - return &api.Node{ - ObjectMeta: api.ObjectMeta{Name: node}, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ +func makeNode(node string, milliCPU, memory int64) *v1.Node { + return &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: node}, + Status: v1.NodeStatus{ + Capacity: v1.ResourceList{ "cpu": *resource.NewMilliQuantity(milliCPU, resource.DecimalSI), "memory": *resource.NewQuantity(memory, resource.BinarySI), }, - Allocatable: api.ResourceList{ + Allocatable: v1.ResourceList{ "cpu": *resource.NewMilliQuantity(milliCPU, resource.DecimalSI), "memory": *resource.NewQuantity(memory, resource.BinarySI), }, @@ -41,7 +41,7 @@ func makeNode(node string, milliCPU, memory int64) *api.Node { } func priorityFunction(mapFn algorithm.PriorityMapFunction, reduceFn algorithm.PriorityReduceFunction) algorithm.PriorityFunction { - return func(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { + return func(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*v1.Node) (schedulerapi.HostPriorityList, error) { result := make(schedulerapi.HostPriorityList, 0, len(nodes)) for i := range nodes { hostResult, err := mapFn(pod, nil, nodeNameToInfo[nodes[i].Name]) diff --git a/plugin/pkg/scheduler/algorithm/priorities/util/BUILD b/plugin/pkg/scheduler/algorithm/priorities/util/BUILD index 793bc4f7003..af916ec858c 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/util/BUILD +++ b/plugin/pkg/scheduler/algorithm/priorities/util/BUILD @@ -19,8 +19,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/labels:go_default_library", "//pkg/util/sets:go_default_library", ], diff --git a/plugin/pkg/scheduler/algorithm/priorities/util/non_zero.go b/plugin/pkg/scheduler/algorithm/priorities/util/non_zero.go index 8588471d479..b928fefa517 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/util/non_zero.go +++ b/plugin/pkg/scheduler/algorithm/priorities/util/non_zero.go @@ -16,9 +16,7 @@ limitations under the License. package util -import ( - "k8s.io/kubernetes/pkg/api" -) +import "k8s.io/kubernetes/pkg/api/v1" // For each of these resources, a pod that doesn't request the resource explicitly // will be treated as having requested the amount indicated below, for the purpose @@ -32,18 +30,18 @@ const DefaultMilliCpuRequest int64 = 100 // 0.1 core const DefaultMemoryRequest int64 = 200 * 1024 * 1024 // 200 MB // GetNonzeroRequests returns the default resource request if none is found or what is provided on the request -// TODO: Consider setting default as a fixed fraction of machine capacity (take "capacity api.ResourceList" +// TODO: Consider setting default as a fixed fraction of machine capacity (take "capacity v1.ResourceList" // as an additional argument here) rather than using constants -func GetNonzeroRequests(requests *api.ResourceList) (int64, int64) { +func GetNonzeroRequests(requests *v1.ResourceList) (int64, int64) { var outMilliCPU, outMemory int64 // Override if un-set, but not if explicitly set to zero - if _, found := (*requests)[api.ResourceCPU]; !found { + if _, found := (*requests)[v1.ResourceCPU]; !found { outMilliCPU = DefaultMilliCpuRequest } else { outMilliCPU = requests.Cpu().MilliValue() } // Override if un-set, but not if explicitly set to zero - if _, found := (*requests)[api.ResourceMemory]; !found { + if _, found := (*requests)[v1.ResourceMemory]; !found { outMemory = DefaultMemoryRequest } else { outMemory = requests.Memory().Value() diff --git a/plugin/pkg/scheduler/algorithm/priorities/util/topologies.go b/plugin/pkg/scheduler/algorithm/priorities/util/topologies.go index 36890cb0e9d..e5d091c27c1 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/util/topologies.go +++ b/plugin/pkg/scheduler/algorithm/priorities/util/topologies.go @@ -17,8 +17,8 @@ limitations under the License. package util import ( - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/sets" ) @@ -27,7 +27,7 @@ import ( // according to the namespaces indicated in podAffinityTerm. // 1. If the namespaces is nil considers the given pod's namespace // 2. If the namespaces is empty list then considers all the namespaces -func getNamespacesFromPodAffinityTerm(pod *api.Pod, podAffinityTerm api.PodAffinityTerm) sets.String { +func getNamespacesFromPodAffinityTerm(pod *v1.Pod, podAffinityTerm v1.PodAffinityTerm) sets.String { names := sets.String{} if podAffinityTerm.Namespaces == nil { names.Insert(pod.Namespace) @@ -39,7 +39,7 @@ func getNamespacesFromPodAffinityTerm(pod *api.Pod, podAffinityTerm api.PodAffin // PodMatchesTermsNamespaceAndSelector returns true if the given // matches the namespace and selector defined by `s . -func PodMatchesTermsNamespaceAndSelector(pod *api.Pod, affinityPod *api.Pod, term *api.PodAffinityTerm) (bool, error) { +func PodMatchesTermsNamespaceAndSelector(pod *v1.Pod, affinityPod *v1.Pod, term *v1.PodAffinityTerm) (bool, error) { namespaces := getNamespacesFromPodAffinityTerm(affinityPod, *term) if len(namespaces) != 0 && !namespaces.Has(pod.Namespace) { return false, nil @@ -53,7 +53,7 @@ func PodMatchesTermsNamespaceAndSelector(pod *api.Pod, affinityPod *api.Pod, ter } // nodesHaveSameTopologyKeyInternal checks if nodeA and nodeB have same label value with given topologyKey as label key. -func nodesHaveSameTopologyKeyInternal(nodeA, nodeB *api.Node, topologyKey string) bool { +func nodesHaveSameTopologyKeyInternal(nodeA, nodeB *v1.Node, topologyKey string) bool { return nodeA.Labels != nil && nodeB.Labels != nil && len(nodeA.Labels[topologyKey]) > 0 && nodeA.Labels[topologyKey] == nodeB.Labels[topologyKey] } @@ -63,7 +63,7 @@ type Topologies struct { // NodesHaveSameTopologyKey checks if nodeA and nodeB have same label value with given topologyKey as label key. // If the topologyKey is nil/empty, check if the two nodes have any of the default topologyKeys, and have same corresponding label value. -func (tps *Topologies) NodesHaveSameTopologyKey(nodeA, nodeB *api.Node, topologyKey string) bool { +func (tps *Topologies) NodesHaveSameTopologyKey(nodeA, nodeB *v1.Node, topologyKey string) bool { if len(topologyKey) == 0 { // assumes this is allowed only for PreferredDuringScheduling pod anti-affinity (ensured by api/validation) for _, defaultKey := range tps.DefaultKeys { diff --git a/plugin/pkg/scheduler/algorithm/priorities/util/util.go b/plugin/pkg/scheduler/algorithm/priorities/util/util.go index 0547e0548c4..6f086b59a0d 100644 --- a/plugin/pkg/scheduler/algorithm/priorities/util/util.go +++ b/plugin/pkg/scheduler/algorithm/priorities/util/util.go @@ -16,11 +16,9 @@ limitations under the License. package util -import ( - "k8s.io/kubernetes/pkg/api" -) +import "k8s.io/kubernetes/pkg/api/v1" -func GetControllerRef(pod *api.Pod) *api.OwnerReference { +func GetControllerRef(pod *v1.Pod) *v1.OwnerReference { if len(pod.OwnerReferences) == 0 { return nil } diff --git a/plugin/pkg/scheduler/algorithm/scheduler_interface.go b/plugin/pkg/scheduler/algorithm/scheduler_interface.go index 9b4611e397e..761bce0985a 100644 --- a/plugin/pkg/scheduler/algorithm/scheduler_interface.go +++ b/plugin/pkg/scheduler/algorithm/scheduler_interface.go @@ -17,7 +17,7 @@ limitations under the License. package algorithm import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" ) @@ -28,16 +28,16 @@ type SchedulerExtender interface { // Filter based on extender-implemented predicate functions. The filtered list is // expected to be a subset of the supplied list. failedNodesMap optionally contains // the list of failed nodes and failure reasons. - Filter(pod *api.Pod, nodes []*api.Node) (filteredNodes []*api.Node, failedNodesMap schedulerapi.FailedNodesMap, err error) + Filter(pod *v1.Pod, nodes []*v1.Node) (filteredNodes []*v1.Node, failedNodesMap schedulerapi.FailedNodesMap, err error) // Prioritize based on extender-implemented priority functions. The returned scores & weight // are used to compute the weighted score for an extender. The weighted scores are added to // the scores computed by Kubernetes scheduler. The total scores are used to do the host selection. - Prioritize(pod *api.Pod, nodes []*api.Node) (hostPriorities *schedulerapi.HostPriorityList, weight int, err error) + Prioritize(pod *v1.Pod, nodes []*v1.Node) (hostPriorities *schedulerapi.HostPriorityList, weight int, err error) } // ScheduleAlgorithm is an interface implemented by things that know how to schedule pods // onto machines. type ScheduleAlgorithm interface { - Schedule(*api.Pod, NodeLister) (selectedMachine string, err error) + Schedule(*v1.Pod, NodeLister) (selectedMachine string, err error) } diff --git a/plugin/pkg/scheduler/algorithm/scheduler_interface_test.go b/plugin/pkg/scheduler/algorithm/scheduler_interface_test.go index fe9641c2913..d3940bee0d4 100755 --- a/plugin/pkg/scheduler/algorithm/scheduler_interface_test.go +++ b/plugin/pkg/scheduler/algorithm/scheduler_interface_test.go @@ -19,7 +19,7 @@ package algorithm import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" ) // Some functions used by multiple scheduler tests. @@ -31,7 +31,7 @@ type schedulerTester struct { } // Call if you know exactly where pod should get scheduled. -func (st *schedulerTester) expectSchedule(pod *api.Pod, expected string) { +func (st *schedulerTester) expectSchedule(pod *v1.Pod, expected string) { actual, err := st.scheduler.Schedule(pod, st.nodeLister) if err != nil { st.t.Errorf("Unexpected error %v\nTried to schedule: %#v", err, pod) @@ -43,7 +43,7 @@ func (st *schedulerTester) expectSchedule(pod *api.Pod, expected string) { } // Call if you can't predict where pod will be scheduled. -func (st *schedulerTester) expectSuccess(pod *api.Pod) { +func (st *schedulerTester) expectSuccess(pod *v1.Pod) { _, err := st.scheduler.Schedule(pod, st.nodeLister) if err != nil { st.t.Errorf("Unexpected error %v\nTried to schedule: %#v", err, pod) @@ -52,7 +52,7 @@ func (st *schedulerTester) expectSuccess(pod *api.Pod) { } // Call if pod should *not* schedule. -func (st *schedulerTester) expectFailure(pod *api.Pod) { +func (st *schedulerTester) expectFailure(pod *v1.Pod) { _, err := st.scheduler.Schedule(pod, st.nodeLister) if err == nil { st.t.Error("Unexpected non-error") diff --git a/plugin/pkg/scheduler/algorithm/types.go b/plugin/pkg/scheduler/algorithm/types.go index 99c29a5cad6..b889187f8b2 100644 --- a/plugin/pkg/scheduler/algorithm/types.go +++ b/plugin/pkg/scheduler/algorithm/types.go @@ -17,7 +17,7 @@ limitations under the License. package algorithm import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) @@ -25,25 +25,25 @@ import ( // FitPredicate is a function that indicates if a pod fits into an existing node. // The failure information is given by the error. // TODO: Change interface{} to a specific type. -type FitPredicate func(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []PredicateFailureReason, error) +type FitPredicate func(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []PredicateFailureReason, error) // PriorityMapFunction is a function that computes per-node results for a given node. // TODO: Figure out the exact API of this method. // TODO: Change interface{} to a specific type. -type PriorityMapFunction func(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) +type PriorityMapFunction func(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) // PriorityReduceFunction is a function that aggregated per-node results and computes // final scores for all nodes. // TODO: Figure out the exact API of this method. // TODO: Change interface{} to a specific type. -type PriorityReduceFunction func(pod *api.Pod, meta interface{}, nodeNameToInfo map[string]*schedulercache.NodeInfo, result schedulerapi.HostPriorityList) error +type PriorityReduceFunction func(pod *v1.Pod, meta interface{}, nodeNameToInfo map[string]*schedulercache.NodeInfo, result schedulerapi.HostPriorityList) error // MetdataProducer is a function that computes metadata for a given pod. -type MetadataProducer func(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo) interface{} +type MetadataProducer func(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo) interface{} // DEPRECATED // Use Map-Reduce pattern for priority functions. -type PriorityFunction func(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) +type PriorityFunction func(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*v1.Node) (schedulerapi.HostPriorityList, error) type PriorityConfig struct { Map PriorityMapFunction @@ -55,7 +55,7 @@ type PriorityConfig struct { } // EmptyMetadataProducer returns a no-op MetadataProducer type. -func EmptyMetadataProducer(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo) interface{} { +func EmptyMetadataProducer(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo) interface{} { return nil } @@ -63,4 +63,4 @@ type PredicateFailureReason interface { GetReason() string } -type GetEquivalencePodFunc func(pod *api.Pod) interface{} +type GetEquivalencePodFunc func(pod *v1.Pod) interface{} diff --git a/plugin/pkg/scheduler/algorithmprovider/defaults/BUILD b/plugin/pkg/scheduler/algorithmprovider/defaults/BUILD index c29fd8d7c4d..87e76c59b51 100644 --- a/plugin/pkg/scheduler/algorithmprovider/defaults/BUILD +++ b/plugin/pkg/scheduler/algorithmprovider/defaults/BUILD @@ -15,7 +15,7 @@ go_library( srcs = ["defaults.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/cloudprovider/providers/aws:go_default_library", "//pkg/util/sets:go_default_library", "//plugin/pkg/scheduler:go_default_library", @@ -33,9 +33,9 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/runtime:go_default_library", "//pkg/util/sets:go_default_library", diff --git a/plugin/pkg/scheduler/algorithmprovider/defaults/compatibility_test.go b/plugin/pkg/scheduler/algorithmprovider/defaults/compatibility_test.go index 7e3a4d64633..2a88f436c0e 100644 --- a/plugin/pkg/scheduler/algorithmprovider/defaults/compatibility_test.go +++ b/plugin/pkg/scheduler/algorithmprovider/defaults/compatibility_test.go @@ -23,9 +23,9 @@ import ( "net/http/httptest" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/sets" @@ -338,9 +338,9 @@ func TestCompatibility_v1_Scheduler(t *testing.T) { } server := httptest.NewServer(&handler) defer server.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) - if _, err := factory.NewConfigFactory(client, "some-scheduler-name", api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains).CreateFromConfig(policy); err != nil { + if _, err := factory.NewConfigFactory(client, "some-scheduler-name", v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains).CreateFromConfig(policy); err != nil { t.Errorf("%s: Error constructing: %v", v, err) continue } diff --git a/plugin/pkg/scheduler/algorithmprovider/defaults/defaults.go b/plugin/pkg/scheduler/algorithmprovider/defaults/defaults.go index 53fc9e6b4b2..f7ac0cf4021 100644 --- a/plugin/pkg/scheduler/algorithmprovider/defaults/defaults.go +++ b/plugin/pkg/scheduler/algorithmprovider/defaults/defaults.go @@ -21,7 +21,7 @@ import ( "os" "strconv" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/cloudprovider/providers/aws" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/plugin/pkg/scheduler" @@ -228,7 +228,7 @@ func copyAndReplace(set sets.String, replaceWhat, replaceWith string) sets.Strin } // GetEquivalencePod returns a EquivalencePod which contains a group of pod attributes which can be reused. -func GetEquivalencePod(pod *api.Pod) interface{} { +func GetEquivalencePod(pod *v1.Pod) interface{} { equivalencePod := EquivalencePod{} // For now we only consider pods: // 1. OwnerReferences is Controller @@ -260,5 +260,5 @@ func isValidControllerKind(kind string) bool { // EquivalencePod is a group of pod attributes which can be reused as equivalence to schedule other pods. type EquivalencePod struct { - ControllerRef api.OwnerReference + ControllerRef v1.OwnerReference } diff --git a/plugin/pkg/scheduler/api/BUILD b/plugin/pkg/scheduler/api/BUILD index 532f96fd6f5..8fc25950cf7 100644 --- a/plugin/pkg/scheduler/api/BUILD +++ b/plugin/pkg/scheduler/api/BUILD @@ -18,8 +18,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/runtime:go_default_library", ], diff --git a/plugin/pkg/scheduler/api/types.go b/plugin/pkg/scheduler/api/types.go index 9e83c7802fc..7c506fa7b14 100644 --- a/plugin/pkg/scheduler/api/types.go +++ b/plugin/pkg/scheduler/api/types.go @@ -19,8 +19,8 @@ package api import ( "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/restclient" ) @@ -134,9 +134,9 @@ type ExtenderConfig struct { // nodes for a pod. type ExtenderArgs struct { // Pod being scheduled - Pod api.Pod `json:"pod"` + Pod v1.Pod `json:"pod"` // List of candidate nodes where the pod can be scheduled - Nodes api.NodeList `json:"nodes"` + Nodes v1.NodeList `json:"nodes"` } // FailedNodesMap represents the filtered out nodes, with node names and failure messages @@ -145,7 +145,7 @@ type FailedNodesMap map[string]string // ExtenderFilterResult represents the results of a filter call to an extender type ExtenderFilterResult struct { // Filtered set of nodes where the pod can be scheduled - Nodes api.NodeList `json:"nodes,omitempty"` + Nodes v1.NodeList `json:"nodes,omitempty"` // Filtered out nodes where the pod can't be scheduled and the failure messages FailedNodes FailedNodesMap `json:"failedNodes,omitempty"` // Error message indicating failure diff --git a/plugin/pkg/scheduler/equivalence_cache.go b/plugin/pkg/scheduler/equivalence_cache.go index cd13b250aea..1770fb91834 100644 --- a/plugin/pkg/scheduler/equivalence_cache.go +++ b/plugin/pkg/scheduler/equivalence_cache.go @@ -17,13 +17,15 @@ limitations under the License. package scheduler import ( - "github.com/golang/groupcache/lru" "hash/adler32" - "k8s.io/kubernetes/pkg/api" + "github.com/golang/groupcache/lru" + + "sync" + + "k8s.io/kubernetes/pkg/api/v1" hashutil "k8s.io/kubernetes/pkg/util/hash" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" - "sync" ) // TODO(harryz) figure out the right number for this, 4096 may be too big @@ -68,7 +70,7 @@ func (ec *EquivalenceCache) addPodPredicate(podKey uint64, nodeName string, fit } // AddPodPredicatesCache cache pod predicate for equivalence class -func (ec *EquivalenceCache) AddPodPredicatesCache(pod *api.Pod, fitNodeList []*api.Node, failedPredicates *FailedPredicateMap) { +func (ec *EquivalenceCache) AddPodPredicatesCache(pod *v1.Pod, fitNodeList []*v1.Node, failedPredicates *FailedPredicateMap) { equivalenceHash := ec.hashEquivalencePod(pod) for _, fitNode := range fitNodeList { @@ -80,10 +82,10 @@ func (ec *EquivalenceCache) AddPodPredicatesCache(pod *api.Pod, fitNodeList []*a } // GetCachedPredicates gets cached predicates for equivalence class -func (ec *EquivalenceCache) GetCachedPredicates(pod *api.Pod, nodes []*api.Node) ([]*api.Node, FailedPredicateMap, []*api.Node) { - fitNodeList := []*api.Node{} +func (ec *EquivalenceCache) GetCachedPredicates(pod *v1.Pod, nodes []*v1.Node) ([]*v1.Node, FailedPredicateMap, []*v1.Node) { + fitNodeList := []*v1.Node{} failedPredicates := FailedPredicateMap{} - noCacheNodeList := []*api.Node{} + noCacheNodeList := []*v1.Node{} equivalenceHash := ec.hashEquivalencePod(pod) for _, node := range nodes { findCache := false @@ -124,7 +126,7 @@ func (ec *EquivalenceCache) SendClearAllCacheReq() { } // hashEquivalencePod returns the hash of equivalence pod. -func (ec *EquivalenceCache) hashEquivalencePod(pod *api.Pod) uint64 { +func (ec *EquivalenceCache) hashEquivalencePod(pod *v1.Pod) uint64 { equivalencePod := ec.getEquivalencePod(pod) hash := adler32.New() hashutil.DeepHashObject(hash, equivalencePod) diff --git a/plugin/pkg/scheduler/extender.go b/plugin/pkg/scheduler/extender.go index 846e6681bc3..fd01b7328da 100644 --- a/plugin/pkg/scheduler/extender.go +++ b/plugin/pkg/scheduler/extender.go @@ -24,7 +24,7 @@ import ( "net/http" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/restclient" utilnet "k8s.io/kubernetes/pkg/util/net" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" @@ -94,20 +94,20 @@ func NewHTTPExtender(config *schedulerapi.ExtenderConfig, apiVersion string) (al // Filter based on extender implemented predicate functions. The filtered list is // expected to be a subset of the supplied list. failedNodesMap optionally contains // the list of failed nodes and failure reasons. -func (h *HTTPExtender) Filter(pod *api.Pod, nodes []*api.Node) ([]*api.Node, schedulerapi.FailedNodesMap, error) { +func (h *HTTPExtender) Filter(pod *v1.Pod, nodes []*v1.Node) ([]*v1.Node, schedulerapi.FailedNodesMap, error) { var result schedulerapi.ExtenderFilterResult if h.filterVerb == "" { return nodes, schedulerapi.FailedNodesMap{}, nil } - nodeItems := make([]api.Node, 0, len(nodes)) + nodeItems := make([]v1.Node, 0, len(nodes)) for _, node := range nodes { nodeItems = append(nodeItems, *node) } args := schedulerapi.ExtenderArgs{ Pod: *pod, - Nodes: api.NodeList{Items: nodeItems}, + Nodes: v1.NodeList{Items: nodeItems}, } if err := h.send(h.filterVerb, &args, &result); err != nil { @@ -117,7 +117,7 @@ func (h *HTTPExtender) Filter(pod *api.Pod, nodes []*api.Node) ([]*api.Node, sch return nil, nil, fmt.Errorf(result.Error) } - nodeResult := make([]*api.Node, 0, len(result.Nodes.Items)) + nodeResult := make([]*v1.Node, 0, len(result.Nodes.Items)) for i := range result.Nodes.Items { nodeResult = append(nodeResult, &result.Nodes.Items[i]) } @@ -127,7 +127,7 @@ func (h *HTTPExtender) Filter(pod *api.Pod, nodes []*api.Node) ([]*api.Node, sch // Prioritize based on extender implemented priority functions. Weight*priority is added // up for each such priority function. The returned score is added to the score computed // by Kubernetes scheduler. The total score is used to do the host selection. -func (h *HTTPExtender) Prioritize(pod *api.Pod, nodes []*api.Node) (*schedulerapi.HostPriorityList, int, error) { +func (h *HTTPExtender) Prioritize(pod *v1.Pod, nodes []*v1.Node) (*schedulerapi.HostPriorityList, int, error) { var result schedulerapi.HostPriorityList if h.prioritizeVerb == "" { @@ -138,13 +138,13 @@ func (h *HTTPExtender) Prioritize(pod *api.Pod, nodes []*api.Node) (*schedulerap return &result, 0, nil } - nodeItems := make([]api.Node, 0, len(nodes)) + nodeItems := make([]v1.Node, 0, len(nodes)) for _, node := range nodes { nodeItems = append(nodeItems, *node) } args := schedulerapi.ExtenderArgs{ Pod: *pod, - Nodes: api.NodeList{Items: nodeItems}, + Nodes: v1.NodeList{Items: nodeItems}, } if err := h.send(h.prioritizeVerb, &args, &result); err != nil { diff --git a/plugin/pkg/scheduler/extender_test.go b/plugin/pkg/scheduler/extender_test.go index db82927c9f2..515d7635c9d 100644 --- a/plugin/pkg/scheduler/extender_test.go +++ b/plugin/pkg/scheduler/extender_test.go @@ -21,52 +21,52 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) -type fitPredicate func(pod *api.Pod, node *api.Node) (bool, error) -type priorityFunc func(pod *api.Pod, nodes []*api.Node) (*schedulerapi.HostPriorityList, error) +type fitPredicate func(pod *v1.Pod, node *v1.Node) (bool, error) +type priorityFunc func(pod *v1.Pod, nodes []*v1.Node) (*schedulerapi.HostPriorityList, error) type priorityConfig struct { function priorityFunc weight int } -func errorPredicateExtender(pod *api.Pod, node *api.Node) (bool, error) { +func errorPredicateExtender(pod *v1.Pod, node *v1.Node) (bool, error) { return false, fmt.Errorf("Some error") } -func falsePredicateExtender(pod *api.Pod, node *api.Node) (bool, error) { +func falsePredicateExtender(pod *v1.Pod, node *v1.Node) (bool, error) { return false, nil } -func truePredicateExtender(pod *api.Pod, node *api.Node) (bool, error) { +func truePredicateExtender(pod *v1.Pod, node *v1.Node) (bool, error) { return true, nil } -func machine1PredicateExtender(pod *api.Pod, node *api.Node) (bool, error) { +func machine1PredicateExtender(pod *v1.Pod, node *v1.Node) (bool, error) { if node.Name == "machine1" { return true, nil } return false, nil } -func machine2PredicateExtender(pod *api.Pod, node *api.Node) (bool, error) { +func machine2PredicateExtender(pod *v1.Pod, node *v1.Node) (bool, error) { if node.Name == "machine2" { return true, nil } return false, nil } -func errorPrioritizerExtender(pod *api.Pod, nodes []*api.Node) (*schedulerapi.HostPriorityList, error) { +func errorPrioritizerExtender(pod *v1.Pod, nodes []*v1.Node) (*schedulerapi.HostPriorityList, error) { return &schedulerapi.HostPriorityList{}, fmt.Errorf("Some error") } -func machine1PrioritizerExtender(pod *api.Pod, nodes []*api.Node) (*schedulerapi.HostPriorityList, error) { +func machine1PrioritizerExtender(pod *v1.Pod, nodes []*v1.Node) (*schedulerapi.HostPriorityList, error) { result := schedulerapi.HostPriorityList{} for _, node := range nodes { score := 1 @@ -78,7 +78,7 @@ func machine1PrioritizerExtender(pod *api.Pod, nodes []*api.Node) (*schedulerapi return &result, nil } -func machine2PrioritizerExtender(pod *api.Pod, nodes []*api.Node) (*schedulerapi.HostPriorityList, error) { +func machine2PrioritizerExtender(pod *v1.Pod, nodes []*v1.Node) (*schedulerapi.HostPriorityList, error) { result := schedulerapi.HostPriorityList{} for _, node := range nodes { score := 1 @@ -90,7 +90,7 @@ func machine2PrioritizerExtender(pod *api.Pod, nodes []*api.Node) (*schedulerapi return &result, nil } -func machine2Prioritizer(_ *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { +func machine2Prioritizer(_ *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*v1.Node) (schedulerapi.HostPriorityList, error) { result := []schedulerapi.HostPriority{} for _, node := range nodes { score := 1 @@ -108,15 +108,15 @@ type FakeExtender struct { weight int } -func (f *FakeExtender) Filter(pod *api.Pod, nodes []*api.Node) ([]*api.Node, schedulerapi.FailedNodesMap, error) { - filtered := []*api.Node{} +func (f *FakeExtender) Filter(pod *v1.Pod, nodes []*v1.Node) ([]*v1.Node, schedulerapi.FailedNodesMap, error) { + filtered := []*v1.Node{} failedNodesMap := schedulerapi.FailedNodesMap{} for _, node := range nodes { fits := true for _, predicate := range f.predicates { fit, err := predicate(pod, node) if err != nil { - return []*api.Node{}, schedulerapi.FailedNodesMap{}, err + return []*v1.Node{}, schedulerapi.FailedNodesMap{}, err } if !fit { fits = false @@ -132,7 +132,7 @@ func (f *FakeExtender) Filter(pod *api.Pod, nodes []*api.Node) ([]*api.Node, sch return filtered, failedNodesMap, nil } -func (f *FakeExtender) Prioritize(pod *api.Pod, nodes []*api.Node) (*schedulerapi.HostPriorityList, int, error) { +func (f *FakeExtender) Prioritize(pod *v1.Pod, nodes []*v1.Node) (*schedulerapi.HostPriorityList, int, error) { result := schedulerapi.HostPriorityList{} combinedScores := map[string]int{} for _, prioritizer := range f.prioritizers { @@ -164,8 +164,8 @@ func TestGenericSchedulerWithExtenders(t *testing.T) { extenderPredicates []fitPredicate extenderPrioritizers []priorityConfig nodes []string - pod *api.Pod - pods []*api.Pod + pod *v1.Pod + pods []*v1.Pod expectedHost string expectsErr bool }{ @@ -288,7 +288,7 @@ func TestGenericSchedulerWithExtenders(t *testing.T) { cache.AddPod(pod) } for _, name := range test.nodes { - cache.AddNode(&api.Node{ObjectMeta: api.ObjectMeta{Name: name}}) + cache.AddNode(&v1.Node{ObjectMeta: v1.ObjectMeta{Name: name}}) } scheduler := NewGenericScheduler( cache, test.predicates, algorithm.EmptyMetadataProducer, test.prioritizers, algorithm.EmptyMetadataProducer, extenders) diff --git a/plugin/pkg/scheduler/factory/BUILD b/plugin/pkg/scheduler/factory/BUILD index df497cb26ba..c7cfb5d950b 100644 --- a/plugin/pkg/scheduler/factory/BUILD +++ b/plugin/pkg/scheduler/factory/BUILD @@ -20,9 +20,10 @@ go_library( deps = [ "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/controller/informers:go_default_library", "//pkg/fields:go_default_library", "//pkg/types:go_default_library", @@ -49,12 +50,12 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/testapi:go_default_library", "//pkg/api/testing:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/runtime:go_default_library", "//pkg/types:go_default_library", diff --git a/plugin/pkg/scheduler/factory/factory.go b/plugin/pkg/scheduler/factory/factory.go index 23fd57f274f..d47434442ed 100644 --- a/plugin/pkg/scheduler/factory/factory.go +++ b/plugin/pkg/scheduler/factory/factory.go @@ -27,8 +27,9 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller/informers" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/types" @@ -42,7 +43,7 @@ import ( "k8s.io/kubernetes/plugin/pkg/scheduler/api/validation" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) @@ -110,7 +111,7 @@ func NewConfigFactory(client clientset.Interface, schedulerName string, hardPodA schedulerCache := schedulercache.New(30*time.Second, stopEverything) // TODO: pass this in as an argument... - informerFactory := informers.NewSharedInformerFactory(client, 0) + informerFactory := informers.NewSharedInformerFactory(client, nil, 0) pvcInformer := informerFactory.PersistentVolumeClaims() c := &ConfigFactory{ @@ -141,7 +142,7 @@ func NewConfigFactory(client clientset.Interface, schedulerName string, hardPodA // they may need to call. c.ScheduledPodLister.Indexer, c.scheduledPodPopulator = cache.NewIndexerInformer( c.createAssignedNonTerminatedPodLW(), - &api.Pod{}, + &v1.Pod{}, 0, cache.ResourceEventHandlerFuncs{ AddFunc: c.addPodToCache, @@ -153,7 +154,7 @@ func NewConfigFactory(client clientset.Interface, schedulerName string, hardPodA c.NodeLister.Store, c.nodePopulator = cache.NewInformer( c.createNodeLW(), - &api.Node{}, + &v1.Node{}, 0, cache.ResourceEventHandlerFuncs{ AddFunc: c.addNodeToCache, @@ -165,14 +166,14 @@ func NewConfigFactory(client clientset.Interface, schedulerName string, hardPodA // TODO(harryz) need to fill all the handlers here and below for equivalence cache c.PVLister.Store, c.pvPopulator = cache.NewInformer( c.createPersistentVolumeLW(), - &api.PersistentVolume{}, + &v1.PersistentVolume{}, 0, cache.ResourceEventHandlerFuncs{}, ) c.ServiceLister.Indexer, c.servicePopulator = cache.NewIndexerInformer( c.createServiceLW(), - &api.Service{}, + &v1.Service{}, 0, cache.ResourceEventHandlerFuncs{}, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, @@ -180,7 +181,7 @@ func NewConfigFactory(client clientset.Interface, schedulerName string, hardPodA c.ControllerLister.Indexer, c.controllerPopulator = cache.NewIndexerInformer( c.createControllerLW(), - &api.ReplicationController{}, + &v1.ReplicationController{}, 0, cache.ResourceEventHandlerFuncs{}, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, @@ -191,9 +192,9 @@ func NewConfigFactory(client clientset.Interface, schedulerName string, hardPodA // TODO(harryz) need to update all the handlers here and below for equivalence cache func (c *ConfigFactory) addPodToCache(obj interface{}) { - pod, ok := obj.(*api.Pod) + pod, ok := obj.(*v1.Pod) if !ok { - glog.Errorf("cannot convert to *api.Pod: %v", obj) + glog.Errorf("cannot convert to *v1.Pod: %v", obj) return } @@ -203,14 +204,14 @@ func (c *ConfigFactory) addPodToCache(obj interface{}) { } func (c *ConfigFactory) updatePodInCache(oldObj, newObj interface{}) { - oldPod, ok := oldObj.(*api.Pod) + oldPod, ok := oldObj.(*v1.Pod) if !ok { - glog.Errorf("cannot convert oldObj to *api.Pod: %v", oldObj) + glog.Errorf("cannot convert oldObj to *v1.Pod: %v", oldObj) return } - newPod, ok := newObj.(*api.Pod) + newPod, ok := newObj.(*v1.Pod) if !ok { - glog.Errorf("cannot convert newObj to *api.Pod: %v", newObj) + glog.Errorf("cannot convert newObj to *v1.Pod: %v", newObj) return } @@ -220,19 +221,19 @@ func (c *ConfigFactory) updatePodInCache(oldObj, newObj interface{}) { } func (c *ConfigFactory) deletePodFromCache(obj interface{}) { - var pod *api.Pod + var pod *v1.Pod switch t := obj.(type) { - case *api.Pod: + case *v1.Pod: pod = t case cache.DeletedFinalStateUnknown: var ok bool - pod, ok = t.Obj.(*api.Pod) + pod, ok = t.Obj.(*v1.Pod) if !ok { - glog.Errorf("cannot convert to *api.Pod: %v", t.Obj) + glog.Errorf("cannot convert to *v1.Pod: %v", t.Obj) return } default: - glog.Errorf("cannot convert to *api.Pod: %v", t) + glog.Errorf("cannot convert to *v1.Pod: %v", t) return } if err := c.schedulerCache.RemovePod(pod); err != nil { @@ -241,9 +242,9 @@ func (c *ConfigFactory) deletePodFromCache(obj interface{}) { } func (c *ConfigFactory) addNodeToCache(obj interface{}) { - node, ok := obj.(*api.Node) + node, ok := obj.(*v1.Node) if !ok { - glog.Errorf("cannot convert to *api.Node: %v", obj) + glog.Errorf("cannot convert to *v1.Node: %v", obj) return } @@ -253,14 +254,14 @@ func (c *ConfigFactory) addNodeToCache(obj interface{}) { } func (c *ConfigFactory) updateNodeInCache(oldObj, newObj interface{}) { - oldNode, ok := oldObj.(*api.Node) + oldNode, ok := oldObj.(*v1.Node) if !ok { - glog.Errorf("cannot convert oldObj to *api.Node: %v", oldObj) + glog.Errorf("cannot convert oldObj to *v1.Node: %v", oldObj) return } - newNode, ok := newObj.(*api.Node) + newNode, ok := newObj.(*v1.Node) if !ok { - glog.Errorf("cannot convert newObj to *api.Node: %v", newObj) + glog.Errorf("cannot convert newObj to *v1.Node: %v", newObj) return } @@ -270,19 +271,19 @@ func (c *ConfigFactory) updateNodeInCache(oldObj, newObj interface{}) { } func (c *ConfigFactory) deleteNodeFromCache(obj interface{}) { - var node *api.Node + var node *v1.Node switch t := obj.(type) { - case *api.Node: + case *v1.Node: node = t case cache.DeletedFinalStateUnknown: var ok bool - node, ok = t.Obj.(*api.Node) + node, ok = t.Obj.(*v1.Node) if !ok { - glog.Errorf("cannot convert to *api.Node: %v", t.Obj) + glog.Errorf("cannot convert to *v1.Node: %v", t.Obj) return } default: - glog.Errorf("cannot convert to *api.Node: %v", t) + glog.Errorf("cannot convert to *v1.Node: %v", t) return } if err := c.schedulerCache.RemoveNode(node); err != nil { @@ -386,7 +387,7 @@ func (f *ConfigFactory) CreateFromKeys(predicateKeys, priorityKeys sets.String, Algorithm: algo, Binder: &binder{f.Client}, PodConditionUpdater: &podConditionUpdater{f.Client}, - NextPod: func() *api.Pod { + NextPod: func() *v1.Pod { return f.getNextPod() }, Error: f.makeDefaultErrorFunc(&podBackoff, f.PodQueue), @@ -454,7 +455,7 @@ func (f *ConfigFactory) getPluginArgs() (*PluginFactoryArgs, error) { func (f *ConfigFactory) Run() { // Watch and queue pods that need scheduling. - cache.NewReflector(f.createUnassignedNonTerminatedPodLW(), &api.Pod{}, f.PodQueue, 0).RunUntil(f.StopEverything) + cache.NewReflector(f.createUnassignedNonTerminatedPodLW(), &v1.Pod{}, f.PodQueue, 0).RunUntil(f.StopEverything) // Begin populating scheduled pods. go f.scheduledPodPopulator.Run(f.StopEverything) @@ -481,9 +482,9 @@ func (f *ConfigFactory) Run() { cache.NewReflector(f.createReplicaSetLW(), &extensions.ReplicaSet{}, f.ReplicaSetLister.Indexer, 0).RunUntil(f.StopEverything) } -func (f *ConfigFactory) getNextPod() *api.Pod { +func (f *ConfigFactory) getNextPod() *v1.Pod { for { - pod := cache.Pop(f.PodQueue).(*api.Pod) + pod := cache.Pop(f.PodQueue).(*v1.Pod) if f.responsibleForPod(pod) { glog.V(4).Infof("About to try and schedule pod %v", pod.Name) return pod @@ -491,8 +492,8 @@ func (f *ConfigFactory) getNextPod() *api.Pod { } } -func (f *ConfigFactory) responsibleForPod(pod *api.Pod) bool { - if f.SchedulerName == api.DefaultSchedulerName { +func (f *ConfigFactory) responsibleForPod(pod *v1.Pod) bool { + if f.SchedulerName == v1.DefaultSchedulerName { return pod.Annotations[SchedulerAnnotationKey] == f.SchedulerName || pod.Annotations[SchedulerAnnotationKey] == "" } else { return pod.Annotations[SchedulerAnnotationKey] == f.SchedulerName @@ -500,20 +501,20 @@ func (f *ConfigFactory) responsibleForPod(pod *api.Pod) bool { } func getNodeConditionPredicate() cache.NodeConditionPredicate { - return func(node *api.Node) bool { + return func(node *v1.Node) bool { for i := range node.Status.Conditions { cond := &node.Status.Conditions[i] // We consider the node for scheduling only when its: // - NodeReady condition status is ConditionTrue, // - NodeOutOfDisk condition status is ConditionFalse, // - NodeNetworkUnavailable condition status is ConditionFalse. - if cond.Type == api.NodeReady && cond.Status != api.ConditionTrue { + if cond.Type == v1.NodeReady && cond.Status != v1.ConditionTrue { glog.V(4).Infof("Ignoring node %v with %v condition status %v", node.Name, cond.Type, cond.Status) return false - } else if cond.Type == api.NodeOutOfDisk && cond.Status != api.ConditionFalse { + } else if cond.Type == v1.NodeOutOfDisk && cond.Status != v1.ConditionFalse { glog.V(4).Infof("Ignoring node %v with %v condition status %v", node.Name, cond.Type, cond.Status) return false - } else if cond.Type == api.NodeNetworkUnavailable && cond.Status != api.ConditionFalse { + } else if cond.Type == v1.NodeNetworkUnavailable && cond.Status != v1.ConditionFalse { glog.V(4).Infof("Ignoring node %v with %v condition status %v", node.Name, cond.Type, cond.Status) return false } @@ -530,16 +531,16 @@ func getNodeConditionPredicate() cache.NodeConditionPredicate { // Returns a cache.ListWatch that finds all pods that need to be // scheduled. func (factory *ConfigFactory) createUnassignedNonTerminatedPodLW() *cache.ListWatch { - selector := fields.ParseSelectorOrDie("spec.nodeName==" + "" + ",status.phase!=" + string(api.PodSucceeded) + ",status.phase!=" + string(api.PodFailed)) - return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "pods", api.NamespaceAll, selector) + selector := fields.ParseSelectorOrDie("spec.nodeName==" + "" + ",status.phase!=" + string(v1.PodSucceeded) + ",status.phase!=" + string(v1.PodFailed)) + return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "pods", v1.NamespaceAll, selector) } // Returns a cache.ListWatch that finds all pods that are // already scheduled. // TODO: return a ListerWatcher interface instead? func (factory *ConfigFactory) createAssignedNonTerminatedPodLW() *cache.ListWatch { - selector := fields.ParseSelectorOrDie("spec.nodeName!=" + "" + ",status.phase!=" + string(api.PodSucceeded) + ",status.phase!=" + string(api.PodFailed)) - return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "pods", api.NamespaceAll, selector) + selector := fields.ParseSelectorOrDie("spec.nodeName!=" + "" + ",status.phase!=" + string(v1.PodSucceeded) + ",status.phase!=" + string(v1.PodFailed)) + return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "pods", v1.NamespaceAll, selector) } // createNodeLW returns a cache.ListWatch that gets all changes to nodes. @@ -547,36 +548,36 @@ func (factory *ConfigFactory) createNodeLW() *cache.ListWatch { // all nodes are considered to ensure that the scheduler cache has access to all nodes for lookups // the NodeCondition is used to filter out the nodes that are not ready or unschedulable // the filtered list is used as the super set of nodes to consider for scheduling - return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "nodes", api.NamespaceAll, fields.ParseSelectorOrDie("")) + return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "nodes", v1.NamespaceAll, fields.ParseSelectorOrDie("")) } // createPersistentVolumeLW returns a cache.ListWatch that gets all changes to persistentVolumes. func (factory *ConfigFactory) createPersistentVolumeLW() *cache.ListWatch { - return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "persistentVolumes", api.NamespaceAll, fields.ParseSelectorOrDie("")) + return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "persistentVolumes", v1.NamespaceAll, fields.ParseSelectorOrDie("")) } // createPersistentVolumeClaimLW returns a cache.ListWatch that gets all changes to persistentVolumeClaims. func (factory *ConfigFactory) createPersistentVolumeClaimLW() *cache.ListWatch { - return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "persistentVolumeClaims", api.NamespaceAll, fields.ParseSelectorOrDie("")) + return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "persistentVolumeClaims", v1.NamespaceAll, fields.ParseSelectorOrDie("")) } // Returns a cache.ListWatch that gets all changes to services. func (factory *ConfigFactory) createServiceLW() *cache.ListWatch { - return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "services", api.NamespaceAll, fields.ParseSelectorOrDie("")) + return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "services", v1.NamespaceAll, fields.ParseSelectorOrDie("")) } // Returns a cache.ListWatch that gets all changes to controllers. func (factory *ConfigFactory) createControllerLW() *cache.ListWatch { - return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "replicationControllers", api.NamespaceAll, fields.ParseSelectorOrDie("")) + return cache.NewListWatchFromClient(factory.Client.Core().RESTClient(), "replicationControllers", v1.NamespaceAll, fields.ParseSelectorOrDie("")) } // Returns a cache.ListWatch that gets all changes to replicasets. func (factory *ConfigFactory) createReplicaSetLW() *cache.ListWatch { - return cache.NewListWatchFromClient(factory.Client.Extensions().RESTClient(), "replicasets", api.NamespaceAll, fields.ParseSelectorOrDie("")) + return cache.NewListWatchFromClient(factory.Client.Extensions().RESTClient(), "replicasets", v1.NamespaceAll, fields.ParseSelectorOrDie("")) } -func (factory *ConfigFactory) makeDefaultErrorFunc(backoff *podBackoff, podQueue *cache.FIFO) func(pod *api.Pod, err error) { - return func(pod *api.Pod, err error) { +func (factory *ConfigFactory) makeDefaultErrorFunc(backoff *podBackoff, podQueue *cache.FIFO) func(pod *v1.Pod, err error) { + return func(pod *v1.Pod, err error) { if err == scheduler.ErrNoNodesAvailable { glog.V(4).Infof("Unable to schedule %v %v: no nodes are registered to the cluster; waiting", pod.Namespace, pod.Name) } else { @@ -621,9 +622,9 @@ func (factory *ConfigFactory) makeDefaultErrorFunc(backoff *podBackoff, podQueue } } -// nodeEnumerator allows a cache.Poller to enumerate items in an api.NodeList +// nodeEnumerator allows a cache.Poller to enumerate items in an v1.NodeList type nodeEnumerator struct { - *api.NodeList + *v1.NodeList } // Len returns the number of items in the node list. @@ -644,7 +645,7 @@ type binder struct { } // Bind just does a POST binding RPC. -func (b *binder) Bind(binding *api.Binding) error { +func (b *binder) Bind(binding *v1.Binding) error { glog.V(3).Infof("Attempting to bind %v to %v", binding.Name, binding.Target.Name) ctx := api.WithNamespace(api.NewContext(), binding.Namespace) return b.Client.Core().RESTClient().Post().Namespace(api.NamespaceValue(ctx)).Resource("bindings").Body(binding).Do().Error() @@ -656,9 +657,9 @@ type podConditionUpdater struct { Client clientset.Interface } -func (p *podConditionUpdater) Update(pod *api.Pod, condition *api.PodCondition) error { +func (p *podConditionUpdater) Update(pod *v1.Pod, condition *v1.PodCondition) error { glog.V(2).Infof("Updating pod condition for %s/%s to (%s==%s)", pod.Namespace, pod.Name, condition.Type, condition.Status) - if api.UpdatePodCondition(&pod.Status, condition) { + if v1.UpdatePodCondition(&pod.Status, condition) { _, err := p.Client.Core().Pods(pod.Namespace).UpdateStatus(pod) return err } diff --git a/plugin/pkg/scheduler/factory/factory_test.go b/plugin/pkg/scheduler/factory/factory_test.go index 02c35db7371..2a7271919fc 100644 --- a/plugin/pkg/scheduler/factory/factory_test.go +++ b/plugin/pkg/scheduler/factory/factory_test.go @@ -23,12 +23,12 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/testapi" apitesting "k8s.io/kubernetes/pkg/api/testing" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/types" @@ -47,8 +47,8 @@ func TestCreate(t *testing.T) { } server := httptest.NewServer(&handler) defer server.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) - factory := NewConfigFactory(client, api.DefaultSchedulerName, api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) + factory := NewConfigFactory(client, v1.DefaultSchedulerName, v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) factory.Create() } @@ -65,8 +65,8 @@ func TestCreateFromConfig(t *testing.T) { } server := httptest.NewServer(&handler) defer server.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) - factory := NewConfigFactory(client, api.DefaultSchedulerName, api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) + factory := NewConfigFactory(client, v1.DefaultSchedulerName, v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) // Pre-register some predicate and priority functions RegisterFitPredicate("PredicateOne", PredicateOne) @@ -106,8 +106,8 @@ func TestCreateFromEmptyConfig(t *testing.T) { } server := httptest.NewServer(&handler) defer server.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) - factory := NewConfigFactory(client, api.DefaultSchedulerName, api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) + factory := NewConfigFactory(client, v1.DefaultSchedulerName, v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) configData = []byte(`{}`) if err := runtime.DecodeInto(latestschedulerapi.Codec, configData, &policy); err != nil { @@ -117,26 +117,26 @@ func TestCreateFromEmptyConfig(t *testing.T) { factory.CreateFromConfig(policy) } -func PredicateOne(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func PredicateOne(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { return true, nil, nil } -func PredicateTwo(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func PredicateTwo(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { return true, nil, nil } -func PriorityOne(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { +func PriorityOne(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*v1.Node) (schedulerapi.HostPriorityList, error) { return []schedulerapi.HostPriority{}, nil } -func PriorityTwo(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { +func PriorityTwo(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*v1.Node) (schedulerapi.HostPriorityList, error) { return []schedulerapi.HostPriority{}, nil } func TestDefaultErrorFunc(t *testing.T) { - testPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"}, - Spec: apitesting.DeepEqualSafePodSpec(), + testPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: "bar"}, + Spec: apitesting.V1DeepEqualSafePodSpec(), } handler := utiltesting.FakeHandler{ StatusCode: 200, @@ -149,7 +149,7 @@ func TestDefaultErrorFunc(t *testing.T) { mux.Handle(testapi.Default.ResourcePath("pods", "bar", "foo"), &handler) server := httptest.NewServer(mux) defer server.Close() - factory := NewConfigFactory(clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}), api.DefaultSchedulerName, api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + factory := NewConfigFactory(clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}), v1.DefaultSchedulerName, v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) queue := cache.NewFIFO(cache.MetaNamespaceKeyFunc) podBackoff := podBackoff{ perPodBackoff: map[types.NamespacedName]*backoffEntry{}, @@ -178,11 +178,11 @@ func TestDefaultErrorFunc(t *testing.T) { } func TestNodeEnumerator(t *testing.T) { - testList := &api.NodeList{ - Items: []api.Node{ - {ObjectMeta: api.ObjectMeta{Name: "foo"}}, - {ObjectMeta: api.ObjectMeta{Name: "bar"}}, - {ObjectMeta: api.ObjectMeta{Name: "baz"}}, + testList := &v1.NodeList{ + Items: []v1.Node{ + {ObjectMeta: v1.ObjectMeta{Name: "foo"}}, + {ObjectMeta: v1.ObjectMeta{Name: "bar"}}, + {ObjectMeta: v1.ObjectMeta{Name: "baz"}}, }, } me := nodeEnumerator{testList} @@ -192,7 +192,7 @@ func TestNodeEnumerator(t *testing.T) { } for i := range testList.Items { gotObj := me.Get(i) - if e, a := testList.Items[i].Name, gotObj.(*api.Node).Name; e != a { + if e, a := testList.Items[i].Name, gotObj.(*v1.Node).Name; e != a { t.Errorf("Expected %v, got %v", e, a) } if e, a := &testList.Items[i], gotObj; !reflect.DeepEqual(e, a) { @@ -211,14 +211,14 @@ func (f *fakeClock) Now() time.Time { func TestBind(t *testing.T) { table := []struct { - binding *api.Binding + binding *v1.Binding }{ - {binding: &api.Binding{ - ObjectMeta: api.ObjectMeta{ - Namespace: api.NamespaceDefault, + {binding: &v1.Binding{ + ObjectMeta: v1.ObjectMeta{ + Namespace: v1.NamespaceDefault, Name: "foo", }, - Target: api.ObjectReference{ + Target: v1.ObjectReference{ Name: "foohost.kubernetes.mydomain.com", }, }}, @@ -232,7 +232,7 @@ func TestBind(t *testing.T) { } server := httptest.NewServer(&handler) defer server.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) b := binder{client} if err := b.Bind(item.binding); err != nil { @@ -240,7 +240,7 @@ func TestBind(t *testing.T) { continue } expectedBody := runtime.EncodeOrDie(testapi.Default.Codec(), item.binding) - handler.ValidateRequest(t, testapi.Default.ResourcePath("bindings", api.NamespaceDefault, ""), "POST", &expectedBody) + handler.ValidateRequest(t, testapi.Default.ResourcePath("bindings", v1.NamespaceDefault, ""), "POST", &expectedBody) } } @@ -317,45 +317,45 @@ func TestResponsibleForPod(t *testing.T) { } server := httptest.NewServer(&handler) defer server.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) // factory of "default-scheduler" - factoryDefaultScheduler := NewConfigFactory(client, api.DefaultSchedulerName, api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + factoryDefaultScheduler := NewConfigFactory(client, v1.DefaultSchedulerName, v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) // factory of "foo-scheduler" - factoryFooScheduler := NewConfigFactory(client, "foo-scheduler", api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + factoryFooScheduler := NewConfigFactory(client, "foo-scheduler", v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) // scheduler annotations to be tested schedulerAnnotationFitsDefault := map[string]string{"scheduler.alpha.kubernetes.io/name": "default-scheduler"} schedulerAnnotationFitsFoo := map[string]string{"scheduler.alpha.kubernetes.io/name": "foo-scheduler"} schedulerAnnotationFitsNone := map[string]string{"scheduler.alpha.kubernetes.io/name": "bar-scheduler"} tests := []struct { - pod *api.Pod + pod *v1.Pod pickedByDefault bool pickedByFoo bool }{ { // pod with no annotation "scheduler.alpha.kubernetes.io/name=" should be // picked by the default scheduler, NOT by the one of name "foo-scheduler" - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: "bar"}}, pickedByDefault: true, pickedByFoo: false, }, { // pod with annotation "scheduler.alpha.kubernetes.io/name=default-scheduler" should be picked // by the scheduler of name "default-scheduler", NOT by the one of name "foo-scheduler" - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar", Annotations: schedulerAnnotationFitsDefault}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: "bar", Annotations: schedulerAnnotationFitsDefault}}, pickedByDefault: true, pickedByFoo: false, }, { // pod with annotataion "scheduler.alpha.kubernetes.io/name=foo-scheduler" should be NOT // be picked by the scheduler of name "default-scheduler", but by the one of name "foo-scheduler" - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar", Annotations: schedulerAnnotationFitsFoo}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: "bar", Annotations: schedulerAnnotationFitsFoo}}, pickedByDefault: false, pickedByFoo: true, }, { // pod with annotataion "scheduler.alpha.kubernetes.io/name=foo-scheduler" should be NOT // be picked by niether the scheduler of name "default-scheduler" nor the one of name "foo-scheduler" - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar", Annotations: schedulerAnnotationFitsNone}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo", Namespace: "bar", Annotations: schedulerAnnotationFitsNone}}, pickedByDefault: false, pickedByFoo: false, }, @@ -381,9 +381,9 @@ func TestInvalidHardPodAffinitySymmetricWeight(t *testing.T) { server := httptest.NewServer(&handler) // TODO: Uncomment when fix #19254 // defer server.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) // factory of "default-scheduler" - factory := NewConfigFactory(client, api.DefaultSchedulerName, -1, api.DefaultFailureDomains) + factory := NewConfigFactory(client, v1.DefaultSchedulerName, -1, v1.DefaultFailureDomains) _, err := factory.Create() if err == nil { t.Errorf("expected err: invalid hardPodAffinitySymmetricWeight, got nothing") @@ -398,7 +398,7 @@ func TestInvalidFactoryArgs(t *testing.T) { } server := httptest.NewServer(&handler) defer server.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) testCases := []struct { hardPodAffinitySymmetricWeight int @@ -407,12 +407,12 @@ func TestInvalidFactoryArgs(t *testing.T) { }{ { hardPodAffinitySymmetricWeight: -1, - failureDomains: api.DefaultFailureDomains, + failureDomains: v1.DefaultFailureDomains, expectErr: "invalid hardPodAffinitySymmetricWeight: -1, must be in the range 0-100", }, { hardPodAffinitySymmetricWeight: 101, - failureDomains: api.DefaultFailureDomains, + failureDomains: v1.DefaultFailureDomains, expectErr: "invalid hardPodAffinitySymmetricWeight: 101, must be in the range 0-100", }, { @@ -423,7 +423,7 @@ func TestInvalidFactoryArgs(t *testing.T) { } for _, test := range testCases { - factory := NewConfigFactory(client, api.DefaultSchedulerName, test.hardPodAffinitySymmetricWeight, test.failureDomains) + factory := NewConfigFactory(client, v1.DefaultSchedulerName, test.hardPodAffinitySymmetricWeight, test.failureDomains) _, err := factory.Create() if err == nil { t.Errorf("expected err: %s, got nothing", test.expectErr) @@ -434,32 +434,32 @@ func TestInvalidFactoryArgs(t *testing.T) { func TestNodeConditionPredicate(t *testing.T) { nodeFunc := getNodeConditionPredicate() - nodeList := &api.NodeList{ - Items: []api.Node{ + nodeList := &v1.NodeList{ + Items: []v1.Node{ // node1 considered - {ObjectMeta: api.ObjectMeta{Name: "node1"}, Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeReady, Status: api.ConditionTrue}}}}, + {ObjectMeta: v1.ObjectMeta{Name: "node1"}, Status: v1.NodeStatus{Conditions: []v1.NodeCondition{{Type: v1.NodeReady, Status: v1.ConditionTrue}}}}, // node2 ignored - node not Ready - {ObjectMeta: api.ObjectMeta{Name: "node2"}, Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeReady, Status: api.ConditionFalse}}}}, + {ObjectMeta: v1.ObjectMeta{Name: "node2"}, Status: v1.NodeStatus{Conditions: []v1.NodeCondition{{Type: v1.NodeReady, Status: v1.ConditionFalse}}}}, // node3 ignored - node out of disk - {ObjectMeta: api.ObjectMeta{Name: "node3"}, Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeOutOfDisk, Status: api.ConditionTrue}}}}, + {ObjectMeta: v1.ObjectMeta{Name: "node3"}, Status: v1.NodeStatus{Conditions: []v1.NodeCondition{{Type: v1.NodeOutOfDisk, Status: v1.ConditionTrue}}}}, // node4 considered - {ObjectMeta: api.ObjectMeta{Name: "node4"}, Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeOutOfDisk, Status: api.ConditionFalse}}}}, + {ObjectMeta: v1.ObjectMeta{Name: "node4"}, Status: v1.NodeStatus{Conditions: []v1.NodeCondition{{Type: v1.NodeOutOfDisk, Status: v1.ConditionFalse}}}}, // node5 ignored - node out of disk - {ObjectMeta: api.ObjectMeta{Name: "node5"}, Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeReady, Status: api.ConditionTrue}, {Type: api.NodeOutOfDisk, Status: api.ConditionTrue}}}}, + {ObjectMeta: v1.ObjectMeta{Name: "node5"}, Status: v1.NodeStatus{Conditions: []v1.NodeCondition{{Type: v1.NodeReady, Status: v1.ConditionTrue}, {Type: v1.NodeOutOfDisk, Status: v1.ConditionTrue}}}}, // node6 considered - {ObjectMeta: api.ObjectMeta{Name: "node6"}, Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeReady, Status: api.ConditionTrue}, {Type: api.NodeOutOfDisk, Status: api.ConditionFalse}}}}, + {ObjectMeta: v1.ObjectMeta{Name: "node6"}, Status: v1.NodeStatus{Conditions: []v1.NodeCondition{{Type: v1.NodeReady, Status: v1.ConditionTrue}, {Type: v1.NodeOutOfDisk, Status: v1.ConditionFalse}}}}, // node7 ignored - node out of disk, node not Ready - {ObjectMeta: api.ObjectMeta{Name: "node7"}, Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeReady, Status: api.ConditionFalse}, {Type: api.NodeOutOfDisk, Status: api.ConditionTrue}}}}, + {ObjectMeta: v1.ObjectMeta{Name: "node7"}, Status: v1.NodeStatus{Conditions: []v1.NodeCondition{{Type: v1.NodeReady, Status: v1.ConditionFalse}, {Type: v1.NodeOutOfDisk, Status: v1.ConditionTrue}}}}, // node8 ignored - node not Ready - {ObjectMeta: api.ObjectMeta{Name: "node8"}, Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeReady, Status: api.ConditionFalse}, {Type: api.NodeOutOfDisk, Status: api.ConditionFalse}}}}, + {ObjectMeta: v1.ObjectMeta{Name: "node8"}, Status: v1.NodeStatus{Conditions: []v1.NodeCondition{{Type: v1.NodeReady, Status: v1.ConditionFalse}, {Type: v1.NodeOutOfDisk, Status: v1.ConditionFalse}}}}, // node9 ignored - node unschedulable - {ObjectMeta: api.ObjectMeta{Name: "node9"}, Spec: api.NodeSpec{Unschedulable: true}}, + {ObjectMeta: v1.ObjectMeta{Name: "node9"}, Spec: v1.NodeSpec{Unschedulable: true}}, // node10 considered - {ObjectMeta: api.ObjectMeta{Name: "node10"}, Spec: api.NodeSpec{Unschedulable: false}}, + {ObjectMeta: v1.ObjectMeta{Name: "node10"}, Spec: v1.NodeSpec{Unschedulable: false}}, // node11 considered - {ObjectMeta: api.ObjectMeta{Name: "node11"}}, + {ObjectMeta: v1.ObjectMeta{Name: "node11"}}, }, } diff --git a/plugin/pkg/scheduler/generic_scheduler.go b/plugin/pkg/scheduler/generic_scheduler.go index 3cd648a8cde..dcfc467077f 100644 --- a/plugin/pkg/scheduler/generic_scheduler.go +++ b/plugin/pkg/scheduler/generic_scheduler.go @@ -26,7 +26,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/workqueue" @@ -39,7 +39,7 @@ import ( type FailedPredicateMap map[string][]algorithm.PredicateFailureReason type FitError struct { - Pod *api.Pod + Pod *v1.Pod FailedPredicates FailedPredicateMap } @@ -89,7 +89,7 @@ type genericScheduler struct { // Schedule tries to schedule the given pod to one of node in the node list. // If it succeeds, it will return the name of the node. // If it fails, it will return a Fiterror error with reasons. -func (g *genericScheduler) Schedule(pod *api.Pod, nodeLister algorithm.NodeLister) (string, error) { +func (g *genericScheduler) Schedule(pod *v1.Pod, nodeLister algorithm.NodeLister) (string, error) { var trace *util.Trace if pod != nil { trace = util.NewTrace(fmt.Sprintf("Scheduling %s/%s", pod.Namespace, pod.Name)) @@ -160,14 +160,14 @@ func (g *genericScheduler) selectHost(priorityList schedulerapi.HostPriorityList // Filters the nodes to find the ones that fit based on the given predicate functions // Each node is passed through the predicate functions to determine if it is a fit func findNodesThatFit( - pod *api.Pod, + pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, - nodes []*api.Node, + nodes []*v1.Node, predicateFuncs map[string]algorithm.FitPredicate, extenders []algorithm.SchedulerExtender, metadataProducer algorithm.MetadataProducer, -) ([]*api.Node, FailedPredicateMap, error) { - var filtered []*api.Node +) ([]*v1.Node, FailedPredicateMap, error) { + var filtered []*v1.Node failedPredicateMap := FailedPredicateMap{} if len(predicateFuncs) == 0 { @@ -175,7 +175,7 @@ func findNodesThatFit( } else { // Create filtered list with enough space to avoid growing it // and allow assigning. - filtered = make([]*api.Node, len(nodes)) + filtered = make([]*v1.Node, len(nodes)) errs := []error{} var predicateResultLock sync.Mutex var filteredLen int32 @@ -202,7 +202,7 @@ func findNodesThatFit( workqueue.Parallelize(16, len(nodes), checkNode) filtered = filtered[:filteredLen] if len(errs) > 0 { - return []*api.Node{}, FailedPredicateMap{}, errors.NewAggregate(errs) + return []*v1.Node{}, FailedPredicateMap{}, errors.NewAggregate(errs) } } @@ -210,7 +210,7 @@ func findNodesThatFit( for _, extender := range extenders { filteredList, failedMap, err := extender.Filter(pod, filtered) if err != nil { - return []*api.Node{}, FailedPredicateMap{}, err + return []*v1.Node{}, FailedPredicateMap{}, err } for failedNodeName, failedMsg := range failedMap { @@ -229,7 +229,7 @@ func findNodesThatFit( } // Checks whether node with a given name and NodeInfo satisfies all predicateFuncs. -func podFitsOnNode(pod *api.Pod, meta interface{}, info *schedulercache.NodeInfo, predicateFuncs map[string]algorithm.FitPredicate) (bool, []algorithm.PredicateFailureReason, error) { +func podFitsOnNode(pod *v1.Pod, meta interface{}, info *schedulercache.NodeInfo, predicateFuncs map[string]algorithm.FitPredicate) (bool, []algorithm.PredicateFailureReason, error) { var failedPredicates []algorithm.PredicateFailureReason for _, predicate := range predicateFuncs { fit, reasons, err := predicate(pod, meta, info) @@ -251,11 +251,11 @@ func podFitsOnNode(pod *api.Pod, meta interface{}, info *schedulercache.NodeInfo // The node scores returned by the priority function are multiplied by the weights to get weighted scores // All scores are finally combined (added) to get the total weighted scores of all nodes func PrioritizeNodes( - pod *api.Pod, + pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, meta interface{}, priorityConfigs []algorithm.PriorityConfig, - nodes []*api.Node, + nodes []*v1.Node, extenders []algorithm.SchedulerExtender, ) (schedulerapi.HostPriorityList, error) { // If no priority configs are provided, then the EqualPriority function is applied @@ -381,7 +381,7 @@ func PrioritizeNodes( } // EqualPriority is a prioritizer function that gives an equal weight of one to all nodes -func EqualPriorityMap(_ *api.Pod, _ interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { +func EqualPriorityMap(_ *v1.Pod, _ interface{}, nodeInfo *schedulercache.NodeInfo) (schedulerapi.HostPriority, error) { node := nodeInfo.Node() if node == nil { return schedulerapi.HostPriority{}, fmt.Errorf("node not found") diff --git a/plugin/pkg/scheduler/generic_scheduler_test.go b/plugin/pkg/scheduler/generic_scheduler_test.go index 52b4aa95b1c..c7972c359ac 100644 --- a/plugin/pkg/scheduler/generic_scheduler_test.go +++ b/plugin/pkg/scheduler/generic_scheduler_test.go @@ -24,9 +24,9 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" @@ -37,15 +37,15 @@ import ( "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) -func falsePredicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func falsePredicate(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { return false, []algorithm.PredicateFailureReason{algorithmpredicates.ErrFakePredicate}, nil } -func truePredicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func truePredicate(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { return true, nil, nil } -func matchesPredicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func matchesPredicate(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { node := nodeInfo.Node() if node == nil { return false, nil, fmt.Errorf("node not found") @@ -56,14 +56,14 @@ func matchesPredicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.N return false, []algorithm.PredicateFailureReason{algorithmpredicates.ErrFakePredicate}, nil } -func hasNoPodsPredicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { +func hasNoPodsPredicate(pod *v1.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason, error) { if len(nodeInfo.Pods()) == 0 { return true, nil, nil } return false, []algorithm.PredicateFailureReason{algorithmpredicates.ErrFakePredicate}, nil } -func numericPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { +func numericPriority(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*v1.Node) (schedulerapi.HostPriorityList, error) { result := []schedulerapi.HostPriority{} for _, node := range nodes { score, err := strconv.Atoi(node.Name) @@ -78,7 +78,7 @@ func numericPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.Nod return result, nil } -func reverseNumericPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { +func reverseNumericPriority(pod *v1.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*v1.Node) (schedulerapi.HostPriorityList, error) { var maxScore float64 minScore := math.MaxFloat64 reverseResult := []schedulerapi.HostPriority{} @@ -101,10 +101,10 @@ func reverseNumericPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulerca return reverseResult, nil } -func makeNodeList(nodeNames []string) []*api.Node { - result := make([]*api.Node, 0, len(nodeNames)) +func makeNodeList(nodeNames []string) []*v1.Node { + result := make([]*v1.Node, 0, len(nodeNames)) for _, nodeName := range nodeNames { - result = append(result, &api.Node{ObjectMeta: api.ObjectMeta{Name: nodeName}}) + result = append(result, &v1.Node{ObjectMeta: v1.ObjectMeta{Name: nodeName}}) } return result } @@ -181,8 +181,8 @@ func TestGenericScheduler(t *testing.T) { predicates map[string]algorithm.FitPredicate prioritizers []algorithm.PriorityConfig nodes []string - pod *api.Pod - pods []*api.Pod + pod *v1.Pod + pods []*v1.Pod expectedHosts sets.String expectsErr bool wErr error @@ -192,10 +192,10 @@ func TestGenericScheduler(t *testing.T) { prioritizers: []algorithm.PriorityConfig{{Map: EqualPriorityMap, Weight: 1}}, nodes: []string{"machine1", "machine2"}, expectsErr: true, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "2"}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "2"}}, name: "test 1", wErr: &FitError{ - Pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "2"}}, + Pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "2"}}, FailedPredicates: FailedPredicateMap{ "machine1": []algorithm.PredicateFailureReason{algorithmpredicates.ErrFakePredicate}, "machine2": []algorithm.PredicateFailureReason{algorithmpredicates.ErrFakePredicate}, @@ -214,7 +214,7 @@ func TestGenericScheduler(t *testing.T) { predicates: map[string]algorithm.FitPredicate{"matches": matchesPredicate}, prioritizers: []algorithm.PriorityConfig{{Map: EqualPriorityMap, Weight: 1}}, nodes: []string{"machine1", "machine2"}, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "machine2"}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "machine2"}}, expectedHosts: sets.NewString("machine2"), name: "test 3", wErr: nil, @@ -231,7 +231,7 @@ func TestGenericScheduler(t *testing.T) { predicates: map[string]algorithm.FitPredicate{"matches": matchesPredicate}, prioritizers: []algorithm.PriorityConfig{{Function: numericPriority, Weight: 1}}, nodes: []string{"3", "2", "1"}, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "2"}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "2"}}, expectedHosts: sets.NewString("2"), name: "test 5", wErr: nil, @@ -240,7 +240,7 @@ func TestGenericScheduler(t *testing.T) { predicates: map[string]algorithm.FitPredicate{"true": truePredicate}, prioritizers: []algorithm.PriorityConfig{{Function: numericPriority, Weight: 1}, {Function: reverseNumericPriority, Weight: 2}}, nodes: []string{"3", "2", "1"}, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "2"}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "2"}}, expectedHosts: sets.NewString("1"), name: "test 6", wErr: nil, @@ -249,11 +249,11 @@ func TestGenericScheduler(t *testing.T) { predicates: map[string]algorithm.FitPredicate{"true": truePredicate, "false": falsePredicate}, prioritizers: []algorithm.PriorityConfig{{Function: numericPriority, Weight: 1}}, nodes: []string{"3", "2", "1"}, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "2"}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "2"}}, expectsErr: true, name: "test 7", wErr: &FitError{ - Pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "2"}}, + Pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "2"}}, FailedPredicates: FailedPredicateMap{ "3": []algorithm.PredicateFailureReason{algorithmpredicates.ErrFakePredicate}, "2": []algorithm.PredicateFailureReason{algorithmpredicates.ErrFakePredicate}, @@ -266,24 +266,24 @@ func TestGenericScheduler(t *testing.T) { "nopods": hasNoPodsPredicate, "matches": matchesPredicate, }, - pods: []*api.Pod{ + pods: []*v1.Pod{ { - ObjectMeta: api.ObjectMeta{Name: "2"}, - Spec: api.PodSpec{ + ObjectMeta: v1.ObjectMeta{Name: "2"}, + Spec: v1.PodSpec{ NodeName: "2", }, - Status: api.PodStatus{ - Phase: api.PodRunning, + Status: v1.PodStatus{ + Phase: v1.PodRunning, }, }, }, - pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "2"}}, + pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "2"}}, prioritizers: []algorithm.PriorityConfig{{Function: numericPriority, Weight: 1}}, nodes: []string{"1", "2"}, expectsErr: true, name: "test 8", wErr: &FitError{ - Pod: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "2"}}, + Pod: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "2"}}, FailedPredicates: FailedPredicateMap{ "1": []algorithm.PredicateFailureReason{algorithmpredicates.ErrFakePredicate}, "2": []algorithm.PredicateFailureReason{algorithmpredicates.ErrFakePredicate}, @@ -297,7 +297,7 @@ func TestGenericScheduler(t *testing.T) { cache.AddPod(pod) } for _, name := range test.nodes { - cache.AddNode(&api.Node{ObjectMeta: api.ObjectMeta{Name: name}}) + cache.AddNode(&v1.Node{ObjectMeta: v1.ObjectMeta{Name: name}}) } scheduler := NewGenericScheduler( @@ -322,7 +322,7 @@ func TestFindFitAllError(t *testing.T) { "2": schedulercache.NewNodeInfo(), "1": schedulercache.NewNodeInfo(), } - _, predicateMap, err := findNodesThatFit(&api.Pod{}, nodeNameToInfo, makeNodeList(nodes), predicates, nil, algorithm.EmptyMetadataProducer) + _, predicateMap, err := findNodesThatFit(&v1.Pod{}, nodeNameToInfo, makeNodeList(nodes), predicates, nil, algorithm.EmptyMetadataProducer) if err != nil { t.Errorf("unexpected error: %v", err) @@ -346,14 +346,14 @@ func TestFindFitAllError(t *testing.T) { func TestFindFitSomeError(t *testing.T) { nodes := []string{"3", "2", "1"} predicates := map[string]algorithm.FitPredicate{"true": truePredicate, "match": matchesPredicate} - pod := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "1"}} + pod := &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "1"}} nodeNameToInfo := map[string]*schedulercache.NodeInfo{ "3": schedulercache.NewNodeInfo(), "2": schedulercache.NewNodeInfo(), "1": schedulercache.NewNodeInfo(pod), } for name := range nodeNameToInfo { - nodeNameToInfo[name].SetNode(&api.Node{ObjectMeta: api.ObjectMeta{Name: name}}) + nodeNameToInfo[name].SetNode(&v1.Node{ObjectMeta: v1.ObjectMeta{Name: name}}) } _, predicateMap, err := findNodesThatFit(pod, nodeNameToInfo, makeNodeList(nodes), predicates, nil, algorithm.EmptyMetadataProducer) @@ -379,15 +379,15 @@ func TestFindFitSomeError(t *testing.T) { } } -func makeNode(node string, milliCPU, memory int64) *api.Node { - return &api.Node{ - ObjectMeta: api.ObjectMeta{Name: node}, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ +func makeNode(node string, milliCPU, memory int64) *v1.Node { + return &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: node}, + Status: v1.NodeStatus{ + Capacity: v1.ResourceList{ "cpu": *resource.NewMilliQuantity(milliCPU, resource.DecimalSI), "memory": *resource.NewQuantity(memory, resource.BinarySI), }, - Allocatable: api.ResourceList{ + Allocatable: v1.ResourceList{ "cpu": *resource.NewMilliQuantity(milliCPU, resource.DecimalSI), "memory": *resource.NewQuantity(memory, resource.BinarySI), }, @@ -402,19 +402,19 @@ func makeNode(node string, milliCPU, memory int64) *api.Node { // - don't get the same score no matter what we schedule. func TestZeroRequest(t *testing.T) { // A pod with no resources. We expect spreading to count it as having the default resources. - noResources := api.PodSpec{ - Containers: []api.Container{ + noResources := v1.PodSpec{ + Containers: []v1.Container{ {}, }, } noResources1 := noResources noResources1.NodeName = "machine1" // A pod with the same resources as a 0-request pod gets by default as its resources (for spreading). - small := api.PodSpec{ - Containers: []api.Container{ + small := v1.PodSpec{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse( strconv.FormatInt(priorityutil.DefaultMilliCpuRequest, 10) + "m"), "memory": resource.MustParse( @@ -427,11 +427,11 @@ func TestZeroRequest(t *testing.T) { small2 := small small2.NodeName = "machine2" // A larger pod. - large := api.PodSpec{ - Containers: []api.Container{ + large := v1.PodSpec{ + Containers: []v1.Container{ { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse( strconv.FormatInt(priorityutil.DefaultMilliCpuRequest*3, 10) + "m"), "memory": resource.MustParse( @@ -446,38 +446,38 @@ func TestZeroRequest(t *testing.T) { large2 := large large2.NodeName = "machine2" tests := []struct { - pod *api.Pod - pods []*api.Pod - nodes []*api.Node + pod *v1.Pod + pods []*v1.Pod + nodes []*v1.Node test string }{ // The point of these next two tests is to show you get the same priority for a zero-request pod // as for a pod with the defaults requests, both when the zero-request pod is already on the machine // and when the zero-request pod is the one being scheduled. { - pod: &api.Pod{Spec: noResources}, - nodes: []*api.Node{makeNode("machine1", 1000, priorityutil.DefaultMemoryRequest*10), makeNode("machine2", 1000, priorityutil.DefaultMemoryRequest*10)}, + pod: &v1.Pod{Spec: noResources}, + nodes: []*v1.Node{makeNode("machine1", 1000, priorityutil.DefaultMemoryRequest*10), makeNode("machine2", 1000, priorityutil.DefaultMemoryRequest*10)}, test: "test priority of zero-request pod with machine with zero-request pod", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: large1}, {Spec: noResources1}, {Spec: large2}, {Spec: small2}, }, }, { - pod: &api.Pod{Spec: small}, - nodes: []*api.Node{makeNode("machine1", 1000, priorityutil.DefaultMemoryRequest*10), makeNode("machine2", 1000, priorityutil.DefaultMemoryRequest*10)}, + pod: &v1.Pod{Spec: small}, + nodes: []*v1.Node{makeNode("machine1", 1000, priorityutil.DefaultMemoryRequest*10), makeNode("machine2", 1000, priorityutil.DefaultMemoryRequest*10)}, test: "test priority of nonzero-request pod with machine with zero-request pod", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: large1}, {Spec: noResources1}, {Spec: large2}, {Spec: small2}, }, }, // The point of this test is to verify that we're not just getting the same score no matter what we schedule. { - pod: &api.Pod{Spec: large}, - nodes: []*api.Node{makeNode("machine1", 1000, priorityutil.DefaultMemoryRequest*10), makeNode("machine2", 1000, priorityutil.DefaultMemoryRequest*10)}, + pod: &v1.Pod{Spec: large}, + nodes: []*v1.Node{makeNode("machine1", 1000, priorityutil.DefaultMemoryRequest*10), makeNode("machine2", 1000, priorityutil.DefaultMemoryRequest*10)}, test: "test priority of larger pod with machine with zero-request pod", - pods: []*api.Pod{ + pods: []*v1.Pod{ {Spec: large1}, {Spec: noResources1}, {Spec: large2}, {Spec: small2}, }, @@ -494,8 +494,8 @@ func TestZeroRequest(t *testing.T) { {Map: algorithmpriorities.BalancedResourceAllocationMap, Weight: 1}, { Function: algorithmpriorities.NewSelectorSpreadPriority( - algorithm.FakeServiceLister([]*api.Service{}), - algorithm.FakeControllerLister([]*api.ReplicationController{}), + algorithm.FakeServiceLister([]*v1.Service{}), + algorithm.FakeControllerLister([]*v1.ReplicationController{}), algorithm.FakeReplicaSetLister([]*extensions.ReplicaSet{})), Weight: 1, }, diff --git a/plugin/pkg/scheduler/scheduler.go b/plugin/pkg/scheduler/scheduler.go index 690064f0eae..6f52ba00287 100644 --- a/plugin/pkg/scheduler/scheduler.go +++ b/plugin/pkg/scheduler/scheduler.go @@ -19,7 +19,7 @@ package scheduler import ( "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" @@ -31,11 +31,11 @@ import ( // Binder knows how to write a binding. type Binder interface { - Bind(binding *api.Binding) error + Bind(binding *v1.Binding) error } type PodConditionUpdater interface { - Update(pod *api.Pod, podCondition *api.PodCondition) error + Update(pod *v1.Pod, podCondition *v1.PodCondition) error } // Scheduler watches for new unscheduled pods. It attempts to find @@ -60,11 +60,11 @@ type Config struct { // is available. We don't use a channel for this, because scheduling // a pod may take some amount of time and we don't want pods to get // stale while they sit in a channel. - NextPod func() *api.Pod + NextPod func() *v1.Pod // Error is called if there is an error. It is passed the pod in // question, and the error - Error func(*api.Pod, error) + Error func(*v1.Pod, error) // Recorder is the EventRecorder to use Recorder record.EventRecorder @@ -96,11 +96,11 @@ func (s *Scheduler) scheduleOne() { if err != nil { glog.V(1).Infof("Failed to schedule pod: %v/%v", pod.Namespace, pod.Name) s.config.Error(pod, err) - s.config.Recorder.Eventf(pod, api.EventTypeWarning, "FailedScheduling", "%v", err) - s.config.PodConditionUpdater.Update(pod, &api.PodCondition{ - Type: api.PodScheduled, - Status: api.ConditionFalse, - Reason: api.PodReasonUnschedulable, + s.config.Recorder.Eventf(pod, v1.EventTypeWarning, "FailedScheduling", "%v", err) + s.config.PodConditionUpdater.Update(pod, &v1.PodCondition{ + Type: v1.PodScheduled, + Status: v1.ConditionFalse, + Reason: v1.PodReasonUnschedulable, }) return } @@ -126,9 +126,9 @@ func (s *Scheduler) scheduleOne() { go func() { defer metrics.E2eSchedulingLatency.Observe(metrics.SinceInMicroseconds(start)) - b := &api.Binding{ - ObjectMeta: api.ObjectMeta{Namespace: pod.Namespace, Name: pod.Name}, - Target: api.ObjectReference{ + b := &v1.Binding{ + ObjectMeta: v1.ObjectMeta{Namespace: pod.Namespace, Name: pod.Name}, + Target: v1.ObjectReference{ Kind: "Node", Name: dest, }, @@ -144,15 +144,15 @@ func (s *Scheduler) scheduleOne() { glog.Errorf("scheduler cache ForgetPod failed: %v", err) } s.config.Error(pod, err) - s.config.Recorder.Eventf(pod, api.EventTypeNormal, "FailedScheduling", "Binding rejected: %v", err) - s.config.PodConditionUpdater.Update(pod, &api.PodCondition{ - Type: api.PodScheduled, - Status: api.ConditionFalse, + s.config.Recorder.Eventf(pod, v1.EventTypeNormal, "FailedScheduling", "Binding rejected: %v", err) + s.config.PodConditionUpdater.Update(pod, &v1.PodCondition{ + Type: v1.PodScheduled, + Status: v1.ConditionFalse, Reason: "BindingRejected", }) return } metrics.BindingLatency.Observe(metrics.SinceInMicroseconds(bindingStart)) - s.config.Recorder.Eventf(pod, api.EventTypeNormal, "Scheduled", "Successfully assigned %v to %v", pod.Name, dest) + s.config.Recorder.Eventf(pod, v1.EventTypeNormal, "Scheduled", "Successfully assigned %v to %v", pod.Name, dest) }() } diff --git a/plugin/pkg/scheduler/scheduler_test.go b/plugin/pkg/scheduler/scheduler_test.go index 1cb118ee8c4..5f4adf01994 100644 --- a/plugin/pkg/scheduler/scheduler_test.go +++ b/plugin/pkg/scheduler/scheduler_test.go @@ -23,9 +23,9 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/testapi" + "k8s.io/kubernetes/pkg/api/v1" clientcache "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/labels" @@ -38,38 +38,38 @@ import ( ) type fakeBinder struct { - b func(binding *api.Binding) error + b func(binding *v1.Binding) error } -func (fb fakeBinder) Bind(binding *api.Binding) error { return fb.b(binding) } +func (fb fakeBinder) Bind(binding *v1.Binding) error { return fb.b(binding) } type fakePodConditionUpdater struct{} -func (fc fakePodConditionUpdater) Update(pod *api.Pod, podCondition *api.PodCondition) error { +func (fc fakePodConditionUpdater) Update(pod *v1.Pod, podCondition *v1.PodCondition) error { return nil } -func podWithID(id, desiredHost string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: id, SelfLink: testapi.Default.SelfLink("pods", id)}, - Spec: api.PodSpec{ +func podWithID(id, desiredHost string) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: id, SelfLink: testapi.Default.SelfLink("pods", id)}, + Spec: v1.PodSpec{ NodeName: desiredHost, }, } } -func podWithPort(id, desiredHost string, port int) *api.Pod { +func podWithPort(id, desiredHost string, port int) *v1.Pod { pod := podWithID(id, desiredHost) - pod.Spec.Containers = []api.Container{ - {Name: "ctr", Ports: []api.ContainerPort{{HostPort: int32(port)}}}, + pod.Spec.Containers = []v1.Container{ + {Name: "ctr", Ports: []v1.ContainerPort{{HostPort: int32(port)}}}, } return pod } -func podWithResources(id, desiredHost string, limits api.ResourceList, requests api.ResourceList) *api.Pod { +func podWithResources(id, desiredHost string, limits v1.ResourceList, requests v1.ResourceList) *v1.Pod { pod := podWithID(id, desiredHost) - pod.Spec.Containers = []api.Container{ - {Name: "ctr", Resources: api.ResourceRequirements{Limits: limits, Requests: requests}}, + pod.Spec.Containers = []v1.Container{ + {Name: "ctr", Resources: v1.ResourceRequirements{Limits: limits, Requests: requests}}, } return pod } @@ -79,7 +79,7 @@ type mockScheduler struct { err error } -func (es mockScheduler) Schedule(pod *api.Pod, ml algorithm.NodeLister) (string, error) { +func (es mockScheduler) Schedule(pod *v1.Pod, ml algorithm.NodeLister) (string, error) { return es.machine, es.err } @@ -88,22 +88,22 @@ func TestScheduler(t *testing.T) { eventBroadcaster.StartLogging(t.Logf).Stop() errS := errors.New("scheduler") errB := errors.New("binder") - testNode := api.Node{ObjectMeta: api.ObjectMeta{Name: "machine1"}} + testNode := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "machine1"}} table := []struct { injectBindError error - sendPod *api.Pod + sendPod *v1.Pod algo algorithm.ScheduleAlgorithm - expectErrorPod *api.Pod - expectAssumedPod *api.Pod + expectErrorPod *v1.Pod + expectAssumedPod *v1.Pod expectError error - expectBind *api.Binding + expectBind *v1.Binding eventReason string }{ { sendPod: podWithID("foo", ""), algo: mockScheduler{testNode.Name, nil}, - expectBind: &api.Binding{ObjectMeta: api.ObjectMeta{Name: "foo"}, Target: api.ObjectReference{Kind: "Node", Name: testNode.Name}}, + expectBind: &v1.Binding{ObjectMeta: v1.ObjectMeta{Name: "foo"}, Target: v1.ObjectReference{Kind: "Node", Name: testNode.Name}}, expectAssumedPod: podWithID("foo", testNode.Name), eventReason: "Scheduled", }, { @@ -115,7 +115,7 @@ func TestScheduler(t *testing.T) { }, { sendPod: podWithID("foo", ""), algo: mockScheduler{testNode.Name, nil}, - expectBind: &api.Binding{ObjectMeta: api.ObjectMeta{Name: "foo"}, Target: api.ObjectReference{Kind: "Node", Name: testNode.Name}}, + expectBind: &v1.Binding{ObjectMeta: v1.ObjectMeta{Name: "foo"}, Target: v1.ObjectReference{Kind: "Node", Name: testNode.Name}}, expectAssumedPod: podWithID("foo", testNode.Name), injectBindError: errB, expectError: errB, @@ -126,36 +126,36 @@ func TestScheduler(t *testing.T) { for i, item := range table { var gotError error - var gotPod *api.Pod - var gotAssumedPod *api.Pod - var gotBinding *api.Binding + var gotPod *v1.Pod + var gotAssumedPod *v1.Pod + var gotBinding *v1.Binding c := &Config{ SchedulerCache: &schedulertesting.FakeCache{ - AssumeFunc: func(pod *api.Pod) { + AssumeFunc: func(pod *v1.Pod) { gotAssumedPod = pod }, }, NodeLister: algorithm.FakeNodeLister( - []*api.Node{&testNode}, + []*v1.Node{&testNode}, ), Algorithm: item.algo, - Binder: fakeBinder{func(b *api.Binding) error { + Binder: fakeBinder{func(b *v1.Binding) error { gotBinding = b return item.injectBindError }}, PodConditionUpdater: fakePodConditionUpdater{}, - Error: func(p *api.Pod, err error) { + Error: func(p *v1.Pod, err error) { gotPod = p gotError = err }, - NextPod: func() *api.Pod { + NextPod: func() *v1.Pod { return item.sendPod }, - Recorder: eventBroadcaster.NewRecorder(api.EventSource{Component: "scheduler"}), + Recorder: eventBroadcaster.NewRecorder(v1.EventSource{Component: "scheduler"}), } s := New(c) called := make(chan struct{}) - events := eventBroadcaster.StartEventWatcher(func(e *api.Event) { + events := eventBroadcaster.StartEventWatcher(func(e *v1.Event) { if e, a := item.eventReason, e.Reason; e != a { t.Errorf("%v: expected %v, got %v", i, e, a) } @@ -185,9 +185,9 @@ func TestSchedulerNoPhantomPodAfterExpire(t *testing.T) { queuedPodStore := clientcache.NewFIFO(clientcache.MetaNamespaceKeyFunc) scache := schedulercache.New(100*time.Millisecond, stop) pod := podWithPort("pod.Name", "", 8080) - node := api.Node{ObjectMeta: api.ObjectMeta{Name: "machine1"}} + node := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "machine1"}} scache.AddNode(&node) - nodeLister := algorithm.FakeNodeLister([]*api.Node{&node}) + nodeLister := algorithm.FakeNodeLister([]*v1.Node{&node}) predicateMap := map[string]algorithm.FitPredicate{"PodFitsHostPorts": predicates.PodFitsHostPorts} scheduler, bindingChan, _ := setupTestSchedulerWithOnePodOnNode(t, queuedPodStore, scache, nodeLister, predicateMap, pod, &node) @@ -225,9 +225,9 @@ func TestSchedulerNoPhantomPodAfterExpire(t *testing.T) { scheduler.scheduleOne() select { case b := <-bindingChan: - expectBinding := &api.Binding{ - ObjectMeta: api.ObjectMeta{Name: "bar"}, - Target: api.ObjectReference{Kind: "Node", Name: node.Name}, + expectBinding := &v1.Binding{ + ObjectMeta: v1.ObjectMeta{Name: "bar"}, + Target: v1.ObjectReference{Kind: "Node", Name: node.Name}, } if !reflect.DeepEqual(expectBinding, b) { t.Errorf("binding want=%v, get=%v", expectBinding, b) @@ -243,9 +243,9 @@ func TestSchedulerNoPhantomPodAfterDelete(t *testing.T) { queuedPodStore := clientcache.NewFIFO(clientcache.MetaNamespaceKeyFunc) scache := schedulercache.New(10*time.Minute, stop) firstPod := podWithPort("pod.Name", "", 8080) - node := api.Node{ObjectMeta: api.ObjectMeta{Name: "machine1"}} + node := v1.Node{ObjectMeta: v1.ObjectMeta{Name: "machine1"}} scache.AddNode(&node) - nodeLister := algorithm.FakeNodeLister([]*api.Node{&node}) + nodeLister := algorithm.FakeNodeLister([]*v1.Node{&node}) predicateMap := map[string]algorithm.FitPredicate{"PodFitsHostPorts": predicates.PodFitsHostPorts} scheduler, bindingChan, errChan := setupTestSchedulerWithOnePodOnNode(t, queuedPodStore, scache, nodeLister, predicateMap, firstPod, &node) @@ -285,9 +285,9 @@ func TestSchedulerNoPhantomPodAfterDelete(t *testing.T) { scheduler.scheduleOne() select { case b := <-bindingChan: - expectBinding := &api.Binding{ - ObjectMeta: api.ObjectMeta{Name: "bar"}, - Target: api.ObjectReference{Kind: "Node", Name: node.Name}, + expectBinding := &v1.Binding{ + ObjectMeta: v1.ObjectMeta{Name: "bar"}, + Target: v1.ObjectReference{Kind: "Node", Name: node.Name}, } if !reflect.DeepEqual(expectBinding, b) { t.Errorf("binding want=%v, get=%v", expectBinding, b) @@ -300,7 +300,7 @@ func TestSchedulerNoPhantomPodAfterDelete(t *testing.T) { // queuedPodStore: pods queued before processing. // cache: scheduler cache that might contain assumed pods. func setupTestSchedulerWithOnePodOnNode(t *testing.T, queuedPodStore *clientcache.FIFO, scache schedulercache.Cache, - nodeLister algorithm.FakeNodeLister, predicateMap map[string]algorithm.FitPredicate, pod *api.Pod, node *api.Node) (*Scheduler, chan *api.Binding, chan error) { + nodeLister algorithm.FakeNodeLister, predicateMap map[string]algorithm.FitPredicate, pod *v1.Pod, node *v1.Node) (*Scheduler, chan *v1.Binding, chan error) { scheduler, bindingChan, errChan := setupTestScheduler(queuedPodStore, scache, nodeLister, predicateMap) @@ -314,9 +314,9 @@ func setupTestSchedulerWithOnePodOnNode(t *testing.T, queuedPodStore *clientcach select { case b := <-bindingChan: - expectBinding := &api.Binding{ - ObjectMeta: api.ObjectMeta{Name: pod.Name}, - Target: api.ObjectReference{Kind: "Node", Name: node.Name}, + expectBinding := &v1.Binding{ + ObjectMeta: v1.ObjectMeta{Name: pod.Name}, + Target: v1.ObjectReference{Kind: "Node", Name: node.Name}, } if !reflect.DeepEqual(expectBinding, b) { t.Errorf("binding want=%v, get=%v", expectBinding, b) @@ -336,29 +336,29 @@ func TestSchedulerFailedSchedulingReasons(t *testing.T) { // Design the baseline for the pods, and we will make nodes that dont fit it later. var cpu = int64(4) var mem = int64(500) - podWithTooBigResourceRequests := podWithResources("bar", "", api.ResourceList{ - api.ResourceCPU: *(resource.NewQuantity(cpu, resource.DecimalSI)), - api.ResourceMemory: *(resource.NewQuantity(mem, resource.DecimalSI)), - }, api.ResourceList{ - api.ResourceCPU: *(resource.NewQuantity(cpu, resource.DecimalSI)), - api.ResourceMemory: *(resource.NewQuantity(mem, resource.DecimalSI)), + podWithTooBigResourceRequests := podWithResources("bar", "", v1.ResourceList{ + v1.ResourceCPU: *(resource.NewQuantity(cpu, resource.DecimalSI)), + v1.ResourceMemory: *(resource.NewQuantity(mem, resource.DecimalSI)), + }, v1.ResourceList{ + v1.ResourceCPU: *(resource.NewQuantity(cpu, resource.DecimalSI)), + v1.ResourceMemory: *(resource.NewQuantity(mem, resource.DecimalSI)), }) // create several nodes which cannot schedule the above pod - nodes := []*api.Node{} + nodes := []*v1.Node{} for i := 0; i < 100; i++ { - node := api.Node{ - ObjectMeta: api.ObjectMeta{Name: fmt.Sprintf("machine%v", i)}, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourceCPU: *(resource.NewQuantity(cpu/2, resource.DecimalSI)), - api.ResourceMemory: *(resource.NewQuantity(mem/5, resource.DecimalSI)), - api.ResourcePods: *(resource.NewQuantity(10, resource.DecimalSI)), + node := v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: fmt.Sprintf("machine%v", i)}, + Status: v1.NodeStatus{ + Capacity: v1.ResourceList{ + v1.ResourceCPU: *(resource.NewQuantity(cpu/2, resource.DecimalSI)), + v1.ResourceMemory: *(resource.NewQuantity(mem/5, resource.DecimalSI)), + v1.ResourcePods: *(resource.NewQuantity(10, resource.DecimalSI)), }, - Allocatable: api.ResourceList{ - api.ResourceCPU: *(resource.NewQuantity(cpu/2, resource.DecimalSI)), - api.ResourceMemory: *(resource.NewQuantity(mem/5, resource.DecimalSI)), - api.ResourcePods: *(resource.NewQuantity(10, resource.DecimalSI)), + Allocatable: v1.ResourceList{ + v1.ResourceCPU: *(resource.NewQuantity(cpu/2, resource.DecimalSI)), + v1.ResourceMemory: *(resource.NewQuantity(mem/5, resource.DecimalSI)), + v1.ResourcePods: *(resource.NewQuantity(10, resource.DecimalSI)), }}, } scache.AddNode(&node) @@ -373,8 +373,8 @@ func TestSchedulerFailedSchedulingReasons(t *testing.T) { failedPredicatesMap := FailedPredicateMap{} for _, node := range nodes { failedPredicatesMap[node.Name] = []algorithm.PredicateFailureReason{ - predicates.NewInsufficientResourceError(api.ResourceCPU, 4000, 0, 2000), - predicates.NewInsufficientResourceError(api.ResourceMemory, 500, 0, 100), + predicates.NewInsufficientResourceError(v1.ResourceCPU, 4000, 0, 2000), + predicates.NewInsufficientResourceError(v1.ResourceMemory, 500, 0, 100), } } scheduler, _, errChan := setupTestScheduler(queuedPodStore, scache, nodeLister, predicateMap) @@ -400,7 +400,7 @@ func TestSchedulerFailedSchedulingReasons(t *testing.T) { // queuedPodStore: pods queued before processing. // scache: scheduler cache that might contain assumed pods. -func setupTestScheduler(queuedPodStore *clientcache.FIFO, scache schedulercache.Cache, nodeLister algorithm.FakeNodeLister, predicateMap map[string]algorithm.FitPredicate) (*Scheduler, chan *api.Binding, chan error) { +func setupTestScheduler(queuedPodStore *clientcache.FIFO, scache schedulercache.Cache, nodeLister algorithm.FakeNodeLister, predicateMap map[string]algorithm.FitPredicate) (*Scheduler, chan *v1.Binding, chan error) { algo := NewGenericScheduler( scache, predicateMap, @@ -408,20 +408,20 @@ func setupTestScheduler(queuedPodStore *clientcache.FIFO, scache schedulercache. []algorithm.PriorityConfig{}, algorithm.EmptyMetadataProducer, []algorithm.SchedulerExtender{}) - bindingChan := make(chan *api.Binding, 1) + bindingChan := make(chan *v1.Binding, 1) errChan := make(chan error, 1) cfg := &Config{ SchedulerCache: scache, NodeLister: nodeLister, Algorithm: algo, - Binder: fakeBinder{func(b *api.Binding) error { + Binder: fakeBinder{func(b *v1.Binding) error { bindingChan <- b return nil }}, - NextPod: func() *api.Pod { - return clientcache.Pop(queuedPodStore).(*api.Pod) + NextPod: func() *v1.Pod { + return clientcache.Pop(queuedPodStore).(*v1.Pod) }, - Error: func(p *api.Pod, err error) { + Error: func(p *v1.Pod, err error) { errChan <- err }, Recorder: &record.FakeRecorder{}, diff --git a/plugin/pkg/scheduler/schedulercache/BUILD b/plugin/pkg/scheduler/schedulercache/BUILD index 6bd9ab1ad73..db545c00026 100644 --- a/plugin/pkg/scheduler/schedulercache/BUILD +++ b/plugin/pkg/scheduler/schedulercache/BUILD @@ -20,8 +20,8 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/labels:go_default_library", "//pkg/util/wait:go_default_library", @@ -36,8 +36,8 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/resource:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/labels:go_default_library", "//plugin/pkg/scheduler/algorithm/priorities/util:go_default_library", ], diff --git a/plugin/pkg/scheduler/schedulercache/cache.go b/plugin/pkg/scheduler/schedulercache/cache.go index 985f9ed0f73..697b3789073 100644 --- a/plugin/pkg/scheduler/schedulercache/cache.go +++ b/plugin/pkg/scheduler/schedulercache/cache.go @@ -22,7 +22,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/wait" ) @@ -57,7 +57,7 @@ type schedulerCache struct { } type podState struct { - pod *api.Pod + pod *v1.Pod // Used by assumedPod to determinate expiration. deadline *time.Time } @@ -90,10 +90,10 @@ func (cache *schedulerCache) UpdateNodeNameToInfoMap(nodeNameToInfo map[string]* return nil } -func (cache *schedulerCache) List(selector labels.Selector) ([]*api.Pod, error) { +func (cache *schedulerCache) List(selector labels.Selector) ([]*v1.Pod, error) { cache.mu.Lock() defer cache.mu.Unlock() - var pods []*api.Pod + var pods []*v1.Pod for _, info := range cache.nodes { for _, pod := range info.pods { if selector.Matches(labels.Set(pod.Labels)) { @@ -104,12 +104,12 @@ func (cache *schedulerCache) List(selector labels.Selector) ([]*api.Pod, error) return pods, nil } -func (cache *schedulerCache) AssumePod(pod *api.Pod) error { +func (cache *schedulerCache) AssumePod(pod *v1.Pod) error { return cache.assumePod(pod, time.Now()) } // assumePod exists for making test deterministic by taking time as input argument. -func (cache *schedulerCache) assumePod(pod *api.Pod, now time.Time) error { +func (cache *schedulerCache) assumePod(pod *v1.Pod, now time.Time) error { cache.mu.Lock() defer cache.mu.Unlock() @@ -132,7 +132,7 @@ func (cache *schedulerCache) assumePod(pod *api.Pod, now time.Time) error { return nil } -func (cache *schedulerCache) ForgetPod(pod *api.Pod) error { +func (cache *schedulerCache) ForgetPod(pod *v1.Pod) error { key, err := getPodKey(pod) if err != nil { return err @@ -157,7 +157,7 @@ func (cache *schedulerCache) ForgetPod(pod *api.Pod) error { return nil } -func (cache *schedulerCache) AddPod(pod *api.Pod) error { +func (cache *schedulerCache) AddPod(pod *v1.Pod) error { key, err := getPodKey(pod) if err != nil { return err @@ -184,7 +184,7 @@ func (cache *schedulerCache) AddPod(pod *api.Pod) error { return nil } -func (cache *schedulerCache) UpdatePod(oldPod, newPod *api.Pod) error { +func (cache *schedulerCache) UpdatePod(oldPod, newPod *v1.Pod) error { key, err := getPodKey(oldPod) if err != nil { return err @@ -207,7 +207,7 @@ func (cache *schedulerCache) UpdatePod(oldPod, newPod *api.Pod) error { return nil } -func (cache *schedulerCache) updatePod(oldPod, newPod *api.Pod) error { +func (cache *schedulerCache) updatePod(oldPod, newPod *v1.Pod) error { if err := cache.removePod(oldPod); err != nil { return err } @@ -215,7 +215,7 @@ func (cache *schedulerCache) updatePod(oldPod, newPod *api.Pod) error { return nil } -func (cache *schedulerCache) addPod(pod *api.Pod) { +func (cache *schedulerCache) addPod(pod *v1.Pod) { n, ok := cache.nodes[pod.Spec.NodeName] if !ok { n = NewNodeInfo() @@ -224,7 +224,7 @@ func (cache *schedulerCache) addPod(pod *api.Pod) { n.addPod(pod) } -func (cache *schedulerCache) removePod(pod *api.Pod) error { +func (cache *schedulerCache) removePod(pod *v1.Pod) error { n := cache.nodes[pod.Spec.NodeName] if err := n.removePod(pod); err != nil { return err @@ -235,7 +235,7 @@ func (cache *schedulerCache) removePod(pod *api.Pod) error { return nil } -func (cache *schedulerCache) RemovePod(pod *api.Pod) error { +func (cache *schedulerCache) RemovePod(pod *v1.Pod) error { key, err := getPodKey(pod) if err != nil { return err @@ -260,7 +260,7 @@ func (cache *schedulerCache) RemovePod(pod *api.Pod) error { return nil } -func (cache *schedulerCache) AddNode(node *api.Node) error { +func (cache *schedulerCache) AddNode(node *v1.Node) error { cache.mu.Lock() defer cache.mu.Unlock() @@ -272,7 +272,7 @@ func (cache *schedulerCache) AddNode(node *api.Node) error { return n.SetNode(node) } -func (cache *schedulerCache) UpdateNode(oldNode, newNode *api.Node) error { +func (cache *schedulerCache) UpdateNode(oldNode, newNode *v1.Node) error { cache.mu.Lock() defer cache.mu.Unlock() @@ -284,7 +284,7 @@ func (cache *schedulerCache) UpdateNode(oldNode, newNode *api.Node) error { return n.SetNode(newNode) } -func (cache *schedulerCache) RemoveNode(node *api.Node) error { +func (cache *schedulerCache) RemoveNode(node *v1.Node) error { cache.mu.Lock() defer cache.mu.Unlock() diff --git a/plugin/pkg/scheduler/schedulercache/cache_test.go b/plugin/pkg/scheduler/schedulercache/cache_test.go index fb0e062f9ce..b5a632cbbd7 100644 --- a/plugin/pkg/scheduler/schedulercache/cache_test.go +++ b/plugin/pkg/scheduler/schedulercache/cache_test.go @@ -22,8 +22,8 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" priorityutil "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util" ) @@ -42,19 +42,19 @@ func deepEqualWithoutGeneration(t *testing.T, testcase int, actual, expected *No // on node level. func TestAssumePodScheduled(t *testing.T) { nodeName := "node" - testPods := []*api.Pod{ - makeBasePod(nodeName, "test", "100m", "500", []api.ContainerPort{{HostPort: 80}}), - makeBasePod(nodeName, "test-1", "100m", "500", []api.ContainerPort{{HostPort: 80}}), - makeBasePod(nodeName, "test-2", "200m", "1Ki", []api.ContainerPort{{HostPort: 8080}}), - makeBasePod(nodeName, "test-nonzero", "", "", []api.ContainerPort{{HostPort: 80}}), + testPods := []*v1.Pod{ + makeBasePod(nodeName, "test", "100m", "500", []v1.ContainerPort{{HostPort: 80}}), + makeBasePod(nodeName, "test-1", "100m", "500", []v1.ContainerPort{{HostPort: 80}}), + makeBasePod(nodeName, "test-2", "200m", "1Ki", []v1.ContainerPort{{HostPort: 8080}}), + makeBasePod(nodeName, "test-nonzero", "", "", []v1.ContainerPort{{HostPort: 80}}), } tests := []struct { - pods []*api.Pod + pods []*v1.Pod wNodeInfo *NodeInfo }{{ - pods: []*api.Pod{testPods[0]}, + pods: []*v1.Pod{testPods[0]}, wNodeInfo: &NodeInfo{ requestedResource: &Resource{ MilliCPU: 100, @@ -65,10 +65,10 @@ func TestAssumePodScheduled(t *testing.T) { Memory: 500, }, allocatableResource: &Resource{}, - pods: []*api.Pod{testPods[0]}, + pods: []*v1.Pod{testPods[0]}, }, }, { - pods: []*api.Pod{testPods[1], testPods[2]}, + pods: []*v1.Pod{testPods[1], testPods[2]}, wNodeInfo: &NodeInfo{ requestedResource: &Resource{ MilliCPU: 300, @@ -79,10 +79,10 @@ func TestAssumePodScheduled(t *testing.T) { Memory: 1524, }, allocatableResource: &Resource{}, - pods: []*api.Pod{testPods[1], testPods[2]}, + pods: []*v1.Pod{testPods[1], testPods[2]}, }, }, { // test non-zero request - pods: []*api.Pod{testPods[3]}, + pods: []*v1.Pod{testPods[3]}, wNodeInfo: &NodeInfo{ requestedResource: &Resource{ MilliCPU: 0, @@ -93,7 +93,7 @@ func TestAssumePodScheduled(t *testing.T) { Memory: priorityutil.DefaultMemoryRequest, }, allocatableResource: &Resource{}, - pods: []*api.Pod{testPods[3]}, + pods: []*v1.Pod{testPods[3]}, }, }} @@ -119,7 +119,7 @@ func TestAssumePodScheduled(t *testing.T) { } type testExpirePodStruct struct { - pod *api.Pod + pod *v1.Pod assumedTime time.Time } @@ -127,9 +127,9 @@ type testExpirePodStruct struct { // The removal will be reflected in node info. func TestExpirePod(t *testing.T) { nodeName := "node" - testPods := []*api.Pod{ - makeBasePod(nodeName, "test-1", "100m", "500", []api.ContainerPort{{HostPort: 80}}), - makeBasePod(nodeName, "test-2", "200m", "1Ki", []api.ContainerPort{{HostPort: 8080}}), + testPods := []*v1.Pod{ + makeBasePod(nodeName, "test-1", "100m", "500", []v1.ContainerPort{{HostPort: 80}}), + makeBasePod(nodeName, "test-2", "200m", "1Ki", []v1.ContainerPort{{HostPort: 8080}}), } now := time.Now() ttl := 10 * time.Second @@ -160,7 +160,7 @@ func TestExpirePod(t *testing.T) { Memory: 1024, }, allocatableResource: &Resource{}, - pods: []*api.Pod{testPods[1]}, + pods: []*v1.Pod{testPods[1]}, }, }} @@ -186,18 +186,18 @@ func TestAddPodWillConfirm(t *testing.T) { now := time.Now() ttl := 10 * time.Second - testPods := []*api.Pod{ - makeBasePod(nodeName, "test-1", "100m", "500", []api.ContainerPort{{HostPort: 80}}), - makeBasePod(nodeName, "test-2", "200m", "1Ki", []api.ContainerPort{{HostPort: 8080}}), + testPods := []*v1.Pod{ + makeBasePod(nodeName, "test-1", "100m", "500", []v1.ContainerPort{{HostPort: 80}}), + makeBasePod(nodeName, "test-2", "200m", "1Ki", []v1.ContainerPort{{HostPort: 8080}}), } tests := []struct { - podsToAssume []*api.Pod - podsToAdd []*api.Pod + podsToAssume []*v1.Pod + podsToAdd []*v1.Pod wNodeInfo *NodeInfo }{{ // two pod were assumed at same time. But first one is called Add() and gets confirmed. - podsToAssume: []*api.Pod{testPods[0], testPods[1]}, - podsToAdd: []*api.Pod{testPods[0]}, + podsToAssume: []*v1.Pod{testPods[0], testPods[1]}, + podsToAdd: []*v1.Pod{testPods[0]}, wNodeInfo: &NodeInfo{ requestedResource: &Resource{ MilliCPU: 100, @@ -208,7 +208,7 @@ func TestAddPodWillConfirm(t *testing.T) { Memory: 500, }, allocatableResource: &Resource{}, - pods: []*api.Pod{testPods[0]}, + pods: []*v1.Pod{testPods[0]}, }, }} @@ -235,9 +235,9 @@ func TestAddPodWillConfirm(t *testing.T) { func TestAddPodAfterExpiration(t *testing.T) { nodeName := "node" ttl := 10 * time.Second - basePod := makeBasePod(nodeName, "test", "100m", "500", []api.ContainerPort{{HostPort: 80}}) + basePod := makeBasePod(nodeName, "test", "100m", "500", []v1.ContainerPort{{HostPort: 80}}) tests := []struct { - pod *api.Pod + pod *v1.Pod wNodeInfo *NodeInfo }{{ @@ -252,7 +252,7 @@ func TestAddPodAfterExpiration(t *testing.T) { Memory: 500, }, allocatableResource: &Resource{}, - pods: []*api.Pod{basePod}, + pods: []*v1.Pod{basePod}, }, }} @@ -281,19 +281,19 @@ func TestAddPodAfterExpiration(t *testing.T) { func TestUpdatePod(t *testing.T) { nodeName := "node" ttl := 10 * time.Second - testPods := []*api.Pod{ - makeBasePod(nodeName, "test", "100m", "500", []api.ContainerPort{{HostPort: 80}}), - makeBasePod(nodeName, "test", "200m", "1Ki", []api.ContainerPort{{HostPort: 8080}}), + testPods := []*v1.Pod{ + makeBasePod(nodeName, "test", "100m", "500", []v1.ContainerPort{{HostPort: 80}}), + makeBasePod(nodeName, "test", "200m", "1Ki", []v1.ContainerPort{{HostPort: 8080}}), } tests := []struct { - podsToAssume []*api.Pod - podsToAdd []*api.Pod - podsToUpdate []*api.Pod + podsToAssume []*v1.Pod + podsToAdd []*v1.Pod + podsToUpdate []*v1.Pod wNodeInfo []*NodeInfo }{{ // add a pod and then update it twice - podsToAdd: []*api.Pod{testPods[0]}, - podsToUpdate: []*api.Pod{testPods[0], testPods[1], testPods[0]}, + podsToAdd: []*v1.Pod{testPods[0]}, + podsToUpdate: []*v1.Pod{testPods[0], testPods[1], testPods[0]}, wNodeInfo: []*NodeInfo{{ requestedResource: &Resource{ MilliCPU: 200, @@ -304,7 +304,7 @@ func TestUpdatePod(t *testing.T) { Memory: 1024, }, allocatableResource: &Resource{}, - pods: []*api.Pod{testPods[1]}, + pods: []*v1.Pod{testPods[1]}, }, { requestedResource: &Resource{ MilliCPU: 100, @@ -315,7 +315,7 @@ func TestUpdatePod(t *testing.T) { Memory: 500, }, allocatableResource: &Resource{}, - pods: []*api.Pod{testPods[0]}, + pods: []*v1.Pod{testPods[0]}, }}, }} @@ -345,20 +345,20 @@ func TestUpdatePod(t *testing.T) { func TestExpireAddUpdatePod(t *testing.T) { nodeName := "node" ttl := 10 * time.Second - testPods := []*api.Pod{ - makeBasePod(nodeName, "test", "100m", "500", []api.ContainerPort{{HostPort: 80}}), - makeBasePod(nodeName, "test", "200m", "1Ki", []api.ContainerPort{{HostPort: 8080}}), + testPods := []*v1.Pod{ + makeBasePod(nodeName, "test", "100m", "500", []v1.ContainerPort{{HostPort: 80}}), + makeBasePod(nodeName, "test", "200m", "1Ki", []v1.ContainerPort{{HostPort: 8080}}), } tests := []struct { - podsToAssume []*api.Pod - podsToAdd []*api.Pod - podsToUpdate []*api.Pod + podsToAssume []*v1.Pod + podsToAdd []*v1.Pod + podsToUpdate []*v1.Pod wNodeInfo []*NodeInfo }{{ // Pod is assumed, expired, and added. Then it would be updated twice. - podsToAssume: []*api.Pod{testPods[0]}, - podsToAdd: []*api.Pod{testPods[0]}, - podsToUpdate: []*api.Pod{testPods[0], testPods[1], testPods[0]}, + podsToAssume: []*v1.Pod{testPods[0]}, + podsToAdd: []*v1.Pod{testPods[0]}, + podsToUpdate: []*v1.Pod{testPods[0], testPods[1], testPods[0]}, wNodeInfo: []*NodeInfo{{ requestedResource: &Resource{ MilliCPU: 200, @@ -369,7 +369,7 @@ func TestExpireAddUpdatePod(t *testing.T) { Memory: 1024, }, allocatableResource: &Resource{}, - pods: []*api.Pod{testPods[1]}, + pods: []*v1.Pod{testPods[1]}, }, { requestedResource: &Resource{ MilliCPU: 100, @@ -380,7 +380,7 @@ func TestExpireAddUpdatePod(t *testing.T) { Memory: 500, }, allocatableResource: &Resource{}, - pods: []*api.Pod{testPods[0]}, + pods: []*v1.Pod{testPods[0]}, }}, }} @@ -417,9 +417,9 @@ func TestExpireAddUpdatePod(t *testing.T) { // TestRemovePod tests after added pod is removed, its information should also be subtracted. func TestRemovePod(t *testing.T) { nodeName := "node" - basePod := makeBasePod(nodeName, "test", "100m", "500", []api.ContainerPort{{HostPort: 80}}) + basePod := makeBasePod(nodeName, "test", "100m", "500", []v1.ContainerPort{{HostPort: 80}}) tests := []struct { - pod *api.Pod + pod *v1.Pod wNodeInfo *NodeInfo }{{ @@ -434,7 +434,7 @@ func TestRemovePod(t *testing.T) { Memory: 500, }, allocatableResource: &Resource{}, - pods: []*api.Pod{basePod}, + pods: []*v1.Pod{basePod}, }, }} @@ -459,11 +459,11 @@ func TestRemovePod(t *testing.T) { func TestForgetPod(t *testing.T) { nodeName := "node" - basePod := makeBasePod(nodeName, "test", "100m", "500", []api.ContainerPort{{HostPort: 80}}) + basePod := makeBasePod(nodeName, "test", "100m", "500", []v1.ContainerPort{{HostPort: 80}}) tests := []struct { - pods []*api.Pod + pods []*v1.Pod }{{ - pods: []*api.Pod{basePod}, + pods: []*v1.Pod{basePod}, }} now := time.Now() ttl := 10 * time.Second @@ -517,22 +517,22 @@ func benchmarkExpire(b *testing.B, podNum int) { } } -func makeBasePod(nodeName, objName, cpu, mem string, ports []api.ContainerPort) *api.Pod { - req := api.ResourceList{} +func makeBasePod(nodeName, objName, cpu, mem string, ports []v1.ContainerPort) *v1.Pod { + req := v1.ResourceList{} if cpu != "" { - req = api.ResourceList{ - api.ResourceCPU: resource.MustParse(cpu), - api.ResourceMemory: resource.MustParse(mem), + req = v1.ResourceList{ + v1.ResourceCPU: resource.MustParse(cpu), + v1.ResourceMemory: resource.MustParse(mem), } } - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Namespace: "node_info_cache_test", Name: objName, }, - Spec: api.PodSpec{ - Containers: []api.Container{{ - Resources: api.ResourceRequirements{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ + Resources: v1.ResourceRequirements{ Requests: req, }, Ports: ports, diff --git a/plugin/pkg/scheduler/schedulercache/interface.go b/plugin/pkg/scheduler/schedulercache/interface.go index 2f0a84b2a2e..1ca64fa800b 100644 --- a/plugin/pkg/scheduler/schedulercache/interface.go +++ b/plugin/pkg/scheduler/schedulercache/interface.go @@ -17,7 +17,7 @@ limitations under the License. package schedulercache import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" ) @@ -59,29 +59,29 @@ type Cache interface { // AssumePod assumes a pod scheduled and aggregates the pod's information into its node. // The implementation also decides the policy to expire pod before being confirmed (receiving Add event). // After expiration, its information would be subtracted. - AssumePod(pod *api.Pod) error + AssumePod(pod *v1.Pod) error // ForgetPod removes an assumed pod from cache. - ForgetPod(pod *api.Pod) error + ForgetPod(pod *v1.Pod) error // AddPod either confirms a pod if it's assumed, or adds it back if it's expired. // If added back, the pod's information would be added again. - AddPod(pod *api.Pod) error + AddPod(pod *v1.Pod) error // UpdatePod removes oldPod's information and adds newPod's information. - UpdatePod(oldPod, newPod *api.Pod) error + UpdatePod(oldPod, newPod *v1.Pod) error // RemovePod removes a pod. The pod's information would be subtracted from assigned node. - RemovePod(pod *api.Pod) error + RemovePod(pod *v1.Pod) error // AddNode adds overall information about node. - AddNode(node *api.Node) error + AddNode(node *v1.Node) error // UpdateNode updates overall information about node. - UpdateNode(oldNode, newNode *api.Node) error + UpdateNode(oldNode, newNode *v1.Node) error // RemoveNode removes overall information about node. - RemoveNode(node *api.Node) error + RemoveNode(node *v1.Node) error // UpdateNodeNameToInfoMap updates the passed infoMap to the current contents of Cache. // The node info contains aggregated information of pods scheduled (including assumed to be) @@ -89,5 +89,5 @@ type Cache interface { UpdateNodeNameToInfoMap(infoMap map[string]*NodeInfo) error // List lists all cached pods (including assumed ones). - List(labels.Selector) ([]*api.Pod, error) + List(labels.Selector) ([]*v1.Pod, error) } diff --git a/plugin/pkg/scheduler/schedulercache/node_info.go b/plugin/pkg/scheduler/schedulercache/node_info.go index 8b98ca8cacf..4a173b6b2ee 100644 --- a/plugin/pkg/scheduler/schedulercache/node_info.go +++ b/plugin/pkg/scheduler/schedulercache/node_info.go @@ -21,8 +21,8 @@ import ( "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" clientcache "k8s.io/kubernetes/pkg/client/cache" priorityutil "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util" ) @@ -32,10 +32,10 @@ var emptyResource = Resource{} // NodeInfo is node level aggregated information. type NodeInfo struct { // Overall node information. - node *api.Node + node *v1.Node - pods []*api.Pod - podsWithAffinity []*api.Pod + pods []*v1.Pod + podsWithAffinity []*v1.Pod // Total requested resource of all pods on this node. // It includes assumed pods which scheduler sends binding to apiserver but @@ -59,14 +59,14 @@ type Resource struct { MilliCPU int64 Memory int64 NvidiaGPU int64 - OpaqueIntResources map[api.ResourceName]int64 + OpaqueIntResources map[v1.ResourceName]int64 } -func (r *Resource) ResourceList() api.ResourceList { - result := api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(r.MilliCPU, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(r.Memory, resource.BinarySI), - api.ResourceNvidiaGPU: *resource.NewQuantity(r.NvidiaGPU, resource.DecimalSI), +func (r *Resource) ResourceList() v1.ResourceList { + result := v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(r.MilliCPU, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(r.Memory, resource.BinarySI), + v1.ResourceNvidiaGPU: *resource.NewQuantity(r.NvidiaGPU, resource.DecimalSI), } for rName, rQuant := range r.OpaqueIntResources { result[rName] = *resource.NewQuantity(rQuant, resource.DecimalSI) @@ -77,7 +77,7 @@ func (r *Resource) ResourceList() api.ResourceList { // NewNodeInfo returns a ready to use empty NodeInfo object. // If any pods are given in arguments, their information will be aggregated in // the returned object. -func NewNodeInfo(pods ...*api.Pod) *NodeInfo { +func NewNodeInfo(pods ...*v1.Pod) *NodeInfo { ni := &NodeInfo{ requestedResource: &Resource{}, nonzeroRequest: &Resource{}, @@ -92,7 +92,7 @@ func NewNodeInfo(pods ...*api.Pod) *NodeInfo { } // Returns overall information about this node. -func (n *NodeInfo) Node() *api.Node { +func (n *NodeInfo) Node() *v1.Node { if n == nil { return nil } @@ -100,7 +100,7 @@ func (n *NodeInfo) Node() *api.Node { } // Pods return all pods scheduled (including assumed to be) on this node. -func (n *NodeInfo) Pods() []*api.Pod { +func (n *NodeInfo) Pods() []*v1.Pod { if n == nil { return nil } @@ -108,7 +108,7 @@ func (n *NodeInfo) Pods() []*api.Pod { } // PodsWithAffinity return all pods with (anti)affinity constraints on this node. -func (n *NodeInfo) PodsWithAffinity() []*api.Pod { +func (n *NodeInfo) PodsWithAffinity() []*v1.Pod { if n == nil { return nil } @@ -156,10 +156,10 @@ func (n *NodeInfo) Clone() *NodeInfo { generation: n.generation, } if len(n.pods) > 0 { - clone.pods = append([]*api.Pod(nil), n.pods...) + clone.pods = append([]*v1.Pod(nil), n.pods...) } if len(n.podsWithAffinity) > 0 { - clone.podsWithAffinity = append([]*api.Pod(nil), n.podsWithAffinity...) + clone.podsWithAffinity = append([]*v1.Pod(nil), n.podsWithAffinity...) } return clone } @@ -173,8 +173,8 @@ func (n *NodeInfo) String() string { return fmt.Sprintf("&NodeInfo{Pods:%v, RequestedResource:%#v, NonZeroRequest: %#v}", podKeys, n.requestedResource, n.nonzeroRequest) } -func hasPodAffinityConstraints(pod *api.Pod) bool { - affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations) +func hasPodAffinityConstraints(pod *v1.Pod) bool { + affinity, err := v1.GetAffinityFromPodAnnotations(pod.Annotations) if err != nil || affinity == nil { return false } @@ -182,14 +182,14 @@ func hasPodAffinityConstraints(pod *api.Pod) bool { } // addPod adds pod information to this NodeInfo. -func (n *NodeInfo) addPod(pod *api.Pod) { +func (n *NodeInfo) addPod(pod *v1.Pod) { // cpu, mem, nvidia_gpu, non0_cpu, non0_mem := calculateResource(pod) res, non0_cpu, non0_mem := calculateResource(pod) n.requestedResource.MilliCPU += res.MilliCPU n.requestedResource.Memory += res.Memory n.requestedResource.NvidiaGPU += res.NvidiaGPU if n.requestedResource.OpaqueIntResources == nil && len(res.OpaqueIntResources) > 0 { - n.requestedResource.OpaqueIntResources = map[api.ResourceName]int64{} + n.requestedResource.OpaqueIntResources = map[v1.ResourceName]int64{} } for rName, rQuant := range res.OpaqueIntResources { n.requestedResource.OpaqueIntResources[rName] += rQuant @@ -204,7 +204,7 @@ func (n *NodeInfo) addPod(pod *api.Pod) { } // removePod subtracts pod information to this NodeInfo. -func (n *NodeInfo) removePod(pod *api.Pod) error { +func (n *NodeInfo) removePod(pod *v1.Pod) error { k1, err := getPodKey(pod) if err != nil { return err @@ -240,7 +240,7 @@ func (n *NodeInfo) removePod(pod *api.Pod) error { n.requestedResource.Memory -= res.Memory n.requestedResource.NvidiaGPU -= res.NvidiaGPU if len(res.OpaqueIntResources) > 0 && n.requestedResource.OpaqueIntResources == nil { - n.requestedResource.OpaqueIntResources = map[api.ResourceName]int64{} + n.requestedResource.OpaqueIntResources = map[v1.ResourceName]int64{} } for rName, rQuant := range res.OpaqueIntResources { n.requestedResource.OpaqueIntResources[rName] -= rQuant @@ -254,21 +254,21 @@ func (n *NodeInfo) removePod(pod *api.Pod) error { return fmt.Errorf("no corresponding pod %s in pods of node %s", pod.Name, n.node.Name) } -func calculateResource(pod *api.Pod) (res Resource, non0_cpu int64, non0_mem int64) { +func calculateResource(pod *v1.Pod) (res Resource, non0_cpu int64, non0_mem int64) { for _, c := range pod.Spec.Containers { for rName, rQuant := range c.Resources.Requests { switch rName { - case api.ResourceCPU: + case v1.ResourceCPU: res.MilliCPU += rQuant.MilliValue() - case api.ResourceMemory: + case v1.ResourceMemory: res.Memory += rQuant.Value() - case api.ResourceNvidiaGPU: + case v1.ResourceNvidiaGPU: res.NvidiaGPU += rQuant.Value() default: - if api.IsOpaqueIntResourceName(rName) { + if v1.IsOpaqueIntResourceName(rName) { // Lazily allocate opaque resource map. if res.OpaqueIntResources == nil { - res.OpaqueIntResources = map[api.ResourceName]int64{} + res.OpaqueIntResources = map[v1.ResourceName]int64{} } res.OpaqueIntResources[rName] += rQuant.Value() } @@ -284,23 +284,23 @@ func calculateResource(pod *api.Pod) (res Resource, non0_cpu int64, non0_mem int } // Sets the overall node information. -func (n *NodeInfo) SetNode(node *api.Node) error { +func (n *NodeInfo) SetNode(node *v1.Node) error { n.node = node for rName, rQuant := range node.Status.Allocatable { switch rName { - case api.ResourceCPU: + case v1.ResourceCPU: n.allocatableResource.MilliCPU = rQuant.MilliValue() - case api.ResourceMemory: + case v1.ResourceMemory: n.allocatableResource.Memory = rQuant.Value() - case api.ResourceNvidiaGPU: + case v1.ResourceNvidiaGPU: n.allocatableResource.NvidiaGPU = rQuant.Value() - case api.ResourcePods: + case v1.ResourcePods: n.allowedPodNumber = int(rQuant.Value()) default: - if api.IsOpaqueIntResourceName(rName) { + if v1.IsOpaqueIntResourceName(rName) { // Lazily allocate opaque resource map. if n.allocatableResource.OpaqueIntResources == nil { - n.allocatableResource.OpaqueIntResources = map[api.ResourceName]int64{} + n.allocatableResource.OpaqueIntResources = map[v1.ResourceName]int64{} } n.allocatableResource.OpaqueIntResources[rName] = rQuant.Value() } @@ -311,7 +311,7 @@ func (n *NodeInfo) SetNode(node *api.Node) error { } // Removes the overall information about the node. -func (n *NodeInfo) RemoveNode(node *api.Node) error { +func (n *NodeInfo) RemoveNode(node *v1.Node) error { // We don't remove NodeInfo for because there can still be some pods on this node - // this is because notifications about pods are delivered in a different watch, // and thus can potentially be observed later, even though they happened before @@ -324,6 +324,6 @@ func (n *NodeInfo) RemoveNode(node *api.Node) error { } // getPodKey returns the string key of a pod. -func getPodKey(pod *api.Pod) (string, error) { +func getPodKey(pod *v1.Pod) (string, error) { return clientcache.MetaNamespaceKeyFunc(pod) } diff --git a/plugin/pkg/scheduler/schedulercache/util.go b/plugin/pkg/scheduler/schedulercache/util.go index 12e6848bc57..d5d52f49119 100644 --- a/plugin/pkg/scheduler/schedulercache/util.go +++ b/plugin/pkg/scheduler/schedulercache/util.go @@ -16,11 +16,11 @@ limitations under the License. package schedulercache -import "k8s.io/kubernetes/pkg/api" +import "k8s.io/kubernetes/pkg/api/v1" // CreateNodeNameToInfoMap obtains a list of pods and pivots that list into a map where the keys are node names // and the values are the aggregated information for that node. -func CreateNodeNameToInfoMap(pods []*api.Pod, nodes []*api.Node) map[string]*NodeInfo { +func CreateNodeNameToInfoMap(pods []*v1.Pod, nodes []*v1.Node) map[string]*NodeInfo { nodeNameToInfo := make(map[string]*NodeInfo) for _, pod := range pods { nodeName := pod.Spec.NodeName diff --git a/plugin/pkg/scheduler/testing/BUILD b/plugin/pkg/scheduler/testing/BUILD index ad8192ece85..54d827f0212 100644 --- a/plugin/pkg/scheduler/testing/BUILD +++ b/plugin/pkg/scheduler/testing/BUILD @@ -18,7 +18,7 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/labels:go_default_library", "//plugin/pkg/scheduler/schedulercache:go_default_library", ], diff --git a/plugin/pkg/scheduler/testing/fake_cache.go b/plugin/pkg/scheduler/testing/fake_cache.go index b4106c38fef..fb0d0c6d53b 100644 --- a/plugin/pkg/scheduler/testing/fake_cache.go +++ b/plugin/pkg/scheduler/testing/fake_cache.go @@ -17,37 +17,37 @@ limitations under the License. package schedulercache import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) // FakeCache is used for testing type FakeCache struct { - AssumeFunc func(*api.Pod) + AssumeFunc func(*v1.Pod) } -func (f *FakeCache) AssumePod(pod *api.Pod) error { +func (f *FakeCache) AssumePod(pod *v1.Pod) error { f.AssumeFunc(pod) return nil } -func (f *FakeCache) ForgetPod(pod *api.Pod) error { return nil } +func (f *FakeCache) ForgetPod(pod *v1.Pod) error { return nil } -func (f *FakeCache) AddPod(pod *api.Pod) error { return nil } +func (f *FakeCache) AddPod(pod *v1.Pod) error { return nil } -func (f *FakeCache) UpdatePod(oldPod, newPod *api.Pod) error { return nil } +func (f *FakeCache) UpdatePod(oldPod, newPod *v1.Pod) error { return nil } -func (f *FakeCache) RemovePod(pod *api.Pod) error { return nil } +func (f *FakeCache) RemovePod(pod *v1.Pod) error { return nil } -func (f *FakeCache) AddNode(node *api.Node) error { return nil } +func (f *FakeCache) AddNode(node *v1.Node) error { return nil } -func (f *FakeCache) UpdateNode(oldNode, newNode *api.Node) error { return nil } +func (f *FakeCache) UpdateNode(oldNode, newNode *v1.Node) error { return nil } -func (f *FakeCache) RemoveNode(node *api.Node) error { return nil } +func (f *FakeCache) RemoveNode(node *v1.Node) error { return nil } func (f *FakeCache) UpdateNodeNameToInfoMap(infoMap map[string]*schedulercache.NodeInfo) error { return nil } -func (f *FakeCache) List(s labels.Selector) ([]*api.Pod, error) { return nil, nil } +func (f *FakeCache) List(s labels.Selector) ([]*v1.Pod, error) { return nil, nil } diff --git a/plugin/pkg/scheduler/testing/pods_to_cache.go b/plugin/pkg/scheduler/testing/pods_to_cache.go index 586760bf916..c5a96fde11e 100644 --- a/plugin/pkg/scheduler/testing/pods_to_cache.go +++ b/plugin/pkg/scheduler/testing/pods_to_cache.go @@ -17,35 +17,35 @@ limitations under the License. package schedulercache import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) // PodsToCache is used for testing -type PodsToCache []*api.Pod +type PodsToCache []*v1.Pod -func (p PodsToCache) AssumePod(pod *api.Pod) error { return nil } +func (p PodsToCache) AssumePod(pod *v1.Pod) error { return nil } -func (p PodsToCache) ForgetPod(pod *api.Pod) error { return nil } +func (p PodsToCache) ForgetPod(pod *v1.Pod) error { return nil } -func (p PodsToCache) AddPod(pod *api.Pod) error { return nil } +func (p PodsToCache) AddPod(pod *v1.Pod) error { return nil } -func (p PodsToCache) UpdatePod(oldPod, newPod *api.Pod) error { return nil } +func (p PodsToCache) UpdatePod(oldPod, newPod *v1.Pod) error { return nil } -func (p PodsToCache) RemovePod(pod *api.Pod) error { return nil } +func (p PodsToCache) RemovePod(pod *v1.Pod) error { return nil } -func (p PodsToCache) AddNode(node *api.Node) error { return nil } +func (p PodsToCache) AddNode(node *v1.Node) error { return nil } -func (p PodsToCache) UpdateNode(oldNode, newNode *api.Node) error { return nil } +func (p PodsToCache) UpdateNode(oldNode, newNode *v1.Node) error { return nil } -func (p PodsToCache) RemoveNode(node *api.Node) error { return nil } +func (p PodsToCache) RemoveNode(node *v1.Node) error { return nil } func (p PodsToCache) UpdateNodeNameToInfoMap(infoMap map[string]*schedulercache.NodeInfo) error { return nil } -func (p PodsToCache) List(s labels.Selector) (selected []*api.Pod, err error) { +func (p PodsToCache) List(s labels.Selector) (selected []*v1.Pod, err error) { for _, pod := range p { if s.Matches(labels.Set(pod.Labels)) { selected = append(selected, pod) diff --git a/test/e2e/BUILD b/test/e2e/BUILD index 3b29763f3a4..bd7bafd04e7 100644 --- a/test/e2e/BUILD +++ b/test/e2e/BUILD @@ -117,27 +117,28 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/annotations:go_default_library", "//pkg/api/errors:go_default_library", - "//pkg/api/pod:go_default_library", "//pkg/api/resource:go_default_library", - "//pkg/api/service:go_default_library", "//pkg/api/unversioned:go_default_library", "//pkg/api/v1:go_default_library", + "//pkg/api/v1/pod:go_default_library", + "//pkg/api/v1/service:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/apis/apps:go_default_library", - "//pkg/apis/autoscaling:go_default_library", + "//pkg/apis/apps/v1beta1:go_default_library", + "//pkg/apis/autoscaling/v1:go_default_library", "//pkg/apis/batch:go_default_library", + "//pkg/apis/batch/v1:go_default_library", "//pkg/apis/batch/v2alpha1:go_default_library", "//pkg/apis/extensions:go_default_library", "//pkg/apis/extensions/v1beta1:go_default_library", - "//pkg/apis/storage:go_default_library", - "//pkg/apis/storage/util:go_default_library", + "//pkg/apis/storage/v1beta1:go_default_library", + "//pkg/apis/storage/v1beta1/util:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/transport:go_default_library", - "//pkg/client/unversioned:go_default_library", "//pkg/client/unversioned/clientcmd:go_default_library", "//pkg/client/unversioned/clientcmd/api:go_default_library", "//pkg/cloudprovider/providers/aws:go_default_library", @@ -225,8 +226,8 @@ go_library( tags = ["automanaged"], visibility = ["//visibility:private"], deps = [ - "//pkg/api:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/metrics:go_default_library", "//test/e2e/framework:go_default_library", "//vendor:github.com/onsi/ginkgo", diff --git a/test/e2e/addon_update.go b/test/e2e/addon_update.go index 50aef73444a..0ebe73af989 100644 --- a/test/e2e/addon_update.go +++ b/test/e2e/addon_update.go @@ -25,8 +25,8 @@ import ( "time" "golang.org/x/crypto/ssh" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" @@ -205,7 +205,7 @@ spec: const ( addonTestPollInterval = 3 * time.Second addonTestPollTimeout = 5 * time.Minute - defaultNsName = api.NamespaceDefault + defaultNsName = v1.NamespaceDefault addonNsName = "kube-system" ) diff --git a/test/e2e/autoscaling_utils.go b/test/e2e/autoscaling_utils.go index ce060acaf48..7b7ff7eafa6 100644 --- a/test/e2e/autoscaling_utils.go +++ b/test/e2e/autoscaling_utils.go @@ -21,8 +21,9 @@ import ( "strconv" "time" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/test/e2e/framework" testutils "k8s.io/kubernetes/test/utils" @@ -97,7 +98,7 @@ cpuLimit argument is in millicores, cpuLimit is a maximum amount of cpu that can func newResourceConsumer(name, kind string, replicas, initCPUTotal, initMemoryTotal, initCustomMetric, consumptionTimeInSeconds, requestSizeInMillicores, requestSizeInMegabytes int, requestSizeCustomMetric int, cpuLimit, memLimit int64, f *framework.Framework) *ResourceConsumer { - runServiceAndWorkloadForResourceConsumer(f.ClientSet, f.Namespace.Name, name, kind, replicas, cpuLimit, memLimit) + runServiceAndWorkloadForResourceConsumer(f.ClientSet, f.InternalClientset, f.Namespace.Name, name, kind, replicas, cpuLimit, memLimit) rc := &ResourceConsumer{ name: name, controllerName: name + "-ctrl", @@ -303,20 +304,20 @@ func (rc *ResourceConsumer) CleanUp() { rc.stopCustomMetric <- 0 // Wait some time to ensure all child goroutines are finished. time.Sleep(10 * time.Second) - framework.ExpectNoError(framework.DeleteRCAndPods(rc.framework.ClientSet, rc.framework.Namespace.Name, rc.name)) + framework.ExpectNoError(framework.DeleteRCAndPods(rc.framework.ClientSet, rc.framework.InternalClientset, rc.framework.Namespace.Name, rc.name)) framework.ExpectNoError(rc.framework.ClientSet.Core().Services(rc.framework.Namespace.Name).Delete(rc.name, nil)) - framework.ExpectNoError(framework.DeleteRCAndPods(rc.framework.ClientSet, rc.framework.Namespace.Name, rc.controllerName)) + framework.ExpectNoError(framework.DeleteRCAndPods(rc.framework.ClientSet, rc.framework.InternalClientset, rc.framework.Namespace.Name, rc.controllerName)) framework.ExpectNoError(rc.framework.ClientSet.Core().Services(rc.framework.Namespace.Name).Delete(rc.controllerName, nil)) } -func runServiceAndWorkloadForResourceConsumer(c clientset.Interface, ns, name, kind string, replicas int, cpuLimitMillis, memLimitMb int64) { +func runServiceAndWorkloadForResourceConsumer(c clientset.Interface, internalClient internalclientset.Interface, ns, name, kind string, replicas int, cpuLimitMillis, memLimitMb int64) { By(fmt.Sprintf("Running consuming RC %s via %s with %v replicas", name, kind, replicas)) - _, err := c.Core().Services(ns).Create(&api.Service{ - ObjectMeta: api.ObjectMeta{ + _, err := c.Core().Services(ns).Create(&v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{{ + Spec: v1.ServiceSpec{ + Ports: []v1.ServicePort{{ Port: port, TargetPort: intstr.FromInt(targetPort), }}, @@ -329,16 +330,17 @@ func runServiceAndWorkloadForResourceConsumer(c clientset.Interface, ns, name, k framework.ExpectNoError(err) rcConfig := testutils.RCConfig{ - Client: c, - Image: resourceConsumerImage, - Name: name, - Namespace: ns, - Timeout: timeoutRC, - Replicas: replicas, - CpuRequest: cpuLimitMillis, - CpuLimit: cpuLimitMillis, - MemRequest: memLimitMb * 1024 * 1024, // MemLimit is in bytes - MemLimit: memLimitMb * 1024 * 1024, + Client: c, + InternalClient: internalClient, + Image: resourceConsumerImage, + Name: name, + Namespace: ns, + Timeout: timeoutRC, + Replicas: replicas, + CpuRequest: cpuLimitMillis, + CpuLimit: cpuLimitMillis, + MemRequest: memLimitMb * 1024 * 1024, // MemLimit is in bytes + MemLimit: memLimitMb * 1024 * 1024, } switch kind { @@ -364,12 +366,12 @@ func runServiceAndWorkloadForResourceConsumer(c clientset.Interface, ns, name, k By(fmt.Sprintf("Running controller")) controllerName := name + "-ctrl" - _, err = c.Core().Services(ns).Create(&api.Service{ - ObjectMeta: api.ObjectMeta{ + _, err = c.Core().Services(ns).Create(&v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: controllerName, }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{{ + Spec: v1.ServiceSpec{ + Ports: []v1.ServicePort{{ Port: port, TargetPort: intstr.FromInt(targetPort), }}, @@ -381,7 +383,7 @@ func runServiceAndWorkloadForResourceConsumer(c clientset.Interface, ns, name, k }) framework.ExpectNoError(err) - dnsClusterFirst := api.DNSClusterFirst + dnsClusterFirst := v1.DNSClusterFirst controllerRcConfig := testutils.RCConfig{ Client: c, Image: resourceConsumerControllerImage, diff --git a/test/e2e/batch_v1_jobs.go b/test/e2e/batch_v1_jobs.go index 71d582f1191..82b9cde6cb9 100644 --- a/test/e2e/batch_v1_jobs.go +++ b/test/e2e/batch_v1_jobs.go @@ -25,8 +25,10 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/apis/batch" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + batchinternal "k8s.io/kubernetes/pkg/apis/batch" + batch "k8s.io/kubernetes/pkg/apis/batch/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/wait" @@ -53,7 +55,7 @@ var _ = framework.KubeDescribe("V1Job", func() { // Simplest case: all pods succeed promptly It("should run a job to completion when tasks succeed", func() { By("Creating a job") - job := newTestV1Job("succeed", "all-succeed", api.RestartPolicyNever, parallelism, completions) + job := newTestV1Job("succeed", "all-succeed", v1.RestartPolicyNever, parallelism, completions) job, err := createV1Job(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -72,7 +74,7 @@ var _ = framework.KubeDescribe("V1Job", func() { // up to 5 minutes between restarts, making test timeouts // due to successive failures too likely with a reasonable // test timeout. - job := newTestV1Job("failOnce", "fail-once-local", api.RestartPolicyOnFailure, parallelism, completions) + job := newTestV1Job("failOnce", "fail-once-local", v1.RestartPolicyOnFailure, parallelism, completions) job, err := createV1Job(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -90,7 +92,7 @@ var _ = framework.KubeDescribe("V1Job", func() { // Worst case analysis: 15 failures, each taking 1 minute to // run due to some slowness, 1 in 2^15 chance of happening, // causing test flake. Should be very rare. - job := newTestV1Job("randomlySucceedOrFail", "rand-non-local", api.RestartPolicyNever, parallelism, completions) + job := newTestV1Job("randomlySucceedOrFail", "rand-non-local", v1.RestartPolicyNever, parallelism, completions) job, err := createV1Job(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -101,7 +103,7 @@ var _ = framework.KubeDescribe("V1Job", func() { It("should keep restarting failed pods", func() { By("Creating a job") - job := newTestV1Job("fail", "all-fail", api.RestartPolicyNever, parallelism, completions) + job := newTestV1Job("fail", "all-fail", v1.RestartPolicyNever, parallelism, completions) job, err := createV1Job(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -119,7 +121,7 @@ var _ = framework.KubeDescribe("V1Job", func() { startParallelism := int32(1) endParallelism := int32(2) By("Creating a job") - job := newTestV1Job("notTerminate", "scale-up", api.RestartPolicyNever, startParallelism, completions) + job := newTestV1Job("notTerminate", "scale-up", v1.RestartPolicyNever, startParallelism, completions) job, err := createV1Job(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -128,7 +130,7 @@ var _ = framework.KubeDescribe("V1Job", func() { Expect(err).NotTo(HaveOccurred()) By("scale job up") - scaler, err := kubectl.ScalerFor(batch.Kind("Job"), f.ClientSet) + scaler, err := kubectl.ScalerFor(batchinternal.Kind("Job"), f.InternalClientset) Expect(err).NotTo(HaveOccurred()) waitForScale := kubectl.NewRetryParams(5*time.Second, 1*time.Minute) waitForReplicas := kubectl.NewRetryParams(5*time.Second, 5*time.Minute) @@ -144,7 +146,7 @@ var _ = framework.KubeDescribe("V1Job", func() { startParallelism := int32(2) endParallelism := int32(1) By("Creating a job") - job := newTestV1Job("notTerminate", "scale-down", api.RestartPolicyNever, startParallelism, completions) + job := newTestV1Job("notTerminate", "scale-down", v1.RestartPolicyNever, startParallelism, completions) job, err := createV1Job(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -153,7 +155,7 @@ var _ = framework.KubeDescribe("V1Job", func() { Expect(err).NotTo(HaveOccurred()) By("scale job down") - scaler, err := kubectl.ScalerFor(batch.Kind("Job"), f.ClientSet) + scaler, err := kubectl.ScalerFor(batchinternal.Kind("Job"), f.InternalClientset) Expect(err).NotTo(HaveOccurred()) waitForScale := kubectl.NewRetryParams(5*time.Second, 1*time.Minute) waitForReplicas := kubectl.NewRetryParams(5*time.Second, 5*time.Minute) @@ -167,7 +169,7 @@ var _ = framework.KubeDescribe("V1Job", func() { It("should delete a job", func() { By("Creating a job") - job := newTestV1Job("notTerminate", "foo", api.RestartPolicyNever, parallelism, completions) + job := newTestV1Job("notTerminate", "foo", v1.RestartPolicyNever, parallelism, completions) job, err := createV1Job(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -176,7 +178,7 @@ var _ = framework.KubeDescribe("V1Job", func() { Expect(err).NotTo(HaveOccurred()) By("delete a job") - reaper, err := kubectl.ReaperFor(batch.Kind("Job"), f.ClientSet) + reaper, err := kubectl.ReaperFor(batchinternal.Kind("Job"), f.InternalClientset) Expect(err).NotTo(HaveOccurred()) timeout := 1 * time.Minute err = reaper.Stop(f.Namespace.Name, job.Name, timeout, api.NewDeleteOptions(0)) @@ -190,7 +192,7 @@ var _ = framework.KubeDescribe("V1Job", func() { It("should fail a job", func() { By("Creating a job") - job := newTestV1Job("notTerminate", "foo", api.RestartPolicyNever, parallelism, completions) + job := newTestV1Job("notTerminate", "foo", v1.RestartPolicyNever, parallelism, completions) activeDeadlineSeconds := int64(10) job.Spec.ActiveDeadlineSeconds = &activeDeadlineSeconds job, err := createV1Job(f.ClientSet, f.Namespace.Name, job) @@ -215,34 +217,34 @@ var _ = framework.KubeDescribe("V1Job", func() { }) // newTestV1Job returns a job which does one of several testing behaviors. -func newTestV1Job(behavior, name string, rPol api.RestartPolicy, parallelism, completions int32) *batch.Job { +func newTestV1Job(behavior, name string, rPol v1.RestartPolicy, parallelism, completions int32) *batch.Job { job := &batch.Job{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, Spec: batch.JobSpec{ Parallelism: ¶llelism, Completions: &completions, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"somekey": "somevalue"}, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ RestartPolicy: rPol, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: "data", - VolumeSource: api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + VolumeSource: v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "c", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { MountPath: "/data", Name: "data", @@ -289,21 +291,21 @@ func updateV1Job(c clientset.Interface, ns string, job *batch.Job) (*batch.Job, } func deleteV1Job(c clientset.Interface, ns, name string) error { - return c.Batch().Jobs(ns).Delete(name, api.NewDeleteOptions(0)) + return c.Batch().Jobs(ns).Delete(name, v1.NewDeleteOptions(0)) } // Wait for all pods to become Running. Only use when pods will run for a long time, or it will be racy. func waitForAllPodsRunningV1(c clientset.Interface, ns, jobName string, parallelism int32) error { label := labels.SelectorFromSet(labels.Set(map[string]string{v1JobSelectorKey: jobName})) return wait.Poll(framework.Poll, v1JobTimeout, func() (bool, error) { - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := c.Core().Pods(ns).List(options) if err != nil { return false, err } count := int32(0) for _, p := range pods.Items { - if p.Status.Phase == api.PodRunning { + if p.Status.Phase == v1.PodRunning { count++ } } @@ -330,7 +332,7 @@ func waitForV1JobFail(c clientset.Interface, ns, jobName string, timeout time.Du return false, err } for _, c := range curr.Status.Conditions { - if c.Type == batch.JobFailed && c.Status == api.ConditionTrue { + if c.Type == batch.JobFailed && c.Status == v1.ConditionTrue { return true, nil } } diff --git a/test/e2e/cadvisor.go b/test/e2e/cadvisor.go index 27876a6314e..4e099f9e3fa 100644 --- a/test/e2e/cadvisor.go +++ b/test/e2e/cadvisor.go @@ -20,8 +20,8 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" @@ -39,7 +39,7 @@ var _ = framework.KubeDescribe("Cadvisor", func() { func CheckCadvisorHealthOnAllNodes(c clientset.Interface, timeout time.Duration) { // It should be OK to list unschedulable Nodes here. By("getting list of nodes") - nodeList, err := c.Core().Nodes().List(api.ListOptions{}) + nodeList, err := c.Core().Nodes().List(v1.ListOptions{}) framework.ExpectNoError(err) var errors []error diff --git a/test/e2e/cluster_logging_es.go b/test/e2e/cluster_logging_es.go index b1b8c5f0185..e37656e64fd 100644 --- a/test/e2e/cluster_logging_es.go +++ b/test/e2e/cluster_logging_es.go @@ -24,6 +24,7 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/test/e2e/framework" @@ -52,7 +53,7 @@ var _ = framework.KubeDescribe("Cluster level logging using Elasticsearch [Featu By("Running synthetic logger") createSynthLogger(f, expectedLinesCount) - defer f.PodClient().Delete(synthLoggerPodName, &api.DeleteOptions{}) + defer f.PodClient().Delete(synthLoggerPodName, &v1.DeleteOptions{}) err = framework.WaitForPodSuccessInNamespace(f.ClientSet, synthLoggerPodName, f.Namespace.Name) framework.ExpectNoError(err, fmt.Sprintf("Should've successfully waited for pod %s to succeed", synthLoggerPodName)) @@ -101,7 +102,7 @@ func checkElasticsearchReadiness(f *framework.Framework) error { // Wait for the Elasticsearch pods to enter the running state. By("Checking to make sure the Elasticsearch pods are running") label := labels.SelectorFromSet(labels.Set(map[string]string{"k8s-app": "elasticsearch-logging"})) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := f.ClientSet.Core().Pods(api.NamespaceSystem).List(options) Expect(err).NotTo(HaveOccurred()) for _, pod := range pods.Items { diff --git a/test/e2e/cluster_logging_gcl.go b/test/e2e/cluster_logging_gcl.go index db84062b7e9..9d5e65687ee 100644 --- a/test/e2e/cluster_logging_gcl.go +++ b/test/e2e/cluster_logging_gcl.go @@ -23,7 +23,7 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/json" "k8s.io/kubernetes/test/e2e/framework" @@ -42,7 +42,7 @@ var _ = framework.KubeDescribe("Cluster level logging using GCL", func() { It("should check that logs from containers are ingested in GCL", func() { By("Running synthetic logger") createSynthLogger(f, expectedLinesCount) - defer f.PodClient().Delete(synthLoggerPodName, &api.DeleteOptions{}) + defer f.PodClient().Delete(synthLoggerPodName, &v1.DeleteOptions{}) err := framework.WaitForPodSuccessInNamespace(f.ClientSet, synthLoggerPodName, f.Namespace.Name) framework.ExpectNoError(err, fmt.Sprintf("Should've successfully waited for pod %s to succeed", synthLoggerPodName)) diff --git a/test/e2e/cluster_logging_utils.go b/test/e2e/cluster_logging_utils.go index 2dfa0205255..950b789bf45 100644 --- a/test/e2e/cluster_logging_utils.go +++ b/test/e2e/cluster_logging_utils.go @@ -22,6 +22,7 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/test/e2e/framework" ) @@ -41,14 +42,14 @@ const ( ) func createSynthLogger(f *framework.Framework, linesCount int) { - f.PodClient().Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + f.PodClient().Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: synthLoggerPodName, Namespace: f.Namespace.Name, }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyOnFailure, - Containers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyOnFailure, + Containers: []v1.Container{ { Name: synthLoggerPodName, Image: "gcr.io/google_containers/busybox:1.24", @@ -72,7 +73,7 @@ func reportLogsFromFluentdPod(f *framework.Framework) error { } label := labels.SelectorFromSet(labels.Set(map[string]string{"k8s-app": "fluentd-logging"})) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} fluentdPods, err := f.ClientSet.Core().Pods(api.NamespaceSystem).List(options) for _, fluentdPod := range fluentdPods.Items { diff --git a/test/e2e/cluster_size_autoscaling.go b/test/e2e/cluster_size_autoscaling.go index 6f9684ef68a..e26391d54dc 100644 --- a/test/e2e/cluster_size_autoscaling.go +++ b/test/e2e/cluster_size_autoscaling.go @@ -26,8 +26,8 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/test/e2e/framework" @@ -63,8 +63,8 @@ var _ = framework.KubeDescribe("Cluster size autoscaling [Slow]", func() { nodes := framework.GetReadySchedulableNodesOrDie(f.ClientSet) nodeCount = len(nodes.Items) Expect(nodeCount).NotTo(BeZero()) - cpu := nodes.Items[0].Status.Capacity[api.ResourceCPU] - mem := nodes.Items[0].Status.Capacity[api.ResourceMemory] + cpu := nodes.Items[0].Status.Capacity[v1.ResourceCPU] + mem := nodes.Items[0].Status.Capacity[v1.ResourceMemory] coresPerNode = int((&cpu).MilliValue() / 1000) memCapacityMb = int((&mem).Value() / 1024 / 1024) @@ -98,7 +98,7 @@ var _ = framework.KubeDescribe("Cluster size autoscaling [Slow]", func() { It("shouldn't increase cluster size if pending pod is too large [Feature:ClusterSizeAutoscalingScaleUp]", func() { By("Creating unschedulable pod") ReserveMemory(f, "memory-reservation", 1, memCapacityMb, false) - defer framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, "memory-reservation") + defer framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, "memory-reservation") By("Waiting for scale up hoping it won't happen") // Verfiy, that the appropreate event was generated. @@ -106,7 +106,7 @@ var _ = framework.KubeDescribe("Cluster size autoscaling [Slow]", func() { EventsLoop: for start := time.Now(); time.Since(start) < scaleUpTimeout; time.Sleep(20 * time.Second) { By("Waiting for NotTriggerScaleUp event") - events, err := f.ClientSet.Core().Events(f.Namespace.Name).List(api.ListOptions{}) + events, err := f.ClientSet.Core().Events(f.Namespace.Name).List(v1.ListOptions{}) framework.ExpectNoError(err) for _, e := range events.Items { @@ -125,7 +125,7 @@ var _ = framework.KubeDescribe("Cluster size autoscaling [Slow]", func() { It("should increase cluster size if pending pods are small [Feature:ClusterSizeAutoscalingScaleUp]", func() { ReserveMemory(f, "memory-reservation", 100, nodeCount*memCapacityMb, false) - defer framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, "memory-reservation") + defer framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, "memory-reservation") // Verify, that cluster size is increased framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet, @@ -144,7 +144,7 @@ var _ = framework.KubeDescribe("Cluster size autoscaling [Slow]", func() { glog.Infof("Not enabling cluster autoscaler for the node pool (on purpose).") ReserveMemory(f, "memory-reservation", 100, nodeCount*memCapacityMb, false) - defer framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, "memory-reservation") + defer framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, "memory-reservation") // Verify, that cluster size is increased framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet, @@ -166,7 +166,7 @@ var _ = framework.KubeDescribe("Cluster size autoscaling [Slow]", func() { It("should increase cluster size if pods are pending due to host port conflict [Feature:ClusterSizeAutoscalingScaleUp]", func() { CreateHostPortPods(f, "host-port", nodeCount+2, false) - defer framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, "host-port") + defer framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, "host-port") framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet, func(size int) bool { return size >= nodeCount+2 }, scaleUpTimeout)) @@ -218,7 +218,7 @@ var _ = framework.KubeDescribe("Cluster size autoscaling [Slow]", func() { func(size int) bool { return size >= nodeCount+1 }, scaleUpTimeout)) framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c)) - framework.ExpectNoError(framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, "node-selector")) + framework.ExpectNoError(framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, "node-selector")) }) It("should scale up correct target pool [Feature:ClusterSizeAutoscalingScaleUp]", func() { @@ -233,7 +233,7 @@ var _ = framework.KubeDescribe("Cluster size autoscaling [Slow]", func() { By("Creating rc with 2 pods too big to fit default-pool but fitting extra-pool") ReserveMemory(f, "memory-reservation", 2, 2*memCapacityMb, false) - defer framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, "memory-reservation") + defer framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, "memory-reservation") // Apparently GKE master is restarted couple minutes after the node pool is added // reseting all the timers in scale down code. Adding 5 extra minutes to workaround @@ -458,14 +458,15 @@ func CreateNodeSelectorPods(f *framework.Framework, id string, replicas int, nod By(fmt.Sprintf("Running RC which reserves host port and defines node selector")) config := &testutils.RCConfig{ - Client: f.ClientSet, - Name: "node-selector", - Namespace: f.Namespace.Name, - Timeout: defaultTimeout, - Image: framework.GetPauseImageName(f.ClientSet), - Replicas: replicas, - HostPorts: map[string]int{"port1": 4321}, - NodeSelector: map[string]string{"cluster-autoscaling-test.special-node": "true"}, + Client: f.ClientSet, + InternalClient: f.InternalClientset, + Name: "node-selector", + Namespace: f.Namespace.Name, + Timeout: defaultTimeout, + Image: framework.GetPauseImageName(f.ClientSet), + Replicas: replicas, + HostPorts: map[string]int{"port1": 4321}, + NodeSelector: map[string]string{"cluster-autoscaling-test.special-node": "true"}, } err := framework.RunRC(*config) if expectRunning { @@ -476,13 +477,14 @@ func CreateNodeSelectorPods(f *framework.Framework, id string, replicas int, nod func CreateHostPortPods(f *framework.Framework, id string, replicas int, expectRunning bool) { By(fmt.Sprintf("Running RC which reserves host port")) config := &testutils.RCConfig{ - Client: f.ClientSet, - Name: id, - Namespace: f.Namespace.Name, - Timeout: defaultTimeout, - Image: framework.GetPauseImageName(f.ClientSet), - Replicas: replicas, - HostPorts: map[string]int{"port1": 4321}, + Client: f.ClientSet, + InternalClient: f.InternalClientset, + Name: id, + Namespace: f.Namespace.Name, + Timeout: defaultTimeout, + Image: framework.GetPauseImageName(f.ClientSet), + Replicas: replicas, + HostPorts: map[string]int{"port1": 4321}, } err := framework.RunRC(*config) if expectRunning { @@ -494,13 +496,14 @@ func ReserveCpu(f *framework.Framework, id string, replicas, millicores int) { By(fmt.Sprintf("Running RC which reserves %v millicores", millicores)) request := int64(millicores / replicas) config := &testutils.RCConfig{ - Client: f.ClientSet, - Name: id, - Namespace: f.Namespace.Name, - Timeout: defaultTimeout, - Image: framework.GetPauseImageName(f.ClientSet), - Replicas: replicas, - CpuRequest: request, + Client: f.ClientSet, + InternalClient: f.InternalClientset, + Name: id, + Namespace: f.Namespace.Name, + Timeout: defaultTimeout, + Image: framework.GetPauseImageName(f.ClientSet), + Replicas: replicas, + CpuRequest: request, } framework.ExpectNoError(framework.RunRC(*config)) } @@ -509,13 +512,14 @@ func ReserveMemory(f *framework.Framework, id string, replicas, megabytes int, e By(fmt.Sprintf("Running RC which reserves %v MB of memory", megabytes)) request := int64(1024 * 1024 * megabytes / replicas) config := &testutils.RCConfig{ - Client: f.ClientSet, - Name: id, - Namespace: f.Namespace.Name, - Timeout: defaultTimeout, - Image: framework.GetPauseImageName(f.ClientSet), - Replicas: replicas, - MemRequest: request, + Client: f.ClientSet, + InternalClient: f.InternalClientset, + Name: id, + Namespace: f.Namespace.Name, + Timeout: defaultTimeout, + Image: framework.GetPauseImageName(f.ClientSet), + Replicas: replicas, + MemRequest: request, } err := framework.RunRC(*config) if expectRunning { @@ -526,9 +530,9 @@ func ReserveMemory(f *framework.Framework, id string, replicas, megabytes int, e // WaitForClusterSize waits until the cluster size matches the given function. func WaitForClusterSizeFunc(c clientset.Interface, sizeFunc func(int) bool, timeout time.Duration) error { for start := time.Now(); time.Since(start) < timeout; time.Sleep(20 * time.Second) { - nodes, err := c.Core().Nodes().List(api.ListOptions{FieldSelector: fields.Set{ + nodes, err := c.Core().Nodes().List(v1.ListOptions{FieldSelector: fields.Set{ "spec.unschedulable": "false", - }.AsSelector()}) + }.AsSelector().String()}) if err != nil { glog.Warningf("Failed to list nodes: %v", err) continue @@ -536,8 +540,8 @@ func WaitForClusterSizeFunc(c clientset.Interface, sizeFunc func(int) bool, time numNodes := len(nodes.Items) // Filter out not-ready nodes. - framework.FilterNodes(nodes, func(node api.Node) bool { - return framework.IsNodeConditionSetAsExpected(&node, api.NodeReady, true) + framework.FilterNodes(nodes, func(node v1.Node) bool { + return framework.IsNodeConditionSetAsExpected(&node, v1.NodeReady, true) }) numReady := len(nodes.Items) @@ -553,7 +557,7 @@ func WaitForClusterSizeFunc(c clientset.Interface, sizeFunc func(int) bool, time func waitForAllCaPodsReadyInNamespace(f *framework.Framework, c clientset.Interface) error { var notready []string for start := time.Now(); time.Now().Before(start.Add(scaleUpTimeout)); time.Sleep(20 * time.Second) { - pods, err := c.Core().Pods(f.Namespace.Name).List(api.ListOptions{}) + pods, err := c.Core().Pods(f.Namespace.Name).List(v1.ListOptions{}) if err != nil { return fmt.Errorf("failed to get pods: %v", err) } @@ -561,16 +565,16 @@ func waitForAllCaPodsReadyInNamespace(f *framework.Framework, c clientset.Interf for _, pod := range pods.Items { ready := false for _, c := range pod.Status.Conditions { - if c.Type == api.PodReady && c.Status == api.ConditionTrue { + if c.Type == v1.PodReady && c.Status == v1.ConditionTrue { ready = true } } // Failed pods in this context generally mean that they have been // double scheduled onto a node, but then failed a constraint check. - if pod.Status.Phase == api.PodFailed { + if pod.Status.Phase == v1.PodFailed { glog.Warningf("Pod has failed: %v", pod) } - if !ready && pod.Status.Phase != api.PodFailed { + if !ready && pod.Status.Phase != v1.PodFailed { notready = append(notready, pod.Name) } } diff --git a/test/e2e/cluster_upgrade.go b/test/e2e/cluster_upgrade.go index 8fd43d5b51a..2e34ef45430 100644 --- a/test/e2e/cluster_upgrade.go +++ b/test/e2e/cluster_upgrade.go @@ -21,8 +21,8 @@ import ( "path" "strings" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/chaosmonkey" "k8s.io/kubernetes/test/e2e/framework" @@ -152,11 +152,11 @@ func testService(f *framework.Framework, sem *chaosmonkey.Semaphore, testDuringD By("creating a TCP service " + serviceName + " with type=LoadBalancer in namespace " + f.Namespace.Name) // TODO it's weird that we have to do this and then wait WaitForLoadBalancer which changes // tcpService. - tcpService := jig.CreateTCPServiceOrFail(f.Namespace.Name, func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer + tcpService := jig.CreateTCPServiceOrFail(f.Namespace.Name, func(s *v1.Service) { + s.Spec.Type = v1.ServiceTypeLoadBalancer }) tcpService = jig.WaitForLoadBalancerOrFail(f.Namespace.Name, tcpService.Name, loadBalancerCreateTimeoutDefault) - jig.SanityCheckService(tcpService, api.ServiceTypeLoadBalancer) + jig.SanityCheckService(tcpService, v1.ServiceTypeLoadBalancer) // Get info to hit it with tcpIngressIP := getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]) @@ -188,7 +188,7 @@ func testService(f *framework.Framework, sem *chaosmonkey.Semaphore, testDuringD // Sanity check and hit it once more By("hitting the pod through the service's LoadBalancer") jig.TestReachableHTTP(tcpIngressIP, svcPort, loadBalancerLagTimeoutDefault) - jig.SanityCheckService(tcpService, api.ServiceTypeLoadBalancer) + jig.SanityCheckService(tcpService, v1.ServiceTypeLoadBalancer) } func checkMasterVersion(c clientset.Interface, want string) error { diff --git a/test/e2e/common/BUILD b/test/e2e/common/BUILD index 9a3ed2ef848..29e86bad36c 100644 --- a/test/e2e/common/BUILD +++ b/test/e2e/common/BUILD @@ -33,13 +33,14 @@ go_library( ], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/api/v1/pod:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/unversioned:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/conditions:go_default_library", "//pkg/kubelet:go_default_library", "//pkg/kubelet/events:go_default_library", "//pkg/kubelet/sysctl:go_default_library", diff --git a/test/e2e/common/configmap.go b/test/e2e/common/configmap.go index 47780ff977f..20d7a0aa80b 100644 --- a/test/e2e/common/configmap.go +++ b/test/e2e/common/configmap.go @@ -21,7 +21,7 @@ import ( "os" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -79,8 +79,8 @@ var _ = framework.KubeDescribe("ConfigMap", func() { volumeMountPath := "/etc/configmap-volume" containerName := "configmap-volume-test" - configMap := &api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ + configMap := &v1.ConfigMap{ + ObjectMeta: v1.ObjectMeta{ Namespace: f.Namespace.Name, Name: name, }, @@ -95,29 +95,29 @@ var _ = framework.KubeDescribe("ConfigMap", func() { framework.Failf("unable to create test configMap %s: %v", configMap.Name, err) } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-configmaps-" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - ConfigMap: &api.ConfigMapVolumeSource{ - LocalObjectReference: api.LocalObjectReference{ + VolumeSource: v1.VolumeSource{ + ConfigMap: &v1.ConfigMapVolumeSource{ + LocalObjectReference: v1.LocalObjectReference{ Name: name, }, }, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: containerName, Image: "gcr.io/google_containers/mounttest:0.7", Command: []string{"/mt", "--break_on_expected_content=false", "--retry_time=120", "--file_content_in_loop=/etc/configmap-volume/data-1"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: volumeMountPath, @@ -126,7 +126,7 @@ var _ = framework.KubeDescribe("ConfigMap", func() { }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } By("Creating the pod") @@ -157,22 +157,22 @@ var _ = framework.KubeDescribe("ConfigMap", func() { framework.Failf("unable to create test configMap %s: %v", configMap.Name, err) } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-configmaps-" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "env-test", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"sh", "-c", "env"}, - Env: []api.EnvVar{ + Env: []v1.EnvVar{ { Name: "CONFIG_DATA_1", - ValueFrom: &api.EnvVarSource{ - ConfigMapKeyRef: &api.ConfigMapKeySelector{ - LocalObjectReference: api.LocalObjectReference{ + ValueFrom: &v1.EnvVarSource{ + ConfigMapKeyRef: &v1.ConfigMapKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ Name: name, }, Key: "data-1", @@ -182,7 +182,7 @@ var _ = framework.KubeDescribe("ConfigMap", func() { }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } @@ -207,17 +207,17 @@ var _ = framework.KubeDescribe("ConfigMap", func() { framework.Failf("unable to create test configMap %s: %v", configMap.Name, err) } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-configmaps-" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - ConfigMap: &api.ConfigMapVolumeSource{ - LocalObjectReference: api.LocalObjectReference{ + VolumeSource: v1.VolumeSource{ + ConfigMap: &v1.ConfigMapVolumeSource{ + LocalObjectReference: v1.LocalObjectReference{ Name: name, }, }, @@ -225,21 +225,21 @@ var _ = framework.KubeDescribe("ConfigMap", func() { }, { Name: volumeName2, - VolumeSource: api.VolumeSource{ - ConfigMap: &api.ConfigMapVolumeSource{ - LocalObjectReference: api.LocalObjectReference{ + VolumeSource: v1.VolumeSource{ + ConfigMap: &v1.ConfigMapVolumeSource{ + LocalObjectReference: v1.LocalObjectReference{ Name: name, }, }, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "configmap-volume-test", Image: "gcr.io/google_containers/mounttest:0.7", Args: []string{"--file_content=/etc/configmap-volume/data-1"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: volumeMountPath, @@ -253,7 +253,7 @@ var _ = framework.KubeDescribe("ConfigMap", func() { }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } @@ -264,9 +264,9 @@ var _ = framework.KubeDescribe("ConfigMap", func() { }) }) -func newConfigMap(f *framework.Framework, name string) *api.ConfigMap { - return &api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ +func newConfigMap(f *framework.Framework, name string) *v1.ConfigMap { + return &v1.ConfigMap{ + ObjectMeta: v1.ObjectMeta{ Namespace: f.Namespace.Name, Name: name, }, @@ -292,32 +292,32 @@ func doConfigMapE2EWithoutMappings(f *framework.Framework, uid, fsGroup int64, d framework.Failf("unable to create test configMap %s: %v", configMap.Name, err) } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-configmaps-" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ - SecurityContext: &api.PodSecurityContext{}, - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + SecurityContext: &v1.PodSecurityContext{}, + Volumes: []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - ConfigMap: &api.ConfigMapVolumeSource{ - LocalObjectReference: api.LocalObjectReference{ + VolumeSource: v1.VolumeSource{ + ConfigMap: &v1.ConfigMapVolumeSource{ + LocalObjectReference: v1.LocalObjectReference{ Name: name, }, }, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "configmap-volume-test", Image: "gcr.io/google_containers/mounttest:0.7", Args: []string{ "--file_content=/etc/configmap-volume/data-1", "--file_mode=/etc/configmap-volume/data-1"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: volumeMountPath, @@ -325,7 +325,7 @@ func doConfigMapE2EWithoutMappings(f *framework.Framework, uid, fsGroup int64, d }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } @@ -353,7 +353,6 @@ func doConfigMapE2EWithoutMappings(f *framework.Framework, uid, fsGroup int64, d output = append(output, "mode of file \"/etc/configmap-volume/data-1\": "+modeString) } f.TestContainerOutput("consume configMaps", pod, 0, output) - } func doConfigMapE2EWithMappings(f *framework.Framework, uid, fsGroup int64, itemMode *int32) { @@ -371,21 +370,21 @@ func doConfigMapE2EWithMappings(f *framework.Framework, uid, fsGroup int64, item framework.Failf("unable to create test configMap %s: %v", configMap.Name, err) } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-configmaps-" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ - SecurityContext: &api.PodSecurityContext{}, - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + SecurityContext: &v1.PodSecurityContext{}, + Volumes: []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - ConfigMap: &api.ConfigMapVolumeSource{ - LocalObjectReference: api.LocalObjectReference{ + VolumeSource: v1.VolumeSource{ + ConfigMap: &v1.ConfigMapVolumeSource{ + LocalObjectReference: v1.LocalObjectReference{ Name: name, }, - Items: []api.KeyToPath{ + Items: []v1.KeyToPath{ { Key: "data-2", Path: "path/to/data-2", @@ -395,13 +394,13 @@ func doConfigMapE2EWithMappings(f *framework.Framework, uid, fsGroup int64, item }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "configmap-volume-test", Image: "gcr.io/google_containers/mounttest:0.7", Args: []string{"--file_content=/etc/configmap-volume/path/to/data-2", "--file_mode=/etc/configmap-volume/path/to/data-2"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: volumeMountPath, @@ -410,7 +409,7 @@ func doConfigMapE2EWithMappings(f *framework.Framework, uid, fsGroup int64, item }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } diff --git a/test/e2e/common/container_probe.go b/test/e2e/common/container_probe.go index 30b6fd0e94f..4a693f6bde6 100644 --- a/test/e2e/common/container_probe.go +++ b/test/e2e/common/container_probe.go @@ -20,7 +20,7 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -80,7 +80,7 @@ var _ = framework.KubeDescribe("Probing container", func() { if err != nil { return false, err } - return api.IsPodReady(p), nil + return v1.IsPodReady(p), nil }, 1*time.Minute, 1*time.Second).ShouldNot(BeTrue(), "pod should not be ready") p, err := podClient.Get(p.Name) @@ -94,20 +94,20 @@ var _ = framework.KubeDescribe("Probing container", func() { }) It("should be restarted with a exec \"cat /tmp/health\" liveness probe [Conformance]", func() { - runLivenessTest(f, &api.Pod{ - ObjectMeta: api.ObjectMeta{ + runLivenessTest(f, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "liveness-exec", Labels: map[string]string{"test": "liveness"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "liveness", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"/bin/sh", "-c", "echo ok >/tmp/health; sleep 10; rm -rf /tmp/health; sleep 600"}, - LivenessProbe: &api.Probe{ - Handler: api.Handler{ - Exec: &api.ExecAction{ + LivenessProbe: &v1.Probe{ + Handler: v1.Handler{ + Exec: &v1.ExecAction{ Command: []string{"cat", "/tmp/health"}, }, }, @@ -121,20 +121,20 @@ var _ = framework.KubeDescribe("Probing container", func() { }) It("should *not* be restarted with a exec \"cat /tmp/health\" liveness probe [Conformance]", func() { - runLivenessTest(f, &api.Pod{ - ObjectMeta: api.ObjectMeta{ + runLivenessTest(f, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "liveness-exec", Labels: map[string]string{"test": "liveness"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "liveness", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"/bin/sh", "-c", "echo ok >/tmp/health; sleep 600"}, - LivenessProbe: &api.Probe{ - Handler: api.Handler{ - Exec: &api.ExecAction{ + LivenessProbe: &v1.Probe{ + Handler: v1.Handler{ + Exec: &v1.ExecAction{ Command: []string{"cat", "/tmp/health"}, }, }, @@ -148,20 +148,20 @@ var _ = framework.KubeDescribe("Probing container", func() { }) It("should be restarted with a /healthz http liveness probe [Conformance]", func() { - runLivenessTest(f, &api.Pod{ - ObjectMeta: api.ObjectMeta{ + runLivenessTest(f, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "liveness-http", Labels: map[string]string{"test": "liveness"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "liveness", Image: "gcr.io/google_containers/liveness:e2e", Command: []string{"/server"}, - LivenessProbe: &api.Probe{ - Handler: api.Handler{ - HTTPGet: &api.HTTPGetAction{ + LivenessProbe: &v1.Probe{ + Handler: v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Path: "/healthz", Port: intstr.FromInt(8080), }, @@ -177,20 +177,20 @@ var _ = framework.KubeDescribe("Probing container", func() { // Slow by design (5 min) It("should have monotonically increasing restart count [Conformance] [Slow]", func() { - runLivenessTest(f, &api.Pod{ - ObjectMeta: api.ObjectMeta{ + runLivenessTest(f, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "liveness-http", Labels: map[string]string{"test": "liveness"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "liveness", Image: "gcr.io/google_containers/liveness:e2e", Command: []string{"/server"}, - LivenessProbe: &api.Probe{ - Handler: api.Handler{ - HTTPGet: &api.HTTPGetAction{ + LivenessProbe: &v1.Probe{ + Handler: v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Path: "/healthz", Port: intstr.FromInt(8080), }, @@ -205,20 +205,20 @@ var _ = framework.KubeDescribe("Probing container", func() { }) It("should *not* be restarted with a /healthz http liveness probe [Conformance]", func() { - runLivenessTest(f, &api.Pod{ - ObjectMeta: api.ObjectMeta{ + runLivenessTest(f, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "liveness-http", Labels: map[string]string{"test": "liveness"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "liveness", Image: "gcr.io/google_containers/nginx-slim:0.7", - Ports: []api.ContainerPort{{ContainerPort: 80}}, - LivenessProbe: &api.Probe{ - Handler: api.Handler{ - HTTPGet: &api.HTTPGetAction{ + Ports: []v1.ContainerPort{{ContainerPort: 80}}, + LivenessProbe: &v1.Probe{ + Handler: v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Path: "/", Port: intstr.FromInt(80), }, @@ -236,20 +236,20 @@ var _ = framework.KubeDescribe("Probing container", func() { It("should be restarted with a docker exec liveness probe with timeout [Conformance]", func() { // TODO: enable this test once the default exec handler supports timeout. Skip("The default exec handler, dockertools.NativeExecHandler, does not support timeouts due to a limitation in the Docker Remote API") - runLivenessTest(f, &api.Pod{ - ObjectMeta: api.ObjectMeta{ + runLivenessTest(f, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "liveness-exec", Labels: map[string]string{"test": "liveness"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "liveness", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"/bin/sh", "-c", "sleep 600"}, - LivenessProbe: &api.Probe{ - Handler: api.Handler{ - Exec: &api.ExecAction{ + LivenessProbe: &v1.Probe{ + Handler: v1.Handler{ + Exec: &v1.ExecAction{ Command: []string{"/bin/sh", "-c", "sleep 10"}, }, }, @@ -264,7 +264,7 @@ var _ = framework.KubeDescribe("Probing container", func() { }) }) -func getContainerStartedTime(p *api.Pod, containerName string) (time.Time, error) { +func getContainerStartedTime(p *v1.Pod, containerName string) (time.Time, error) { for _, status := range p.Status.ContainerStatuses { if status.Name != containerName { continue @@ -277,16 +277,16 @@ func getContainerStartedTime(p *api.Pod, containerName string) (time.Time, error return time.Time{}, fmt.Errorf("cannot find container named %q", containerName) } -func getTransitionTimeForReadyCondition(p *api.Pod) (time.Time, error) { +func getTransitionTimeForReadyCondition(p *v1.Pod) (time.Time, error) { for _, cond := range p.Status.Conditions { - if cond.Type == api.PodReady { + if cond.Type == v1.PodReady { return cond.LastTransitionTime.Time, nil } } return time.Time{}, fmt.Errorf("No ready condition can be found for pod") } -func getRestartCount(p *api.Pod) int { +func getRestartCount(p *v1.Pod) int { count := 0 for _, containerStatus := range p.Status.ContainerStatuses { count += int(containerStatus.RestartCount) @@ -294,11 +294,11 @@ func getRestartCount(p *api.Pod) int { return count } -func makePodSpec(readinessProbe, livenessProbe *api.Probe) *api.Pod { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "test-webserver-" + string(uuid.NewUUID())}, - Spec: api.PodSpec{ - Containers: []api.Container{ +func makePodSpec(readinessProbe, livenessProbe *v1.Probe) *v1.Pod { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "test-webserver-" + string(uuid.NewUUID())}, + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: probTestContainerName, Image: "gcr.io/google_containers/test-webserver:e2e", @@ -326,10 +326,10 @@ func (b webserverProbeBuilder) withInitialDelay() webserverProbeBuilder { return b } -func (b webserverProbeBuilder) build() *api.Probe { - probe := &api.Probe{ - Handler: api.Handler{ - HTTPGet: &api.HTTPGetAction{ +func (b webserverProbeBuilder) build() *v1.Probe { + probe := &v1.Probe{ + Handler: v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Port: intstr.FromInt(80), Path: "/", }, @@ -344,7 +344,7 @@ func (b webserverProbeBuilder) build() *api.Probe { return probe } -func runLivenessTest(f *framework.Framework, pod *api.Pod, expectNumRestarts int, timeout time.Duration) { +func runLivenessTest(f *framework.Framework, pod *v1.Pod, expectNumRestarts int, timeout time.Duration) { podClient := f.PodClient() ns := f.Namespace.Name Expect(pod.Spec.Containers).NotTo(BeEmpty()) @@ -352,7 +352,7 @@ func runLivenessTest(f *framework.Framework, pod *api.Pod, expectNumRestarts int // At the end of the test, clean up by removing the pod. defer func() { By("deleting the pod") - podClient.Delete(pod.Name, api.NewDeleteOptions(0)) + podClient.Delete(pod.Name, v1.NewDeleteOptions(0)) }() By(fmt.Sprintf("Creating pod %s in namespace %s", pod.Name, ns)) podClient.Create(pod) @@ -368,7 +368,7 @@ func runLivenessTest(f *framework.Framework, pod *api.Pod, expectNumRestarts int By("checking the pod's current state and verifying that restartCount is present") pod, err := podClient.Get(pod.Name) framework.ExpectNoError(err, fmt.Sprintf("getting pod %s in namespace %s", pod.Name, ns)) - initialRestartCount := api.GetExistingContainerStatus(pod.Status.ContainerStatuses, containerName).RestartCount + initialRestartCount := v1.GetExistingContainerStatus(pod.Status.ContainerStatuses, containerName).RestartCount framework.Logf("Initial restart count of pod %s is %d", pod.Name, initialRestartCount) // Wait for the restart state to be as desired. @@ -378,7 +378,7 @@ func runLivenessTest(f *framework.Framework, pod *api.Pod, expectNumRestarts int for start := time.Now(); time.Now().Before(deadline); time.Sleep(2 * time.Second) { pod, err = podClient.Get(pod.Name) framework.ExpectNoError(err, fmt.Sprintf("getting pod %s", pod.Name)) - restartCount := api.GetExistingContainerStatus(pod.Status.ContainerStatuses, containerName).RestartCount + restartCount := v1.GetExistingContainerStatus(pod.Status.ContainerStatuses, containerName).RestartCount if restartCount != lastRestartCount { framework.Logf("Restart count of pod %s/%s is now %d (%v elapsed)", ns, pod.Name, restartCount, time.Since(start)) diff --git a/test/e2e/common/docker_containers.go b/test/e2e/common/docker_containers.go index 329c2faa7ba..896178f7c4d 100644 --- a/test/e2e/common/docker_containers.go +++ b/test/e2e/common/docker_containers.go @@ -17,7 +17,7 @@ limitations under the License. package common import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -67,21 +67,21 @@ var _ = framework.KubeDescribe("Docker Containers", func() { const testContainerName = "test-container" // Return a prototypical entrypoint test pod -func entrypointTestPod() *api.Pod { +func entrypointTestPod() *v1.Pod { podName := "client-containers-" + string(uuid.NewUUID()) - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: testContainerName, Image: "gcr.io/google_containers/eptest:0.1", }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } } diff --git a/test/e2e/common/downward_api.go b/test/e2e/common/downward_api.go index b6ac8662716..f8ee9cb12de 100644 --- a/test/e2e/common/downward_api.go +++ b/test/e2e/common/downward_api.go @@ -19,8 +19,8 @@ package common import ( "fmt" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -32,11 +32,11 @@ var _ = framework.KubeDescribe("Downward API", func() { It("should provide pod name and namespace as env vars [Conformance]", func() { podName := "downward-api-" + string(uuid.NewUUID()) - env := []api.EnvVar{ + env := []v1.EnvVar{ { Name: "POD_NAME", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ + ValueFrom: &v1.EnvVarSource{ + FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "metadata.name", }, @@ -44,8 +44,8 @@ var _ = framework.KubeDescribe("Downward API", func() { }, { Name: "POD_NAMESPACE", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ + ValueFrom: &v1.EnvVarSource{ + FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "metadata.namespace", }, @@ -63,11 +63,11 @@ var _ = framework.KubeDescribe("Downward API", func() { It("should provide pod IP as an env var [Conformance]", func() { podName := "downward-api-" + string(uuid.NewUUID()) - env := []api.EnvVar{ + env := []v1.EnvVar{ { Name: "POD_IP", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ + ValueFrom: &v1.EnvVarSource{ + FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "status.podIP", }, @@ -84,35 +84,35 @@ var _ = framework.KubeDescribe("Downward API", func() { It("should provide container's limits.cpu/memory and requests.cpu/memory as env vars [Conformance]", func() { podName := "downward-api-" + string(uuid.NewUUID()) - env := []api.EnvVar{ + env := []v1.EnvVar{ { Name: "CPU_LIMIT", - ValueFrom: &api.EnvVarSource{ - ResourceFieldRef: &api.ResourceFieldSelector{ + ValueFrom: &v1.EnvVarSource{ + ResourceFieldRef: &v1.ResourceFieldSelector{ Resource: "limits.cpu", }, }, }, { Name: "MEMORY_LIMIT", - ValueFrom: &api.EnvVarSource{ - ResourceFieldRef: &api.ResourceFieldSelector{ + ValueFrom: &v1.EnvVarSource{ + ResourceFieldRef: &v1.ResourceFieldSelector{ Resource: "limits.memory", }, }, }, { Name: "CPU_REQUEST", - ValueFrom: &api.EnvVarSource{ - ResourceFieldRef: &api.ResourceFieldSelector{ + ValueFrom: &v1.EnvVarSource{ + ResourceFieldRef: &v1.ResourceFieldSelector{ Resource: "requests.cpu", }, }, }, { Name: "MEMORY_REQUEST", - ValueFrom: &api.EnvVarSource{ - ResourceFieldRef: &api.ResourceFieldSelector{ + ValueFrom: &v1.EnvVarSource{ + ResourceFieldRef: &v1.ResourceFieldSelector{ Resource: "requests.memory", }, }, @@ -130,19 +130,19 @@ var _ = framework.KubeDescribe("Downward API", func() { It("should provide default limits.cpu/memory from node allocatable [Conformance]", func() { podName := "downward-api-" + string(uuid.NewUUID()) - env := []api.EnvVar{ + env := []v1.EnvVar{ { Name: "CPU_LIMIT", - ValueFrom: &api.EnvVarSource{ - ResourceFieldRef: &api.ResourceFieldSelector{ + ValueFrom: &v1.EnvVarSource{ + ResourceFieldRef: &v1.ResourceFieldSelector{ Resource: "limits.cpu", }, }, }, { Name: "MEMORY_LIMIT", - ValueFrom: &api.EnvVarSource{ - ResourceFieldRef: &api.ResourceFieldSelector{ + ValueFrom: &v1.EnvVarSource{ + ResourceFieldRef: &v1.ResourceFieldSelector{ Resource: "limits.memory", }, }, @@ -152,13 +152,13 @@ var _ = framework.KubeDescribe("Downward API", func() { fmt.Sprintf("CPU_LIMIT=[1-9]"), fmt.Sprintf("MEMORY_LIMIT=[1-9]"), } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{"name": podName}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "dapi-container", Image: "gcr.io/google_containers/busybox:1.24", @@ -166,7 +166,7 @@ var _ = framework.KubeDescribe("Downward API", func() { Env: env, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } @@ -174,38 +174,38 @@ var _ = framework.KubeDescribe("Downward API", func() { }) }) -func testDownwardAPI(f *framework.Framework, podName string, env []api.EnvVar, expectations []string) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func testDownwardAPI(f *framework.Framework, podName string, env []v1.EnvVar, expectations []string) { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{"name": podName}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "dapi-container", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"sh", "-c", "env"}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceCPU: resource.MustParse("250m"), - api.ResourceMemory: resource.MustParse("32Mi"), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("250m"), + v1.ResourceMemory: resource.MustParse("32Mi"), }, - Limits: api.ResourceList{ - api.ResourceCPU: resource.MustParse("1250m"), - api.ResourceMemory: resource.MustParse("64Mi"), + Limits: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("1250m"), + v1.ResourceMemory: resource.MustParse("64Mi"), }, }, Env: env, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } testDownwardAPIUsingPod(f, pod, env, expectations) } -func testDownwardAPIUsingPod(f *framework.Framework, pod *api.Pod, env []api.EnvVar, expectations []string) { +func testDownwardAPIUsingPod(f *framework.Framework, pod *v1.Pod, env []v1.EnvVar, expectations []string) { f.TestContainerOutputRegexp("downward api env vars", pod, 0, expectations) } diff --git a/test/e2e/common/downwardapi_volume.go b/test/e2e/common/downwardapi_volume.go index 9f3f8453d46..3b2141f52e5 100644 --- a/test/e2e/common/downwardapi_volume.go +++ b/test/e2e/common/downwardapi_volume.go @@ -20,8 +20,8 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -72,7 +72,7 @@ var _ = framework.KubeDescribe("Downward API volume", func() { uid := int64(1001) gid := int64(1234) pod := downwardAPIVolumePodForSimpleTest(podName, "/etc/podname") - pod.Spec.SecurityContext = &api.PodSecurityContext{ + pod.Spec.SecurityContext = &v1.PodSecurityContext{ RunAsUser: &uid, FSGroup: &gid, } @@ -98,7 +98,7 @@ var _ = framework.KubeDescribe("Downward API volume", func() { podLogTimeout, framework.Poll).Should(ContainSubstring("key1=\"value1\"\n")) //modify labels - podClient.Update(podName, func(pod *api.Pod) { + podClient.Update(podName, func(pod *v1.Pod) { pod.Labels["key3"] = "value3" }) @@ -127,7 +127,7 @@ var _ = framework.KubeDescribe("Downward API volume", func() { podLogTimeout, framework.Poll).Should(ContainSubstring("builder=\"bar\"\n")) //modify annotations - podClient.Update(podName, func(pod *api.Pod) { + podClient.Update(podName, func(pod *v1.Pod) { pod.Annotations["builder"] = "foo" }) @@ -189,15 +189,15 @@ var _ = framework.KubeDescribe("Downward API volume", func() { }) -func downwardAPIVolumePodForModeTest(name, filePath string, itemMode, defaultMode *int32) *api.Pod { +func downwardAPIVolumePodForModeTest(name, filePath string, itemMode, defaultMode *int32) *v1.Pod { pod := downwardAPIVolumeBasePod(name, nil, nil) - pod.Spec.Containers = []api.Container{ + pod.Spec.Containers = []v1.Container{ { Name: "client-container", Image: "gcr.io/google_containers/mounttest:0.7", Command: []string{"/mt", "--file_mode=" + filePath}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "podinfo", MountPath: "/etc", @@ -215,15 +215,15 @@ func downwardAPIVolumePodForModeTest(name, filePath string, itemMode, defaultMod return pod } -func downwardAPIVolumePodForSimpleTest(name string, filePath string) *api.Pod { +func downwardAPIVolumePodForSimpleTest(name string, filePath string) *v1.Pod { pod := downwardAPIVolumeBasePod(name, nil, nil) - pod.Spec.Containers = []api.Container{ + pod.Spec.Containers = []v1.Container{ { Name: "client-container", Image: "gcr.io/google_containers/mounttest:0.7", Command: []string{"/mt", "--file_content=" + filePath}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "podinfo", MountPath: "/etc", @@ -236,35 +236,35 @@ func downwardAPIVolumePodForSimpleTest(name string, filePath string) *api.Pod { return pod } -func downwardAPIVolumeForContainerResources(name string, filePath string) *api.Pod { +func downwardAPIVolumeForContainerResources(name string, filePath string) *v1.Pod { pod := downwardAPIVolumeBasePod(name, nil, nil) pod.Spec.Containers = downwardAPIVolumeBaseContainers("client-container", filePath) return pod } -func downwardAPIVolumeForDefaultContainerResources(name string, filePath string) *api.Pod { +func downwardAPIVolumeForDefaultContainerResources(name string, filePath string) *v1.Pod { pod := downwardAPIVolumeBasePod(name, nil, nil) pod.Spec.Containers = downwardAPIVolumeDefaultBaseContainer("client-container", filePath) return pod } -func downwardAPIVolumeBaseContainers(name, filePath string) []api.Container { - return []api.Container{ +func downwardAPIVolumeBaseContainers(name, filePath string) []v1.Container { + return []v1.Container{ { Name: name, Image: "gcr.io/google_containers/mounttest:0.7", Command: []string{"/mt", "--file_content=" + filePath}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceCPU: resource.MustParse("250m"), - api.ResourceMemory: resource.MustParse("32Mi"), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("250m"), + v1.ResourceMemory: resource.MustParse("32Mi"), }, - Limits: api.ResourceList{ - api.ResourceCPU: resource.MustParse("1250m"), - api.ResourceMemory: resource.MustParse("64Mi"), + Limits: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("1250m"), + v1.ResourceMemory: resource.MustParse("64Mi"), }, }, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "podinfo", MountPath: "/etc", @@ -276,13 +276,13 @@ func downwardAPIVolumeBaseContainers(name, filePath string) []api.Container { } -func downwardAPIVolumeDefaultBaseContainer(name, filePath string) []api.Container { - return []api.Container{ +func downwardAPIVolumeDefaultBaseContainer(name, filePath string) []v1.Container { + return []v1.Container{ { Name: name, Image: "gcr.io/google_containers/mounttest:0.7", Command: []string{"/mt", "--file_content=" + filePath}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "podinfo", MountPath: "/etc", @@ -293,15 +293,15 @@ func downwardAPIVolumeDefaultBaseContainer(name, filePath string) []api.Containe } -func downwardAPIVolumePodForUpdateTest(name string, labels, annotations map[string]string, filePath string) *api.Pod { +func downwardAPIVolumePodForUpdateTest(name string, labels, annotations map[string]string, filePath string) *v1.Pod { pod := downwardAPIVolumeBasePod(name, labels, annotations) - pod.Spec.Containers = []api.Container{ + pod.Spec.Containers = []v1.Container{ { Name: "client-container", Image: "gcr.io/google_containers/mounttest:0.7", Command: []string{"/mt", "--break_on_expected_content=false", "--retry_time=120", "--file_content_in_loop=" + filePath}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "podinfo", MountPath: "/etc", @@ -315,51 +315,51 @@ func downwardAPIVolumePodForUpdateTest(name string, labels, annotations map[stri return pod } -func downwardAPIVolumeBasePod(name string, labels, annotations map[string]string) *api.Pod { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func downwardAPIVolumeBasePod(name string, labels, annotations map[string]string) *v1.Pod { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: labels, Annotations: annotations, }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "podinfo", - VolumeSource: api.VolumeSource{ - DownwardAPI: &api.DownwardAPIVolumeSource{ - Items: []api.DownwardAPIVolumeFile{ + VolumeSource: v1.VolumeSource{ + DownwardAPI: &v1.DownwardAPIVolumeSource{ + Items: []v1.DownwardAPIVolumeFile{ { Path: "podname", - FieldRef: &api.ObjectFieldSelector{ + FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "metadata.name", }, }, { Path: "cpu_limit", - ResourceFieldRef: &api.ResourceFieldSelector{ + ResourceFieldRef: &v1.ResourceFieldSelector{ ContainerName: "client-container", Resource: "limits.cpu", }, }, { Path: "cpu_request", - ResourceFieldRef: &api.ResourceFieldSelector{ + ResourceFieldRef: &v1.ResourceFieldSelector{ ContainerName: "client-container", Resource: "requests.cpu", }, }, { Path: "memory_limit", - ResourceFieldRef: &api.ResourceFieldSelector{ + ResourceFieldRef: &v1.ResourceFieldSelector{ ContainerName: "client-container", Resource: "limits.memory", }, }, { Path: "memory_request", - ResourceFieldRef: &api.ResourceFieldSelector{ + ResourceFieldRef: &v1.ResourceFieldSelector{ ContainerName: "client-container", Resource: "requests.memory", }, @@ -369,18 +369,18 @@ func downwardAPIVolumeBasePod(name string, labels, annotations map[string]string }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } return pod } -func applyLabelsAndAnnotationsToDownwardAPIPod(labels, annotations map[string]string, pod *api.Pod) { +func applyLabelsAndAnnotationsToDownwardAPIPod(labels, annotations map[string]string, pod *v1.Pod) { if len(labels) > 0 { - pod.Spec.Volumes[0].DownwardAPI.Items = append(pod.Spec.Volumes[0].DownwardAPI.Items, api.DownwardAPIVolumeFile{ + pod.Spec.Volumes[0].DownwardAPI.Items = append(pod.Spec.Volumes[0].DownwardAPI.Items, v1.DownwardAPIVolumeFile{ Path: "labels", - FieldRef: &api.ObjectFieldSelector{ + FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "metadata.labels", }, @@ -388,9 +388,9 @@ func applyLabelsAndAnnotationsToDownwardAPIPod(labels, annotations map[string]st } if len(annotations) > 0 { - pod.Spec.Volumes[0].DownwardAPI.Items = append(pod.Spec.Volumes[0].DownwardAPI.Items, api.DownwardAPIVolumeFile{ + pod.Spec.Volumes[0].DownwardAPI.Items = append(pod.Spec.Volumes[0].DownwardAPI.Items, v1.DownwardAPIVolumeFile{ Path: "annotations", - FieldRef: &api.ObjectFieldSelector{ + FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "metadata.annotations", }, diff --git a/test/e2e/common/empty_dir.go b/test/e2e/common/empty_dir.go index f9bd314b0b1..456e7a3a2a3 100644 --- a/test/e2e/common/empty_dir.go +++ b/test/e2e/common/empty_dir.go @@ -20,8 +20,8 @@ import ( "fmt" "path" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -40,80 +40,80 @@ var _ = framework.KubeDescribe("EmptyDir volumes", func() { Context("when FSGroup is specified [Feature:FSGroup]", func() { It("new files should be created with FSGroup ownership when container is root", func() { - doTestSetgidFSGroup(f, testImageRootUid, api.StorageMediumMemory) + doTestSetgidFSGroup(f, testImageRootUid, v1.StorageMediumMemory) }) It("new files should be created with FSGroup ownership when container is non-root", func() { - doTestSetgidFSGroup(f, testImageNonRootUid, api.StorageMediumMemory) + doTestSetgidFSGroup(f, testImageNonRootUid, v1.StorageMediumMemory) }) It("files with FSGroup ownership should support (root,0644,tmpfs)", func() { - doTest0644FSGroup(f, testImageRootUid, api.StorageMediumMemory) + doTest0644FSGroup(f, testImageRootUid, v1.StorageMediumMemory) }) It("volume on default medium should have the correct mode using FSGroup", func() { - doTestVolumeModeFSGroup(f, testImageRootUid, api.StorageMediumDefault) + doTestVolumeModeFSGroup(f, testImageRootUid, v1.StorageMediumDefault) }) It("volume on tmpfs should have the correct mode using FSGroup", func() { - doTestVolumeModeFSGroup(f, testImageRootUid, api.StorageMediumMemory) + doTestVolumeModeFSGroup(f, testImageRootUid, v1.StorageMediumMemory) }) }) It("volume on tmpfs should have the correct mode [Conformance]", func() { - doTestVolumeMode(f, testImageRootUid, api.StorageMediumMemory) + doTestVolumeMode(f, testImageRootUid, v1.StorageMediumMemory) }) It("should support (root,0644,tmpfs) [Conformance]", func() { - doTest0644(f, testImageRootUid, api.StorageMediumMemory) + doTest0644(f, testImageRootUid, v1.StorageMediumMemory) }) It("should support (root,0666,tmpfs) [Conformance]", func() { - doTest0666(f, testImageRootUid, api.StorageMediumMemory) + doTest0666(f, testImageRootUid, v1.StorageMediumMemory) }) It("should support (root,0777,tmpfs) [Conformance]", func() { - doTest0777(f, testImageRootUid, api.StorageMediumMemory) + doTest0777(f, testImageRootUid, v1.StorageMediumMemory) }) It("should support (non-root,0644,tmpfs) [Conformance]", func() { - doTest0644(f, testImageNonRootUid, api.StorageMediumMemory) + doTest0644(f, testImageNonRootUid, v1.StorageMediumMemory) }) It("should support (non-root,0666,tmpfs) [Conformance]", func() { - doTest0666(f, testImageNonRootUid, api.StorageMediumMemory) + doTest0666(f, testImageNonRootUid, v1.StorageMediumMemory) }) It("should support (non-root,0777,tmpfs) [Conformance]", func() { - doTest0777(f, testImageNonRootUid, api.StorageMediumMemory) + doTest0777(f, testImageNonRootUid, v1.StorageMediumMemory) }) It("volume on default medium should have the correct mode [Conformance]", func() { - doTestVolumeMode(f, testImageRootUid, api.StorageMediumDefault) + doTestVolumeMode(f, testImageRootUid, v1.StorageMediumDefault) }) It("should support (root,0644,default) [Conformance]", func() { - doTest0644(f, testImageRootUid, api.StorageMediumDefault) + doTest0644(f, testImageRootUid, v1.StorageMediumDefault) }) It("should support (root,0666,default) [Conformance]", func() { - doTest0666(f, testImageRootUid, api.StorageMediumDefault) + doTest0666(f, testImageRootUid, v1.StorageMediumDefault) }) It("should support (root,0777,default) [Conformance]", func() { - doTest0777(f, testImageRootUid, api.StorageMediumDefault) + doTest0777(f, testImageRootUid, v1.StorageMediumDefault) }) It("should support (non-root,0644,default) [Conformance]", func() { - doTest0644(f, testImageNonRootUid, api.StorageMediumDefault) + doTest0644(f, testImageNonRootUid, v1.StorageMediumDefault) }) It("should support (non-root,0666,default) [Conformance]", func() { - doTest0666(f, testImageNonRootUid, api.StorageMediumDefault) + doTest0666(f, testImageNonRootUid, v1.StorageMediumDefault) }) It("should support (non-root,0777,default) [Conformance]", func() { - doTest0777(f, testImageNonRootUid, api.StorageMediumDefault) + doTest0777(f, testImageNonRootUid, v1.StorageMediumDefault) }) }) @@ -122,11 +122,11 @@ const ( volumeName = "test-volume" ) -func doTestSetgidFSGroup(f *framework.Framework, image string, medium api.StorageMedium) { +func doTestSetgidFSGroup(f *framework.Framework, image string, medium v1.StorageMedium) { var ( volumePath = "/test-volume" filePath = path.Join(volumePath, "test-file") - source = &api.EmptyDirVolumeSource{Medium: medium} + source = &v1.EmptyDirVolumeSource{Medium: medium} pod = testPodWithVolume(testImageRootUid, volumePath, source) ) @@ -146,16 +146,16 @@ func doTestSetgidFSGroup(f *framework.Framework, image string, medium api.Storag "content of file \"/test-volume/test-file\": mount-tester new file", "owner GID of \"/test-volume/test-file\": 123", } - if medium == api.StorageMediumMemory { + if medium == v1.StorageMediumMemory { out = append(out, "mount type of \"/test-volume\": tmpfs") } f.TestContainerOutput(msg, pod, 0, out) } -func doTestVolumeModeFSGroup(f *framework.Framework, image string, medium api.StorageMedium) { +func doTestVolumeModeFSGroup(f *framework.Framework, image string, medium v1.StorageMedium) { var ( volumePath = "/test-volume" - source = &api.EmptyDirVolumeSource{Medium: medium} + source = &v1.EmptyDirVolumeSource{Medium: medium} pod = testPodWithVolume(testImageRootUid, volumePath, source) ) @@ -171,17 +171,17 @@ func doTestVolumeModeFSGroup(f *framework.Framework, image string, medium api.St out := []string{ "perms of file \"/test-volume\": -rwxrwxrwx", } - if medium == api.StorageMediumMemory { + if medium == v1.StorageMediumMemory { out = append(out, "mount type of \"/test-volume\": tmpfs") } f.TestContainerOutput(msg, pod, 0, out) } -func doTest0644FSGroup(f *framework.Framework, image string, medium api.StorageMedium) { +func doTest0644FSGroup(f *framework.Framework, image string, medium v1.StorageMedium) { var ( volumePath = "/test-volume" filePath = path.Join(volumePath, "test-file") - source = &api.EmptyDirVolumeSource{Medium: medium} + source = &v1.EmptyDirVolumeSource{Medium: medium} pod = testPodWithVolume(image, volumePath, source) ) @@ -199,16 +199,16 @@ func doTest0644FSGroup(f *framework.Framework, image string, medium api.StorageM "perms of file \"/test-volume/test-file\": -rw-r--r--", "content of file \"/test-volume/test-file\": mount-tester new file", } - if medium == api.StorageMediumMemory { + if medium == v1.StorageMediumMemory { out = append(out, "mount type of \"/test-volume\": tmpfs") } f.TestContainerOutput(msg, pod, 0, out) } -func doTestVolumeMode(f *framework.Framework, image string, medium api.StorageMedium) { +func doTestVolumeMode(f *framework.Framework, image string, medium v1.StorageMedium) { var ( volumePath = "/test-volume" - source = &api.EmptyDirVolumeSource{Medium: medium} + source = &v1.EmptyDirVolumeSource{Medium: medium} pod = testPodWithVolume(testImageRootUid, volumePath, source) ) @@ -221,17 +221,17 @@ func doTestVolumeMode(f *framework.Framework, image string, medium api.StorageMe out := []string{ "perms of file \"/test-volume\": -rwxrwxrwx", } - if medium == api.StorageMediumMemory { + if medium == v1.StorageMediumMemory { out = append(out, "mount type of \"/test-volume\": tmpfs") } f.TestContainerOutput(msg, pod, 0, out) } -func doTest0644(f *framework.Framework, image string, medium api.StorageMedium) { +func doTest0644(f *framework.Framework, image string, medium v1.StorageMedium) { var ( volumePath = "/test-volume" filePath = path.Join(volumePath, "test-file") - source = &api.EmptyDirVolumeSource{Medium: medium} + source = &v1.EmptyDirVolumeSource{Medium: medium} pod = testPodWithVolume(image, volumePath, source) ) @@ -246,17 +246,17 @@ func doTest0644(f *framework.Framework, image string, medium api.StorageMedium) "perms of file \"/test-volume/test-file\": -rw-r--r--", "content of file \"/test-volume/test-file\": mount-tester new file", } - if medium == api.StorageMediumMemory { + if medium == v1.StorageMediumMemory { out = append(out, "mount type of \"/test-volume\": tmpfs") } f.TestContainerOutput(msg, pod, 0, out) } -func doTest0666(f *framework.Framework, image string, medium api.StorageMedium) { +func doTest0666(f *framework.Framework, image string, medium v1.StorageMedium) { var ( volumePath = "/test-volume" filePath = path.Join(volumePath, "test-file") - source = &api.EmptyDirVolumeSource{Medium: medium} + source = &v1.EmptyDirVolumeSource{Medium: medium} pod = testPodWithVolume(image, volumePath, source) ) @@ -271,17 +271,17 @@ func doTest0666(f *framework.Framework, image string, medium api.StorageMedium) "perms of file \"/test-volume/test-file\": -rw-rw-rw-", "content of file \"/test-volume/test-file\": mount-tester new file", } - if medium == api.StorageMediumMemory { + if medium == v1.StorageMediumMemory { out = append(out, "mount type of \"/test-volume\": tmpfs") } f.TestContainerOutput(msg, pod, 0, out) } -func doTest0777(f *framework.Framework, image string, medium api.StorageMedium) { +func doTest0777(f *framework.Framework, image string, medium v1.StorageMedium) { var ( volumePath = "/test-volume" filePath = path.Join(volumePath, "test-file") - source = &api.EmptyDirVolumeSource{Medium: medium} + source = &v1.EmptyDirVolumeSource{Medium: medium} pod = testPodWithVolume(image, volumePath, source) ) @@ -296,36 +296,36 @@ func doTest0777(f *framework.Framework, image string, medium api.StorageMedium) "perms of file \"/test-volume/test-file\": -rwxrwxrwx", "content of file \"/test-volume/test-file\": mount-tester new file", } - if medium == api.StorageMediumMemory { + if medium == v1.StorageMediumMemory { out = append(out, "mount type of \"/test-volume\": tmpfs") } f.TestContainerOutput(msg, pod, 0, out) } -func formatMedium(medium api.StorageMedium) string { - if medium == api.StorageMediumMemory { +func formatMedium(medium v1.StorageMedium) string { + if medium == v1.StorageMediumMemory { return "tmpfs" } return "node default medium" } -func testPodWithVolume(image, path string, source *api.EmptyDirVolumeSource) *api.Pod { +func testPodWithVolume(image, path string, source *v1.EmptyDirVolumeSource) *v1.Pod { podName := "pod-" + string(uuid.NewUUID()) - return &api.Pod{ + return &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: containerName, Image: image, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: path, @@ -333,16 +333,16 @@ func testPodWithVolume(image, path string, source *api.EmptyDirVolumeSource) *ap }, }, }, - SecurityContext: &api.PodSecurityContext{ - SELinuxOptions: &api.SELinuxOptions{ + SecurityContext: &v1.PodSecurityContext{ + SELinuxOptions: &v1.SELinuxOptions{ Level: "s0", }, }, - RestartPolicy: api.RestartPolicyNever, - Volumes: []api.Volume{ + RestartPolicy: v1.RestartPolicyNever, + Volumes: []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ + VolumeSource: v1.VolumeSource{ EmptyDir: source, }, }, diff --git a/test/e2e/common/expansion.go b/test/e2e/common/expansion.go index c7be116541e..27154792a54 100644 --- a/test/e2e/common/expansion.go +++ b/test/e2e/common/expansion.go @@ -17,7 +17,7 @@ limitations under the License. package common import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -31,18 +31,18 @@ var _ = framework.KubeDescribe("Variable Expansion", func() { It("should allow composing env vars into new env vars [Conformance]", func() { podName := "var-expansion-" + string(uuid.NewUUID()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{"name": podName}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "dapi-container", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"sh", "-c", "env"}, - Env: []api.EnvVar{ + Env: []v1.EnvVar{ { Name: "FOO", Value: "foo-value", @@ -58,7 +58,7 @@ var _ = framework.KubeDescribe("Variable Expansion", func() { }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } @@ -71,18 +71,18 @@ var _ = framework.KubeDescribe("Variable Expansion", func() { It("should allow substituting values in a container's command [Conformance]", func() { podName := "var-expansion-" + string(uuid.NewUUID()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{"name": podName}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "dapi-container", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"sh", "-c", "TEST_VAR=wrong echo \"$(TEST_VAR)\""}, - Env: []api.EnvVar{ + Env: []v1.EnvVar{ { Name: "TEST_VAR", Value: "test-value", @@ -90,7 +90,7 @@ var _ = framework.KubeDescribe("Variable Expansion", func() { }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } @@ -101,19 +101,19 @@ var _ = framework.KubeDescribe("Variable Expansion", func() { It("should allow substituting values in a container's args [Conformance]", func() { podName := "var-expansion-" + string(uuid.NewUUID()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{"name": podName}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "dapi-container", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"sh", "-c"}, Args: []string{"TEST_VAR=wrong echo \"$(TEST_VAR)\""}, - Env: []api.EnvVar{ + Env: []v1.EnvVar{ { Name: "TEST_VAR", Value: "test-value", @@ -121,7 +121,7 @@ var _ = framework.KubeDescribe("Variable Expansion", func() { }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } diff --git a/test/e2e/common/host_path.go b/test/e2e/common/host_path.go index a05af03e972..2ee90614c33 100644 --- a/test/e2e/common/host_path.go +++ b/test/e2e/common/host_path.go @@ -21,8 +21,8 @@ import ( "os" "path" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/test/e2e/framework" @@ -41,7 +41,7 @@ var _ = framework.KubeDescribe("HostPath", func() { It("should give a volume the correct mode [Conformance]", func() { volumePath := "/test-volume" - source := &api.HostPathVolumeSource{ + source := &v1.HostPathVolumeSource{ Path: "/tmp", } pod := testPodWithHostVol(volumePath, source) @@ -60,7 +60,7 @@ var _ = framework.KubeDescribe("HostPath", func() { volumePath := "/test-volume" filePath := path.Join(volumePath, "test-file") retryDuration := 180 - source := &api.HostPathVolumeSource{ + source := &v1.HostPathVolumeSource{ Path: "/tmp", } pod := testPodWithHostVol(volumePath, source) @@ -90,7 +90,7 @@ var _ = framework.KubeDescribe("HostPath", func() { filePathInWriter := path.Join(volumePath, fileName) filePathInReader := path.Join(volumePath, subPath, fileName) - source := &api.HostPathVolumeSource{ + source := &v1.HostPathVolumeSource{ Path: "/tmp", } pod := testPodWithHostVol(volumePath, source) @@ -118,11 +118,11 @@ var _ = framework.KubeDescribe("HostPath", func() { const containerName1 = "test-container-1" const containerName2 = "test-container-2" -func mount(source *api.HostPathVolumeSource) []api.Volume { - return []api.Volume{ +func mount(source *v1.HostPathVolumeSource) []v1.Volume { + return []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ + VolumeSource: v1.VolumeSource{ HostPath: source, }, }, @@ -130,23 +130,23 @@ func mount(source *api.HostPathVolumeSource) []api.Volume { } //TODO: To merge this with the emptyDir tests, we can make source a lambda. -func testPodWithHostVol(path string, source *api.HostPathVolumeSource) *api.Pod { +func testPodWithHostVol(path string, source *v1.HostPathVolumeSource) *v1.Pod { podName := "pod-host-path-test" - return &api.Pod{ + return &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: containerName1, Image: "gcr.io/google_containers/mounttest:0.7", - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: path, @@ -156,7 +156,7 @@ func testPodWithHostVol(path string, source *api.HostPathVolumeSource) *api.Pod { Name: containerName2, Image: "gcr.io/google_containers/mounttest:0.7", - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: path, @@ -164,7 +164,7 @@ func testPodWithHostVol(path string, source *api.HostPathVolumeSource) *api.Pod }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, Volumes: mount(source), }, } diff --git a/test/e2e/common/init_container.go b/test/e2e/common/init_container.go index ce5f1f027a3..1496fcf5e20 100644 --- a/test/e2e/common/init_container.go +++ b/test/e2e/common/init_container.go @@ -21,9 +21,10 @@ import ( "strconv" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - client "k8s.io/kubernetes/pkg/client/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + podutil "k8s.io/kubernetes/pkg/api/v1/pod" + "k8s.io/kubernetes/pkg/client/conditions" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/pkg/watch" "k8s.io/kubernetes/test/e2e/framework" @@ -45,17 +46,17 @@ var _ = framework.KubeDescribe("InitContainer", func() { By("creating the pod") name := "pod-init-" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: map[string]string{ "name": "foo", "time": value, }, }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - InitContainers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyNever, + InitContainers: []v1.Container{ { Name: "init1", Image: "gcr.io/google_containers/busybox:1.24", @@ -67,7 +68,7 @@ var _ = framework.KubeDescribe("InitContainer", func() { Command: []string{"/bin/true"}, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "run1", Image: "gcr.io/google_containers/busybox:1.24", @@ -76,19 +77,25 @@ var _ = framework.KubeDescribe("InitContainer", func() { }, }, } + if err := podutil.SetInitContainersAnnotations(pod); err != nil { + Expect(err).To(BeNil()) + } startedPod := podClient.Create(pod) - w, err := podClient.Watch(api.SingleObject(startedPod.ObjectMeta)) + w, err := podClient.Watch(v1.SingleObject(startedPod.ObjectMeta)) Expect(err).NotTo(HaveOccurred(), "error watching a pod") wr := watch.NewRecorder(w) - event, err := watch.Until(framework.PodStartTimeout, wr, client.PodCompleted) + event, err := watch.Until(framework.PodStartTimeout, wr, conditions.PodCompleted) Expect(err).To(BeNil()) framework.CheckInvariants(wr.Events(), framework.ContainerInitInvariant) - endPod := event.Object.(*api.Pod) + endPod := event.Object.(*v1.Pod) + if err := podutil.SetInitContainersAndStatuses(endPod); err != nil { + Expect(err).To(BeNil()) + } - Expect(endPod.Status.Phase).To(Equal(api.PodSucceeded)) - _, init := api.GetPodCondition(&endPod.Status, api.PodInitialized) + Expect(endPod.Status.Phase).To(Equal(v1.PodSucceeded)) + _, init := v1.GetPodCondition(&endPod.Status, v1.PodInitialized) Expect(init).NotTo(BeNil()) - Expect(init.Status).To(Equal(api.ConditionTrue)) + Expect(init.Status).To(Equal(v1.ConditionTrue)) Expect(len(endPod.Status.InitContainerStatuses)).To(Equal(2)) for _, status := range endPod.Status.InitContainerStatuses { @@ -104,16 +111,16 @@ var _ = framework.KubeDescribe("InitContainer", func() { By("creating the pod") name := "pod-init-" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: map[string]string{ "name": "foo", "time": value, }, }, - Spec: api.PodSpec{ - InitContainers: []api.Container{ + Spec: v1.PodSpec{ + InitContainers: []v1.Container{ { Name: "init1", Image: "gcr.io/google_containers/busybox:1.24", @@ -125,33 +132,39 @@ var _ = framework.KubeDescribe("InitContainer", func() { Command: []string{"/bin/true"}, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "run1", Image: framework.GetPauseImageName(f.ClientSet), - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(30*1024*1024, resource.DecimalSI), + Resources: v1.ResourceRequirements{ + Limits: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(30*1024*1024, resource.DecimalSI), }, }, }, }, }, } + if err := podutil.SetInitContainersAnnotations(pod); err != nil { + Expect(err).To(BeNil()) + } startedPod := podClient.Create(pod) - w, err := podClient.Watch(api.SingleObject(startedPod.ObjectMeta)) + w, err := podClient.Watch(v1.SingleObject(startedPod.ObjectMeta)) Expect(err).NotTo(HaveOccurred(), "error watching a pod") wr := watch.NewRecorder(w) - event, err := watch.Until(framework.PodStartTimeout, wr, client.PodRunning) + event, err := watch.Until(framework.PodStartTimeout, wr, conditions.PodRunning) Expect(err).To(BeNil()) framework.CheckInvariants(wr.Events(), framework.ContainerInitInvariant) - endPod := event.Object.(*api.Pod) + endPod := event.Object.(*v1.Pod) - Expect(endPod.Status.Phase).To(Equal(api.PodRunning)) - _, init := api.GetPodCondition(&endPod.Status, api.PodInitialized) + Expect(endPod.Status.Phase).To(Equal(v1.PodRunning)) + _, init := v1.GetPodCondition(&endPod.Status, v1.PodInitialized) Expect(init).NotTo(BeNil()) - Expect(init.Status).To(Equal(api.ConditionTrue)) + Expect(init.Status).To(Equal(v1.ConditionTrue)) + if err := podutil.SetInitContainersAndStatuses(endPod); err != nil { + Expect(err).To(BeNil()) + } Expect(len(endPod.Status.InitContainerStatuses)).To(Equal(2)) for _, status := range endPod.Status.InitContainerStatuses { @@ -167,16 +180,17 @@ var _ = framework.KubeDescribe("InitContainer", func() { By("creating the pod") name := "pod-init-" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: map[string]string{ "name": "foo", "time": value, }, }, - Spec: api.PodSpec{ - InitContainers: []api.Container{ + Spec: v1.PodSpec{ + InitContainers: []v1.Container{ { Name: "init1", Image: "gcr.io/google_containers/busybox:1.24", @@ -188,22 +202,25 @@ var _ = framework.KubeDescribe("InitContainer", func() { Command: []string{"/bin/true"}, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "run1", Image: framework.GetPauseImageName(f.ClientSet), - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(30*1024*1024, resource.DecimalSI), + Resources: v1.ResourceRequirements{ + Limits: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(30*1024*1024, resource.DecimalSI), }, }, }, }, }, } + if err := podutil.SetInitContainersAnnotations(pod); err != nil { + Expect(err).To(BeNil()) + } startedPod := podClient.Create(pod) - w, err := podClient.Watch(api.SingleObject(startedPod.ObjectMeta)) + w, err := podClient.Watch(v1.SingleObject(startedPod.ObjectMeta)) Expect(err).NotTo(HaveOccurred(), "error watching a pod") wr := watch.NewRecorder(w) @@ -212,7 +229,10 @@ var _ = framework.KubeDescribe("InitContainer", func() { // check for the first container to fail at least once func(evt watch.Event) (bool, error) { switch t := evt.Object.(type) { - case *api.Pod: + case *v1.Pod: + if err := podutil.SetInitContainersAndStatuses(t); err != nil { + Expect(err).To(BeNil()) + } for _, status := range t.Status.ContainerStatuses { if status.State.Waiting == nil { return false, fmt.Errorf("container %q should not be out of waiting: %#v", status.Name, status) @@ -244,7 +264,10 @@ var _ = framework.KubeDescribe("InitContainer", func() { // verify we get two restarts func(evt watch.Event) (bool, error) { switch t := evt.Object.(type) { - case *api.Pod: + case *v1.Pod: + if err := podutil.SetInitContainersAndStatuses(t); err != nil { + Expect(err).To(BeNil()) + } status := t.Status.InitContainerStatuses[0] if status.RestartCount < 3 { return false, nil @@ -259,12 +282,15 @@ var _ = framework.KubeDescribe("InitContainer", func() { ) Expect(err).To(BeNil()) framework.CheckInvariants(wr.Events(), framework.ContainerInitInvariant) - endPod := event.Object.(*api.Pod) + endPod := event.Object.(*v1.Pod) + if err := podutil.SetInitContainersAndStatuses(endPod); err != nil { + Expect(err).To(BeNil()) + } - Expect(endPod.Status.Phase).To(Equal(api.PodPending)) - _, init := api.GetPodCondition(&endPod.Status, api.PodInitialized) + Expect(endPod.Status.Phase).To(Equal(v1.PodPending)) + _, init := v1.GetPodCondition(&endPod.Status, v1.PodInitialized) Expect(init).NotTo(BeNil()) - Expect(init.Status).To(Equal(api.ConditionFalse)) + Expect(init.Status).To(Equal(v1.ConditionFalse)) Expect(init.Reason).To(Equal("ContainersNotInitialized")) Expect(init.Message).To(Equal("containers with incomplete status: [init1 init2]")) Expect(len(endPod.Status.InitContainerStatuses)).To(Equal(2)) @@ -276,17 +302,17 @@ var _ = framework.KubeDescribe("InitContainer", func() { By("creating the pod") name := "pod-init-" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: map[string]string{ "name": "foo", "time": value, }, }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - InitContainers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyNever, + InitContainers: []v1.Container{ { Name: "init1", Image: "gcr.io/google_containers/busybox:1.24", @@ -298,24 +324,27 @@ var _ = framework.KubeDescribe("InitContainer", func() { Command: []string{"/bin/false"}, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "run1", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"/bin/true"}, - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(30*1024*1024, resource.DecimalSI), + Resources: v1.ResourceRequirements{ + Limits: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(30*1024*1024, resource.DecimalSI), }, }, }, }, }, } + if err := podutil.SetInitContainersAnnotations(pod); err != nil { + Expect(err).To(BeNil()) + } startedPod := podClient.Create(pod) - w, err := podClient.Watch(api.SingleObject(startedPod.ObjectMeta)) + w, err := podClient.Watch(v1.SingleObject(startedPod.ObjectMeta)) Expect(err).NotTo(HaveOccurred(), "error watching a pod") wr := watch.NewRecorder(w) @@ -324,7 +353,10 @@ var _ = framework.KubeDescribe("InitContainer", func() { // check for the second container to fail at least once func(evt watch.Event) (bool, error) { switch t := evt.Object.(type) { - case *api.Pod: + case *v1.Pod: + if err := podutil.SetInitContainersAndStatuses(t); err != nil { + Expect(err).To(BeNil()) + } for _, status := range t.Status.ContainerStatuses { if status.State.Waiting == nil { return false, fmt.Errorf("container %q should not be out of waiting: %#v", status.Name, status) @@ -358,16 +390,16 @@ var _ = framework.KubeDescribe("InitContainer", func() { return false, fmt.Errorf("unexpected object: %#v", t) } }, - client.PodCompleted, + conditions.PodCompleted, ) Expect(err).To(BeNil()) framework.CheckInvariants(wr.Events(), framework.ContainerInitInvariant) - endPod := event.Object.(*api.Pod) + endPod := event.Object.(*v1.Pod) - Expect(endPod.Status.Phase).To(Equal(api.PodFailed)) - _, init := api.GetPodCondition(&endPod.Status, api.PodInitialized) + Expect(endPod.Status.Phase).To(Equal(v1.PodFailed)) + _, init := v1.GetPodCondition(&endPod.Status, v1.PodInitialized) Expect(init).NotTo(BeNil()) - Expect(init.Status).To(Equal(api.ConditionFalse)) + Expect(init.Status).To(Equal(v1.ConditionFalse)) Expect(init.Reason).To(Equal("ContainersNotInitialized")) Expect(init.Message).To(Equal("containers with incomplete status: [init2]")) Expect(len(endPod.Status.InitContainerStatuses)).To(Equal(2)) diff --git a/test/e2e/common/kubelet_etc_hosts.go b/test/e2e/common/kubelet_etc_hosts.go index 49715695d0a..ae0bb80642a 100644 --- a/test/e2e/common/kubelet_etc_hosts.go +++ b/test/e2e/common/kubelet_etc_hosts.go @@ -22,7 +22,7 @@ import ( "github.com/golang/glog" . "github.com/onsi/ginkgo" - api "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/test/e2e/framework" ) @@ -34,8 +34,8 @@ const ( ) type KubeletManagedHostConfig struct { - hostNetworkPod *api.Pod - pod *api.Pod + hostNetworkPod *v1.Pod + pod *v1.Pod f *framework.Framework } @@ -128,17 +128,17 @@ func (config *KubeletManagedHostConfig) getEtcHostsContent(podName, containerNam return config.f.ExecCommandInContainer(podName, containerName, "cat", "/etc/hosts") } -func (config *KubeletManagedHostConfig) createPodSpec(podName string) *api.Pod { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func (config *KubeletManagedHostConfig) createPodSpec(podName string) *v1.Pod { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "busybox-1", Image: etcHostsImageName, - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, Command: []string{ "sleep", "900", @@ -147,7 +147,7 @@ func (config *KubeletManagedHostConfig) createPodSpec(podName string) *api.Pod { { Name: "busybox-2", Image: etcHostsImageName, - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, Command: []string{ "sleep", "900", @@ -156,12 +156,12 @@ func (config *KubeletManagedHostConfig) createPodSpec(podName string) *api.Pod { { Name: "busybox-3", Image: etcHostsImageName, - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, Command: []string{ "sleep", "900", }, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "host-etc-hosts", MountPath: "/etc/hosts", @@ -169,11 +169,11 @@ func (config *KubeletManagedHostConfig) createPodSpec(podName string) *api.Pod { }, }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: "host-etc-hosts", - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{ + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{ Path: "/etc/hosts", }, }, @@ -184,20 +184,19 @@ func (config *KubeletManagedHostConfig) createPodSpec(podName string) *api.Pod { return pod } -func (config *KubeletManagedHostConfig) createPodSpecWithHostNetwork(podName string) *api.Pod { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func (config *KubeletManagedHostConfig) createPodSpecWithHostNetwork(podName string) *v1.Pod { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, - Containers: []api.Container{ + Spec: v1.PodSpec{ + HostNetwork: true, + SecurityContext: &v1.PodSecurityContext{}, + Containers: []v1.Container{ { Name: "busybox-1", Image: etcHostsImageName, - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, Command: []string{ "sleep", "900", @@ -206,7 +205,7 @@ func (config *KubeletManagedHostConfig) createPodSpecWithHostNetwork(podName str { Name: "busybox-2", Image: etcHostsImageName, - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, Command: []string{ "sleep", "900", diff --git a/test/e2e/common/pods.go b/test/e2e/common/pods.go index 36ba4229eaf..bc49a7af816 100644 --- a/test/e2e/common/pods.go +++ b/test/e2e/common/pods.go @@ -26,7 +26,7 @@ import ( "golang.org/x/net/websocket" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/intstr" @@ -46,7 +46,7 @@ var ( ) // testHostIP tests that a pod gets a host IP -func testHostIP(podClient *framework.PodClient, pod *api.Pod) { +func testHostIP(podClient *framework.PodClient, pod *v1.Pod) { By("creating pod") podClient.CreateSync(pod) @@ -69,7 +69,7 @@ func testHostIP(podClient *framework.PodClient, pod *api.Pod) { } } -func startPodAndGetBackOffs(podClient *framework.PodClient, pod *api.Pod, sleepAmount time.Duration) (time.Duration, time.Duration) { +func startPodAndGetBackOffs(podClient *framework.PodClient, pod *v1.Pod, sleepAmount time.Duration) (time.Duration, time.Duration) { podClient.CreateSync(pod) time.Sleep(sleepAmount) Expect(pod.Spec.Containers).NotTo(BeEmpty()) @@ -102,7 +102,7 @@ func getRestartDelay(podClient *framework.PodClient, podName string, containerNa time.Sleep(time.Second) pod, err := podClient.Get(podName) framework.ExpectNoError(err, fmt.Sprintf("getting pod %s", podName)) - status, ok := api.GetContainerStatus(pod.Status.ContainerStatuses, containerName) + status, ok := v1.GetContainerStatus(pod.Status.ContainerStatuses, containerName) if !ok { framework.Logf("getRestartDelay: status missing") continue @@ -127,12 +127,12 @@ var _ = framework.KubeDescribe("Pods", func() { It("should get a host IP [Conformance]", func() { name := "pod-hostip-" + string(uuid.NewUUID()) - testHostIP(podClient, &api.Pod{ - ObjectMeta: api.ObjectMeta{ + testHostIP(podClient, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "test", Image: framework.GetPauseImageName(f.ClientSet), @@ -146,16 +146,16 @@ var _ = framework.KubeDescribe("Pods", func() { By("creating the pod") name := "pod-submit-remove-" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: map[string]string{ "name": "foo", "time": value, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "nginx", Image: "gcr.io/google_containers/nginx-slim:0.7", @@ -166,12 +166,12 @@ var _ = framework.KubeDescribe("Pods", func() { By("setting up watch") selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value})) - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} pods, err := podClient.List(options) Expect(err).NotTo(HaveOccurred(), "failed to query for pods") Expect(len(pods.Items)).To(Equal(0)) - options = api.ListOptions{ - LabelSelector: selector, + options = v1.ListOptions{ + LabelSelector: selector.String(), ResourceVersion: pods.ListMeta.ResourceVersion, } w, err := podClient.Watch(options) @@ -182,7 +182,7 @@ var _ = framework.KubeDescribe("Pods", func() { By("verifying the pod is in kubernetes") selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value})) - options = api.ListOptions{LabelSelector: selector} + options = v1.ListOptions{LabelSelector: selector.String()} pods, err = podClient.List(options) Expect(err).NotTo(HaveOccurred(), "failed to query for pods") Expect(len(pods.Items)).To(Equal(1)) @@ -206,7 +206,7 @@ var _ = framework.KubeDescribe("Pods", func() { framework.Logf("running pod: %#v", pod) By("deleting the pod gracefully") - err = podClient.Delete(pod.Name, api.NewDeleteOptions(30)) + err = podClient.Delete(pod.Name, v1.NewDeleteOptions(30)) Expect(err).NotTo(HaveOccurred(), "failed to delete pod") By("verifying the kubelet observed the termination notice") @@ -233,13 +233,13 @@ var _ = framework.KubeDescribe("Pods", func() { By("verifying pod deletion was observed") deleted := false timeout := false - var lastPod *api.Pod + var lastPod *v1.Pod timer := time.After(30 * time.Second) for !deleted && !timeout { select { case event, _ := <-w.ResultChan(): if event.Type == watch.Deleted { - lastPod = event.Object.(*api.Pod) + lastPod = event.Object.(*v1.Pod) deleted = true } case <-timer: @@ -254,7 +254,7 @@ var _ = framework.KubeDescribe("Pods", func() { Expect(lastPod.Spec.TerminationGracePeriodSeconds).ToNot(BeZero()) selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value})) - options = api.ListOptions{LabelSelector: selector} + options = v1.ListOptions{LabelSelector: selector.String()} pods, err = podClient.List(options) Expect(err).NotTo(HaveOccurred(), "failed to query for pods") Expect(len(pods.Items)).To(Equal(0)) @@ -264,16 +264,16 @@ var _ = framework.KubeDescribe("Pods", func() { By("creating the pod") name := "pod-update-" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: map[string]string{ "name": "foo", "time": value, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "nginx", Image: "gcr.io/google_containers/nginx-slim:0.7", @@ -287,13 +287,13 @@ var _ = framework.KubeDescribe("Pods", func() { By("verifying the pod is in kubernetes") selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value})) - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} pods, err := podClient.List(options) Expect(err).NotTo(HaveOccurred(), "failed to query for pods") Expect(len(pods.Items)).To(Equal(1)) By("updating the pod") - podClient.Update(name, func(pod *api.Pod) { + podClient.Update(name, func(pod *v1.Pod) { value = strconv.Itoa(time.Now().Nanosecond()) pod.Labels["time"] = value }) @@ -302,7 +302,7 @@ var _ = framework.KubeDescribe("Pods", func() { By("verifying the updated pod is in kubernetes") selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value})) - options = api.ListOptions{LabelSelector: selector} + options = v1.ListOptions{LabelSelector: selector.String()} pods, err = podClient.List(options) Expect(err).NotTo(HaveOccurred(), "failed to query for pods") Expect(len(pods.Items)).To(Equal(1)) @@ -313,16 +313,16 @@ var _ = framework.KubeDescribe("Pods", func() { By("creating the pod") name := "pod-update-activedeadlineseconds-" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: map[string]string{ "name": "foo", "time": value, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "nginx", Image: "gcr.io/google_containers/nginx-slim:0.7", @@ -336,13 +336,13 @@ var _ = framework.KubeDescribe("Pods", func() { By("verifying the pod is in kubernetes") selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value})) - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} pods, err := podClient.List(options) Expect(err).NotTo(HaveOccurred(), "failed to query for pods") Expect(len(pods.Items)).To(Equal(1)) By("updating the pod") - podClient.Update(name, func(pod *api.Pod) { + podClient.Update(name, func(pod *v1.Pod) { newDeadline := int64(5) pod.Spec.ActiveDeadlineSeconds = &newDeadline }) @@ -354,17 +354,17 @@ var _ = framework.KubeDescribe("Pods", func() { // Make a pod that will be a service. // This pod serves its hostname via HTTP. serverName := "server-envvars-" + string(uuid.NewUUID()) - serverPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + serverPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: serverName, Labels: map[string]string{"name": serverName}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "srv", Image: "gcr.io/google_containers/serve_hostname:v1.4", - Ports: []api.ContainerPort{{ContainerPort: 9376}}, + Ports: []v1.ContainerPort{{ContainerPort: 9376}}, }, }, }, @@ -379,15 +379,15 @@ var _ = framework.KubeDescribe("Pods", func() { // to match the service. Another is to rethink environment variable names and possibly // allow overriding the prefix in the service manifest. svcName := "fooservice" - svc := &api.Service{ - ObjectMeta: api.ObjectMeta{ + svc := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: svcName, Labels: map[string]string{ "name": svcName, }, }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{{ + Spec: v1.ServiceSpec{ + Ports: []v1.ServicePort{{ Port: 8765, TargetPort: intstr.FromInt(8080), }}, @@ -402,20 +402,20 @@ var _ = framework.KubeDescribe("Pods", func() { // Make a client pod that verifies that it has the service environment variables. podName := "client-envvars-" + string(uuid.NewUUID()) const containerName = "env3cont" - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{"name": podName}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: containerName, Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"sh", "-c", "env"}, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } @@ -442,12 +442,12 @@ var _ = framework.KubeDescribe("Pods", func() { By("creating the pod") name := "pod-exec-websocket-" + string(uuid.NewUUID()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "main", Image: "gcr.io/google_containers/busybox:1.24", @@ -512,12 +512,12 @@ var _ = framework.KubeDescribe("Pods", func() { By("creating the pod") name := "pod-logs-websocket-" + string(uuid.NewUUID()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "main", Image: "gcr.io/google_containers/busybox:1.24", @@ -566,13 +566,13 @@ var _ = framework.KubeDescribe("Pods", func() { It("should have their auto-restart back-off timer reset on image update [Slow]", func() { podName := "pod-back-off-image" containerName := "back-off" - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{"test": "back-off-image"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: containerName, Image: "gcr.io/google_containers/busybox:1.24", @@ -585,7 +585,7 @@ var _ = framework.KubeDescribe("Pods", func() { delay1, delay2 := startPodAndGetBackOffs(podClient, pod, buildBackOffDuration) By("updating the image") - podClient.Update(podName, func(pod *api.Pod) { + podClient.Update(podName, func(pod *v1.Pod) { pod.Spec.Containers[0].Image = "gcr.io/google_containers/nginx-slim:0.7" }) @@ -607,13 +607,13 @@ var _ = framework.KubeDescribe("Pods", func() { It("should cap back-off at MaxContainerBackOff [Slow]", func() { podName := "back-off-cap" containerName := "back-off-cap" - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{"test": "liveness"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: containerName, Image: "gcr.io/google_containers/busybox:1.24", diff --git a/test/e2e/common/privileged.go b/test/e2e/common/privileged.go index a45d1c301de..95792be1d7d 100644 --- a/test/e2e/common/privileged.go +++ b/test/e2e/common/privileged.go @@ -23,7 +23,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/test/e2e/framework" ) @@ -40,9 +40,9 @@ const ( ) type PrivilegedPodTestConfig struct { - privilegedPod *api.Pod + privilegedPod *v1.Pod f *framework.Framework - hostExecPod *api.Pod + hostExecPod *v1.Pod } var _ = framework.KubeDescribe("PrivilegedPod", func() { @@ -96,21 +96,21 @@ func (config *PrivilegedPodTestConfig) dialFromContainer(containerIP string, con return output } -func (config *PrivilegedPodTestConfig) createPrivilegedPodSpec() *api.Pod { +func (config *PrivilegedPodTestConfig) createPrivilegedPodSpec() *v1.Pod { isPrivileged := true notPrivileged := false - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: privilegedPodName, Namespace: config.f.Namespace.Name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: privilegedContainerName, Image: privilegedContainerImage, - ImagePullPolicy: api.PullIfNotPresent, - SecurityContext: &api.SecurityContext{Privileged: &isPrivileged}, + ImagePullPolicy: v1.PullIfNotPresent, + SecurityContext: &v1.SecurityContext{Privileged: &isPrivileged}, Command: []string{ "/netexec", fmt.Sprintf("--http-port=%d", privilegedHttpPort), @@ -120,8 +120,8 @@ func (config *PrivilegedPodTestConfig) createPrivilegedPodSpec() *api.Pod { { Name: notPrivilegedContainerName, Image: privilegedContainerImage, - ImagePullPolicy: api.PullIfNotPresent, - SecurityContext: &api.SecurityContext{Privileged: ¬Privileged}, + ImagePullPolicy: v1.PullIfNotPresent, + SecurityContext: &v1.SecurityContext{Privileged: ¬Privileged}, Command: []string{ "/netexec", fmt.Sprintf("--http-port=%d", notPrivilegedHttpPort), diff --git a/test/e2e/common/secrets.go b/test/e2e/common/secrets.go index 5d3401ca846..196fc1ffd05 100644 --- a/test/e2e/common/secrets.go +++ b/test/e2e/common/secrets.go @@ -20,7 +20,7 @@ import ( "fmt" "os" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -50,7 +50,7 @@ var _ = framework.KubeDescribe("Secrets", func() { It("should be able to mount in a volume regardless of a different secret existing with same name in different namespace", func() { var ( - namespace2 *api.Namespace + namespace2 *v1.Namespace err error secret2Name = "secret-test-" + string(uuid.NewUUID()) ) @@ -88,37 +88,37 @@ var _ = framework.KubeDescribe("Secrets", func() { framework.Failf("unable to create test secret %s: %v", secret.Name, err) } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-secrets-" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - Secret: &api.SecretVolumeSource{ + VolumeSource: v1.VolumeSource{ + Secret: &v1.SecretVolumeSource{ SecretName: name, }, }, }, { Name: volumeName2, - VolumeSource: api.VolumeSource{ - Secret: &api.SecretVolumeSource{ + VolumeSource: v1.VolumeSource{ + Secret: &v1.SecretVolumeSource{ SecretName: name, }, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "secret-volume-test", Image: "gcr.io/google_containers/mounttest:0.7", Args: []string{ "--file_content=/etc/secret-volume/data-1", "--file_mode=/etc/secret-volume/data-1"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: volumeMountPath, @@ -132,7 +132,7 @@ var _ = framework.KubeDescribe("Secrets", func() { }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } @@ -152,22 +152,22 @@ var _ = framework.KubeDescribe("Secrets", func() { framework.Failf("unable to create test secret %s: %v", secret.Name, err) } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-secrets-" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "secret-env-test", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"sh", "-c", "env"}, - Env: []api.EnvVar{ + Env: []v1.EnvVar{ { Name: "SECRET_DATA", - ValueFrom: &api.EnvVarSource{ - SecretKeyRef: &api.SecretKeySelector{ - LocalObjectReference: api.LocalObjectReference{ + ValueFrom: &v1.EnvVarSource{ + SecretKeyRef: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ Name: name, }, Key: "data-1", @@ -177,7 +177,7 @@ var _ = framework.KubeDescribe("Secrets", func() { }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } @@ -187,9 +187,9 @@ var _ = framework.KubeDescribe("Secrets", func() { }) }) -func secretForTest(namespace, name string) *api.Secret { - return &api.Secret{ - ObjectMeta: api.ObjectMeta{ +func secretForTest(namespace, name string) *v1.Secret { + return &v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Namespace: namespace, Name: name, }, @@ -214,30 +214,30 @@ func doSecretE2EWithoutMapping(f *framework.Framework, defaultMode *int32, secre framework.Failf("unable to create test secret %s: %v", secret.Name, err) } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-secrets-" + string(uuid.NewUUID()), Namespace: f.Namespace.Name, }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - Secret: &api.SecretVolumeSource{ + VolumeSource: v1.VolumeSource{ + Secret: &v1.SecretVolumeSource{ SecretName: secretName, }, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "secret-volume-test", Image: "gcr.io/google_containers/mounttest:0.7", Args: []string{ "--file_content=/etc/secret-volume/data-1", "--file_mode=/etc/secret-volume/data-1"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: volumeMountPath, @@ -245,7 +245,7 @@ func doSecretE2EWithoutMapping(f *framework.Framework, defaultMode *int32, secre }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } @@ -279,18 +279,18 @@ func doSecretE2EWithMapping(f *framework.Framework, mode *int32) { framework.Failf("unable to create test secret %s: %v", secret.Name, err) } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-secrets-" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - Secret: &api.SecretVolumeSource{ + VolumeSource: v1.VolumeSource{ + Secret: &v1.SecretVolumeSource{ SecretName: name, - Items: []api.KeyToPath{ + Items: []v1.KeyToPath{ { Key: "data-1", Path: "new-path-data-1", @@ -300,14 +300,14 @@ func doSecretE2EWithMapping(f *framework.Framework, mode *int32) { }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "secret-volume-test", Image: "gcr.io/google_containers/mounttest:0.7", Args: []string{ "--file_content=/etc/secret-volume/new-path-data-1", "--file_mode=/etc/secret-volume/new-path-data-1"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: volumeMountPath, @@ -315,7 +315,7 @@ func doSecretE2EWithMapping(f *framework.Framework, mode *int32) { }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } diff --git a/test/e2e/common/sysctl.go b/test/e2e/common/sysctl.go index 5aa089f989f..2dbf5228e74 100644 --- a/test/e2e/common/sysctl.go +++ b/test/e2e/common/sysctl.go @@ -19,7 +19,7 @@ package common import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/events" "k8s.io/kubernetes/pkg/kubelet/sysctl" "k8s.io/kubernetes/pkg/util/uuid" @@ -34,29 +34,29 @@ var _ = framework.KubeDescribe("Sysctls", func() { f := framework.NewDefaultFramework("sysctl") var podClient *framework.PodClient - testPod := func() *api.Pod { + testPod := func() *v1.Pod { podName := "sysctl-" + string(uuid.NewUUID()) - pod := api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Annotations: map[string]string{}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "test-container", Image: "gcr.io/google_containers/busybox:1.24", }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } return &pod } - waitForPodErrorEventOrStarted := func(pod *api.Pod) (*api.Event, error) { - var ev *api.Event + waitForPodErrorEventOrStarted := func(pod *v1.Pod) (*v1.Event, error) { + var ev *v1.Event err := wait.Poll(framework.Poll, framework.PodStartTimeout, func() (bool, error) { evnts, err := f.ClientSet.Core().Events(pod.Namespace).Search(pod) if err != nil { @@ -82,7 +82,7 @@ var _ = framework.KubeDescribe("Sysctls", func() { It("should support sysctls", func() { pod := testPod() - pod.Annotations[api.SysctlsPodAnnotationKey] = api.PodAnnotationsFromSysctls([]api.Sysctl{ + pod.Annotations[v1.SysctlsPodAnnotationKey] = v1.PodAnnotationsFromSysctls([]v1.Sysctl{ { Name: "kernel.shm_rmid_forced", Value: "1", @@ -111,7 +111,7 @@ var _ = framework.KubeDescribe("Sysctls", func() { Expect(err).NotTo(HaveOccurred()) By("Checking that the pod succeeded") - Expect(pod.Status.Phase).To(Equal(api.PodSucceeded)) + Expect(pod.Status.Phase).To(Equal(v1.PodSucceeded)) By("Getting logs from the pod") log, err := framework.GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, pod.Spec.Containers[0].Name) @@ -123,7 +123,7 @@ var _ = framework.KubeDescribe("Sysctls", func() { It("should support unsafe sysctls which are actually whitelisted", func() { pod := testPod() - pod.Annotations[api.UnsafeSysctlsPodAnnotationKey] = api.PodAnnotationsFromSysctls([]api.Sysctl{ + pod.Annotations[v1.UnsafeSysctlsPodAnnotationKey] = v1.PodAnnotationsFromSysctls([]v1.Sysctl{ { Name: "kernel.shm_rmid_forced", Value: "1", @@ -152,7 +152,7 @@ var _ = framework.KubeDescribe("Sysctls", func() { Expect(err).NotTo(HaveOccurred()) By("Checking that the pod succeeded") - Expect(pod.Status.Phase).To(Equal(api.PodSucceeded)) + Expect(pod.Status.Phase).To(Equal(v1.PodSucceeded)) By("Getting logs from the pod") log, err := framework.GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, pod.Spec.Containers[0].Name) @@ -164,7 +164,7 @@ var _ = framework.KubeDescribe("Sysctls", func() { It("should reject invalid sysctls", func() { pod := testPod() - pod.Annotations[api.SysctlsPodAnnotationKey] = api.PodAnnotationsFromSysctls([]api.Sysctl{ + pod.Annotations[v1.SysctlsPodAnnotationKey] = v1.PodAnnotationsFromSysctls([]v1.Sysctl{ { Name: "foo-", Value: "bar", @@ -178,7 +178,7 @@ var _ = framework.KubeDescribe("Sysctls", func() { Value: "100000000", }, }) - pod.Annotations[api.UnsafeSysctlsPodAnnotationKey] = api.PodAnnotationsFromSysctls([]api.Sysctl{ + pod.Annotations[v1.UnsafeSysctlsPodAnnotationKey] = v1.PodAnnotationsFromSysctls([]v1.Sysctl{ { Name: "kernel.shmall", Value: "100000000", @@ -206,7 +206,7 @@ var _ = framework.KubeDescribe("Sysctls", func() { It("should not launch unsafe, but not explicitly enabled sysctls on the node", func() { pod := testPod() - pod.Annotations[api.SysctlsPodAnnotationKey] = api.PodAnnotationsFromSysctls([]api.Sysctl{ + pod.Annotations[v1.SysctlsPodAnnotationKey] = v1.PodAnnotationsFromSysctls([]v1.Sysctl{ { Name: "kernel.msgmax", Value: "10000000000", diff --git a/test/e2e/common/volumes.go b/test/e2e/common/volumes.go index 57ebe961dd7..532d363a587 100644 --- a/test/e2e/common/volumes.go +++ b/test/e2e/common/volumes.go @@ -47,10 +47,10 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" apierrs "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/test/e2e/framework" "github.com/golang/glog" @@ -79,31 +79,31 @@ type VolumeTestConfig struct { // Starts a container specified by config.serverImage and exports all // config.serverPorts from it. The returned pod should be used to get the server // IP address and create appropriate VolumeSource. -func startVolumeServer(f *framework.Framework, config VolumeTestConfig) *api.Pod { +func startVolumeServer(f *framework.Framework, config VolumeTestConfig) *v1.Pod { podClient := f.PodClient() portCount := len(config.serverPorts) - serverPodPorts := make([]api.ContainerPort, portCount) + serverPodPorts := make([]v1.ContainerPort, portCount) for i := 0; i < portCount; i++ { portName := fmt.Sprintf("%s-%d", config.prefix, i) - serverPodPorts[i] = api.ContainerPort{ + serverPodPorts[i] = v1.ContainerPort{ Name: portName, ContainerPort: int32(config.serverPorts[i]), - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, } } volumeCount := len(config.volumes) - volumes := make([]api.Volume, volumeCount) - mounts := make([]api.VolumeMount, volumeCount) + volumes := make([]v1.Volume, volumeCount) + mounts := make([]v1.VolumeMount, volumeCount) i := 0 for src, dst := range config.volumes { mountName := fmt.Sprintf("path%d", i) volumes[i].Name = mountName - volumes[i].VolumeSource.HostPath = &api.HostPathVolumeSource{ + volumes[i].VolumeSource.HostPath = &v1.HostPathVolumeSource{ Path: src, } @@ -117,24 +117,24 @@ func startVolumeServer(f *framework.Framework, config VolumeTestConfig) *api.Pod By(fmt.Sprint("creating ", config.prefix, " server pod")) privileged := new(bool) *privileged = true - serverPod := &api.Pod{ + serverPod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.prefix + "-server", Labels: map[string]string{ "role": config.prefix + "-server", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: config.prefix + "-server", Image: config.serverImage, - SecurityContext: &api.SecurityContext{ + SecurityContext: &v1.SecurityContext{ Privileged: privileged, }, Args: config.serverArgs, @@ -191,21 +191,21 @@ func volumeTestCleanup(f *framework.Framework, config VolumeTestConfig) { // Start a client pod using given VolumeSource (exported by startVolumeServer()) // and check that the pod sees the data from the server pod. -func testVolumeClient(f *framework.Framework, config VolumeTestConfig, volume api.VolumeSource, fsGroup *int64, expectedContent string) { +func testVolumeClient(f *framework.Framework, config VolumeTestConfig, volume v1.VolumeSource, fsGroup *int64, expectedContent string) { By(fmt.Sprint("starting ", config.prefix, " client")) - clientPod := &api.Pod{ + clientPod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.prefix + "-client", Labels: map[string]string{ "role": config.prefix + "-client", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: config.prefix + "-client", Image: "gcr.io/google_containers/busybox:1.24", @@ -218,7 +218,7 @@ func testVolumeClient(f *framework.Framework, config VolumeTestConfig, volume ap "-c", "while true ; do cat /opt/index.html ; sleep 2 ; ls -altrh /opt/ ; sleep 2 ; done ", }, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: config.prefix + "-volume", MountPath: "/opt/", @@ -226,12 +226,12 @@ func testVolumeClient(f *framework.Framework, config VolumeTestConfig, volume ap }, }, }, - SecurityContext: &api.PodSecurityContext{ - SELinuxOptions: &api.SELinuxOptions{ + SecurityContext: &v1.PodSecurityContext{ + SELinuxOptions: &v1.SELinuxOptions{ Level: "s0:c0,c1", }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: config.prefix + "-volume", VolumeSource: volume, @@ -265,29 +265,29 @@ func testVolumeClient(f *framework.Framework, config VolumeTestConfig, volume ap // Insert index.html with given content into given volume. It does so by // starting and auxiliary pod which writes the file there. // The volume must be writable. -func injectHtml(client clientset.Interface, config VolumeTestConfig, volume api.VolumeSource, content string) { +func injectHtml(client clientset.Interface, config VolumeTestConfig, volume v1.VolumeSource, content string) { By(fmt.Sprint("starting ", config.prefix, " injector")) podClient := client.Core().Pods(config.namespace) - injectPod := &api.Pod{ + injectPod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.prefix + "-injector", Labels: map[string]string{ "role": config.prefix + "-injector", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: config.prefix + "-injector", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"/bin/sh"}, Args: []string{"-c", "echo '" + content + "' > /mnt/index.html && chmod o+rX /mnt /mnt/index.html"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: config.prefix + "-volume", MountPath: "/mnt", @@ -295,13 +295,13 @@ func injectHtml(client clientset.Interface, config VolumeTestConfig, volume api. }, }, }, - SecurityContext: &api.PodSecurityContext{ - SELinuxOptions: &api.SELinuxOptions{ + SecurityContext: &v1.PodSecurityContext{ + SELinuxOptions: &v1.SELinuxOptions{ Level: "s0:c0,c1", }, }, - RestartPolicy: api.RestartPolicyNever, - Volumes: []api.Volume{ + RestartPolicy: v1.RestartPolicyNever, + Volumes: []v1.Volume{ { Name: config.prefix + "-volume", VolumeSource: volume, @@ -350,7 +350,7 @@ var _ = framework.KubeDescribe("GCP Volumes", func() { // note that namespace deletion is handled by delete-namespace flag clean := true // filled in BeforeEach - var namespace *api.Namespace + var namespace *v1.Namespace BeforeEach(func() { if !isTestEnabled(f.ClientSet) { @@ -381,8 +381,8 @@ var _ = framework.KubeDescribe("GCP Volumes", func() { serverIP := pod.Status.PodIP framework.Logf("NFS server IP address: %v", serverIP) - volume := api.VolumeSource{ - NFS: &api.NFSVolumeSource{ + volume := v1.VolumeSource{ + NFS: &v1.NFSVolumeSource{ Server: serverIP, Path: "/", ReadOnly: true, @@ -416,26 +416,26 @@ var _ = framework.KubeDescribe("GCP Volumes", func() { framework.Logf("Gluster server IP address: %v", serverIP) // create Endpoints for the server - endpoints := api.Endpoints{ + endpoints := v1.Endpoints{ TypeMeta: unversioned.TypeMeta{ Kind: "Endpoints", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.prefix + "-server", }, - Subsets: []api.EndpointSubset{ + Subsets: []v1.EndpointSubset{ { - Addresses: []api.EndpointAddress{ + Addresses: []v1.EndpointAddress{ { IP: serverIP, }, }, - Ports: []api.EndpointPort{ + Ports: []v1.EndpointPort{ { Name: "gluster", Port: 24007, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, }, }, @@ -454,8 +454,8 @@ var _ = framework.KubeDescribe("GCP Volumes", func() { framework.Failf("Failed to create endpoints for Gluster server: %v", err) } - volume := api.VolumeSource{ - Glusterfs: &api.GlusterfsVolumeSource{ + volume := v1.VolumeSource{ + Glusterfs: &v1.GlusterfsVolumeSource{ EndpointsName: config.prefix + "-server", // 'test_vol' comes from test/images/volumes-tester/gluster/run_gluster.sh Path: "test_vol", diff --git a/test/e2e/cronjob.go b/test/e2e/cronjob.go index 7964e162c9f..4b85689eab4 100644 --- a/test/e2e/cronjob.go +++ b/test/e2e/cronjob.go @@ -23,10 +23,11 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/batch" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + batchv1 "k8s.io/kubernetes/pkg/apis/batch/v1" + batch "k8s.io/kubernetes/pkg/apis/batch/v2alpha1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller/job" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -62,7 +63,7 @@ var _ = framework.KubeDescribe("CronJob", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring at least two running jobs exists by listing jobs explicitly") - jobs, err := f.ClientSet.Batch().Jobs(f.Namespace.Name).List(api.ListOptions{}) + jobs, err := f.ClientSet.Batch().Jobs(f.Namespace.Name).List(v1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) activeJobs := filterActiveJobs(jobs) Expect(len(activeJobs) >= 2).To(BeTrue()) @@ -85,7 +86,7 @@ var _ = framework.KubeDescribe("CronJob", func() { Expect(err).To(HaveOccurred()) By("Ensuring no job exists by listing jobs explicitly") - jobs, err := f.ClientSet.Batch().Jobs(f.Namespace.Name).List(api.ListOptions{}) + jobs, err := f.ClientSet.Batch().Jobs(f.Namespace.Name).List(v1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) Expect(jobs.Items).To(HaveLen(0)) @@ -111,7 +112,7 @@ var _ = framework.KubeDescribe("CronJob", func() { Expect(cronJob.Status.Active).Should(HaveLen(1)) By("Ensuring exaclty one running job exists by listing jobs explicitly") - jobs, err := f.ClientSet.Batch().Jobs(f.Namespace.Name).List(api.ListOptions{}) + jobs, err := f.ClientSet.Batch().Jobs(f.Namespace.Name).List(v1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) activeJobs := filterActiveJobs(jobs) Expect(activeJobs).To(HaveLen(1)) @@ -142,7 +143,7 @@ var _ = framework.KubeDescribe("CronJob", func() { Expect(cronJob.Status.Active).Should(HaveLen(1)) By("Ensuring exaclty one running job exists by listing jobs explicitly") - jobs, err := f.ClientSet.Batch().Jobs(f.Namespace.Name).List(api.ListOptions{}) + jobs, err := f.ClientSet.Batch().Jobs(f.Namespace.Name).List(v1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) activeJobs := filterActiveJobs(jobs) Expect(activeJobs).To(HaveLen(1)) @@ -184,7 +185,7 @@ func newTestCronJob(name, schedule string, concurrencyPolicy batch.ConcurrencyPo parallelism := int32(1) completions := int32(1) sj := &batch.CronJob{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, Spec: batch.CronJobSpec{ @@ -194,22 +195,22 @@ func newTestCronJob(name, schedule string, concurrencyPolicy batch.ConcurrencyPo Spec: batch.JobSpec{ Parallelism: ¶llelism, Completions: &completions, - Template: api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyOnFailure, - Volumes: []api.Volume{ + Template: v1.PodTemplateSpec{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyOnFailure, + Volumes: []v1.Volume{ { Name: "data", - VolumeSource: api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + VolumeSource: v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "c", Image: "gcr.io/google_containers/busybox:1.24", - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { MountPath: "/data", Name: "data", @@ -230,21 +231,21 @@ func newTestCronJob(name, schedule string, concurrencyPolicy batch.ConcurrencyPo } func createCronJob(c clientset.Interface, ns string, cronJob *batch.CronJob) (*batch.CronJob, error) { - return c.Batch().CronJobs(ns).Create(cronJob) + return c.BatchV2alpha1().CronJobs(ns).Create(cronJob) } func getCronJob(c clientset.Interface, ns, name string) (*batch.CronJob, error) { - return c.Batch().CronJobs(ns).Get(name) + return c.BatchV2alpha1().CronJobs(ns).Get(name) } func deleteCronJob(c clientset.Interface, ns, name string) error { - return c.Batch().CronJobs(ns).Delete(name, nil) + return c.BatchV2alpha1().CronJobs(ns).Delete(name, nil) } // Wait for at least given amount of active jobs. func waitForActiveJobs(c clientset.Interface, ns, cronJobName string, active int) error { return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) { - curr, err := c.Batch().CronJobs(ns).Get(cronJobName) + curr, err := c.BatchV2alpha1().CronJobs(ns).Get(cronJobName) if err != nil { return false, err } @@ -255,7 +256,7 @@ func waitForActiveJobs(c clientset.Interface, ns, cronJobName string, active int // Wait for no jobs to appear. func waitForNoJobs(c clientset.Interface, ns, jobName string) error { return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) { - curr, err := c.Batch().CronJobs(ns).Get(jobName) + curr, err := c.BatchV2alpha1().CronJobs(ns).Get(jobName) if err != nil { return false, err } @@ -267,7 +268,7 @@ func waitForNoJobs(c clientset.Interface, ns, jobName string) error { // Wait for a job to be replaced with a new one. func waitForJobReplaced(c clientset.Interface, ns, previousJobName string) error { return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) { - jobs, err := c.Batch().Jobs(ns).List(api.ListOptions{}) + jobs, err := c.Batch().Jobs(ns).List(v1.ListOptions{}) if err != nil { return false, err } @@ -284,7 +285,7 @@ func waitForJobReplaced(c clientset.Interface, ns, previousJobName string) error // waitForJobsAtLeast waits for at least a number of jobs to appear. func waitForJobsAtLeast(c clientset.Interface, ns string, atLeast int) error { return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) { - jobs, err := c.Batch().Jobs(ns).List(api.ListOptions{}) + jobs, err := c.Batch().Jobs(ns).List(v1.ListOptions{}) if err != nil { return false, err } @@ -295,7 +296,7 @@ func waitForJobsAtLeast(c clientset.Interface, ns string, atLeast int) error { // waitForAnyFinishedJob waits for any completed job to appear. func waitForAnyFinishedJob(c clientset.Interface, ns string) error { return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) { - jobs, err := c.Batch().Jobs(ns).List(api.ListOptions{}) + jobs, err := c.Batch().Jobs(ns).List(v1.ListOptions{}) if err != nil { return false, err } @@ -311,7 +312,7 @@ func waitForAnyFinishedJob(c clientset.Interface, ns string) error { // checkNoUnexpectedEvents checks unexpected events didn't happen. // Currently only "UnexpectedJob" is checked. func checkNoUnexpectedEvents(c clientset.Interface, ns, cronJobName string) error { - sj, err := c.Batch().CronJobs(ns).Get(cronJobName) + sj, err := c.BatchV2alpha1().CronJobs(ns).Get(cronJobName) if err != nil { return fmt.Errorf("error in getting cronjob %s/%s: %v", ns, cronJobName, err) } @@ -327,7 +328,7 @@ func checkNoUnexpectedEvents(c clientset.Interface, ns, cronJobName string) erro return nil } -func filterActiveJobs(jobs *batch.JobList) (active []*batch.Job) { +func filterActiveJobs(jobs *batchv1.JobList) (active []*batchv1.Job) { for i := range jobs.Items { j := jobs.Items[i] if !job.IsJobFinished(&j) { diff --git a/test/e2e/daemon_restart.go b/test/e2e/daemon_restart.go index 728d8229f3f..1d646877f39 100644 --- a/test/e2e/daemon_restart.go +++ b/test/e2e/daemon_restart.go @@ -21,9 +21,9 @@ import ( "strconv" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/master/ports" "k8s.io/kubernetes/pkg/runtime" @@ -134,8 +134,8 @@ type podTracker struct { cache.ThreadSafeStore } -func (p *podTracker) remember(pod *api.Pod, eventType string) { - if eventType == UPDATE && pod.Status.Phase == api.PodRunning { +func (p *podTracker) remember(pod *v1.Pod, eventType string) { + if eventType == UPDATE && pod.Status.Phase == v1.PodRunning { return } p.Add(fmt.Sprintf("[%v] %v: %v", time.Now(), eventType, pod.Name), pod) @@ -147,7 +147,7 @@ func (p *podTracker) String() (msg string) { if !exists { continue } - pod := obj.(*api.Pod) + pod := obj.(*v1.Pod) msg += fmt.Sprintf("%v Phase %v Host %v\n", k, pod.Status.Phase, pod.Spec.NodeName) } return @@ -159,7 +159,7 @@ func newPodTracker() *podTracker { } // replacePods replaces content of the store with the given pods. -func replacePods(pods []*api.Pod, store cache.Store) { +func replacePods(pods []*v1.Pod, store cache.Store) { found := make([]interface{}, 0, len(pods)) for i := range pods { found = append(found, pods[i]) @@ -170,7 +170,7 @@ func replacePods(pods []*api.Pod, store cache.Store) { // getContainerRestarts returns the count of container restarts across all pods matching the given labelSelector, // and a list of nodenames across which these containers restarted. func getContainerRestarts(c clientset.Interface, ns string, labelSelector labels.Selector) (int, []string) { - options := api.ListOptions{LabelSelector: labelSelector} + options := v1.ListOptions{LabelSelector: labelSelector.String()} pods, err := c.Core().Pods(ns).List(options) framework.ExpectNoError(err) failedContainers := 0 @@ -205,12 +205,13 @@ var _ = framework.KubeDescribe("DaemonRestart [Disruptive]", func() { // All the restart tests need an rc and a watch on pods of the rc. // Additionally some of them might scale the rc during the test. config = testutils.RCConfig{ - Client: f.ClientSet, - Name: rcName, - Namespace: ns, - Image: framework.GetPauseImageName(f.ClientSet), - Replicas: numPods, - CreatedPods: &[]*api.Pod{}, + Client: f.ClientSet, + InternalClient: f.InternalClientset, + Name: rcName, + Namespace: ns, + Image: framework.GetPauseImageName(f.ClientSet), + Replicas: numPods, + CreatedPods: &[]*v1.Pod{}, } Expect(framework.RunRC(config)).NotTo(HaveOccurred()) replacePods(*config.CreatedPods, existingPods) @@ -219,27 +220,27 @@ var _ = framework.KubeDescribe("DaemonRestart [Disruptive]", func() { tracker = newPodTracker() newPods, controller = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - options.LabelSelector = labelSelector + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + options.LabelSelector = labelSelector.String() obj, err := f.ClientSet.Core().Pods(ns).List(options) return runtime.Object(obj), err }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - options.LabelSelector = labelSelector + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + options.LabelSelector = labelSelector.String() return f.ClientSet.Core().Pods(ns).Watch(options) }, }, - &api.Pod{}, + &v1.Pod{}, 0, cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { - tracker.remember(obj.(*api.Pod), ADD) + tracker.remember(obj.(*v1.Pod), ADD) }, UpdateFunc: func(oldObj, newObj interface{}) { - tracker.remember(newObj.(*api.Pod), UPDATE) + tracker.remember(newObj.(*v1.Pod), UPDATE) }, DeleteFunc: func(obj interface{}) { - tracker.remember(obj.(*api.Pod), DEL) + tracker.remember(obj.(*v1.Pod), DEL) }, }, ) @@ -263,7 +264,7 @@ var _ = framework.KubeDescribe("DaemonRestart [Disruptive]", func() { // that it had the opportunity to create/delete pods, if it were going to do so. Scaling the RC // to the same size achieves this, because the scale operation advances the RC's sequence number // and awaits it to be observed and reported back in the RC's status. - framework.ScaleRC(f.ClientSet, ns, rcName, numPods, true) + framework.ScaleRC(f.ClientSet, f.InternalClientset, ns, rcName, numPods, true) // Only check the keys, the pods can be different if the kubelet updated it. // TODO: Can it really? @@ -294,9 +295,9 @@ var _ = framework.KubeDescribe("DaemonRestart [Disruptive]", func() { restarter.kill() // This is best effort to try and create pods while the scheduler is down, // since we don't know exactly when it is restarted after the kill signal. - framework.ExpectNoError(framework.ScaleRC(f.ClientSet, ns, rcName, numPods+5, false)) + framework.ExpectNoError(framework.ScaleRC(f.ClientSet, f.InternalClientset, ns, rcName, numPods+5, false)) restarter.waitUp() - framework.ExpectNoError(framework.ScaleRC(f.ClientSet, ns, rcName, numPods+5, true)) + framework.ExpectNoError(framework.ScaleRC(f.ClientSet, f.InternalClientset, ns, rcName, numPods+5, true)) }) It("Kubelet should not restart containers across restart", func() { diff --git a/test/e2e/daemon_set.go b/test/e2e/daemon_set.go index aa0f59aad32..7b73001a2df 100644 --- a/test/e2e/daemon_set.go +++ b/test/e2e/daemon_set.go @@ -25,9 +25,11 @@ import ( "k8s.io/kubernetes/pkg/api" apierrs "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/extensions" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + extensionsinternal "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" @@ -58,12 +60,12 @@ var _ = framework.KubeDescribe("Daemon set [Serial]", func() { var f *framework.Framework AfterEach(func() { - if daemonsets, err := f.ClientSet.Extensions().DaemonSets(f.Namespace.Name).List(api.ListOptions{}); err == nil { + if daemonsets, err := f.ClientSet.Extensions().DaemonSets(f.Namespace.Name).List(v1.ListOptions{}); err == nil { framework.Logf("daemonset: %s", runtime.EncodeOrDie(api.Codecs.LegacyCodec(registered.EnabledVersions()...), daemonsets)) } else { framework.Logf("unable to dump daemonsets: %v", err) } - if pods, err := f.ClientSet.Core().Pods(f.Namespace.Name).List(api.ListOptions{}); err == nil { + if pods, err := f.ClientSet.Core().Pods(f.Namespace.Name).List(v1.ListOptions{}); err == nil { framework.Logf("pods: %s", runtime.EncodeOrDie(api.Codecs.LegacyCodec(registered.EnabledVersions()...), pods)) } else { framework.Logf("unable to dump pods: %v", err) @@ -93,20 +95,20 @@ var _ = framework.KubeDescribe("Daemon set [Serial]", func() { framework.Logf("Creating simple daemon set %s", dsName) _, err := c.Extensions().DaemonSets(ns).Create(&extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: dsName, }, Spec: extensions.DaemonSetSpec{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: label, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: dsName, Image: image, - Ports: []api.ContainerPort{{ContainerPort: 9376}}, + Ports: []v1.ContainerPort{{ContainerPort: 9376}}, }, }, }, @@ -116,7 +118,7 @@ var _ = framework.KubeDescribe("Daemon set [Serial]", func() { Expect(err).NotTo(HaveOccurred()) defer func() { framework.Logf("Check that reaper kills all daemon pods for %s", dsName) - dsReaper, err := kubectl.ReaperFor(extensions.Kind("DaemonSet"), f.ClientSet) + dsReaper, err := kubectl.ReaperFor(extensionsinternal.Kind("DaemonSet"), f.InternalClientset) Expect(err).NotTo(HaveOccurred()) err = dsReaper.Stop(ns, dsName, 0, nil) Expect(err).NotTo(HaveOccurred()) @@ -135,7 +137,7 @@ var _ = framework.KubeDescribe("Daemon set [Serial]", func() { podClient := c.Core().Pods(ns) selector := labels.Set(label).AsSelector() - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} podList, err := podClient.List(options) Expect(err).NotTo(HaveOccurred()) Expect(len(podList.Items)).To(BeNumerically(">", 0)) @@ -152,22 +154,22 @@ var _ = framework.KubeDescribe("Daemon set [Serial]", func() { nodeSelector := map[string]string{daemonsetColorLabel: "blue"} framework.Logf("Creating daemon with a node selector %s", dsName) _, err := c.Extensions().DaemonSets(ns).Create(&extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: dsName, }, Spec: extensions.DaemonSetSpec{ Selector: &unversioned.LabelSelector{MatchLabels: complexLabel}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: complexLabel, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeSelector: nodeSelector, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: dsName, Image: image, - Ports: []api.ContainerPort{{ContainerPort: 9376}}, + Ports: []v1.ContainerPort{{ContainerPort: 9376}}, }, }, }, @@ -208,7 +210,7 @@ var _ = framework.KubeDescribe("Daemon set [Serial]", func() { nodeSelector := map[string]string{daemonsetColorLabel: "blue"} framework.Logf("Creating daemon with a node affinity %s", dsName) affinity := map[string]string{ - api.AffinityAnnotationKey: fmt.Sprintf(` + v1.AffinityAnnotationKey: fmt.Sprintf(` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -220,22 +222,22 @@ var _ = framework.KubeDescribe("Daemon set [Serial]", func() { }}}`, daemonsetColorLabel, nodeSelector[daemonsetColorLabel]), } _, err := c.Extensions().DaemonSets(ns).Create(&extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: dsName, }, Spec: extensions.DaemonSetSpec{ Selector: &unversioned.LabelSelector{MatchLabels: complexLabel}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: complexLabel, Annotations: affinity, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: dsName, Image: image, - Ports: []api.ContainerPort{{ContainerPort: 9376}}, + Ports: []v1.ContainerPort{{ContainerPort: 9376}}, }, }, }, @@ -296,9 +298,9 @@ func clearDaemonSetNodeLabels(c clientset.Interface) error { return nil } -func setDaemonSetNodeLabels(c clientset.Interface, nodeName string, labels map[string]string) (*api.Node, error) { +func setDaemonSetNodeLabels(c clientset.Interface, nodeName string, labels map[string]string) (*v1.Node, error) { nodeClient := c.Core().Nodes() - var newNode *api.Node + var newNode *v1.Node var newLabels map[string]string err := wait.Poll(dsRetryPeriod, dsRetryTimeout, func() (bool, error) { node, err := nodeClient.Get(nodeName) @@ -339,7 +341,7 @@ func setDaemonSetNodeLabels(c clientset.Interface, nodeName string, labels map[s func checkDaemonPodOnNodes(f *framework.Framework, selector map[string]string, nodeNames []string) func() (bool, error) { return func() (bool, error) { selector := labels.Set(selector).AsSelector() - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} podList, err := f.ClientSet.Core().Pods(f.Namespace.Name).List(options) if err != nil { return false, nil @@ -368,7 +370,7 @@ func checkDaemonPodOnNodes(f *framework.Framework, selector map[string]string, n func checkRunningOnAllNodes(f *framework.Framework, selector map[string]string) func() (bool, error) { return func() (bool, error) { - nodeList, err := f.ClientSet.Core().Nodes().List(api.ListOptions{}) + nodeList, err := f.ClientSet.Core().Nodes().List(v1.ListOptions{}) framework.ExpectNoError(err) nodeNames := make([]string, 0) for _, node := range nodeList.Items { @@ -385,7 +387,7 @@ func checkRunningOnNoNodes(f *framework.Framework, selector map[string]string) f func checkDaemonStatus(f *framework.Framework, dsName string) error { ds, err := f.ClientSet.Extensions().DaemonSets(f.Namespace.Name).Get(dsName) if err != nil { - return fmt.Errorf("Could not get daemon set from api.") + return fmt.Errorf("Could not get daemon set from v1.") } desired, scheduled, ready := ds.Status.DesiredNumberScheduled, ds.Status.CurrentNumberScheduled, ds.Status.NumberReady if desired != scheduled && desired != ready { diff --git a/test/e2e/density.go b/test/e2e/density.go index 93c8fc20e27..3e0aa558e26 100644 --- a/test/e2e/density.go +++ b/test/e2e/density.go @@ -28,8 +28,10 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" @@ -54,10 +56,11 @@ const ( var MaxContainerFailures = 0 type DensityTestConfig struct { - Configs []testutils.RCConfig - ClientSet internalclientset.Interface - PollInterval time.Duration - PodCount int + Configs []testutils.RCConfig + ClientSet clientset.Interface + InternalClientset internalclientset.Interface + PollInterval time.Duration + PodCount int } func density30AddonResourceVerifier(numNodes int) map[string]framework.ResourceConstraint { @@ -159,9 +162,9 @@ func density30AddonResourceVerifier(numNodes int) map[string]framework.ResourceC return constraints } -func logPodStartupStatus(c internalclientset.Interface, expectedPods int, observedLabels map[string]string, period time.Duration, stopCh chan struct{}) { +func logPodStartupStatus(c clientset.Interface, expectedPods int, observedLabels map[string]string, period time.Duration, stopCh chan struct{}) { label := labels.SelectorFromSet(labels.Set(observedLabels)) - podStore := testutils.NewPodStore(c, api.NamespaceAll, label, fields.Everything()) + podStore := testutils.NewPodStore(c, v1.NamespaceAll, label, fields.Everything()) defer podStore.Stop() ticker := time.NewTicker(period) defer ticker.Stop() @@ -209,7 +212,7 @@ func runDensityTest(dtc DensityTestConfig) time.Duration { // Print some data about Pod to Node allocation By("Printing Pod to Node allocation data") - podList, err := dtc.ClientSet.Core().Pods(api.NamespaceAll).List(api.ListOptions{}) + podList, err := dtc.ClientSet.Core().Pods(v1.NamespaceAll).List(v1.ListOptions{}) framework.ExpectNoError(err) pausePodAllocation := make(map[string]int) systemPodAllocation := make(map[string][]string) @@ -238,14 +241,14 @@ func cleanupDensityTest(dtc DensityTestConfig) { for i := range dtc.Configs { rcName := dtc.Configs[i].Name rc, err := dtc.ClientSet.Core().ReplicationControllers(dtc.Configs[i].Namespace).Get(rcName) - if err == nil && rc.Spec.Replicas != 0 { + if err == nil && *(rc.Spec.Replicas) != 0 { if framework.TestContext.GarbageCollectorEnabled { By("Cleaning up only the replication controller, garbage collector will clean up the pods") err := framework.DeleteRCAndWaitForGC(dtc.ClientSet, dtc.Configs[i].Namespace, rcName) framework.ExpectNoError(err) } else { By("Cleaning up the replication controller and pods") - err := framework.DeleteRCAndPods(dtc.ClientSet, dtc.Configs[i].Namespace, rcName) + err := framework.DeleteRCAndPods(dtc.ClientSet, dtc.InternalClientset, dtc.Configs[i].Namespace, rcName) framework.ExpectNoError(err) } } @@ -260,7 +263,7 @@ func cleanupDensityTest(dtc DensityTestConfig) { // results will not be representative for control-plane performance as we'll start hitting // limits on Docker's concurrent container startup. var _ = framework.KubeDescribe("Density", func() { - var c internalclientset.Interface + var c clientset.Interface var nodeCount int var RCName string var additionalPodsPrefix string @@ -270,7 +273,7 @@ var _ = framework.KubeDescribe("Density", func() { var totalPods int var nodeCpuCapacity int64 var nodeMemCapacity int64 - var nodes *api.NodeList + var nodes *v1.NodeList var masters sets.String // Gathers data prior to framework namespace teardown @@ -332,10 +335,10 @@ var _ = framework.KubeDescribe("Density", func() { for _, node := range nodes.Items { var internalIP, externalIP string for _, address := range node.Status.Addresses { - if address.Type == api.NodeInternalIP { + if address.Type == v1.NodeInternalIP { internalIP = address.Address } - if address.Type == api.NodeExternalIP { + if address.Type == v1.NodeExternalIP { externalIP = address.Address } } @@ -399,12 +402,13 @@ var _ = framework.KubeDescribe("Density", func() { podThroughput := 20 timeout := time.Duration(totalPods/podThroughput)*time.Second + 3*time.Minute // createClients is defined in load.go - clients, err := createClients(numberOfRCs) + clients, internalClients, err := createClients(numberOfRCs) for i := 0; i < numberOfRCs; i++ { RCName := fmt.Sprintf("density%v-%v-%v", totalPods, i, uuid) nsName := namespaces[i].Name RCConfigs[i] = testutils.RCConfig{ Client: clients[i], + InternalClient: internalClients[i], Image: framework.GetPauseImageName(f.ClientSet), Name: RCName, Namespace: nsName, @@ -421,10 +425,11 @@ var _ = framework.KubeDescribe("Density", func() { } dConfig := DensityTestConfig{ - ClientSet: f.ClientSet, - Configs: RCConfigs, - PodCount: totalPods, - PollInterval: DensityPollInterval, + ClientSet: f.ClientSet, + InternalClientset: f.InternalClientset, + Configs: RCConfigs, + PodCount: totalPods, + PollInterval: DensityPollInterval, } e2eStartupTime = runDensityTest(dConfig) if itArg.runLatencyTest { @@ -437,12 +442,12 @@ var _ = framework.KubeDescribe("Density", func() { watchTimes := make(map[string]unversioned.Time, 0) var mutex sync.Mutex - checkPod := func(p *api.Pod) { + checkPod := func(p *v1.Pod) { mutex.Lock() defer mutex.Unlock() defer GinkgoRecover() - if p.Status.Phase == api.PodRunning { + if p.Status.Phase == v1.PodRunning { if _, found := watchTimes[p.Name]; !found { watchTimes[p.Name] = unversioned.Now() createTimes[p.Name] = p.CreationTimestamp @@ -472,31 +477,31 @@ var _ = framework.KubeDescribe("Density", func() { nsName := namespaces[i].Name latencyPodsStore, controller := cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - options.LabelSelector = labels.SelectorFromSet(labels.Set{"type": additionalPodsPrefix}) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + options.LabelSelector = labels.SelectorFromSet(labels.Set{"type": additionalPodsPrefix}).String() obj, err := c.Core().Pods(nsName).List(options) return runtime.Object(obj), err }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - options.LabelSelector = labels.SelectorFromSet(labels.Set{"type": additionalPodsPrefix}) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + options.LabelSelector = labels.SelectorFromSet(labels.Set{"type": additionalPodsPrefix}).String() return c.Core().Pods(nsName).Watch(options) }, }, - &api.Pod{}, + &v1.Pod{}, 0, cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { - p, ok := obj.(*api.Pod) + p, ok := obj.(*v1.Pod) if !ok { - framework.Logf("Failed to cast observed object to *api.Pod.") + framework.Logf("Failed to cast observed object to *v1.Pod.") } Expect(ok).To(Equal(true)) go checkPod(p) }, UpdateFunc: func(oldObj, newObj interface{}) { - p, ok := newObj.(*api.Pod) + p, ok := newObj.(*v1.Pod) if !ok { - framework.Logf("Failed to cast observed object to *api.Pod.") + framework.Logf("Failed to cast observed object to *v1.Pod.") } Expect(ok).To(Equal(true)) go checkPod(p) @@ -545,7 +550,7 @@ var _ = framework.KubeDescribe("Density", func() { nodeToLatencyPods := make(map[string]int) for i := range latencyPodStores { for _, item := range latencyPodStores[i].List() { - pod := item.(*api.Pod) + pod := item.(*v1.Pod) nodeToLatencyPods[pod.Spec.NodeName]++ } for node, count := range nodeToLatencyPods { @@ -560,9 +565,9 @@ var _ = framework.KubeDescribe("Density", func() { selector := fields.Set{ "involvedObject.kind": "Pod", "involvedObject.namespace": nsName, - "source": api.DefaultSchedulerName, - }.AsSelector() - options := api.ListOptions{FieldSelector: selector} + "source": v1.DefaultSchedulerName, + }.AsSelector().String() + options := v1.ListOptions{FieldSelector: selector} schedEvents, err := c.Core().Events(nsName).List(options) framework.ExpectNoError(err) for k := range createTimes { @@ -683,39 +688,39 @@ var _ = framework.KubeDescribe("Density", func() { }) }) -func createRunningPodFromRC(wg *sync.WaitGroup, c internalclientset.Interface, name, ns, image, podType string, cpuRequest, memRequest resource.Quantity) { +func createRunningPodFromRC(wg *sync.WaitGroup, c clientset.Interface, name, ns, image, podType string, cpuRequest, memRequest resource.Quantity) { defer GinkgoRecover() defer wg.Done() labels := map[string]string{ "type": podType, "name": name, } - rc := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ + rc := &v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: labels, }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, + Spec: v1.ReplicationControllerSpec{ + Replicas: func(i int) *int32 { x := int32(i); return &x }(1), Selector: labels, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: labels, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: name, Image: image, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceCPU: cpuRequest, - api.ResourceMemory: memRequest, + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceCPU: cpuRequest, + v1.ResourceMemory: memRequest, }, }, }, }, - DNSPolicy: api.DNSDefault, + DNSPolicy: v1.DNSDefault, }, }, }, diff --git a/test/e2e/deployment.go b/test/e2e/deployment.go index 1e5f38c2f63..91783a39c89 100644 --- a/test/e2e/deployment.go +++ b/test/e2e/deployment.go @@ -28,9 +28,12 @@ import ( "k8s.io/kubernetes/pkg/api/annotations" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - client "k8s.io/kubernetes/pkg/client/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + extensionsinternal "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + extensionsclient "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/extensions/v1beta1" deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/labels" @@ -109,23 +112,23 @@ var _ = framework.KubeDescribe("Deployment", func() { func newDeployment(deploymentName string, replicas int32, podLabels map[string]string, imageName string, image string, strategyType extensions.DeploymentStrategyType, revisionHistoryLimit *int32) *extensions.Deployment { zero := int64(0) return &extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: deploymentName, }, Spec: extensions.DeploymentSpec{ - Replicas: replicas, + Replicas: func(i int32) *int32 { return &i }(replicas), Selector: &unversioned.LabelSelector{MatchLabels: podLabels}, Strategy: extensions.DeploymentStrategy{ Type: strategyType, }, RevisionHistoryLimit: revisionHistoryLimit, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: podLabels, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ TerminationGracePeriodSeconds: &zero, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: imageName, Image: image, @@ -168,20 +171,20 @@ func checkDeploymentRevision(c clientset.Interface, ns, deploymentName, revision return deployment, newRS } -func stopDeploymentOverlap(c clientset.Interface, ns, deploymentName, overlapWith string) { - stopDeploymentMaybeOverlap(c, ns, deploymentName, overlapWith) +func stopDeploymentOverlap(c clientset.Interface, internalClient internalclientset.Interface, ns, deploymentName, overlapWith string) { + stopDeploymentMaybeOverlap(c, internalClient, ns, deploymentName, overlapWith) } -func stopDeployment(c clientset.Interface, ns, deploymentName string) { - stopDeploymentMaybeOverlap(c, ns, deploymentName, "") +func stopDeployment(c clientset.Interface, internalClient internalclientset.Interface, ns, deploymentName string) { + stopDeploymentMaybeOverlap(c, internalClient, ns, deploymentName, "") } -func stopDeploymentMaybeOverlap(c clientset.Interface, ns, deploymentName, overlapWith string) { +func stopDeploymentMaybeOverlap(c clientset.Interface, internalClient internalclientset.Interface, ns, deploymentName, overlapWith string) { deployment, err := c.Extensions().Deployments(ns).Get(deploymentName) Expect(err).NotTo(HaveOccurred()) framework.Logf("Deleting deployment %s", deploymentName) - reaper, err := kubectl.ReaperFor(extensions.Kind("Deployment"), c) + reaper, err := kubectl.ReaperFor(extensionsinternal.Kind("Deployment"), internalClient) Expect(err).NotTo(HaveOccurred()) timeout := 1 * time.Minute err = reaper.Stop(ns, deployment.Name, timeout, api.NewDeleteOptions(0)) @@ -194,7 +197,7 @@ func stopDeploymentMaybeOverlap(c clientset.Interface, ns, deploymentName, overl framework.Logf("Ensuring deployment %s's RSes were deleted", deploymentName) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} rss, err := c.Extensions().ReplicaSets(ns).List(options) Expect(err).NotTo(HaveOccurred()) // RSes may be created by overlapping deployments right after this deployment is deleted, ignore them @@ -210,7 +213,7 @@ func stopDeploymentMaybeOverlap(c clientset.Interface, ns, deploymentName, overl Expect(noOverlapRSes).Should(HaveLen(0)) } framework.Logf("Ensuring deployment %s's Pods were deleted", deploymentName) - var pods *api.PodList + var pods *v1.PodList if err := wait.PollImmediate(time.Second, timeout, func() (bool, error) { pods, err = c.Core().Pods(ns).List(options) if err != nil { @@ -220,7 +223,7 @@ func stopDeploymentMaybeOverlap(c clientset.Interface, ns, deploymentName, overl if len(overlapWith) == 0 && len(pods.Items) == 0 { return true, nil } else if len(overlapWith) != 0 { - noOverlapPods := []api.Pod{} + noOverlapPods := []v1.Pod{} for _, pod := range pods.Items { if !strings.HasPrefix(pod.Name, overlapWith) { noOverlapPods = append(noOverlapPods, pod) @@ -270,6 +273,7 @@ func testNewDeployment(f *framework.Framework) { func testDeleteDeployment(f *framework.Framework) { ns := f.Namespace.Name c := f.ClientSet + internalClient := f.InternalClientset deploymentName := "test-new-deployment" podLabels := map[string]string{"name": nginxImageName} @@ -295,7 +299,7 @@ func testDeleteDeployment(f *framework.Framework) { err = fmt.Errorf("expected a replica set, got nil") Expect(err).NotTo(HaveOccurred()) } - stopDeployment(c, ns, deploymentName) + stopDeployment(c, internalClient, ns, deploymentName) } func testRollingUpdateDeployment(f *framework.Framework) { @@ -481,11 +485,11 @@ func testDeploymentCleanUpPolicy(f *framework.Framework) { deploymentName := "test-cleanup-deployment" framework.Logf("Creating deployment %s", deploymentName) - pods, err := c.Core().Pods(ns).List(api.ListOptions{LabelSelector: labels.Everything()}) + pods, err := c.Core().Pods(ns).List(v1.ListOptions{LabelSelector: labels.Everything().String()}) if err != nil { Expect(err).NotTo(HaveOccurred(), "Failed to query for pods: %v", err) } - options := api.ListOptions{ + options := v1.ListOptions{ ResourceVersion: pods.ListMeta.ResourceVersion, } stopCh := make(chan struct{}) @@ -504,7 +508,7 @@ func testDeploymentCleanUpPolicy(f *framework.Framework) { if numPodCreation < 0 { framework.Failf("Expect only one pod creation, the second creation event: %#v\n", event) } - pod, ok := event.Object.(*api.Pod) + pod, ok := event.Object.(*v1.Pod) if !ok { Fail("Expect event Object to be a pod") } @@ -556,8 +560,8 @@ func testRolloverDeployment(f *framework.Framework) { framework.Logf("Creating deployment %s", deploymentName) newDeployment := newDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType, nil) newDeployment.Spec.Strategy.RollingUpdate = &extensions.RollingUpdateDeployment{ - MaxUnavailable: intstr.FromInt(1), - MaxSurge: intstr.FromInt(1), + MaxUnavailable: func(i int) *intstr.IntOrString { x := intstr.FromInt(i); return &x }(1), + MaxSurge: func(i int) *intstr.IntOrString { x := intstr.FromInt(i); return &x }(1), } _, err = c.Extensions().Deployments(ns).Create(newDeployment) Expect(err).NotTo(HaveOccurred()) @@ -571,7 +575,7 @@ func testRolloverDeployment(f *framework.Framework) { _, newRS := checkDeploymentRevision(c, ns, deploymentName, "1", deploymentImageName, deploymentImage) // Before the deployment finishes, update the deployment to rollover the above 2 ReplicaSets and bring up redis pods. - Expect(newRS.Spec.Replicas).Should(BeNumerically("<", deploymentReplicas)) + Expect(*newRS.Spec.Replicas).Should(BeNumerically("<", deploymentReplicas)) updatedDeploymentImageName, updatedDeploymentImage := redisImageName, redisImage deployment, err = framework.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *extensions.Deployment) { update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName @@ -629,7 +633,7 @@ func testPausedDeployment(f *framework.Framework) { if err != nil { Expect(err).NotTo(HaveOccurred()) } - opts := api.ListOptions{LabelSelector: selector} + opts := v1.ListOptions{LabelSelector: selector.String()} w, err := c.Extensions().ReplicaSets(ns).Watch(opts) Expect(err).NotTo(HaveOccurred()) @@ -973,7 +977,7 @@ func testDeploymentLabelAdopted(f *framework.Framework) { // All pods targeted by the deployment should contain pod-template-hash in their labels, and there should be only 3 pods selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} pods, err := c.Core().Pods(ns).List(options) Expect(err).NotTo(HaveOccurred()) err = framework.CheckPodHashLabel(pods) @@ -1015,7 +1019,7 @@ func testScalePausedDeployment(f *framework.Framework) { framework.Logf("Scaling up the paused deployment %q", deploymentName) newReplicas := int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { - update.Spec.Replicas = newReplicas + update.Spec.Replicas = &newReplicas }) Expect(err).NotTo(HaveOccurred()) @@ -1025,8 +1029,8 @@ func testScalePausedDeployment(f *framework.Framework) { rs, err = deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) - if rs.Spec.Replicas != newReplicas { - err = fmt.Errorf("Expected %d replicas for the new replica set, got %d", newReplicas, rs.Spec.Replicas) + if *(rs.Spec.Replicas) != newReplicas { + err = fmt.Errorf("Expected %d replicas for the new replica set, got %d", newReplicas, *(rs.Spec.Replicas)) Expect(err).NotTo(HaveOccurred()) } } @@ -1042,8 +1046,8 @@ func testScaledRolloutDeployment(f *framework.Framework) { deploymentName := "nginx" d := newDeployment(deploymentName, replicas, podLabels, nginxImageName, nginxImage, extensions.RollingUpdateDeploymentStrategyType, nil) d.Spec.Strategy.RollingUpdate = new(extensions.RollingUpdateDeployment) - d.Spec.Strategy.RollingUpdate.MaxSurge = intstr.FromInt(3) - d.Spec.Strategy.RollingUpdate.MaxUnavailable = intstr.FromInt(2) + d.Spec.Strategy.RollingUpdate.MaxSurge = func(i int) *intstr.IntOrString { x := intstr.FromInt(i); return &x }(3) + d.Spec.Strategy.RollingUpdate.MaxUnavailable = func(i int) *intstr.IntOrString { x := intstr.FromInt(i); return &x }(2) By(fmt.Sprintf("Creating deployment %q", deploymentName)) deployment, err := c.Extensions().Deployments(ns).Create(d) @@ -1054,7 +1058,7 @@ func testScaledRolloutDeployment(f *framework.Framework) { // Verify that the required pods have come up. By("Waiting for all required pods to come up") - err = framework.VerifyPods(f.ClientSet, ns, nginxImageName, false, deployment.Spec.Replicas) + err = framework.VerifyPods(f.ClientSet, ns, nginxImageName, false, *(deployment.Spec.Replicas)) if err != nil { framework.Logf("error in waiting for pods to come up: %s", err) Expect(err).NotTo(HaveOccurred()) @@ -1090,18 +1094,18 @@ func testScaledRolloutDeployment(f *framework.Framework) { first, err = c.Extensions().ReplicaSets(first.Namespace).Get(first.Name) Expect(err).NotTo(HaveOccurred()) - firstCond := client.ReplicaSetHasDesiredReplicas(c.Extensions(), first) + firstCond := replicaSetHasDesiredReplicas(c.Extensions(), first) err = wait.PollImmediate(10*time.Millisecond, 1*time.Minute, firstCond) Expect(err).NotTo(HaveOccurred()) - secondCond := client.ReplicaSetHasDesiredReplicas(c.Extensions(), second) + secondCond := replicaSetHasDesiredReplicas(c.Extensions(), second) err = wait.PollImmediate(10*time.Millisecond, 1*time.Minute, secondCond) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Updating the size (up) and template at the same time for deployment %q", deploymentName)) newReplicas := int32(20) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { - update.Spec.Replicas = newReplicas + update.Spec.Replicas = &newReplicas update.Spec.Template.Spec.Containers[0].Image = nautilusImage }) Expect(err).NotTo(HaveOccurred()) @@ -1118,7 +1122,7 @@ func testScaledRolloutDeployment(f *framework.Framework) { for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) - if !ok || desired == deployment.Spec.Replicas { + if !ok || desired == *(deployment.Spec.Replicas) { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) @@ -1150,18 +1154,18 @@ func testScaledRolloutDeployment(f *framework.Framework) { newRs, err := deploymentutil.GetNewReplicaSet(deployment, c) Expect(err).NotTo(HaveOccurred()) - oldCond := client.ReplicaSetHasDesiredReplicas(c.Extensions(), oldRs) + oldCond := replicaSetHasDesiredReplicas(c.Extensions(), oldRs) err = wait.PollImmediate(10*time.Millisecond, 1*time.Minute, oldCond) Expect(err).NotTo(HaveOccurred()) - newCond := client.ReplicaSetHasDesiredReplicas(c.Extensions(), newRs) + newCond := replicaSetHasDesiredReplicas(c.Extensions(), newRs) err = wait.PollImmediate(10*time.Millisecond, 1*time.Minute, newCond) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Updating the size (down) and template at the same time for deployment %q", deploymentName)) newReplicas = int32(5) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { - update.Spec.Replicas = newReplicas + update.Spec.Replicas = &newReplicas update.Spec.Template.Spec.Containers[0].Image = kittenImage }) Expect(err).NotTo(HaveOccurred()) @@ -1178,7 +1182,7 @@ func testScaledRolloutDeployment(f *framework.Framework) { for _, rs := range append(oldRSs, rs) { By(fmt.Sprintf("Ensuring replica set %q has the correct desiredReplicas annotation", rs.Name)) desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) - if !ok || desired == deployment.Spec.Replicas { + if !ok || desired == *(deployment.Spec.Replicas) { continue } err = fmt.Errorf("unexpected desiredReplicas annotation %d for replica set %q", desired, rs.Name) @@ -1189,6 +1193,7 @@ func testScaledRolloutDeployment(f *framework.Framework) { func testOverlappingDeployment(f *framework.Framework) { ns := f.Namespace.Name c := f.ClientSet + internalClient := f.InternalClientset deploymentName := "first-deployment" podLabels := map[string]string{"name": redisImageName} @@ -1219,7 +1224,7 @@ func testOverlappingDeployment(f *framework.Framework) { // Only the first deployment is synced By("Checking only the first overlapping deployment is synced") - options := api.ListOptions{} + options := v1.ListOptions{} rsList, err := c.Extensions().ReplicaSets(ns).List(options) Expect(err).NotTo(HaveOccurred(), "Failed listing all replica sets in namespace %s", ns) Expect(rsList.Items).To(HaveLen(int(replicas))) @@ -1227,7 +1232,7 @@ func testOverlappingDeployment(f *framework.Framework) { Expect(rsList.Items[0].Spec.Template.Spec.Containers[0].Image).To(Equal(deploy.Spec.Template.Spec.Containers[0].Image)) By("Deleting the first deployment") - stopDeploymentOverlap(c, ns, deploy.Name, deployOverlapping.Name) + stopDeploymentOverlap(c, internalClient, ns, deploy.Name, deployOverlapping.Name) // Wait for overlapping annotation cleared By("Waiting for the second deployment to clear overlapping annotation") @@ -1335,11 +1340,11 @@ func randomScale(d *extensions.Deployment, i int) { switch r := rand.Float32(); { case r < 0.3: framework.Logf("%02d: scaling up", i) - d.Spec.Replicas++ + *(d.Spec.Replicas)++ case r < 0.6: - if d.Spec.Replicas > 1 { + if *(d.Spec.Replicas) > 1 { framework.Logf("%02d: scaling down", i) - d.Spec.Replicas-- + *(d.Spec.Replicas)-- } } } @@ -1375,7 +1380,7 @@ func testIterativeDeployments(f *framework.Framework) { // trigger a new deployment framework.Logf("%02d: triggering a new rollout for deployment %q", i, deployment.Name) deployment, err = framework.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *extensions.Deployment) { - newEnv := api.EnvVar{Name: "A", Value: fmt.Sprintf("%d", i)} + newEnv := v1.EnvVar{Name: "A", Value: fmt.Sprintf("%d", i)} update.Spec.Template.Spec.Containers[0].Env = append(update.Spec.Template.Spec.Containers[0].Env, newEnv) randomScale(update, i) }) @@ -1421,7 +1426,7 @@ func testIterativeDeployments(f *framework.Framework) { framework.Logf("%02d: arbitrarily deleting one or more deployment pods for deployment %q", i, deployment.Name) selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) Expect(err).NotTo(HaveOccurred()) - opts := api.ListOptions{LabelSelector: selector} + opts := v1.ListOptions{LabelSelector: selector.String()} podList, err := c.Core().Pods(ns).List(opts) Expect(err).NotTo(HaveOccurred()) if len(podList.Items) == 0 { @@ -1460,3 +1465,14 @@ func testIterativeDeployments(f *framework.Framework) { framework.Logf("Checking deployment %q for a complete condition", deploymentName) Expect(framework.WaitForDeploymentWithCondition(c, ns, deploymentName, deploymentutil.NewRSAvailableReason, extensions.DeploymentProgressing)).NotTo(HaveOccurred()) } + +func replicaSetHasDesiredReplicas(rsClient extensionsclient.ReplicaSetsGetter, replicaSet *extensions.ReplicaSet) wait.ConditionFunc { + desiredGeneration := replicaSet.Generation + return func() (bool, error) { + rs, err := rsClient.ReplicaSets(replicaSet.Namespace).Get(replicaSet.Name) + if err != nil { + return false, err + } + return rs.Status.ObservedGeneration >= desiredGeneration && rs.Status.Replicas == *(rs.Spec.Replicas), nil + } +} diff --git a/test/e2e/disruption.go b/test/e2e/disruption.go index 68d643b0f63..84beed85546 100644 --- a/test/e2e/disruption.go +++ b/test/e2e/disruption.go @@ -24,7 +24,7 @@ import ( . "github.com/onsi/gomega" "k8s.io/client-go/kubernetes" "k8s.io/client-go/pkg/api/unversioned" - api "k8s.io/client-go/pkg/api/v1" + "k8s.io/client-go/pkg/api/v1" extensions "k8s.io/client-go/pkg/apis/extensions/v1beta1" policy "k8s.io/client-go/pkg/apis/policy/v1beta1" "k8s.io/client-go/pkg/util/intstr" @@ -127,15 +127,15 @@ var _ = framework.KubeDescribe("DisruptionController", func() { } // Locate a running pod. - var pod api.Pod + var pod v1.Pod err := wait.PollImmediate(framework.Poll, schedulingTimeout, func() (bool, error) { - podList, err := cs.Pods(ns).List(api.ListOptions{}) + podList, err := cs.Pods(ns).List(v1.ListOptions{}) if err != nil { return false, err } for i := range podList.Items { - if podList.Items[i].Status.Phase == api.PodRunning { + if podList.Items[i].Status.Phase == v1.PodRunning { pod = podList.Items[i] return true, nil } @@ -146,7 +146,7 @@ var _ = framework.KubeDescribe("DisruptionController", func() { Expect(err).NotTo(HaveOccurred()) e := &policy.Eviction{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: pod.Name, Namespace: ns, }, @@ -184,7 +184,7 @@ var _ = framework.KubeDescribe("DisruptionController", func() { func createPodDisruptionBudgetOrDie(cs *kubernetes.Clientset, ns string, minAvailable intstr.IntOrString) { pdb := policy.PodDisruptionBudget{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: ns, }, @@ -199,20 +199,20 @@ func createPodDisruptionBudgetOrDie(cs *kubernetes.Clientset, ns string, minAvai func createPodsOrDie(cs *kubernetes.Clientset, ns string, n int) { for i := 0; i < n; i++ { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: fmt.Sprintf("pod-%d", i), Namespace: ns, Labels: map[string]string{"foo": "bar"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "busybox", Image: "gcr.io/google_containers/echoserver:1.4", }, }, - RestartPolicy: api.RestartPolicyAlways, + RestartPolicy: v1.RestartPolicyAlways, }, } @@ -224,7 +224,7 @@ func createPodsOrDie(cs *kubernetes.Clientset, ns string, n int) { func waitForPodsOrDie(cs *kubernetes.Clientset, ns string, n int) { By("Waiting for all pods to be running") err := wait.PollImmediate(framework.Poll, schedulingTimeout, func() (bool, error) { - pods, err := cs.Core().Pods(ns).List(api.ListOptions{LabelSelector: "foo=bar"}) + pods, err := cs.Core().Pods(ns).List(v1.ListOptions{LabelSelector: "foo=bar"}) if err != nil { return false, err } @@ -237,7 +237,7 @@ func waitForPodsOrDie(cs *kubernetes.Clientset, ns string, n int) { } ready := 0 for i := 0; i < n; i++ { - if pods.Items[i].Status.Phase == api.PodRunning { + if pods.Items[i].Status.Phase == v1.PodRunning { ready++ } } @@ -251,18 +251,18 @@ func waitForPodsOrDie(cs *kubernetes.Clientset, ns string, n int) { } func createReplicaSetOrDie(cs *kubernetes.Clientset, ns string, size int32, exclusive bool) { - container := api.Container{ + container := v1.Container{ Name: "busybox", Image: "gcr.io/google_containers/echoserver:1.4", } if exclusive { - container.Ports = []api.ContainerPort{ + container.Ports = []v1.ContainerPort{ {HostPort: 5555, ContainerPort: 5555}, } } rs := &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "rs", Namespace: ns, }, @@ -271,12 +271,12 @@ func createReplicaSetOrDie(cs *kubernetes.Clientset, ns string, size int32, excl Selector: &unversioned.LabelSelector{ MatchLabels: map[string]string{"foo": "bar"}, }, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"foo": "bar"}, }, - Spec: api.PodSpec{ - Containers: []api.Container{container}, + Spec: v1.PodSpec{ + Containers: []v1.Container{container}, }, }, }, diff --git a/test/e2e/dns.go b/test/e2e/dns.go index 027ab34ccde..3bafd1f256d 100644 --- a/test/e2e/dns.go +++ b/test/e2e/dns.go @@ -24,10 +24,11 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/pod" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/api/v1/pod" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/pkg/util/wait" @@ -42,37 +43,37 @@ var dnsServiceLabelSelector = labels.Set{ "kubernetes.io/cluster-service": "true", }.AsSelector() -func createDNSPod(namespace, wheezyProbeCmd, jessieProbeCmd string, useAnnotation bool) *api.Pod { - dnsPod := &api.Pod{ +func createDNSPod(namespace, wheezyProbeCmd, jessieProbeCmd string, useAnnotation bool) *v1.Pod { + dnsPod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "dns-test-" + string(uuid.NewUUID()), Namespace: namespace, }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "results", - VolumeSource: api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + VolumeSource: v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ // TODO: Consider scraping logs instead of running a webserver. { Name: "webserver", Image: "gcr.io/google_containers/test-webserver:e2e", - Ports: []api.ContainerPort{ + Ports: []v1.ContainerPort{ { Name: "http", ContainerPort: 80, }, }, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "results", MountPath: "/results", @@ -83,7 +84,7 @@ func createDNSPod(namespace, wheezyProbeCmd, jessieProbeCmd string, useAnnotatio Name: "querier", Image: "gcr.io/google_containers/dnsutils:e2e", Command: []string{"sh", "-c", wheezyProbeCmd}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "results", MountPath: "/results", @@ -94,7 +95,7 @@ func createDNSPod(namespace, wheezyProbeCmd, jessieProbeCmd string, useAnnotatio Name: "jessie-querier", Image: "gcr.io/google_containers/jessie-dnsutils:e2e", Command: []string{"sh", "-c", jessieProbeCmd}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "results", MountPath: "/results", @@ -171,11 +172,11 @@ func createTargetedProbeCommand(nameToResolve string, lookup string, fileNamePre return probeCmd, fileName } -func assertFilesExist(fileNames []string, fileDir string, pod *api.Pod, client clientset.Interface) { +func assertFilesExist(fileNames []string, fileDir string, pod *v1.Pod, client clientset.Interface) { assertFilesContain(fileNames, fileDir, pod, client, false, "") } -func assertFilesContain(fileNames []string, fileDir string, pod *api.Pod, client clientset.Interface, check bool, expected string) { +func assertFilesContain(fileNames []string, fileDir string, pod *v1.Pod, client clientset.Interface, check bool, expected string) { var failed []string framework.ExpectNoError(wait.Poll(time.Second*2, time.Second*60, func() (bool, error) { @@ -220,14 +221,14 @@ func assertFilesContain(fileNames []string, fileDir string, pod *api.Pod, client Expect(len(failed)).To(Equal(0)) } -func validateDNSResults(f *framework.Framework, pod *api.Pod, fileNames []string) { +func validateDNSResults(f *framework.Framework, pod *v1.Pod, fileNames []string) { By("submitting the pod to kubernetes") podClient := f.ClientSet.Core().Pods(f.Namespace.Name) defer func() { By("deleting the pod") defer GinkgoRecover() - podClient.Delete(pod.Name, api.NewDeleteOptions(0)) + podClient.Delete(pod.Name, v1.NewDeleteOptions(0)) }() if _, err := podClient.Create(pod); err != nil { framework.Failf("Failed to create %s pod: %v", pod.Name, err) @@ -249,14 +250,14 @@ func validateDNSResults(f *framework.Framework, pod *api.Pod, fileNames []string framework.Logf("DNS probes using %s succeeded\n", pod.Name) } -func validateTargetedProbeOutput(f *framework.Framework, pod *api.Pod, fileNames []string, value string) { +func validateTargetedProbeOutput(f *framework.Framework, pod *v1.Pod, fileNames []string, value string) { By("submitting the pod to kubernetes") podClient := f.ClientSet.Core().Pods(f.Namespace.Name) defer func() { By("deleting the pod") defer GinkgoRecover() - podClient.Delete(pod.Name, api.NewDeleteOptions(0)) + podClient.Delete(pod.Name, v1.NewDeleteOptions(0)) }() if _, err := podClient.Create(pod); err != nil { framework.Failf("Failed to create %s pod: %v", pod.Name, err) @@ -279,7 +280,7 @@ func validateTargetedProbeOutput(f *framework.Framework, pod *api.Pod, fileNames func verifyDNSPodIsRunning(f *framework.Framework) { systemClient := f.ClientSet.Core().Pods(api.NamespaceSystem) By("Waiting for DNS Service to be Running") - options := api.ListOptions{LabelSelector: dnsServiceLabelSelector} + options := v1.ListOptions{LabelSelector: dnsServiceLabelSelector.String()} dnsPods, err := systemClient.List(options) if err != nil { framework.Failf("Failed to list all dns service pods") @@ -291,20 +292,20 @@ func verifyDNSPodIsRunning(f *framework.Framework) { framework.ExpectNoError(framework.WaitForPodRunningInNamespace(f.ClientSet, &pod)) } -func createServiceSpec(serviceName, externalName string, isHeadless bool, selector map[string]string) *api.Service { - headlessService := &api.Service{ - ObjectMeta: api.ObjectMeta{ +func createServiceSpec(serviceName, externalName string, isHeadless bool, selector map[string]string) *v1.Service { + headlessService := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: serviceName, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: selector, }, } if externalName != "" { - headlessService.Spec.Type = api.ServiceTypeExternalName + headlessService.Spec.Type = v1.ServiceTypeExternalName headlessService.Spec.ExternalName = externalName } else { - headlessService.Spec.Ports = []api.ServicePort{ + headlessService.Spec.Ports = []v1.ServicePort{ {Port: 80, Name: "http", Protocol: "TCP"}, } } @@ -463,7 +464,7 @@ var _ = framework.KubeDescribe("DNS", func() { // Test changing the externalName field By("changing the externalName to bar.example.com") - _, err = updateService(f.ClientSet, f.Namespace.Name, serviceName, func(s *api.Service) { + _, err = updateService(f.ClientSet, f.Namespace.Name, serviceName, func(s *v1.Service) { s.Spec.ExternalName = "bar.example.com" }) Expect(err).NotTo(HaveOccurred()) @@ -480,10 +481,10 @@ var _ = framework.KubeDescribe("DNS", func() { // Test changing type from ExternalName to ClusterIP By("changing the service to type=ClusterIP") - _, err = updateService(f.ClientSet, f.Namespace.Name, serviceName, func(s *api.Service) { - s.Spec.Type = api.ServiceTypeClusterIP + _, err = updateService(f.ClientSet, f.Namespace.Name, serviceName, func(s *v1.Service) { + s.Spec.Type = v1.ServiceTypeClusterIP s.Spec.ClusterIP = "127.1.2.3" - s.Spec.Ports = []api.ServicePort{ + s.Spec.Ports = []v1.ServicePort{ {Port: 80, Name: "http", Protocol: "TCP"}, } }) diff --git a/test/e2e/dns_autoscaling.go b/test/e2e/dns_autoscaling.go index 0d4ca8ff5bf..badc6f1b2d9 100644 --- a/test/e2e/dns_autoscaling.go +++ b/test/e2e/dns_autoscaling.go @@ -23,8 +23,8 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -144,7 +144,7 @@ var _ = framework.KubeDescribe("DNS horizontal autoscaling", func() { }) }) -func fetchDNSScalingConfigMap(c clientset.Interface) (*api.ConfigMap, error) { +func fetchDNSScalingConfigMap(c clientset.Interface) (*v1.ConfigMap, error) { cm, err := c.Core().ConfigMaps(DNSNamespace).Get(DNSAutoscalerLabelName) if err != nil { return nil, err @@ -160,15 +160,15 @@ func deleteDNSScalingConfigMap(c clientset.Interface) error { return nil } -func packDNSScalingConfigMap(params map[string]string) *api.ConfigMap { - configMap := api.ConfigMap{} +func packDNSScalingConfigMap(params map[string]string) *v1.ConfigMap { + configMap := v1.ConfigMap{} configMap.ObjectMeta.Name = DNSAutoscalerLabelName configMap.ObjectMeta.Namespace = DNSNamespace configMap.Data = params return &configMap } -func updateDNSScalingConfigMap(c clientset.Interface, configMap *api.ConfigMap) error { +func updateDNSScalingConfigMap(c clientset.Interface, configMap *v1.ConfigMap) error { _, err := c.Core().ConfigMaps(DNSNamespace).Update(configMap) if err != nil { return err @@ -179,7 +179,7 @@ func updateDNSScalingConfigMap(c clientset.Interface, configMap *api.ConfigMap) func getDNSReplicas(c clientset.Interface) (int, error) { label := labels.SelectorFromSet(labels.Set(map[string]string{ClusterAddonLabelKey: KubeDNSLabelName})) - listOpts := api.ListOptions{LabelSelector: label} + listOpts := v1.ListOptions{LabelSelector: label.String()} deployments, err := c.Extensions().Deployments(DNSNamespace).List(listOpts) if err != nil { return 0, err @@ -187,12 +187,12 @@ func getDNSReplicas(c clientset.Interface) (int, error) { Expect(len(deployments.Items)).Should(Equal(1)) deployment := deployments.Items[0] - return int(deployment.Spec.Replicas), nil + return int(*(deployment.Spec.Replicas)), nil } func deleteDNSAutoscalerPod(c clientset.Interface) error { label := labels.SelectorFromSet(labels.Set(map[string]string{ClusterAddonLabelKey: DNSAutoscalerLabelName})) - listOpts := api.ListOptions{LabelSelector: label} + listOpts := v1.ListOptions{LabelSelector: label.String()} pods, err := c.Core().Pods(DNSNamespace).List(listOpts) if err != nil { return err @@ -227,7 +227,7 @@ func waitForDNSReplicasSatisfied(c clientset.Interface, expected int, timeout ti return nil } -func waitForDNSConfigMapCreated(c clientset.Interface, timeout time.Duration) (configMap *api.ConfigMap, err error) { +func waitForDNSConfigMapCreated(c clientset.Interface, timeout time.Duration) (configMap *v1.ConfigMap, err error) { framework.Logf("Waiting up to %v for DNS autoscaling ConfigMap got re-created", timeout) condition := func() (bool, error) { configMap, err = fetchDNSScalingConfigMap(c) diff --git a/test/e2e/dns_configmap.go b/test/e2e/dns_configmap.go index 192e57a385c..e7162639b51 100644 --- a/test/e2e/dns_configmap.go +++ b/test/e2e/dns_configmap.go @@ -21,9 +21,9 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" fed "k8s.io/kubernetes/pkg/dns/federation" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" @@ -42,12 +42,12 @@ type dnsConfigMapTest struct { name string labels []string - cm *api.ConfigMap + cm *v1.ConfigMap isValid bool - dnsPod *api.Pod - utilPod *api.Pod - utilService *api.Service + dnsPod *v1.Pod + utilPod *v1.Pod + utilService *v1.Service } var _ = framework.KubeDescribe("DNS config map", func() { @@ -69,7 +69,7 @@ var _ = framework.KubeDescribe("DNS config map", func() { func (t *dnsConfigMapTest) init() { By("Finding a DNS pod") label := labels.SelectorFromSet(labels.Set(map[string]string{"k8s-app": "kube-dns"})) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := t.f.ClientSet.Core().Pods("kube-system").List(options) Expect(err).NotTo(HaveOccurred()) @@ -94,19 +94,19 @@ func (t *dnsConfigMapTest) run() { invalid := map[string]string{"federations": "invalid.map=xyz"} By("empty -> valid1") - t.setConfigMap(&api.ConfigMap{Data: valid1}, true) + t.setConfigMap(&v1.ConfigMap{Data: valid1}, true) t.validate() By("valid1 -> valid2") - t.setConfigMap(&api.ConfigMap{Data: valid2}, true) + t.setConfigMap(&v1.ConfigMap{Data: valid2}, true) t.validate() By("valid2 -> invalid") - t.setConfigMap(&api.ConfigMap{Data: invalid}, false) + t.setConfigMap(&v1.ConfigMap{Data: invalid}, false) t.validate() By("invalid -> valid1") - t.setConfigMap(&api.ConfigMap{Data: valid1}, true) + t.setConfigMap(&v1.ConfigMap{Data: valid1}, true) t.validate() By("valid1 -> deleted") @@ -114,7 +114,7 @@ func (t *dnsConfigMapTest) run() { t.validate() By("deleted -> invalid") - t.setConfigMap(&api.ConfigMap{Data: invalid}, false) + t.setConfigMap(&v1.ConfigMap{Data: invalid}, false) t.validate() } @@ -210,7 +210,7 @@ func (t *dnsConfigMapTest) runDig(dnsName string) []string { } } -func (t *dnsConfigMapTest) setConfigMap(cm *api.ConfigMap, isValid bool) { +func (t *dnsConfigMapTest) setConfigMap(cm *v1.ConfigMap, isValid bool) { if isValid { t.cm = cm } @@ -219,11 +219,11 @@ func (t *dnsConfigMapTest) setConfigMap(cm *api.ConfigMap, isValid bool) { cm.ObjectMeta.Namespace = t.ns cm.ObjectMeta.Name = t.name - options := api.ListOptions{ + options := v1.ListOptions{ FieldSelector: fields.Set{ "metadata.namespace": t.ns, "metadata.name": t.name, - }.AsSelector(), + }.AsSelector().String(), } cmList, err := t.c.Core().ConfigMaps(t.ns).List(options) Expect(err).NotTo(HaveOccurred()) @@ -253,22 +253,22 @@ func (t *dnsConfigMapTest) createUtilPod() { // Actual port # doesn't matter, just need to exist. const servicePort = 10101 - t.utilPod = &api.Pod{ + t.utilPod = &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Namespace: t.f.Namespace.Name, Labels: map[string]string{"app": "e2e-dns-configmap"}, GenerateName: "e2e-dns-configmap-", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "util", Image: "gcr.io/google_containers/dnsutils:e2e", Command: []string{"sleep", "10000"}, - Ports: []api.ContainerPort{ + Ports: []v1.ContainerPort{ {ContainerPort: servicePort, Protocol: "TCP"}, }, }, @@ -282,17 +282,17 @@ func (t *dnsConfigMapTest) createUtilPod() { framework.Logf("Created pod %v", t.utilPod) Expect(t.f.WaitForPodRunning(t.utilPod.Name)).NotTo(HaveOccurred()) - t.utilService = &api.Service{ + t.utilService = &v1.Service{ TypeMeta: unversioned.TypeMeta{ Kind: "Service", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Namespace: t.f.Namespace.Name, Name: "e2e-dns-configmap", }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: map[string]string{"app": "e2e-dns-configmap"}, - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ { Protocol: "TCP", Port: servicePort, @@ -309,7 +309,7 @@ func (t *dnsConfigMapTest) createUtilPod() { func (t *dnsConfigMapTest) deleteUtilPod() { podClient := t.c.Core().Pods(t.f.Namespace.Name) - if err := podClient.Delete(t.utilPod.Name, api.NewDeleteOptions(0)); err != nil { + if err := podClient.Delete(t.utilPod.Name, v1.NewDeleteOptions(0)); err != nil { framework.Logf("Delete of pod %v:%v failed: %v", t.utilPod.Namespace, t.utilPod.Name, err) } diff --git a/test/e2e/e2e.go b/test/e2e/e2e.go index ba0da19a614..22449966cb3 100644 --- a/test/e2e/e2e.go +++ b/test/e2e/e2e.go @@ -31,6 +31,7 @@ import ( "github.com/onsi/gomega" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" gcecloud "k8s.io/kubernetes/pkg/cloudprovider/providers/gce" "k8s.io/kubernetes/pkg/util/logs" "k8s.io/kubernetes/pkg/util/runtime" @@ -94,19 +95,15 @@ var _ = ginkgo.SynchronizedBeforeSuite(func() []byte { framework.Failf("Failed to setup provider config: %v", err) } - c, err := framework.LoadInternalClientset() + c, err := framework.LoadClientset() if err != nil { glog.Fatal("Error loading client: ", err) } - clientset, err := framework.LoadClientset() - if err != nil { - glog.Fatal("Error loading clientset: ", err) - } // Delete any namespaces except default and kube-system. This ensures no // lingering resources are left over from a previous test run. if framework.TestContext.CleanStart { - deleted, err := framework.DeleteNamespaces(c, nil /* deleteFilter */, []string{api.NamespaceSystem, api.NamespaceDefault}) + deleted, err := framework.DeleteNamespaces(c, nil /* deleteFilter */, []string{api.NamespaceSystem, v1.NamespaceDefault}) if err != nil { framework.Failf("Error deleting orphaned namespaces: %v", err) } @@ -127,9 +124,9 @@ var _ = ginkgo.SynchronizedBeforeSuite(func() []byte { // ready will fail). podStartupTimeout := framework.TestContext.SystemPodsStartupTimeout if err := framework.WaitForPodsRunningReady(c, api.NamespaceSystem, int32(framework.TestContext.MinStartupPods), podStartupTimeout, framework.ImagePullerLabels); err != nil { - framework.DumpAllNamespaceInfo(c, clientset, api.NamespaceSystem) + framework.DumpAllNamespaceInfo(c, api.NamespaceSystem) framework.LogFailedContainers(c, api.NamespaceSystem, framework.Logf) - framework.RunKubernetesServiceTestContainer(c, api.NamespaceDefault) + framework.RunKubernetesServiceTestContainer(c, v1.NamespaceDefault) framework.Failf("Error waiting for all pods to be running and ready: %v", err) } diff --git a/test/e2e/empty_dir_wrapper.go b/test/e2e/empty_dir_wrapper.go index 77d57e57794..28a1e0a0e20 100644 --- a/test/e2e/empty_dir_wrapper.go +++ b/test/e2e/empty_dir_wrapper.go @@ -17,8 +17,8 @@ limitations under the License. package e2e import ( - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -57,8 +57,8 @@ var _ = framework.KubeDescribe("EmptyDir wrapper volumes", func() { volumeName := "secret-volume" volumeMountPath := "/etc/secret-volume" - secret := &api.Secret{ - ObjectMeta: api.ObjectMeta{ + secret := &v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Namespace: f.Namespace.Name, Name: name, }, @@ -77,35 +77,35 @@ var _ = framework.KubeDescribe("EmptyDir wrapper volumes", func() { gitURL, gitRepo, gitCleanup := createGitServer(f) defer gitCleanup() - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-secrets-" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - Secret: &api.SecretVolumeSource{ + VolumeSource: v1.VolumeSource{ + Secret: &v1.SecretVolumeSource{ SecretName: name, }, }, }, { Name: gitVolumeName, - VolumeSource: api.VolumeSource{ - GitRepo: &api.GitRepoVolumeSource{ + VolumeSource: v1.VolumeSource{ + GitRepo: &v1.GitRepoVolumeSource{ Repository: gitURL, Directory: gitRepo, }, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "secret-test", Image: "gcr.io/google_containers/test-webserver:e2e", - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: volumeMountPath, @@ -128,7 +128,7 @@ var _ = framework.KubeDescribe("EmptyDir wrapper volumes", func() { framework.Failf("unable to delete secret %v: %v", secret.Name, err) } By("Cleaning up the git vol pod") - if err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(pod.Name, api.NewDeleteOptions(0)); err != nil { + if err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(pod.Name, v1.NewDeleteOptions(0)); err != nil { framework.Failf("unable to delete git vol pod %v: %v", pod.Name, err) } }() @@ -177,18 +177,18 @@ func createGitServer(f *framework.Framework) (gitURL string, gitRepo string, cle labels := map[string]string{"name": gitServerPodName} - gitServerPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + gitServerPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: gitServerPodName, Labels: labels, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "git-repo", Image: "gcr.io/google_containers/fakegitserver:0.1", ImagePullPolicy: "IfNotPresent", - Ports: []api.ContainerPort{ + Ports: []v1.ContainerPort{ {ContainerPort: int32(containerPort)}, }, }, @@ -200,13 +200,13 @@ func createGitServer(f *framework.Framework) (gitURL string, gitRepo string, cle // Portal IP and port httpPort := 2345 - gitServerSvc := &api.Service{ - ObjectMeta: api.ObjectMeta{ + gitServerSvc := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: "git-server-svc", }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: labels, - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ { Name: "http-portal", Port: int32(httpPort), @@ -222,7 +222,7 @@ func createGitServer(f *framework.Framework) (gitURL string, gitRepo string, cle return "http://" + gitServerSvc.Spec.ClusterIP + ":" + strconv.Itoa(httpPort), "test", func() { By("Cleaning up the git server pod") - if err := f.ClientSet.Core().Pods(f.Namespace.Name).Delete(gitServerPod.Name, api.NewDeleteOptions(0)); err != nil { + if err := f.ClientSet.Core().Pods(f.Namespace.Name).Delete(gitServerPod.Name, v1.NewDeleteOptions(0)); err != nil { framework.Failf("unable to delete git server pod %v: %v", gitServerPod.Name, err) } By("Cleaning up the git server svc") @@ -232,19 +232,19 @@ func createGitServer(f *framework.Framework) (gitURL string, gitRepo string, cle } } -func makeGitRepoVolumes(gitURL, gitRepo string) (volumes []api.Volume, volumeMounts []api.VolumeMount) { +func makeGitRepoVolumes(gitURL, gitRepo string) (volumes []v1.Volume, volumeMounts []v1.VolumeMount) { for i := 0; i < wrappedVolumeRaceGitRepoVolumeCount; i++ { volumeName := fmt.Sprintf("racey-git-repo-%d", i) - volumes = append(volumes, api.Volume{ + volumes = append(volumes, v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - GitRepo: &api.GitRepoVolumeSource{ + VolumeSource: v1.VolumeSource{ + GitRepo: &v1.GitRepoVolumeSource{ Repository: gitURL, Directory: gitRepo, }, }, }) - volumeMounts = append(volumeMounts, api.VolumeMount{ + volumeMounts = append(volumeMounts, v1.VolumeMount{ Name: volumeName, MountPath: fmt.Sprintf("/etc/git-volume-%d", i), }) @@ -257,8 +257,8 @@ func createConfigmapsForRace(f *framework.Framework) (configMapNames []string) { for i := 0; i < wrappedVolumeRaceConfigMapVolumeCount; i++ { configMapName := fmt.Sprintf("racey-configmap-%d", i) configMapNames = append(configMapNames, configMapName) - configMap := &api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ + configMap := &v1.ConfigMap{ + ObjectMeta: v1.ObjectMeta{ Namespace: f.Namespace.Name, Name: configMapName, }, @@ -280,17 +280,17 @@ func deleteConfigMaps(f *framework.Framework, configMapNames []string) { } } -func makeConfigMapVolumes(configMapNames []string) (volumes []api.Volume, volumeMounts []api.VolumeMount) { +func makeConfigMapVolumes(configMapNames []string) (volumes []v1.Volume, volumeMounts []v1.VolumeMount) { for i, configMapName := range configMapNames { volumeName := fmt.Sprintf("racey-configmap-%d", i) - volumes = append(volumes, api.Volume{ + volumes = append(volumes, v1.Volume{ Name: volumeName, - VolumeSource: api.VolumeSource{ - ConfigMap: &api.ConfigMapVolumeSource{ - LocalObjectReference: api.LocalObjectReference{ + VolumeSource: v1.VolumeSource{ + ConfigMap: &v1.ConfigMapVolumeSource{ + LocalObjectReference: v1.LocalObjectReference{ Name: configMapName, }, - Items: []api.KeyToPath{ + Items: []v1.KeyToPath{ { Key: "data-1", Path: "data-1", @@ -299,7 +299,7 @@ func makeConfigMapVolumes(configMapNames []string) (volumes []api.Volume, volume }, }, }) - volumeMounts = append(volumeMounts, api.VolumeMount{ + volumeMounts = append(volumeMounts, v1.VolumeMount{ Name: volumeName, MountPath: fmt.Sprintf("/etc/config-%d", i), }) @@ -307,7 +307,7 @@ func makeConfigMapVolumes(configMapNames []string) (volumes []api.Volume, volume return } -func testNoWrappedVolumeRace(f *framework.Framework, volumes []api.Volume, volumeMounts []api.VolumeMount, podCount int32) { +func testNoWrappedVolumeRace(f *framework.Framework, volumes []v1.Volume, volumeMounts []v1.VolumeMount, podCount int32) { rcName := wrappedVolumeRaceRCNamePrefix + string(uuid.NewUUID()) nodeList := framework.GetReadySchedulableNodesOrDie(f.ClientSet) Expect(len(nodeList.Items)).To(BeNumerically(">", 0)) @@ -315,7 +315,7 @@ func testNoWrappedVolumeRace(f *framework.Framework, volumes []api.Volume, volum By("Creating RC which spawns configmap-volume pods") affinity := map[string]string{ - api.AffinityAnnotationKey: fmt.Sprintf(` + v1.AffinityAnnotationKey: fmt.Sprintf(` {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ @@ -327,35 +327,35 @@ func testNoWrappedVolumeRace(f *framework.Framework, volumes []api.Volume, volum }}}`, targetNode.Name), } - rc := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ + rc := &v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{ Name: rcName, }, - Spec: api.ReplicationControllerSpec{ - Replicas: podCount, + Spec: v1.ReplicationControllerSpec{ + Replicas: &podCount, Selector: map[string]string{ "name": rcName, }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Annotations: affinity, Labels: map[string]string{"name": rcName}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "test-container", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"sleep", "10000"}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceCPU: resource.MustParse("10m"), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("10m"), }, }, VolumeMounts: volumeMounts, }, }, - DNSPolicy: api.DNSDefault, + DNSPolicy: v1.DNSDefault, Volumes: volumes, }, }, @@ -365,7 +365,7 @@ func testNoWrappedVolumeRace(f *framework.Framework, volumes []api.Volume, volum Expect(err).NotTo(HaveOccurred(), "error creating replication controller") defer func() { - err := framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, rcName) + err := framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, rcName) framework.ExpectNoError(err) }() diff --git a/test/e2e/etcd_failure.go b/test/e2e/etcd_failure.go index f9eba185430..d18fd8ef86f 100644 --- a/test/e2e/etcd_failure.go +++ b/test/e2e/etcd_failure.go @@ -19,7 +19,7 @@ package e2e import ( "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -106,7 +106,7 @@ func checkExistingRCRecovers(f *framework.Framework) { By("deleting pods from existing replication controller") framework.ExpectNoError(wait.Poll(time.Millisecond*500, time.Second*60, func() (bool, error) { - options := api.ListOptions{LabelSelector: rcSelector} + options := v1.ListOptions{LabelSelector: rcSelector.String()} pods, err := podClient.List(options) if err != nil { framework.Logf("apiserver returned error, as expected before recovery: %v", err) @@ -116,7 +116,7 @@ func checkExistingRCRecovers(f *framework.Framework) { return false, nil } for _, pod := range pods.Items { - err = podClient.Delete(pod.Name, api.NewDeleteOptions(0)) + err = podClient.Delete(pod.Name, v1.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) } framework.Logf("apiserver has recovered") @@ -125,11 +125,11 @@ func checkExistingRCRecovers(f *framework.Framework) { By("waiting for replication controller to recover") framework.ExpectNoError(wait.Poll(time.Millisecond*500, time.Second*60, func() (bool, error) { - options := api.ListOptions{LabelSelector: rcSelector} + options := v1.ListOptions{LabelSelector: rcSelector.String()} pods, err := podClient.List(options) Expect(err).NotTo(HaveOccurred()) for _, pod := range pods.Items { - if pod.DeletionTimestamp == nil && api.IsPodReady(&pod) { + if pod.DeletionTimestamp == nil && v1.IsPodReady(&pod) { return true, nil } } diff --git a/test/e2e/events.go b/test/e2e/events.go index 0575799cd76..1049bc1fd53 100644 --- a/test/e2e/events.go +++ b/test/e2e/events.go @@ -21,7 +21,7 @@ import ( "strconv" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/uuid" @@ -42,20 +42,20 @@ var _ = framework.KubeDescribe("Events", func() { By("creating the pod") name := "send-events-" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: map[string]string{ "name": "foo", "time": value, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "p", Image: "gcr.io/google_containers/serve_hostname:v1.4", - Ports: []api.ContainerPort{{ContainerPort: 80}}, + Ports: []v1.ContainerPort{{ContainerPort: 80}}, }, }, }, @@ -74,7 +74,7 @@ var _ = framework.KubeDescribe("Events", func() { By("verifying the pod is in kubernetes") selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value})) - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} pods, err := podClient.List(options) Expect(len(pods.Items)).To(Equal(1)) @@ -84,7 +84,7 @@ var _ = framework.KubeDescribe("Events", func() { framework.Failf("Failed to get pod: %v", err) } fmt.Printf("%+v\n", podWithUid) - var events *api.EventList + var events *v1.EventList // Check for scheduler event about the pod. By("checking for scheduler event about the pod") framework.ExpectNoError(wait.Poll(time.Second*2, time.Second*60, func() (bool, error) { @@ -92,9 +92,9 @@ var _ = framework.KubeDescribe("Events", func() { "involvedObject.kind": "Pod", "involvedObject.uid": string(podWithUid.UID), "involvedObject.namespace": f.Namespace.Name, - "source": api.DefaultSchedulerName, - }.AsSelector() - options := api.ListOptions{FieldSelector: selector} + "source": v1.DefaultSchedulerName, + }.AsSelector().String() + options := v1.ListOptions{FieldSelector: selector} events, err := f.ClientSet.Core().Events(f.Namespace.Name).List(options) if err != nil { return false, err @@ -113,8 +113,8 @@ var _ = framework.KubeDescribe("Events", func() { "involvedObject.kind": "Pod", "involvedObject.namespace": f.Namespace.Name, "source": "kubelet", - }.AsSelector() - options := api.ListOptions{FieldSelector: selector} + }.AsSelector().String() + options := v1.ListOptions{FieldSelector: selector} events, err = f.ClientSet.Core().Events(f.Namespace.Name).List(options) if err != nil { return false, err diff --git a/test/e2e/example_cluster_dns.go b/test/e2e/example_cluster_dns.go index f3867b02603..f89717fd965 100644 --- a/test/e2e/example_cluster_dns.go +++ b/test/e2e/example_cluster_dns.go @@ -21,8 +21,8 @@ import ( "path/filepath" "time" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/test/e2e/framework" @@ -73,7 +73,7 @@ var _ = framework.KubeDescribe("ClusterDns [Feature:Example]", func() { // we need two namespaces anyway, so let's forget about // the one created in BeforeEach and create two new ones. - namespaces := []*api.Namespace{nil, nil} + namespaces := []*v1.Namespace{nil, nil} for i := range namespaces { var err error namespaces[i], err = f.CreateNamespace(fmt.Sprintf("dnsexample%d", i), nil) @@ -97,7 +97,7 @@ var _ = framework.KubeDescribe("ClusterDns [Feature:Example]", func() { // the application itself may have not been initialized. Just query the application. for _, ns := range namespaces { label := labels.SelectorFromSet(labels.Set(map[string]string{"name": backendRcName})) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := c.Core().Pods(ns.Name).List(options) Expect(err).NotTo(HaveOccurred()) err = framework.PodsResponding(c, ns.Name, backendPodName, false, pods) @@ -117,7 +117,7 @@ var _ = framework.KubeDescribe("ClusterDns [Feature:Example]", func() { // dns error or timeout. // This code is probably unnecessary, but let's stay on the safe side. label := labels.SelectorFromSet(labels.Set(map[string]string{"name": backendPodName})) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := c.Core().Pods(namespaces[0].Name).List(options) if err != nil || pods == nil || len(pods.Items) == 0 { @@ -151,6 +151,6 @@ var _ = framework.KubeDescribe("ClusterDns [Feature:Example]", func() { }) }) -func getNsCmdFlag(ns *api.Namespace) string { +func getNsCmdFlag(ns *v1.Namespace) string { return fmt.Sprintf("--namespace=%v", ns.Name) } diff --git a/test/e2e/example_k8petstore.go b/test/e2e/example_k8petstore.go index b112529b462..6a03420ac29 100644 --- a/test/e2e/example_k8petstore.go +++ b/test/e2e/example_k8petstore.go @@ -25,7 +25,7 @@ import ( "syscall" "time" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" diff --git a/test/e2e/examples.go b/test/e2e/examples.go index 70343a246bb..06dbd5fcaf6 100644 --- a/test/e2e/examples.go +++ b/test/e2e/examples.go @@ -26,8 +26,8 @@ import ( "sync" "time" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -49,11 +49,11 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { return f.NewClusterVerification( framework.PodStateVerification{ Selectors: map[string]string{selectorKey: selectorValue}, - ValidPhases: []api.PodPhase{api.PodRunning}, + ValidPhases: []v1.PodPhase{v1.PodRunning}, }) } // Customized ForEach wrapper for this test. - forEachPod := func(selectorKey string, selectorValue string, fn func(api.Pod)) { + forEachPod := func(selectorKey string, selectorValue string, fn func(v1.Pod)) { clusterState(selectorKey, selectorValue).ForEach(fn) } var c clientset.Interface @@ -113,7 +113,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { label := labels.SelectorFromSet(labels.Set(map[string]string{selectorKey: selectorValue})) err = testutils.WaitForPodsWithLabelRunning(c, ns, label) Expect(err).NotTo(HaveOccurred()) - forEachPod(selectorKey, selectorValue, func(pod api.Pod) { + forEachPod(selectorKey, selectorValue, func(pod v1.Pod) { if pod.Name != bootstrapPodName { _, err := framework.LookForStringInLog(ns, pod.Name, "redis", expectedOnServer, serverStartTimeout) Expect(err).NotTo(HaveOccurred()) @@ -123,7 +123,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { label = labels.SelectorFromSet(labels.Set(map[string]string{selectorKey: selectorValue})) err = testutils.WaitForPodsWithLabelRunning(c, ns, label) Expect(err).NotTo(HaveOccurred()) - forEachPod(selectorKey, selectorValue, func(pod api.Pod) { + forEachPod(selectorKey, selectorValue, func(pod v1.Pod) { if pod.Name != bootstrapPodName { _, err := framework.LookForStringInLog(ns, pod.Name, "sentinel", expectedOnSentinel, serverStartTimeout) Expect(err).NotTo(HaveOccurred()) @@ -164,7 +164,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { framework.Logf("Now polling for Master startup...") // Only one master pod: But its a natural way to look up pod names. - forEachPod(selectorKey, selectorValue, func(pod api.Pod) { + forEachPod(selectorKey, selectorValue, func(pod v1.Pod) { framework.Logf("Now waiting for master to startup in %v", pod.Name) _, err := framework.LookForStringInLog(ns, pod.Name, "spark-master", "Starting Spark master at", serverStartTimeout) Expect(err).NotTo(HaveOccurred()) @@ -173,7 +173,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { By("waiting for master endpoint") err = framework.WaitForEndpoint(c, ns, "spark-master") Expect(err).NotTo(HaveOccurred()) - forEachPod(selectorKey, selectorValue, func(pod api.Pod) { + forEachPod(selectorKey, selectorValue, func(pod v1.Pod) { _, maErr := framework.LookForStringInLog(f.Namespace.Name, pod.Name, "spark-master", "Starting Spark master at", serverStartTimeout) if maErr != nil { framework.Failf("Didn't find target string. error:", maErr) @@ -194,7 +194,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { framework.Logf("Now polling for worker startup...") forEachPod(selectorKey, selectorValue, - func(pod api.Pod) { + func(pod v1.Pod) { _, slaveErr := framework.LookForStringInLog(ns, pod.Name, "spark-worker", "Successfully registered with master", serverStartTimeout) Expect(slaveErr).NotTo(HaveOccurred()) }) @@ -226,7 +226,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { label := labels.SelectorFromSet(labels.Set(map[string]string{"app": "cassandra"})) err = testutils.WaitForPodsWithLabelRunning(c, ns, label) Expect(err).NotTo(HaveOccurred()) - forEachPod("app", "cassandra", func(pod api.Pod) { + forEachPod("app", "cassandra", func(pod v1.Pod) { framework.Logf("Verifying pod %v ", pod.Name) // TODO how do we do this better? Ready Probe? _, err = framework.LookForStringInLog(ns, pod.Name, "cassandra", "Starting listening for CQL clients", serverStartTimeout) @@ -234,7 +234,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { }) By("Finding each node in the nodetool status lines") - forEachPod("app", "cassandra", func(pod api.Pod) { + forEachPod("app", "cassandra", func(pod v1.Pod) { output := framework.RunKubectlOrDie("exec", pod.Name, nsFlag, "--", "nodetool", "status") matched, _ := regexp.MatchString("UN.*"+pod.Status.PodIP, output) if matched != true { @@ -281,7 +281,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { label := labels.SelectorFromSet(labels.Set(map[string]string{"app": "cassandra"})) err = wait.PollImmediate(statefulsetPoll, statefulsetTimeout, func() (bool, error) { - podList, err := c.Core().Pods(ns).List(api.ListOptions{LabelSelector: label}) + podList, err := c.Core().Pods(ns).List(v1.ListOptions{LabelSelector: label.String()}) if err != nil { return false, fmt.Errorf("Unable to get list of pods in statefulset %s", label) } @@ -294,9 +294,9 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { return false, fmt.Errorf("Too many pods scheduled, expected %d got %d", numPets, len(podList.Items)) } for _, p := range podList.Items { - isReady := api.IsPodReady(&p) - if p.Status.Phase != api.PodRunning || !isReady { - framework.Logf("Waiting for pod %v to enter %v - Ready=True, currently %v - Ready=%v", p.Name, api.PodRunning, p.Status.Phase, isReady) + isReady := v1.IsPodReady(&p) + if p.Status.Phase != v1.PodRunning || !isReady { + framework.Logf("Waiting for pod %v to enter %v - Ready=True, currently %v - Ready=%v", p.Name, v1.PodRunning, p.Status.Phase, isReady) return false, nil } } @@ -305,7 +305,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { Expect(err).NotTo(HaveOccurred()) By("Finding each node in the nodetool status lines") - forEachPod("app", "cassandra", func(pod api.Pod) { + forEachPod("app", "cassandra", func(pod v1.Pod) { output := framework.RunKubectlOrDie("exec", pod.Name, nsFlag, "--", "nodetool", "status") matched, _ := regexp.MatchString("UN.*"+pod.Status.PodIP, output) if matched != true { @@ -357,7 +357,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { label := labels.SelectorFromSet(labels.Set(map[string]string{"name": "storm-worker"})) err = testutils.WaitForPodsWithLabelRunning(c, ns, label) Expect(err).NotTo(HaveOccurred()) - forEachPod("name", "storm-worker", func(pod api.Pod) { + forEachPod("name", "storm-worker", func(pod v1.Pod) { //do nothing, just wait for the pod to be running }) // TODO: Add logging configuration to nimbus & workers images and then @@ -398,7 +398,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { for t := time.Now(); time.Since(t) < timeout; time.Sleep(framework.Poll) { pod, err := c.Core().Pods(ns).Get(podName) framework.ExpectNoError(err, fmt.Sprintf("getting pod %s", podName)) - stat := api.GetExistingContainerStatus(pod.Status.ContainerStatuses, podName) + stat := v1.GetExistingContainerStatus(pod.Status.ContainerStatuses, podName) framework.Logf("Pod: %s, restart count:%d", stat.Name, stat.RestartCount) if stat.RestartCount > 0 { framework.Logf("Saw %v restart, succeeded...", podName) @@ -494,7 +494,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { err := testutils.WaitForPodsWithLabelRunning(c, ns, label) Expect(err).NotTo(HaveOccurred()) checkDbInstances := func() { - forEachPod("db", "rethinkdb", func(pod api.Pod) { + forEachPod("db", "rethinkdb", func(pod v1.Pod) { _, err = framework.LookForStringInLog(ns, pod.Name, "rethinkdb", "Server ready", serverStartTimeout) Expect(err).NotTo(HaveOccurred()) }) @@ -504,7 +504,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { Expect(err).NotTo(HaveOccurred()) By("scaling rethinkdb") - framework.ScaleRC(f.ClientSet, ns, "rethinkdb-rc", 2, true) + framework.ScaleRC(f.ClientSet, f.InternalClientset, ns, "rethinkdb-rc", 2, true) checkDbInstances() By("starting admin") @@ -536,7 +536,7 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { label := labels.SelectorFromSet(labels.Set(map[string]string{"name": "hazelcast"})) err := testutils.WaitForPodsWithLabelRunning(c, ns, label) Expect(err).NotTo(HaveOccurred()) - forEachPod("name", "hazelcast", func(pod api.Pod) { + forEachPod("name", "hazelcast", func(pod v1.Pod) { _, err := framework.LookForStringInLog(ns, pod.Name, "hazelcast", "Members [1]", serverStartTimeout) Expect(err).NotTo(HaveOccurred()) _, err = framework.LookForStringInLog(ns, pod.Name, "hazelcast", "is STARTED", serverStartTimeout) @@ -547,8 +547,8 @@ var _ = framework.KubeDescribe("[Feature:Example]", func() { Expect(err).NotTo(HaveOccurred()) By("scaling hazelcast") - framework.ScaleRC(f.ClientSet, ns, "hazelcast", 2, true) - forEachPod("name", "hazelcast", func(pod api.Pod) { + framework.ScaleRC(f.ClientSet, f.InternalClientset, ns, "hazelcast", 2, true) + forEachPod("name", "hazelcast", func(pod v1.Pod) { _, err := framework.LookForStringInLog(ns, pod.Name, "hazelcast", "Members [2]", serverStartTimeout) Expect(err).NotTo(HaveOccurred()) }) diff --git a/test/e2e/federated-namespace.go b/test/e2e/federated-namespace.go index 5b5be964d34..42818380643 100644 --- a/test/e2e/federated-namespace.go +++ b/test/e2e/federated-namespace.go @@ -23,8 +23,8 @@ import ( "time" clientset "k8s.io/kubernetes/federation/client/clientset_generated/federation_release_1_5/typed/core/v1" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" api_v1 "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -111,7 +111,7 @@ var _ = framework.KubeDescribe("Federation namespace [Feature:Federation]", func // Create resources in the namespace. event := api_v1.Event{ ObjectMeta: api_v1.ObjectMeta{ - Name: api.SimpleNameGenerator.GenerateName(eventNamePrefix), + Name: v1.SimpleNameGenerator.GenerateName(eventNamePrefix), Namespace: nsName, }, InvolvedObject: api_v1.ObjectReference{ @@ -185,7 +185,7 @@ func verifyNsCascadingDeletion(nsClient clientset.NamespaceInterface, clusters m func createNamespace(nsClient clientset.NamespaceInterface) string { ns := api_v1.Namespace{ ObjectMeta: api_v1.ObjectMeta{ - Name: api.SimpleNameGenerator.GenerateName(namespacePrefix), + Name: v1.SimpleNameGenerator.GenerateName(namespacePrefix), }, } By(fmt.Sprintf("Creating namespace %s", ns.Name)) diff --git a/test/e2e/federated-secret.go b/test/e2e/federated-secret.go index ae7a5dba2d0..ae765bad0d3 100644 --- a/test/e2e/federated-secret.go +++ b/test/e2e/federated-secret.go @@ -25,7 +25,6 @@ import ( . "github.com/onsi/gomega" fedclientset "k8s.io/kubernetes/federation/client/clientset_generated/federation_release_1_5" "k8s.io/kubernetes/federation/pkg/federation-controller/util" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/v1" kubeclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" @@ -156,7 +155,7 @@ func createSecretOrFail(clientset *fedclientset.Clientset, nsName string) *v1.Se secret := &v1.Secret{ ObjectMeta: v1.ObjectMeta{ - Name: api.SimpleNameGenerator.GenerateName(secretNamePrefix), + Name: v1.SimpleNameGenerator.GenerateName(secretNamePrefix), Namespace: nsName, }, } diff --git a/test/e2e/federation-util.go b/test/e2e/federation-util.go index f51ff4c0e63..f01694cf6f9 100644 --- a/test/e2e/federation-util.go +++ b/test/e2e/federation-util.go @@ -347,7 +347,7 @@ func cleanupServiceShardLoadBalancer(clusterName string, service *v1.Service, ti return fmt.Errorf("cloud provider undefined") } - internalSvc := &api.Service{} + internalSvc := &v1.Service{} err := api.Scheme.Convert(service, internalSvc, nil) if err != nil { return fmt.Errorf("failed to convert versioned service object to internal type: %v", err) @@ -415,19 +415,19 @@ func discoverService(f *framework.Framework, name string, exists bool, podName s command := []string{"sh", "-c", fmt.Sprintf("until nslookup '%s'; do sleep 10; done", name)} By(fmt.Sprintf("Looking up %q", name)) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "federated-service-discovery-container", Image: "gcr.io/google_containers/busybox:1.24", Command: command, }, }, - RestartPolicy: api.RestartPolicyOnFailure, + RestartPolicy: v1.RestartPolicyOnFailure, }, } @@ -438,7 +438,7 @@ func discoverService(f *framework.Framework, name string, exists bool, podName s By(fmt.Sprintf("Successfully created pod %q in namespace %q", pod.Name, nsName)) defer func() { By(fmt.Sprintf("Deleting pod %q from namespace %q", podName, nsName)) - err := f.ClientSet.Core().Pods(nsName).Delete(podName, api.NewDeleteOptions(0)) + err := f.ClientSet.Core().Pods(nsName).Delete(podName, v1.NewDeleteOptions(0)) framework.ExpectNoError(err, "Deleting pod %q from namespace %q", podName, nsName) By(fmt.Sprintf("Deleted pod %q from namespace %q", podName, nsName)) }() diff --git a/test/e2e/framework/BUILD b/test/e2e/framework/BUILD index 519bf11fc8e..c30d01b88af 100644 --- a/test/e2e/framework/BUILD +++ b/test/e2e/framework/BUILD @@ -38,17 +38,18 @@ go_library( "//pkg/api/v1:go_default_library", "//pkg/api/validation:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/apis/apps:go_default_library", - "//pkg/apis/batch:go_default_library", + "//pkg/apis/apps/v1beta1:go_default_library", + "//pkg/apis/batch/v1:go_default_library", "//pkg/apis/componentconfig:go_default_library", "//pkg/apis/extensions:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", + "//pkg/client/conditions:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/typed/discovery:go_default_library", "//pkg/client/typed/dynamic:go_default_library", - "//pkg/client/unversioned:go_default_library", "//pkg/client/unversioned/clientcmd:go_default_library", "//pkg/client/unversioned/clientcmd/api:go_default_library", "//pkg/client/unversioned/remotecommand:go_default_library", diff --git a/test/e2e/framework/exec_util.go b/test/e2e/framework/exec_util.go index 2a553bd112a..f35de2e78ca 100644 --- a/test/e2e/framework/exec_util.go +++ b/test/e2e/framework/exec_util.go @@ -23,6 +23,7 @@ import ( "strings" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/unversioned/remotecommand" remotecommandserver "k8s.io/kubernetes/pkg/kubelet/server/remotecommand" @@ -62,7 +63,7 @@ func (f *Framework) ExecWithOptions(options ExecOptions) (string, string, error) Namespace(options.Namespace). SubResource("exec"). Param("container", options.ContainerName) - req.VersionedParams(&api.PodExecOptions{ + req.VersionedParams(&v1.PodExecOptions{ Container: options.ContainerName, Command: options.Command, Stdin: options.Stdin != nil, diff --git a/test/e2e/framework/framework.go b/test/e2e/framework/framework.go index bbede98aab1..ae4dd7bd96f 100644 --- a/test/e2e/framework/framework.go +++ b/test/e2e/framework/framework.go @@ -36,7 +36,7 @@ import ( "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/typed/dynamic" "k8s.io/kubernetes/pkg/fields" @@ -60,15 +60,15 @@ const ( type Framework struct { BaseName string - // ClientSet uses internal objects, you should use ClientSet_1_5 where possible. - ClientSet internalclientset.Interface + // ClientSet uses internal objects, you should use ClientSet where possible. + ClientSet clientset.Interface - ClientSet_1_5 *release_1_5.Clientset - StagingClient *staging.Clientset - ClientPool dynamic.ClientPool + InternalClientset *internalclientset.Clientset + StagingClient *staging.Clientset + ClientPool dynamic.ClientPool - Namespace *api.Namespace // Every test has at least one namespace - namespacesToDelete []*api.Namespace // Some tests have more than one. + Namespace *v1.Namespace // Every test has at least one namespace + namespacesToDelete []*v1.Namespace // Some tests have more than one. NamespaceDeletionTimeout time.Duration gatherer *containerResourceGatherer @@ -130,7 +130,7 @@ func NewDefaultGroupVersionFramework(baseName string, groupVersion unversioned.G return f } -func NewFramework(baseName string, options FrameworkOptions, client internalclientset.Interface) *Framework { +func NewFramework(baseName string, options FrameworkOptions, client clientset.Interface) *Framework { f := &Framework{ BaseName: baseName, AddonResourceConstraints: make(map[string]ResourceConstraint), @@ -193,9 +193,9 @@ func (f *Framework) BeforeEach() { if TestContext.KubeAPIContentType != "" { config.ContentType = TestContext.KubeAPIContentType } - f.ClientSet, err = internalclientset.NewForConfig(config) + f.ClientSet, err = clientset.NewForConfig(config) Expect(err).NotTo(HaveOccurred()) - f.ClientSet_1_5, err = release_1_5.NewForConfig(config) + f.InternalClientset, err = internalclientset.NewForConfig(config) Expect(err).NotTo(HaveOccurred()) clientRepoConfig := getClientRepoConfig(config) f.StagingClient, err = staging.NewForConfig(clientRepoConfig) @@ -369,7 +369,7 @@ func (f *Framework) AfterEach() { // Print events if the test failed. if CurrentGinkgoTestDescription().Failed && TestContext.DumpLogsOnFailure { // Pass both unversioned client and and versioned clientset, till we have removed all uses of the unversioned client. - DumpAllNamespaceInfo(f.ClientSet, f.ClientSet_1_5, f.Namespace.Name) + DumpAllNamespaceInfo(f.ClientSet, f.Namespace.Name) By(fmt.Sprintf("Dumping a list of prepulled images on each node")) LogContainersInPodsWithLabels(f.ClientSet, api.NamespaceSystem, ImagePullerLabels, "image-puller", Logf) if f.federated { @@ -439,7 +439,7 @@ func (f *Framework) AfterEach() { } } -func (f *Framework) CreateNamespace(baseName string, labels map[string]string) (*api.Namespace, error) { +func (f *Framework) CreateNamespace(baseName string, labels map[string]string) (*v1.Namespace, error) { createTestingNS := TestContext.CreateTestingNS if createTestingNS == nil { createTestingNS = CreateTestingNS @@ -507,14 +507,14 @@ func (f *Framework) WaitForPodNoLongerRunning(podName string) error { // TestContainerOutput runs the given pod in the given namespace and waits // for all of the containers in the podSpec to move into the 'Success' status, and tests // the specified container log against the given expected output using a substring matcher. -func (f *Framework) TestContainerOutput(scenarioName string, pod *api.Pod, containerIndex int, expectedOutput []string) { +func (f *Framework) TestContainerOutput(scenarioName string, pod *v1.Pod, containerIndex int, expectedOutput []string) { f.testContainerOutputMatcher(scenarioName, pod, containerIndex, expectedOutput, ContainSubstring) } // TestContainerOutputRegexp runs the given pod in the given namespace and waits // for all of the containers in the podSpec to move into the 'Success' status, and tests // the specified container log against the given expected output using a regexp matcher. -func (f *Framework) TestContainerOutputRegexp(scenarioName string, pod *api.Pod, containerIndex int, expectedOutput []string) { +func (f *Framework) TestContainerOutputRegexp(scenarioName string, pod *v1.Pod, containerIndex int, expectedOutput []string) { f.testContainerOutputMatcher(scenarioName, pod, containerIndex, expectedOutput, MatchRegexp) } @@ -524,13 +524,13 @@ func (f *Framework) WaitForAnEndpoint(serviceName string) error { for { // TODO: Endpoints client should take a field selector so we // don't have to list everything. - list, err := f.ClientSet.Core().Endpoints(f.Namespace.Name).List(api.ListOptions{}) + list, err := f.ClientSet.Core().Endpoints(f.Namespace.Name).List(v1.ListOptions{}) if err != nil { return err } rv := list.ResourceVersion - isOK := func(e *api.Endpoints) bool { + isOK := func(e *v1.Endpoints) bool { return e.Name == serviceName && len(e.Subsets) > 0 && len(e.Subsets[0].Addresses) > 0 } for i := range list.Items { @@ -539,8 +539,8 @@ func (f *Framework) WaitForAnEndpoint(serviceName string) error { } } - options := api.ListOptions{ - FieldSelector: fields.Set{"metadata.name": serviceName}.AsSelector(), + options := v1.ListOptions{ + FieldSelector: fields.Set{"metadata.name": serviceName}.AsSelector().String(), ResourceVersion: rv, } w, err := f.ClientSet.Core().Endpoints(f.Namespace.Name).Watch(options) @@ -555,7 +555,7 @@ func (f *Framework) WaitForAnEndpoint(serviceName string) error { // reget and re-watch break } - if e, ok := val.Object.(*api.Endpoints); ok { + if e, ok := val.Object.(*v1.Endpoints); ok { if isOK(e) { return nil } @@ -604,7 +604,7 @@ func (f *Framework) CheckFileSizeViaContainer(podName, containerName, path strin } // CreateServiceForSimpleAppWithPods is a convenience wrapper to create a service and its matching pods all at once. -func (f *Framework) CreateServiceForSimpleAppWithPods(contPort int, svcPort int, appName string, podSpec func(n api.Node) api.PodSpec, count int, block bool) (error, *api.Service) { +func (f *Framework) CreateServiceForSimpleAppWithPods(contPort int, svcPort int, appName string, podSpec func(n v1.Node) v1.PodSpec, count int, block bool) (error, *v1.Service) { var err error = nil theService := f.CreateServiceForSimpleApp(contPort, svcPort, appName) f.CreatePodsPerNodeForSimpleApp(appName, podSpec, count) @@ -615,7 +615,7 @@ func (f *Framework) CreateServiceForSimpleAppWithPods(contPort int, svcPort int, } // CreateServiceForSimpleApp returns a service that selects/exposes pods (send -1 ports if no exposure needed) with an app label. -func (f *Framework) CreateServiceForSimpleApp(contPort, svcPort int, appName string) *api.Service { +func (f *Framework) CreateServiceForSimpleApp(contPort, svcPort int, appName string) *v1.Service { if appName == "" { panic(fmt.Sprintf("no app name provided")) } @@ -625,11 +625,11 @@ func (f *Framework) CreateServiceForSimpleApp(contPort, svcPort int, appName str } // For convenience, user sending ports are optional. - portsFunc := func() []api.ServicePort { + portsFunc := func() []v1.ServicePort { if contPort < 1 || svcPort < 1 { return nil } else { - return []api.ServicePort{{ + return []v1.ServicePort{{ Protocol: "TCP", Port: int32(svcPort), TargetPort: intstr.FromInt(contPort), @@ -637,14 +637,14 @@ func (f *Framework) CreateServiceForSimpleApp(contPort, svcPort int, appName str } } Logf("Creating a service-for-%v for selecting app=%v-pod", appName, appName) - service, err := f.ClientSet.Core().Services(f.Namespace.Name).Create(&api.Service{ - ObjectMeta: api.ObjectMeta{ + service, err := f.ClientSet.Core().Services(f.Namespace.Name).Create(&v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: "service-for-" + appName, Labels: map[string]string{ "app": appName + "-service", }, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Ports: portsFunc(), Selector: serviceSelector, }, @@ -654,7 +654,7 @@ func (f *Framework) CreateServiceForSimpleApp(contPort, svcPort int, appName str } // CreatePodsPerNodeForSimpleApp Creates pods w/ labels. Useful for tests which make a bunch of pods w/o any networking. -func (f *Framework) CreatePodsPerNodeForSimpleApp(appName string, podSpec func(n api.Node) api.PodSpec, maxCount int) map[string]string { +func (f *Framework) CreatePodsPerNodeForSimpleApp(appName string, podSpec func(n v1.Node) v1.PodSpec, maxCount int) map[string]string { nodes := GetReadySchedulableNodesOrDie(f.ClientSet) labels := map[string]string{ "app": appName + "-pod", @@ -663,8 +663,8 @@ func (f *Framework) CreatePodsPerNodeForSimpleApp(appName string, podSpec func(n // one per node, but no more than maxCount. if i <= maxCount { Logf("%v/%v : Creating container with label app=%v-pod", i, maxCount, appName) - _, err := f.ClientSet.Core().Pods(f.Namespace.Name).Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + _, err := f.ClientSet.Core().Pods(f.Namespace.Name).Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: fmt.Sprintf(appName+"-pod-%v", i), Labels: labels, }, @@ -834,22 +834,22 @@ type PodStateVerification struct { Selectors map[string]string // Required: The phases which are valid for your pod. - ValidPhases []api.PodPhase + ValidPhases []v1.PodPhase // Optional: only pods passing this function will pass the filter // Verify a pod. // As an optimization, in addition to specfying filter (boolean), // this function allows specifying an error as well. // The error indicates that the polling of the pod spectrum should stop. - Verify func(api.Pod) (bool, error) + Verify func(v1.Pod) (bool, error) // Optional: only pods with this name will pass the filter. PodName string } type ClusterVerification struct { - client internalclientset.Interface - namespace *api.Namespace // pointer rather than string, since ns isn't created until before each. + client clientset.Interface + namespace *v1.Namespace // pointer rather than string, since ns isn't created until before each. podState PodStateVerification } @@ -861,11 +861,11 @@ func (f *Framework) NewClusterVerification(filter PodStateVerification) *Cluster } } -func passesPodNameFilter(pod api.Pod, name string) bool { +func passesPodNameFilter(pod v1.Pod, name string) bool { return name == "" || strings.Contains(pod.Name, name) } -func passesVerifyFilter(pod api.Pod, verify func(p api.Pod) (bool, error)) (bool, error) { +func passesVerifyFilter(pod v1.Pod, verify func(p v1.Pod) (bool, error)) (bool, error) { if verify == nil { return true, nil } else { @@ -879,7 +879,7 @@ func passesVerifyFilter(pod api.Pod, verify func(p api.Pod) (bool, error)) (bool } } -func passesPhasesFilter(pod api.Pod, validPhases []api.PodPhase) bool { +func passesPhasesFilter(pod v1.Pod, validPhases []v1.PodPhase) bool { passesPhaseFilter := false for _, phase := range validPhases { if pod.Status.Phase == phase { @@ -890,18 +890,18 @@ func passesPhasesFilter(pod api.Pod, validPhases []api.PodPhase) bool { } // filterLabels returns a list of pods which have labels. -func filterLabels(selectors map[string]string, cli internalclientset.Interface, ns string) (*api.PodList, error) { +func filterLabels(selectors map[string]string, cli clientset.Interface, ns string) (*v1.PodList, error) { var err error var selector labels.Selector - var pl *api.PodList + var pl *v1.PodList // List pods based on selectors. This might be a tiny optimization rather then filtering // everything manually. if len(selectors) > 0 { selector = labels.SelectorFromSet(labels.Set(selectors)) - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} pl, err = cli.Core().Pods(ns).List(options) } else { - pl, err = cli.Core().Pods(ns).List(api.ListOptions{}) + pl, err = cli.Core().Pods(ns).List(v1.ListOptions{}) } return pl, err } @@ -909,20 +909,20 @@ func filterLabels(selectors map[string]string, cli internalclientset.Interface, // filter filters pods which pass a filter. It can be used to compose // the more useful abstractions like ForEach, WaitFor, and so on, which // can be used directly by tests. -func (p *PodStateVerification) filter(c internalclientset.Interface, namespace *api.Namespace) ([]api.Pod, error) { +func (p *PodStateVerification) filter(c clientset.Interface, namespace *v1.Namespace) ([]v1.Pod, error) { if len(p.ValidPhases) == 0 || namespace == nil { panic(fmt.Errorf("Need to specify a valid pod phases (%v) and namespace (%v). ", p.ValidPhases, namespace)) } ns := namespace.Name - pl, err := filterLabels(p.Selectors, c, ns) // Build an api.PodList to operate against. + pl, err := filterLabels(p.Selectors, c, ns) // Build an v1.PodList to operate against. Logf("Selector matched %v pods for %v", len(pl.Items), p.Selectors) if len(pl.Items) == 0 || err != nil { return pl.Items, err } unfilteredPods := pl.Items - filteredPods := []api.Pod{} + filteredPods := []v1.Pod{} ReturnPodsSoFar: // Next: Pod must match at least one of the states that the user specified for _, pod := range unfilteredPods { @@ -943,8 +943,8 @@ ReturnPodsSoFar: // WaitFor waits for some minimum number of pods to be verified, according to the PodStateVerification // definition. -func (cl *ClusterVerification) WaitFor(atLeast int, timeout time.Duration) ([]api.Pod, error) { - pods := []api.Pod{} +func (cl *ClusterVerification) WaitFor(atLeast int, timeout time.Duration) ([]v1.Pod, error) { + pods := []v1.Pod{} var returnedErr error err := wait.Poll(1*time.Second, timeout, func() (bool, error) { @@ -983,7 +983,7 @@ func (cl *ClusterVerification) WaitForOrFail(atLeast int, timeout time.Duration) // // For example, if you require at least 5 pods to be running before your test will pass, // its smart to first call "clusterVerification.WaitFor(5)" before you call clusterVerification.ForEach. -func (cl *ClusterVerification) ForEach(podFunc func(api.Pod)) error { +func (cl *ClusterVerification) ForEach(podFunc func(v1.Pod)) error { pods, err := cl.podState.filter(cl.client, cl.namespace) if err == nil { if len(pods) == 0 { diff --git a/test/e2e/framework/kubelet_stats.go b/test/e2e/framework/kubelet_stats.go index 8856643e355..d5be4aff6c9 100644 --- a/test/e2e/framework/kubelet_stats.go +++ b/test/e2e/framework/kubelet_stats.go @@ -29,8 +29,8 @@ import ( cadvisorapi "github.com/google/cadvisor/info/v1" "github.com/prometheus/common/model" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" kubeletmetrics "k8s.io/kubernetes/pkg/kubelet/metrics" kubeletstats "k8s.io/kubernetes/pkg/kubelet/server/stats" @@ -157,7 +157,7 @@ func NewRuntimeOperationMonitor(c clientset.Interface) *RuntimeOperationMonitor client: c, nodesRuntimeOps: make(map[string]NodeRuntimeOperationErrorRate), } - nodes, err := m.client.Core().Nodes().List(api.ListOptions{}) + nodes, err := m.client.Core().Nodes().List(v1.ListOptions{}) if err != nil { Failf("RuntimeOperationMonitor: unable to get list of nodes: %v", err) } @@ -695,7 +695,7 @@ func NewResourceMonitor(c clientset.Interface, containerNames []string, pollingI func (r *ResourceMonitor) Start() { // It should be OK to monitor unschedulable Nodes - nodes, err := r.client.Core().Nodes().List(api.ListOptions{}) + nodes, err := r.client.Core().Nodes().List(v1.ListOptions{}) if err != nil { Failf("ResourceMonitor: unable to get list of nodes: %v", err) } diff --git a/test/e2e/framework/log_size_monitoring.go b/test/e2e/framework/log_size_monitoring.go index 4a9da5750c8..16d607c8b0a 100644 --- a/test/e2e/framework/log_size_monitoring.go +++ b/test/e2e/framework/log_size_monitoring.go @@ -25,7 +25,7 @@ import ( "text/tabwriter" "time" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" ) const ( diff --git a/test/e2e/framework/metrics_util.go b/test/e2e/framework/metrics_util.go index dc832bda1b1..8dcd6360dfa 100644 --- a/test/e2e/framework/metrics_util.go +++ b/test/e2e/framework/metrics_util.go @@ -28,7 +28,8 @@ import ( "time" "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/master/ports" "k8s.io/kubernetes/pkg/metrics" "k8s.io/kubernetes/pkg/util/sets" @@ -323,7 +324,7 @@ func getSchedulingLatency(c clientset.Interface) (SchedulingLatency, error) { result := SchedulingLatency{} // Check if master Node is registered - nodes, err := c.Core().Nodes().List(api.ListOptions{}) + nodes, err := c.Core().Nodes().List(v1.ListOptions{}) ExpectNoError(err) var data string diff --git a/test/e2e/framework/networking_utils.go b/test/e2e/framework/networking_utils.go index 27142807493..14b9f3d24cb 100644 --- a/test/e2e/framework/networking_utils.go +++ b/test/e2e/framework/networking_utils.go @@ -24,10 +24,10 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - api "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - coreclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + coreclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/rand" @@ -87,23 +87,23 @@ func getServiceSelector() map[string]string { type NetworkingTestConfig struct { // TestContaienrPod is a test pod running the netexec image. It is capable // of executing tcp/udp requests against ip:port. - TestContainerPod *api.Pod + TestContainerPod *v1.Pod // HostTestContainerPod is a pod running with hostNetworking=true, and the // hostexec image. - HostTestContainerPod *api.Pod + HostTestContainerPod *v1.Pod // EndpointPods are the pods belonging to the Service created by this // test config. Each invocation of `setup` creates a service with // 1 pod per node running the netexecImage. - EndpointPods []*api.Pod + EndpointPods []*v1.Pod f *Framework podClient *PodClient // NodePortService is a Service with Type=NodePort spanning over all // endpointPods. - NodePortService *api.Service + NodePortService *v1.Service // ExternalAddrs is a list of external IPs of nodes in the cluster. ExternalAddrs []string // Nodes is a list of nodes in the cluster. - Nodes []api.Node + Nodes []v1.Node // MaxTries is the number of retries tolerated for tests run against // endpoints and services created by this config. MaxTries int @@ -298,41 +298,41 @@ func (config *NetworkingTestConfig) GetSelfURL(path string, expected string) { } } -func (config *NetworkingTestConfig) createNetShellPodSpec(podName string, node string) *api.Pod { - probe := &api.Probe{ +func (config *NetworkingTestConfig) createNetShellPodSpec(podName string, node string) *v1.Pod { + probe := &v1.Probe{ InitialDelaySeconds: 10, TimeoutSeconds: 30, PeriodSeconds: 10, SuccessThreshold: 1, FailureThreshold: 3, - Handler: api.Handler{ - HTTPGet: &api.HTTPGetAction{ + Handler: v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Path: "/healthz", Port: intstr.IntOrString{IntVal: EndpointHttpPort}, }, }, } - pod := &api.Pod{ + pod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Namespace: config.Namespace, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "webserver", Image: NetexecImageName, - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, Command: []string{ "/netexec", fmt.Sprintf("--http-port=%d", EndpointHttpPort), fmt.Sprintf("--udp-port=%d", EndpointUdpPort), }, - Ports: []api.ContainerPort{ + Ports: []v1.ContainerPort{ { Name: "http", ContainerPort: EndpointHttpPort, @@ -340,7 +340,7 @@ func (config *NetworkingTestConfig) createNetShellPodSpec(podName string, node s { Name: "udp", ContainerPort: EndpointUdpPort, - Protocol: api.ProtocolUDP, + Protocol: v1.ProtocolUDP, }, }, LivenessProbe: probe, @@ -355,28 +355,28 @@ func (config *NetworkingTestConfig) createNetShellPodSpec(podName string, node s return pod } -func (config *NetworkingTestConfig) createTestPodSpec() *api.Pod { - pod := &api.Pod{ +func (config *NetworkingTestConfig) createTestPodSpec() *v1.Pod { + pod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: testPodName, Namespace: config.Namespace, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "webserver", Image: NetexecImageName, - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, Command: []string{ "/netexec", fmt.Sprintf("--http-port=%d", EndpointHttpPort), fmt.Sprintf("--udp-port=%d", EndpointUdpPort), }, - Ports: []api.ContainerPort{ + Ports: []v1.ContainerPort{ { Name: "http", ContainerPort: TestContainerHttpPort, @@ -390,15 +390,15 @@ func (config *NetworkingTestConfig) createTestPodSpec() *api.Pod { } func (config *NetworkingTestConfig) createNodePortService(selector map[string]string) { - serviceSpec := &api.Service{ - ObjectMeta: api.ObjectMeta{ + serviceSpec := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: nodePortServiceName, }, - Spec: api.ServiceSpec{ - Type: api.ServiceTypeNodePort, - Ports: []api.ServicePort{ - {Port: ClusterHttpPort, Name: "http", Protocol: api.ProtocolTCP, TargetPort: intstr.FromInt(EndpointHttpPort)}, - {Port: ClusterUdpPort, Name: "udp", Protocol: api.ProtocolUDP, TargetPort: intstr.FromInt(EndpointUdpPort)}, + Spec: v1.ServiceSpec{ + Type: v1.ServiceTypeNodePort, + Ports: []v1.ServicePort{ + {Port: ClusterHttpPort, Name: "http", Protocol: v1.ProtocolTCP, TargetPort: intstr.FromInt(EndpointHttpPort)}, + {Port: ClusterUdpPort, Name: "udp", Protocol: v1.ProtocolUDP, TargetPort: intstr.FromInt(EndpointUdpPort)}, }, Selector: selector, }, @@ -434,7 +434,7 @@ func (config *NetworkingTestConfig) createTestPods() { } } -func (config *NetworkingTestConfig) createService(serviceSpec *api.Service) *api.Service { +func (config *NetworkingTestConfig) createService(serviceSpec *v1.Service) *v1.Service { _, err := config.getServiceClient().Create(serviceSpec) Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("Failed to create %s service: %v", serviceSpec.Name, err)) @@ -468,10 +468,10 @@ func (config *NetworkingTestConfig) setup(selector map[string]string) { By("Getting node addresses") ExpectNoError(WaitForAllNodesSchedulable(config.f.ClientSet, 10*time.Minute)) nodeList := GetReadySchedulableNodesOrDie(config.f.ClientSet) - config.ExternalAddrs = NodeAddresses(nodeList, api.NodeExternalIP) + config.ExternalAddrs = NodeAddresses(nodeList, v1.NodeExternalIP) if len(config.ExternalAddrs) < 2 { // fall back to legacy IPs - config.ExternalAddrs = NodeAddresses(nodeList, api.NodeLegacyHostIP) + config.ExternalAddrs = NodeAddresses(nodeList, v1.NodeLegacyHostIP) } Expect(len(config.ExternalAddrs)).To(BeNumerically(">=", 2), fmt.Sprintf("At least two nodes necessary with an external or LegacyHostIP")) config.Nodes = nodeList.Items @@ -481,9 +481,9 @@ func (config *NetworkingTestConfig) setup(selector map[string]string) { for _, p := range config.NodePortService.Spec.Ports { switch p.Protocol { - case api.ProtocolUDP: + case v1.ProtocolUDP: config.NodeUdpPort = int(p.NodePort) - case api.ProtocolTCP: + case v1.ProtocolTCP: config.NodeHttpPort = int(p.NodePort) default: continue @@ -495,7 +495,7 @@ func (config *NetworkingTestConfig) setup(selector map[string]string) { func (config *NetworkingTestConfig) cleanup() { nsClient := config.getNamespacesClient() - nsList, err := nsClient.List(api.ListOptions{}) + nsList, err := nsClient.List(v1.ListOptions{}) if err == nil { for _, ns := range nsList.Items { if strings.Contains(ns.Name, config.f.BaseName) && ns.Name != config.Namespace { @@ -507,8 +507,8 @@ func (config *NetworkingTestConfig) cleanup() { // shuffleNodes copies nodes from the specified slice into a copy in random // order. It returns a new slice. -func shuffleNodes(nodes []api.Node) []api.Node { - shuffled := make([]api.Node, len(nodes)) +func shuffleNodes(nodes []v1.Node) []v1.Node { + shuffled := make([]v1.Node, len(nodes)) perm := rand.Perm(len(nodes)) for i, j := range perm { shuffled[j] = nodes[i] @@ -516,7 +516,7 @@ func shuffleNodes(nodes []api.Node) []api.Node { return shuffled } -func (config *NetworkingTestConfig) createNetProxyPods(podName string, selector map[string]string) []*api.Pod { +func (config *NetworkingTestConfig) createNetProxyPods(podName string, selector map[string]string) []*v1.Pod { ExpectNoError(WaitForAllNodesSchedulable(config.f.ClientSet, 10*time.Minute)) nodeList := GetReadySchedulableNodesOrDie(config.f.ClientSet) @@ -529,7 +529,7 @@ func (config *NetworkingTestConfig) createNetProxyPods(podName string, selector } // create pods, one for each node - createdPods := make([]*api.Pod, 0, len(nodes)) + createdPods := make([]*v1.Pod, 0, len(nodes)) for i, n := range nodes { podName := fmt.Sprintf("%s-%d", podName, i) pod := config.createNetShellPodSpec(podName, n.Name) @@ -539,7 +539,7 @@ func (config *NetworkingTestConfig) createNetProxyPods(podName string, selector } // wait that all of them are up - runningPods := make([]*api.Pod, 0, len(nodes)) + runningPods := make([]*v1.Pod, 0, len(nodes)) for _, p := range createdPods { ExpectNoError(config.f.WaitForPodReady(p.Name)) rp, err := config.getPodClient().Get(p.Name) @@ -552,7 +552,7 @@ func (config *NetworkingTestConfig) createNetProxyPods(podName string, selector func (config *NetworkingTestConfig) DeleteNetProxyPod() { pod := config.EndpointPods[0] - config.getPodClient().Delete(pod.Name, api.NewDeleteOptions(0)) + config.getPodClient().Delete(pod.Name, v1.NewDeleteOptions(0)) config.EndpointPods = config.EndpointPods[1:] // wait for pod being deleted. err := WaitForPodToDisappear(config.f.ClientSet, config.Namespace, pod.Name, labels.Everything(), time.Second, wait.ForeverTestTimeout) @@ -568,7 +568,7 @@ func (config *NetworkingTestConfig) DeleteNetProxyPod() { time.Sleep(5 * time.Second) } -func (config *NetworkingTestConfig) createPod(pod *api.Pod) *api.Pod { +func (config *NetworkingTestConfig) createPod(pod *v1.Pod) *v1.Pod { return config.getPodClient().Create(pod) } diff --git a/test/e2e/framework/nodes_util.go b/test/e2e/framework/nodes_util.go index 7ff5e96ef06..c8eae299aeb 100644 --- a/test/e2e/framework/nodes_util.go +++ b/test/e2e/framework/nodes_util.go @@ -22,8 +22,8 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/util/wait" ) @@ -141,15 +141,15 @@ func nodeUpgradeGKE(v string, img string) error { // nodes it finds. func CheckNodesReady(c clientset.Interface, nt time.Duration, expect int) ([]string, error) { // First, keep getting all of the nodes until we get the number we expect. - var nodeList *api.NodeList + var nodeList *v1.NodeList var errLast error start := time.Now() found := wait.Poll(Poll, nt, func() (bool, error) { // A rolling-update (GCE/GKE implementation of restart) can complete before the apiserver // knows about all of the nodes. Thus, we retry the list nodes call // until we get the expected number of nodes. - nodeList, errLast = c.Core().Nodes().List(api.ListOptions{ - FieldSelector: fields.Set{"spec.unschedulable": "false"}.AsSelector()}) + nodeList, errLast = c.Core().Nodes().List(v1.ListOptions{ + FieldSelector: fields.Set{"spec.unschedulable": "false"}.AsSelector().String()}) if errLast != nil { return false, nil } diff --git a/test/e2e/framework/pods.go b/test/e2e/framework/pods.go index 654c012a539..7822d9b022e 100644 --- a/test/e2e/framework/pods.go +++ b/test/e2e/framework/pods.go @@ -22,9 +22,9 @@ import ( "sync" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + "k8s.io/kubernetes/pkg/api/v1" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" @@ -50,11 +50,11 @@ func (f *Framework) PodClient() *PodClient { type PodClient struct { f *Framework - unversionedcore.PodInterface + v1core.PodInterface } // Create creates a new pod according to the framework specifications (don't wait for it to start). -func (c *PodClient) Create(pod *api.Pod) *api.Pod { +func (c *PodClient) Create(pod *v1.Pod) *v1.Pod { c.mungeSpec(pod) p, err := c.PodInterface.Create(pod) ExpectNoError(err, "Error creating Pod") @@ -62,7 +62,7 @@ func (c *PodClient) Create(pod *api.Pod) *api.Pod { } // CreateSync creates a new pod according to the framework specifications, and wait for it to start. -func (c *PodClient) CreateSync(pod *api.Pod) *api.Pod { +func (c *PodClient) CreateSync(pod *v1.Pod) *v1.Pod { p := c.Create(pod) ExpectNoError(c.f.WaitForPodRunning(p.Name)) // Get the newest pod after it becomes running, some status may change after pod created, such as pod ip. @@ -72,12 +72,12 @@ func (c *PodClient) CreateSync(pod *api.Pod) *api.Pod { } // CreateBatch create a batch of pods. All pods are created before waiting. -func (c *PodClient) CreateBatch(pods []*api.Pod) []*api.Pod { - ps := make([]*api.Pod, len(pods)) +func (c *PodClient) CreateBatch(pods []*v1.Pod) []*v1.Pod { + ps := make([]*v1.Pod, len(pods)) var wg sync.WaitGroup for i, pod := range pods { wg.Add(1) - go func(i int, pod *api.Pod) { + go func(i int, pod *v1.Pod) { defer wg.Done() defer GinkgoRecover() ps[i] = c.CreateSync(pod) @@ -90,7 +90,7 @@ func (c *PodClient) CreateBatch(pods []*api.Pod) []*api.Pod { // Update updates the pod object. It retries if there is a conflict, throw out error if // there is any other errors. name is the pod name, updateFn is the function updating the // pod object. -func (c *PodClient) Update(name string, updateFn func(pod *api.Pod)) { +func (c *PodClient) Update(name string, updateFn func(pod *v1.Pod)) { ExpectNoError(wait.Poll(time.Millisecond*500, time.Second*30, func() (bool, error) { pod, err := c.PodInterface.Get(name) if err != nil { @@ -112,7 +112,7 @@ func (c *PodClient) Update(name string, updateFn func(pod *api.Pod)) { // DeleteSync deletes the pod and wait for the pod to disappear for `timeout`. If the pod doesn't // disappear before the timeout, it will fail the test. -func (c *PodClient) DeleteSync(name string, options *api.DeleteOptions, timeout time.Duration) { +func (c *PodClient) DeleteSync(name string, options *v1.DeleteOptions, timeout time.Duration) { err := c.Delete(name, options) if err != nil && !errors.IsNotFound(err) { Failf("Failed to delete pod %q: %v", name, err) @@ -122,7 +122,7 @@ func (c *PodClient) DeleteSync(name string, options *api.DeleteOptions, timeout } // mungeSpec apply test-suite specific transformations to the pod spec. -func (c *PodClient) mungeSpec(pod *api.Pod) { +func (c *PodClient) mungeSpec(pod *v1.Pod) { if !TestContext.NodeE2E { return } @@ -131,7 +131,7 @@ func (c *PodClient) mungeSpec(pod *api.Pod) { pod.Spec.NodeName = TestContext.NodeName // Node e2e does not support the default DNSClusterFirst policy. Set // the policy to DNSDefault, which is configured per node. - pod.Spec.DNSPolicy = api.DNSDefault + pod.Spec.DNSPolicy = v1.DNSDefault // PrepullImages only works for node e2e now. For cluster e2e, image prepull is not enforced, // we should not munge ImagePullPolicy for cluster e2e pods. @@ -142,7 +142,7 @@ func (c *PodClient) mungeSpec(pod *api.Pod) { // during the test. for i := range pod.Spec.Containers { c := &pod.Spec.Containers[i] - if c.ImagePullPolicy == api.PullAlways { + if c.ImagePullPolicy == v1.PullAlways { // If the image pull policy is PullAlways, the image doesn't need to be in // the white list or pre-pulled, because the image is expected to be pulled // in the test anyway. @@ -153,7 +153,7 @@ func (c *PodClient) mungeSpec(pod *api.Pod) { Expect(ImageWhiteList.Has(c.Image)).To(BeTrue(), "Image %q is not in the white list, consider adding it to CommonImageWhiteList in test/e2e/common/util.go or NodeImageWhiteList in test/e2e_node/image_list.go", c.Image) // Do not pull images during the tests because the images in white list should have // been prepulled. - c.ImagePullPolicy = api.PullNever + c.ImagePullPolicy = v1.PullNever } } @@ -162,11 +162,11 @@ func (c *PodClient) mungeSpec(pod *api.Pod) { func (c *PodClient) WaitForSuccess(name string, timeout time.Duration) { f := c.f Expect(waitForPodCondition(f.ClientSet, f.Namespace.Name, name, "success or failure", timeout, - func(pod *api.Pod) (bool, error) { + func(pod *v1.Pod) (bool, error) { switch pod.Status.Phase { - case api.PodFailed: + case v1.PodFailed: return true, fmt.Errorf("pod %q failed with reason: %q, message: %q", name, pod.Status.Reason, pod.Status.Message) - case api.PodSucceeded: + case v1.PodSucceeded: return true, nil default: return false, nil diff --git a/test/e2e/framework/resource_usage_gatherer.go b/test/e2e/framework/resource_usage_gatherer.go index 16d65443977..70925e4dfc2 100644 --- a/test/e2e/framework/resource_usage_gatherer.go +++ b/test/e2e/framework/resource_usage_gatherer.go @@ -29,8 +29,8 @@ import ( "time" . "github.com/onsi/gomega" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/system" ) @@ -250,7 +250,7 @@ func NewResourceUsageGatherer(c clientset.Interface, options ResourceGathererOpt finished: false, }) } else { - pods, err := c.Core().Pods("kube-system").List(api.ListOptions{}) + pods, err := c.Core().Pods("kube-system").List(v1.ListOptions{}) if err != nil { Logf("Error while listing Pods: %v", err) return nil, err @@ -262,14 +262,14 @@ func NewResourceUsageGatherer(c clientset.Interface, options ResourceGathererOpt g.containerIDs = append(g.containerIDs, containerID) } } - nodeList, err := c.Core().Nodes().List(api.ListOptions{}) + nodeList, err := c.Core().Nodes().List(v1.ListOptions{}) if err != nil { Logf("Error while listing Nodes: %v", err) return nil, err } for _, node := range nodeList.Items { - if !options.masterOnly || system.IsMasterNode(&node) { + if !options.masterOnly || system.IsMasterNode(node.Name) { g.workerWg.Add(1) g.workers = append(g.workers, resourceGatherWorker{ c: c, diff --git a/test/e2e/framework/util.go b/test/e2e/framework/util.go index 1864cb9cd98..e059965bcff 100644 --- a/test/e2e/framework/util.go +++ b/test/e2e/framework/util.go @@ -48,15 +48,16 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/apps" - "k8s.io/kubernetes/pkg/apis/batch" - "k8s.io/kubernetes/pkg/apis/extensions" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + apps "k8s.io/kubernetes/pkg/apis/apps/v1beta1" + batch "k8s.io/kubernetes/pkg/apis/batch/v1" + extensionsinternal "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + "k8s.io/kubernetes/pkg/client/conditions" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/typed/discovery" "k8s.io/kubernetes/pkg/client/typed/dynamic" - client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" gcecloud "k8s.io/kubernetes/pkg/cloudprovider/providers/gce" @@ -250,10 +251,10 @@ func GetServicesProxyRequest(c clientset.Interface, request *restclient.Request) // unique identifier of the e2e run var RunId = uuid.NewUUID() -type CreateTestingNSFn func(baseName string, c clientset.Interface, labels map[string]string) (*api.Namespace, error) +type CreateTestingNSFn func(baseName string, c clientset.Interface, labels map[string]string) (*v1.Namespace, error) type ContainerFailures struct { - status *api.ContainerStateTerminated + status *v1.ContainerStateTerminated Restarts int } @@ -377,10 +378,10 @@ var ProvidersWithSSH = []string{"gce", "gke", "aws"} // providersWithMasterSSH are those providers where master node is accessible with SSH var providersWithMasterSSH = []string{"gce", "gke", "kubemark", "aws"} -type podCondition func(pod *api.Pod) (bool, error) +type podCondition func(pod *v1.Pod) (bool, error) // logPodStates logs basic info of provided pods for debugging. -func logPodStates(pods []api.Pod) { +func logPodStates(pods []v1.Pod) { // Find maximum widths for pod, node, and phase strings for column printing. maxPodW, maxNodeW, maxPhaseW, maxGraceW := len("POD"), len("NODE"), len("PHASE"), len("GRACE") for i := range pods { @@ -416,7 +417,7 @@ func logPodStates(pods []api.Pod) { } // errorBadPodsStates create error message of basic info of bad pods for debugging. -func errorBadPodsStates(badPods []api.Pod, desiredPods int, ns, desiredState string, timeout time.Duration) string { +func errorBadPodsStates(badPods []v1.Pod, desiredPods int, ns, desiredState string, timeout time.Duration) string { errStr := fmt.Sprintf("%d / %d pods in namespace %q are NOT in %s state in %v\n", len(badPods), desiredPods, ns, desiredState, timeout) // Pirnt bad pods info only if there are fewer than 10 bad pods if len(badPods) > 10 { @@ -444,10 +445,10 @@ func errorBadPodsStates(badPods []api.Pod, desiredPods int, ns, desiredState str // pods have been created. func WaitForPodsSuccess(c clientset.Interface, ns string, successPodLabels map[string]string, timeout time.Duration) error { successPodSelector := labels.SelectorFromSet(successPodLabels) - start, badPods, desiredPods := time.Now(), []api.Pod{}, 0 + start, badPods, desiredPods := time.Now(), []v1.Pod{}, 0 if wait.PollImmediate(30*time.Second, timeout, func() (bool, error) { - podList, err := c.Core().Pods(ns).List(api.ListOptions{LabelSelector: successPodSelector}) + podList, err := c.Core().Pods(ns).List(v1.ListOptions{LabelSelector: successPodSelector.String()}) if err != nil { Logf("Error getting pods in namespace %q: %v", ns, err) return false, nil @@ -456,10 +457,10 @@ func WaitForPodsSuccess(c clientset.Interface, ns string, successPodLabels map[s Logf("Waiting for pods to enter Success, but no pods in %q match label %v", ns, successPodLabels) return true, nil } - badPods = []api.Pod{} + badPods = []v1.Pod{} desiredPods = len(podList.Items) for _, pod := range podList.Items { - if pod.Status.Phase != api.PodSucceeded { + if pod.Status.Phase != v1.PodSucceeded { badPods = append(badPods, pod) } } @@ -510,7 +511,7 @@ func WaitForPodsRunningReady(c clientset.Interface, ns string, minPods int32, ti wg := sync.WaitGroup{} wg.Add(1) var waitForSuccessError error - badPods := []api.Pod{} + badPods := []v1.Pod{} desiredPods := 0 go func() { waitForSuccessError = WaitForPodsSuccess(c, ns, ignoreLabels, timeout) @@ -525,34 +526,34 @@ func WaitForPodsRunningReady(c clientset.Interface, ns string, minPods int32, ti replicas, replicaOk := int32(0), int32(0) if hasReadyReplicas { - rcList, err := c.Core().ReplicationControllers(ns).List(api.ListOptions{}) + rcList, err := c.Core().ReplicationControllers(ns).List(v1.ListOptions{}) if err != nil { Logf("Error getting replication controllers in namespace '%s': %v", ns, err) return false, nil } for _, rc := range rcList.Items { - replicas += rc.Spec.Replicas + replicas += *rc.Spec.Replicas replicaOk += rc.Status.ReadyReplicas } - rsList, err := c.Extensions().ReplicaSets(ns).List(api.ListOptions{}) + rsList, err := c.Extensions().ReplicaSets(ns).List(v1.ListOptions{}) if err != nil { Logf("Error getting replication sets in namespace %q: %v", ns, err) return false, nil } for _, rs := range rsList.Items { - replicas += rs.Spec.Replicas + replicas += *rs.Spec.Replicas replicaOk += rs.Status.ReadyReplicas } } - podList, err := c.Core().Pods(ns).List(api.ListOptions{}) + podList, err := c.Core().Pods(ns).List(v1.ListOptions{}) if err != nil { Logf("Error getting pods in namespace '%s': %v", ns, err) return false, nil } nOk := int32(0) - badPods = []api.Pod{} + badPods = []v1.Pod{} desiredPods = len(podList.Items) for _, pod := range podList.Items { if len(ignoreLabels) != 0 && ignoreSelector.Matches(labels.Set(pod.Labels)) { @@ -562,10 +563,10 @@ func WaitForPodsRunningReady(c clientset.Interface, ns string, minPods int32, ti if res, err := testutils.PodRunningReady(&pod); res && err == nil { nOk++ } else { - if pod.Status.Phase != api.PodFailed { + if pod.Status.Phase != v1.PodFailed { Logf("The status of Pod %s is %s (Ready = false), waiting for it to be either Running (with Ready = true) or Failed", pod.ObjectMeta.Name, pod.Status.Phase) badPods = append(badPods, pod) - } else if _, ok := pod.Annotations[api.CreatedByAnnotation]; !ok { + } else if _, ok := pod.Annotations[v1.CreatedByAnnotation]; !ok { Logf("Pod %s is Failed, but it's not controlled by a controller", pod.ObjectMeta.Name) badPods = append(badPods, pod) } @@ -594,8 +595,8 @@ func WaitForPodsRunningReady(c clientset.Interface, ns string, minPods int32, ti return nil } -func podFromManifest(filename string) (*api.Pod, error) { - var pod api.Pod +func podFromManifest(filename string) (*v1.Pod, error) { + var pod v1.Pod Logf("Parsing pod from %v", filename) data := ReadOrDie(filename) json, err := utilyaml.ToJSON(data) @@ -640,7 +641,7 @@ func RunKubernetesServiceTestContainer(c clientset.Interface, ns string) { } } -func kubectlLogPod(c clientset.Interface, pod api.Pod, containerNameSubstr string, logFunc func(ftm string, args ...interface{})) { +func kubectlLogPod(c clientset.Interface, pod v1.Pod, containerNameSubstr string, logFunc func(ftm string, args ...interface{})) { for _, container := range pod.Spec.Containers { if strings.Contains(container.Name, containerNameSubstr) { // Contains() matches all strings if substr is empty @@ -658,7 +659,7 @@ func kubectlLogPod(c clientset.Interface, pod api.Pod, containerNameSubstr strin } func LogFailedContainers(c clientset.Interface, ns string, logFunc func(ftm string, args ...interface{})) { - podList, err := c.Core().Pods(ns).List(api.ListOptions{}) + podList, err := c.Core().Pods(ns).List(v1.ListOptions{}) if err != nil { logFunc("Error getting pods in namespace '%s': %v", ns, err) return @@ -672,7 +673,7 @@ func LogFailedContainers(c clientset.Interface, ns string, logFunc func(ftm stri } func LogPodsWithLabels(c clientset.Interface, ns string, match map[string]string, logFunc func(ftm string, args ...interface{})) { - podList, err := c.Core().Pods(ns).List(api.ListOptions{LabelSelector: labels.SelectorFromSet(match)}) + podList, err := c.Core().Pods(ns).List(v1.ListOptions{LabelSelector: labels.SelectorFromSet(match).String()}) if err != nil { logFunc("Error getting pods in namespace %q: %v", ns, err) return @@ -684,7 +685,7 @@ func LogPodsWithLabels(c clientset.Interface, ns string, match map[string]string } func LogContainersInPodsWithLabels(c clientset.Interface, ns string, match map[string]string, containerSubstr string, logFunc func(ftm string, args ...interface{})) { - podList, err := c.Core().Pods(ns).List(api.ListOptions{LabelSelector: labels.SelectorFromSet(match)}) + podList, err := c.Core().Pods(ns).List(v1.ListOptions{LabelSelector: labels.SelectorFromSet(match).String()}) if err != nil { Logf("Error getting pods in namespace %q: %v", ns, err) return @@ -699,7 +700,7 @@ func LogContainersInPodsWithLabels(c clientset.Interface, ns string, match map[s // Returns the list of deleted namespaces or an error. func DeleteNamespaces(c clientset.Interface, deleteFilter, skipFilter []string) ([]string, error) { By("Deleting namespaces") - nsList, err := c.Core().Namespaces().List(api.ListOptions{}) + nsList, err := c.Core().Namespaces().List(v1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) var deleted []string var wg sync.WaitGroup @@ -746,7 +747,7 @@ func WaitForNamespacesDeleted(c clientset.Interface, namespaces []string, timeou //Now POLL until all namespaces have been eradicated. return wait.Poll(2*time.Second, timeout, func() (bool, error) { - nsList, err := c.Core().Namespaces().List(api.ListOptions{}) + nsList, err := c.Core().Namespaces().List(v1.ListOptions{}) if err != nil { return false, err } @@ -760,11 +761,11 @@ func WaitForNamespacesDeleted(c clientset.Interface, namespaces []string, timeou } func waitForServiceAccountInNamespace(c clientset.Interface, ns, serviceAccountName string, timeout time.Duration) error { - w, err := c.Core().ServiceAccounts(ns).Watch(api.SingleObject(api.ObjectMeta{Name: serviceAccountName})) + w, err := c.Core().ServiceAccounts(ns).Watch(v1.SingleObject(v1.ObjectMeta{Name: serviceAccountName})) if err != nil { return err } - _, err = watch.Until(timeout, w, client.ServiceAccountHasSecrets) + _, err = watch.Until(timeout, w, conditions.ServiceAccountHasSecrets) return err } @@ -795,10 +796,10 @@ func waitForPodCondition(c clientset.Interface, ns, podName, desc string, timeou // WaitForMatchPodsCondition finds match pods based on the input ListOptions. // waits and checks if all match pods are in the given podCondition -func WaitForMatchPodsCondition(c clientset.Interface, opts api.ListOptions, desc string, timeout time.Duration, condition podCondition) error { +func WaitForMatchPodsCondition(c clientset.Interface, opts v1.ListOptions, desc string, timeout time.Duration, condition podCondition) error { Logf("Waiting up to %v for matching pods' status to be %s", timeout, desc) for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) { - pods, err := c.Core().Pods(api.NamespaceAll).List(opts) + pods, err := c.Core().Pods(v1.NamespaceAll).List(opts) if err != nil { return err } @@ -840,7 +841,7 @@ func WaitForFederationApiserverReady(c *federation_release_1_5.Clientset) error } // WaitForPersistentVolumePhase waits for a PersistentVolume to be in a specific phase or until timeout occurs, whichever comes first. -func WaitForPersistentVolumePhase(phase api.PersistentVolumePhase, c clientset.Interface, pvName string, Poll, timeout time.Duration) error { +func WaitForPersistentVolumePhase(phase v1.PersistentVolumePhase, c clientset.Interface, pvName string, Poll, timeout time.Duration) error { Logf("Waiting up to %v for PersistentVolume %s to have phase %s", timeout, pvName, phase) for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) { pv, err := c.Core().PersistentVolumes().Get(pvName) @@ -880,7 +881,7 @@ func WaitForPersistentVolumeDeleted(c clientset.Interface, pvName string, Poll, } // WaitForPersistentVolumeClaimPhase waits for a PersistentVolumeClaim to be in a specific phase or until timeout occurs, whichever comes first. -func WaitForPersistentVolumeClaimPhase(phase api.PersistentVolumeClaimPhase, c clientset.Interface, ns string, pvcName string, Poll, timeout time.Duration) error { +func WaitForPersistentVolumeClaimPhase(phase v1.PersistentVolumeClaimPhase, c clientset.Interface, ns string, pvcName string, Poll, timeout time.Duration) error { Logf("Waiting up to %v for PersistentVolumeClaim %s to have phase %s", timeout, pvcName, phase) for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) { pvc, err := c.Core().PersistentVolumeClaims(ns).Get(pvcName) @@ -901,22 +902,22 @@ func WaitForPersistentVolumeClaimPhase(phase api.PersistentVolumeClaimPhase, c c // CreateTestingNS should be used by every test, note that we append a common prefix to the provided test name. // Please see NewFramework instead of using this directly. -func CreateTestingNS(baseName string, c clientset.Interface, labels map[string]string) (*api.Namespace, error) { +func CreateTestingNS(baseName string, c clientset.Interface, labels map[string]string) (*v1.Namespace, error) { if labels == nil { labels = map[string]string{} } labels["e2e-run"] = string(RunId) - namespaceObj := &api.Namespace{ - ObjectMeta: api.ObjectMeta{ + namespaceObj := &v1.Namespace{ + ObjectMeta: v1.ObjectMeta{ GenerateName: fmt.Sprintf("e2e-tests-%v-", baseName), Namespace: "", Labels: labels, }, - Status: api.NamespaceStatus{}, + Status: v1.NamespaceStatus{}, } // Be robust about making the namespace creation call. - var got *api.Namespace + var got *v1.Namespace if err := wait.PollImmediate(Poll, 30*time.Second, func() (bool, error) { var err error got, err = c.Core().Namespaces().Create(namespaceObj) @@ -958,7 +959,7 @@ func CheckTestingNSDeletedExcept(c clientset.Interface, skip string) error { Logf("Waiting for terminating namespaces to be deleted...") for start := time.Now(); time.Since(start) < timeout; time.Sleep(15 * time.Second) { - namespaces, err := c.Core().Namespaces().List(api.ListOptions{}) + namespaces, err := c.Core().Namespaces().List(v1.ListOptions{}) if err != nil { Logf("Listing namespaces failed: %v", err) continue @@ -966,7 +967,7 @@ func CheckTestingNSDeletedExcept(c clientset.Interface, skip string) error { terminating := 0 for _, ns := range namespaces.Items { if strings.HasPrefix(ns.ObjectMeta.Name, "e2e-tests-") && ns.ObjectMeta.Name != skip { - if ns.Status.Phase == api.NamespaceActive { + if ns.Status.Phase == v1.NamespaceActive { return fmt.Errorf("Namespace %s is active", ns.ObjectMeta.Name) } terminating++ @@ -1041,7 +1042,7 @@ func deleteNS(c clientset.Interface, clientPool dynamic.ClientPool, namespace st // logNamespaces logs the number of namespaces by phase // namespace is the namespace the test was operating against that failed to delete so it can be grepped in logs func logNamespaces(c clientset.Interface, namespace string) { - namespaceList, err := c.Core().Namespaces().List(api.ListOptions{}) + namespaceList, err := c.Core().Namespaces().List(v1.ListOptions{}) if err != nil { Logf("namespace: %v, unable to list namespaces: %v", namespace, err) return @@ -1050,7 +1051,7 @@ func logNamespaces(c clientset.Interface, namespace string) { numActive := 0 numTerminating := 0 for _, namespace := range namespaceList.Items { - if namespace.Status.Phase == api.NamespaceActive { + if namespace.Status.Phase == v1.NamespaceActive { numActive++ } else { numTerminating++ @@ -1076,7 +1077,7 @@ func logNamespace(c clientset.Interface, namespace string) { // countRemainingPods queries the server to count number of remaining pods, and number of pods that had a missing deletion timestamp. func countRemainingPods(c clientset.Interface, namespace string) (int, int, error) { // check for remaining pods - pods, err := c.Core().Pods(namespace).List(api.ListOptions{}) + pods, err := c.Core().Pods(namespace).List(v1.ListOptions{}) if err != nil { return 0, 0, err } @@ -1156,8 +1157,8 @@ func hasRemainingContent(c clientset.Interface, clientPool dynamic.ClientPool, n } func ContainerInitInvariant(older, newer runtime.Object) error { - oldPod := older.(*api.Pod) - newPod := newer.(*api.Pod) + oldPod := older.(*v1.Pod) + newPod := newer.(*v1.Pod) if len(oldPod.Spec.InitContainers) == 0 { return nil } @@ -1183,7 +1184,7 @@ func ContainerInitInvariant(older, newer runtime.Object) error { return nil } -func podInitialized(pod *api.Pod) (ok bool, failed bool, err error) { +func podInitialized(pod *v1.Pod) (ok bool, failed bool, err error) { allInit := true initFailed := false for _, s := range pod.Status.InitContainerStatuses { @@ -1204,7 +1205,7 @@ func podInitialized(pod *api.Pod) (ok bool, failed bool, err error) { return allInit, initFailed, nil } -func initContainersInvariants(pod *api.Pod) error { +func initContainersInvariants(pod *v1.Pod) error { allInit, initFailed, err := podInitialized(pod) if err != nil { return err @@ -1219,7 +1220,7 @@ func initContainersInvariants(pod *api.Pod) error { } } } - _, c := api.GetPodCondition(&pod.Status, api.PodInitialized) + _, c := v1.GetPodCondition(&pod.Status, v1.PodInitialized) if c == nil { return fmt.Errorf("pod does not have initialized condition") } @@ -1227,11 +1228,11 @@ func initContainersInvariants(pod *api.Pod) error { return fmt.Errorf("PodInitialized condition should always have a transition time") } switch { - case c.Status == api.ConditionUnknown: + case c.Status == v1.ConditionUnknown: return fmt.Errorf("PodInitialized condition should never be Unknown") - case c.Status == api.ConditionTrue && (initFailed || !allInit): + case c.Status == v1.ConditionTrue && (initFailed || !allInit): return fmt.Errorf("PodInitialized condition was True but all not all containers initialized") - case c.Status == api.ConditionFalse && (!initFailed && allInit): + case c.Status == v1.ConditionFalse && (!initFailed && allInit): return fmt.Errorf("PodInitialized condition was False but all containers initialized") } return nil @@ -1260,11 +1261,11 @@ func CheckInvariants(events []watch.Event, fns ...InvariantFunc) error { // Waits default amount of time (PodStartTimeout) for the specified pod to become running. // Returns an error if timeout occurs first, or pod goes in to failed state. -func WaitForPodRunningInNamespace(c clientset.Interface, pod *api.Pod) error { +func WaitForPodRunningInNamespace(c clientset.Interface, pod *v1.Pod) error { // this short-cicuit is needed for cases when we pass a list of pods instead // of newly created pod (e.g. VerifyPods) which means we are getting already // running pod for which waiting does not make sense and will always fail - if pod.Status.Phase == api.PodRunning { + if pod.Status.Phase == v1.PodRunning { return nil } return waitTimeoutForPodRunningInNamespace(c, pod.Name, pod.Namespace, pod.ResourceVersion, PodStartTimeout) @@ -1284,11 +1285,11 @@ func waitForPodRunningInNamespaceSlow(c clientset.Interface, podName, namespace, } func waitTimeoutForPodRunningInNamespace(c clientset.Interface, podName, namespace, resourceVersion string, timeout time.Duration) error { - w, err := c.Core().Pods(namespace).Watch(api.SingleObject(api.ObjectMeta{Name: podName, ResourceVersion: resourceVersion})) + w, err := c.Core().Pods(namespace).Watch(v1.SingleObject(v1.ObjectMeta{Name: podName, ResourceVersion: resourceVersion})) if err != nil { return err } - _, err = watch.Until(timeout, w, client.PodRunning) + _, err = watch.Until(timeout, w, conditions.PodRunning) return err } @@ -1299,20 +1300,20 @@ func WaitForPodNoLongerRunningInNamespace(c clientset.Interface, podName, namesp } func WaitTimeoutForPodNoLongerRunningInNamespace(c clientset.Interface, podName, namespace, resourceVersion string, timeout time.Duration) error { - w, err := c.Core().Pods(namespace).Watch(api.SingleObject(api.ObjectMeta{Name: podName, ResourceVersion: resourceVersion})) + w, err := c.Core().Pods(namespace).Watch(v1.SingleObject(v1.ObjectMeta{Name: podName, ResourceVersion: resourceVersion})) if err != nil { return err } - _, err = watch.Until(timeout, w, client.PodCompleted) + _, err = watch.Until(timeout, w, conditions.PodCompleted) return err } func waitTimeoutForPodReadyInNamespace(c clientset.Interface, podName, namespace, resourceVersion string, timeout time.Duration) error { - w, err := c.Core().Pods(namespace).Watch(api.SingleObject(api.ObjectMeta{Name: podName, ResourceVersion: resourceVersion})) + w, err := c.Core().Pods(namespace).Watch(v1.SingleObject(v1.ObjectMeta{Name: podName, ResourceVersion: resourceVersion})) if err != nil { return err } - _, err = watch.Until(timeout, w, client.PodRunningAndReady) + _, err = watch.Until(timeout, w, conditions.PodRunningAndReady) return err } @@ -1320,19 +1321,19 @@ func waitTimeoutForPodReadyInNamespace(c clientset.Interface, podName, namespace // The resourceVersion is used when Watching object changes, it tells since when we care // about changes to the pod. func WaitForPodNotPending(c clientset.Interface, ns, podName, resourceVersion string) error { - w, err := c.Core().Pods(ns).Watch(api.SingleObject(api.ObjectMeta{Name: podName, ResourceVersion: resourceVersion})) + w, err := c.Core().Pods(ns).Watch(v1.SingleObject(v1.ObjectMeta{Name: podName, ResourceVersion: resourceVersion})) if err != nil { return err } - _, err = watch.Until(PodStartTimeout, w, client.PodNotPending) + _, err = watch.Until(PodStartTimeout, w, conditions.PodNotPending) return err } // waitForPodTerminatedInNamespace returns an error if it took too long for the pod // to terminate or if the pod terminated with an unexpected reason. func waitForPodTerminatedInNamespace(c clientset.Interface, podName, reason, namespace string) error { - return waitForPodCondition(c, namespace, podName, "terminated due to deadline exceeded", PodStartTimeout, func(pod *api.Pod) (bool, error) { - if pod.Status.Phase == api.PodFailed { + return waitForPodCondition(c, namespace, podName, "terminated due to deadline exceeded", PodStartTimeout, func(pod *v1.Pod) (bool, error) { + if pod.Status.Phase == v1.PodFailed { if pod.Status.Reason == reason { return true, nil } else { @@ -1346,15 +1347,15 @@ func waitForPodTerminatedInNamespace(c clientset.Interface, podName, reason, nam // waitForPodSuccessInNamespaceTimeout returns nil if the pod reached state success, or an error if it reached failure or ran too long. func waitForPodSuccessInNamespaceTimeout(c clientset.Interface, podName string, namespace string, timeout time.Duration) error { - return waitForPodCondition(c, namespace, podName, "success or failure", timeout, func(pod *api.Pod) (bool, error) { - if pod.Spec.RestartPolicy == api.RestartPolicyAlways { + return waitForPodCondition(c, namespace, podName, "success or failure", timeout, func(pod *v1.Pod) (bool, error) { + if pod.Spec.RestartPolicy == v1.RestartPolicyAlways { return true, fmt.Errorf("pod %q will never terminate with a succeeded state since its restart policy is Always", podName) } switch pod.Status.Phase { - case api.PodSucceeded: + case v1.PodSucceeded: By("Saw pod success") return true, nil - case api.PodFailed: + case v1.PodFailed: return true, fmt.Errorf("pod %q failed with status: %+v", podName, pod.Status) default: return false, nil @@ -1374,12 +1375,12 @@ func WaitForPodSuccessInNamespaceSlow(c clientset.Interface, podName string, nam // waitForRCPodOnNode returns the pod from the given replication controller (described by rcName) which is scheduled on the given node. // In case of failure or too long waiting time, an error is returned. -func waitForRCPodOnNode(c clientset.Interface, ns, rcName, node string) (*api.Pod, error) { +func waitForRCPodOnNode(c clientset.Interface, ns, rcName, node string) (*v1.Pod, error) { label := labels.SelectorFromSet(labels.Set(map[string]string{"name": rcName})) - var p *api.Pod = nil + var p *v1.Pod = nil err := wait.PollImmediate(10*time.Second, 5*time.Minute, func() (bool, error) { Logf("Waiting for pod %s to appear on node %s", rcName, node) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := c.Core().Pods(ns).List(options) if err != nil { return false, err @@ -1398,10 +1399,10 @@ func waitForRCPodOnNode(c clientset.Interface, ns, rcName, node string) (*api.Po // WaitForRCToStabilize waits till the RC has a matching generation/replica count between spec and status. func WaitForRCToStabilize(c clientset.Interface, ns, name string, timeout time.Duration) error { - options := api.ListOptions{FieldSelector: fields.Set{ + options := v1.ListOptions{FieldSelector: fields.Set{ "metadata.name": name, "metadata.namespace": ns, - }.AsSelector()} + }.AsSelector().String()} w, err := c.Core().ReplicationControllers(ns).Watch(options) if err != nil { return err @@ -1412,14 +1413,14 @@ func WaitForRCToStabilize(c clientset.Interface, ns, name string, timeout time.D return false, apierrs.NewNotFound(unversioned.GroupResource{Resource: "replicationcontrollers"}, "") } switch rc := event.Object.(type) { - case *api.ReplicationController: + case *v1.ReplicationController: if rc.Name == name && rc.Namespace == ns && rc.Generation <= rc.Status.ObservedGeneration && - rc.Spec.Replicas == rc.Status.Replicas { + *(rc.Spec.Replicas) == rc.Status.Replicas { return true, nil } Logf("Waiting for rc %s to stabilize, generation %v observed generation %v spec.replicas %d status.replicas %d", - name, rc.Generation, rc.Status.ObservedGeneration, rc.Spec.Replicas, rc.Status.Replicas) + name, rc.Generation, rc.Status.ObservedGeneration, *(rc.Spec.Replicas), rc.Status.Replicas) } return false, nil }) @@ -1429,7 +1430,7 @@ func WaitForRCToStabilize(c clientset.Interface, ns, name string, timeout time.D func WaitForPodToDisappear(c clientset.Interface, ns, podName string, label labels.Selector, interval, timeout time.Duration) error { return wait.PollImmediate(interval, timeout, func() (bool, error) { Logf("Waiting for pod %s to disappear", podName) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := c.Core().Pods(ns).List(options) if err != nil { return false, err @@ -1493,7 +1494,7 @@ func WaitForService(c clientset.Interface, namespace, name string, exist bool, i func WaitForServiceEndpointsNum(c clientset.Interface, namespace, serviceName string, expectNum int, interval, timeout time.Duration) error { return wait.Poll(interval, timeout, func() (bool, error) { Logf("Waiting for amount of service:%s endpoints to be %d", serviceName, expectNum) - list, err := c.Core().Endpoints(namespace).List(api.ListOptions{}) + list, err := c.Core().Endpoints(namespace).List(v1.ListOptions{}) if err != nil { return false, err } @@ -1507,7 +1508,7 @@ func WaitForServiceEndpointsNum(c clientset.Interface, namespace, serviceName st }) } -func countEndpointsNum(e *api.Endpoints) int { +func countEndpointsNum(e *v1.Endpoints) int { num := 0 for _, sub := range e.Subsets { num += len(sub.Addresses) @@ -1556,10 +1557,10 @@ type podProxyResponseChecker struct { label labels.Selector controllerName string respondName bool // Whether the pod should respond with its own name. - pods *api.PodList + pods *v1.PodList } -func PodProxyResponseChecker(c clientset.Interface, ns string, label labels.Selector, controllerName string, respondName bool, pods *api.PodList) podProxyResponseChecker { +func PodProxyResponseChecker(c clientset.Interface, ns string, label labels.Selector, controllerName string, respondName bool, pods *v1.PodList) podProxyResponseChecker { return podProxyResponseChecker{c, ns, label, controllerName, respondName, pods} } @@ -1567,7 +1568,7 @@ func PodProxyResponseChecker(c clientset.Interface, ns string, label labels.Sele // reply with their own pod name. func (r podProxyResponseChecker) CheckAllResponses() (done bool, err error) { successes := 0 - options := api.ListOptions{LabelSelector: r.label} + options := v1.ListOptions{LabelSelector: r.label.String()} currentPods, err := r.c.Core().Pods(r.ns).List(options) Expect(err).NotTo(HaveOccurred()) for i, pod := range r.pods.Items { @@ -1680,21 +1681,21 @@ func KubectlVersion() (semver.Version, error) { return version.Parse(matches[1]) } -func PodsResponding(c clientset.Interface, ns, name string, wantName bool, pods *api.PodList) error { +func PodsResponding(c clientset.Interface, ns, name string, wantName bool, pods *v1.PodList) error { By("trying to dial each unique pod") label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name})) return wait.PollImmediate(Poll, podRespondingTimeout, PodProxyResponseChecker(c, ns, label, name, wantName, pods).CheckAllResponses) } -func PodsCreated(c clientset.Interface, ns, name string, replicas int32) (*api.PodList, error) { +func PodsCreated(c clientset.Interface, ns, name string, replicas int32) (*v1.PodList, error) { label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name})) return PodsCreatedByLabel(c, ns, name, replicas, label) } -func PodsCreatedByLabel(c clientset.Interface, ns, name string, replicas int32, label labels.Selector) (*api.PodList, error) { +func PodsCreatedByLabel(c clientset.Interface, ns, name string, replicas int32, label labels.Selector) (*v1.PodList, error) { timeout := 2 * time.Minute for start := time.Now(); time.Since(start) < timeout; time.Sleep(5 * time.Second) { - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} // List the pods, making sure we observe all the replicas. pods, err := c.Core().Pods(ns).List(options) @@ -1702,7 +1703,7 @@ func PodsCreatedByLabel(c clientset.Interface, ns, name string, replicas int32, return nil, err } - created := []api.Pod{} + created := []v1.Pod{} for _, pod := range pods.Items { if pod.DeletionTimestamp != nil { continue @@ -1719,7 +1720,7 @@ func PodsCreatedByLabel(c clientset.Interface, ns, name string, replicas int32, return nil, fmt.Errorf("Pod name %s: Gave up waiting %v for %d pods to come up", name, timeout, replicas) } -func podsRunning(c clientset.Interface, pods *api.PodList) []error { +func podsRunning(c clientset.Interface, pods *v1.PodList) []error { // Wait for the pods to enter the running state. Waiting loops until the pods // are running so non-running pods cause a timeout for this test. By("ensuring each pod is running") @@ -1727,7 +1728,7 @@ func podsRunning(c clientset.Interface, pods *api.PodList) []error { error_chan := make(chan error) for _, pod := range pods.Items { - go func(p api.Pod) { + go func(p v1.Pod) { error_chan <- WaitForPodRunningInNamespace(c, &p) }(pod) } @@ -1845,7 +1846,15 @@ func LoadFederationClientset_1_5() (*federation_release_1_5.Clientset, error) { return c, nil } -func LoadInternalClientset() (*clientset.Clientset, error) { +func LoadInternalClientset() (*internalclientset.Clientset, error) { + config, err := LoadConfig() + if err != nil { + return nil, fmt.Errorf("error creating client: %v", err.Error()) + } + return internalclientset.NewForConfig(config) +} + +func LoadClientset() (*clientset.Clientset, error) { config, err := LoadConfig() if err != nil { return nil, fmt.Errorf("error creating client: %v", err.Error()) @@ -1853,14 +1862,6 @@ func LoadInternalClientset() (*clientset.Clientset, error) { return clientset.NewForConfig(config) } -func LoadClientset() (*release_1_5.Clientset, error) { - config, err := LoadConfig() - if err != nil { - return nil, fmt.Errorf("error creating client: %v", err.Error()) - } - return release_1_5.NewForConfig(config) -} - // randomSuffix provides a random string to append to pods,services,rcs. // TODO: Allow service names to have the same form as names // for pods and replication controllers so we don't @@ -2156,7 +2157,7 @@ func TryKill(cmd *exec.Cmd) { // for all of the containers in the podSpec to move into the 'Success' status, and tests // the specified container log against the given expected output using the given matcher. func (f *Framework) testContainerOutputMatcher(scenarioName string, - pod *api.Pod, + pod *v1.Pod, containerIndex int, expectedOutput []string, matcher func(string, ...interface{}) gomegatypes.GomegaMatcher) { @@ -2170,7 +2171,7 @@ func (f *Framework) testContainerOutputMatcher(scenarioName string, // MatchContainerOutput creates a pod and waits for all it's containers to exit with success. // It then tests that the matcher with each expectedOutput matches the output of the specified container. func (f *Framework) MatchContainerOutput( - pod *api.Pod, + pod *v1.Pod, containerName string, expectedOutput []string, matcher func(string, ...interface{}) gomegatypes.GomegaMatcher) error { @@ -2180,7 +2181,7 @@ func (f *Framework) MatchContainerOutput( createdPod := podClient.Create(pod) defer func() { By("delete the pod") - podClient.DeleteSync(createdPod.Name, &api.DeleteOptions{}, podNoLongerRunningTimeout) + podClient.DeleteSync(createdPod.Name, &v1.DeleteOptions{}, podNoLongerRunningTimeout) }() // Wait for client pod to complete. @@ -2260,9 +2261,9 @@ func DumpEventsInNamespace(eventsLister EventsLister, namespace string) { // you may or may not see the killing/deletion/Cleanup events. } -func DumpAllNamespaceInfo(c clientset.Interface, cs *release_1_5.Clientset, namespace string) { +func DumpAllNamespaceInfo(c clientset.Interface, namespace string) { DumpEventsInNamespace(func(opts v1.ListOptions, ns string) (*v1.EventList, error) { - return cs.Core().Events(ns).List(opts) + return c.Core().Events(ns).List(opts) }, namespace) // If cluster is large, then the following logs are basically useless, because: @@ -2270,7 +2271,7 @@ func DumpAllNamespaceInfo(c clientset.Interface, cs *release_1_5.Clientset, name // 2. there are so many of them that working with them are mostly impossible // So we dump them only if the cluster is relatively small. maxNodesForDump := 20 - if nodes, err := c.Core().Nodes().List(api.ListOptions{}); err == nil { + if nodes, err := c.Core().Nodes().List(v1.ListOptions{}); err == nil { if len(nodes.Items) <= maxNodesForDump { dumpAllPodInfo(c) dumpAllNodeInfo(c) @@ -2296,7 +2297,7 @@ func (o byFirstTimestamp) Less(i, j int) bool { } func dumpAllPodInfo(c clientset.Interface) { - pods, err := c.Core().Pods("").List(api.ListOptions{}) + pods, err := c.Core().Pods("").List(v1.ListOptions{}) if err != nil { Logf("unable to fetch pod debug info: %v", err) } @@ -2305,7 +2306,7 @@ func dumpAllPodInfo(c clientset.Interface) { func dumpAllNodeInfo(c clientset.Interface) { // It should be OK to list unschedulable Nodes here. - nodes, err := c.Core().Nodes().List(api.ListOptions{}) + nodes, err := c.Core().Nodes().List(v1.ListOptions{}) if err != nil { Logf("unable to fetch node list: %v", err) return @@ -2356,30 +2357,30 @@ func DumpNodeDebugInfo(c clientset.Interface, nodeNames []string, logFunc func(f // logNodeEvents logs kubelet events from the given node. This includes kubelet // restart and node unhealthy events. Note that listing events like this will mess // with latency metrics, beware of calling it during a test. -func getNodeEvents(c clientset.Interface, nodeName string) []api.Event { +func getNodeEvents(c clientset.Interface, nodeName string) []v1.Event { selector := fields.Set{ "involvedObject.kind": "Node", "involvedObject.name": nodeName, - "involvedObject.namespace": api.NamespaceAll, + "involvedObject.namespace": v1.NamespaceAll, "source": "kubelet", - }.AsSelector() - options := api.ListOptions{FieldSelector: selector} + }.AsSelector().String() + options := v1.ListOptions{FieldSelector: selector} events, err := c.Core().Events(api.NamespaceSystem).List(options) if err != nil { Logf("Unexpected error retrieving node events %v", err) - return []api.Event{} + return []v1.Event{} } return events.Items } // waitListSchedulableNodesOrDie is a wrapper around listing nodes supporting retries. -func waitListSchedulableNodesOrDie(c clientset.Interface) *api.NodeList { - var nodes *api.NodeList +func waitListSchedulableNodesOrDie(c clientset.Interface) *v1.NodeList { + var nodes *v1.NodeList var err error if wait.PollImmediate(Poll, SingleCallTimeout, func() (bool, error) { - nodes, err = c.Core().Nodes().List(api.ListOptions{FieldSelector: fields.Set{ + nodes, err = c.Core().Nodes().List(v1.ListOptions{FieldSelector: fields.Set{ "spec.unschedulable": "false", - }.AsSelector()}) + }.AsSelector().String()}) return err == nil, nil }) != nil { ExpectNoError(err, "Timed out while listing nodes for e2e cluster.") @@ -2391,26 +2392,26 @@ func waitListSchedulableNodesOrDie(c clientset.Interface) *api.NodeList { // 1) doesn't have "unschedulable" field set // 2) it's Ready condition is set to true // 3) doesn't have NetworkUnavailable condition set to true -func isNodeSchedulable(node *api.Node) bool { - nodeReady := IsNodeConditionSetAsExpected(node, api.NodeReady, true) - networkReady := IsNodeConditionUnset(node, api.NodeNetworkUnavailable) || - IsNodeConditionSetAsExpectedSilent(node, api.NodeNetworkUnavailable, false) +func isNodeSchedulable(node *v1.Node) bool { + nodeReady := IsNodeConditionSetAsExpected(node, v1.NodeReady, true) + networkReady := IsNodeConditionUnset(node, v1.NodeNetworkUnavailable) || + IsNodeConditionSetAsExpectedSilent(node, v1.NodeNetworkUnavailable, false) return !node.Spec.Unschedulable && nodeReady && networkReady } // Test whether a fake pod can be scheduled on "node", given its current taints. -func isNodeUntainted(node *api.Node) bool { - fakePod := &api.Pod{ +func isNodeUntainted(node *v1.Node) bool { + fakePod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "fake-not-scheduled", Namespace: "fake-not-scheduled", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "fake-not-scheduled", Image: "fake-not-scheduled", @@ -2432,11 +2433,11 @@ func isNodeUntainted(node *api.Node) bool { // 1) Needs to be schedulable. // 2) Needs to be ready. // If EITHER 1 or 2 is not true, most tests will want to ignore the node entirely. -func GetReadySchedulableNodesOrDie(c clientset.Interface) (nodes *api.NodeList) { +func GetReadySchedulableNodesOrDie(c clientset.Interface) (nodes *v1.NodeList) { nodes = waitListSchedulableNodesOrDie(c) // previous tests may have cause failures of some nodes. Let's skip // 'Not Ready' nodes, just in case (there is no need to fail the test). - FilterNodes(nodes, func(node api.Node) bool { + FilterNodes(nodes, func(node v1.Node) bool { return isNodeSchedulable(&node) && isNodeUntainted(&node) }) return nodes @@ -2445,12 +2446,12 @@ func GetReadySchedulableNodesOrDie(c clientset.Interface) (nodes *api.NodeList) func WaitForAllNodesSchedulable(c clientset.Interface, timeout time.Duration) error { Logf("Waiting up to %v for all (but %d) nodes to be schedulable", timeout, TestContext.AllowedNotReadyNodes) - var notSchedulable []*api.Node + var notSchedulable []*v1.Node return wait.PollImmediate(30*time.Second, timeout, func() (bool, error) { notSchedulable = nil - opts := api.ListOptions{ + opts := v1.ListOptions{ ResourceVersion: "0", - FieldSelector: fields.Set{"spec.unschedulable": "false"}.AsSelector(), + FieldSelector: fields.Set{"spec.unschedulable": "false"}.AsSelector().String(), } nodes, err := c.Core().Nodes().List(opts) if err != nil { @@ -2476,8 +2477,8 @@ func WaitForAllNodesSchedulable(c clientset.Interface, timeout time.Duration) er for i := range notSchedulable { Logf("-> %s Ready=%t Network=%t", notSchedulable[i].Name, - IsNodeConditionSetAsExpected(notSchedulable[i], api.NodeReady, true), - IsNodeConditionSetAsExpected(notSchedulable[i], api.NodeNetworkUnavailable, false)) + IsNodeConditionSetAsExpected(notSchedulable[i], v1.NodeReady, true), + IsNodeConditionSetAsExpected(notSchedulable[i], v1.NodeNetworkUnavailable, false)) } } if len(notSchedulable) > TestContext.AllowedNotReadyNodes { @@ -2508,15 +2509,15 @@ func RemoveLabelOffNode(c clientset.Interface, nodeName string, labelKey string) ExpectNoError(testutils.VerifyLabelsRemoved(c, nodeName, []string{labelKey})) } -func AddOrUpdateTaintOnNode(c clientset.Interface, nodeName string, taint api.Taint) { +func AddOrUpdateTaintOnNode(c clientset.Interface, nodeName string, taint v1.Taint) { for attempt := 0; attempt < UpdateRetries; attempt++ { node, err := c.Core().Nodes().Get(nodeName) ExpectNoError(err) - nodeTaints, err := api.GetTaintsFromNodeAnnotations(node.Annotations) + nodeTaints, err := v1.GetTaintsFromNodeAnnotations(node.Annotations) ExpectNoError(err) - var newTaints []api.Taint + var newTaints []v1.Taint updated := false for _, existingTaint := range nodeTaints { if taint.MatchTaint(existingTaint) { @@ -2538,7 +2539,7 @@ func AddOrUpdateTaintOnNode(c clientset.Interface, nodeName string, taint api.Ta if node.Annotations == nil { node.Annotations = make(map[string]string) } - node.Annotations[api.TaintsAnnotationKey] = string(taintsData) + node.Annotations[v1.TaintsAnnotationKey] = string(taintsData) _, err = c.Core().Nodes().Update(node) if err != nil { if !apierrs.IsConflict(err) { @@ -2553,7 +2554,7 @@ func AddOrUpdateTaintOnNode(c clientset.Interface, nodeName string, taint api.Ta } } -func taintExists(taints []api.Taint, taintToFind api.Taint) bool { +func taintExists(taints []v1.Taint, taintToFind v1.Taint) bool { for _, taint := range taints { if taint.MatchTaint(taintToFind) { return true @@ -2562,12 +2563,12 @@ func taintExists(taints []api.Taint, taintToFind api.Taint) bool { return false } -func ExpectNodeHasTaint(c clientset.Interface, nodeName string, taint api.Taint) { +func ExpectNodeHasTaint(c clientset.Interface, nodeName string, taint v1.Taint) { By("verifying the node has the taint " + taint.ToString()) node, err := c.Core().Nodes().Get(nodeName) ExpectNoError(err) - nodeTaints, err := api.GetTaintsFromNodeAnnotations(node.Annotations) + nodeTaints, err := v1.GetTaintsFromNodeAnnotations(node.Annotations) ExpectNoError(err) if len(nodeTaints) == 0 || !taintExists(nodeTaints, taint) { @@ -2575,8 +2576,8 @@ func ExpectNodeHasTaint(c clientset.Interface, nodeName string, taint api.Taint) } } -func deleteTaint(oldTaints []api.Taint, taintToDelete api.Taint) ([]api.Taint, error) { - newTaints := []api.Taint{} +func deleteTaint(oldTaints []v1.Taint, taintToDelete v1.Taint) ([]v1.Taint, error) { + newTaints := []v1.Taint{} found := false for _, oldTaint := range oldTaints { if oldTaint.MatchTaint(taintToDelete) { @@ -2594,13 +2595,13 @@ func deleteTaint(oldTaints []api.Taint, taintToDelete api.Taint) ([]api.Taint, e // RemoveTaintOffNode is for cleaning up taints temporarily added to node, // won't fail if target taint doesn't exist or has been removed. -func RemoveTaintOffNode(c clientset.Interface, nodeName string, taint api.Taint) { +func RemoveTaintOffNode(c clientset.Interface, nodeName string, taint v1.Taint) { By("removing the taint " + taint.ToString() + " off the node " + nodeName) for attempt := 0; attempt < UpdateRetries; attempt++ { node, err := c.Core().Nodes().Get(nodeName) ExpectNoError(err) - nodeTaints, err := api.GetTaintsFromNodeAnnotations(node.Annotations) + nodeTaints, err := v1.GetTaintsFromNodeAnnotations(node.Annotations) ExpectNoError(err) if len(nodeTaints) == 0 { return @@ -2613,11 +2614,11 @@ func RemoveTaintOffNode(c clientset.Interface, nodeName string, taint api.Taint) newTaints, err := deleteTaint(nodeTaints, taint) ExpectNoError(err) if len(newTaints) == 0 { - delete(node.Annotations, api.TaintsAnnotationKey) + delete(node.Annotations, v1.TaintsAnnotationKey) } else { taintsData, err := json.Marshal(newTaints) ExpectNoError(err) - node.Annotations[api.TaintsAnnotationKey] = string(taintsData) + node.Annotations[v1.TaintsAnnotationKey] = string(taintsData) } _, err = c.Core().Nodes().Update(node) @@ -2636,16 +2637,16 @@ func RemoveTaintOffNode(c clientset.Interface, nodeName string, taint api.Taint) nodeUpdated, err := c.Core().Nodes().Get(nodeName) ExpectNoError(err) By("verifying the node doesn't have the taint " + taint.ToString()) - taintsGot, err := api.GetTaintsFromNodeAnnotations(nodeUpdated.Annotations) + taintsGot, err := v1.GetTaintsFromNodeAnnotations(nodeUpdated.Annotations) ExpectNoError(err) if taintExists(taintsGot, taint) { Failf("Failed removing taint " + taint.ToString() + " of the node " + nodeName) } } -func ScaleRC(clientset clientset.Interface, ns, name string, size uint, wait bool) error { +func ScaleRC(clientset clientset.Interface, internalClientset internalclientset.Interface, ns, name string, size uint, wait bool) error { By(fmt.Sprintf("Scaling replication controller %s in namespace %s to %d", name, ns, size)) - scaler, err := kubectl.ScalerFor(api.Kind("ReplicationController"), clientset) + scaler, err := kubectl.ScalerFor(api.Kind("ReplicationController"), internalClientset) if err != nil { return err } @@ -2674,9 +2675,9 @@ func WaitForRCPodsRunning(c clientset.Interface, ns, rcName string) error { return nil } -func ScaleDeployment(clientset clientset.Interface, ns, name string, size uint, wait bool) error { +func ScaleDeployment(clientset clientset.Interface, internalClientset internalclientset.Interface, ns, name string, size uint, wait bool) error { By(fmt.Sprintf("Scaling Deployment %s in namespace %s to %d", name, ns, size)) - scaler, err := kubectl.ScalerFor(extensions.Kind("Deployment"), clientset) + scaler, err := kubectl.ScalerFor(extensionsinternal.Kind("Deployment"), internalClientset) if err != nil { return err } @@ -2722,7 +2723,7 @@ func podsWithLabelScheduled(c clientset.Interface, ns string, label labels.Selec // Wait for all matching pods to become scheduled and at least one // matching pod exists. Return the list of matching pods. -func WaitForPodsWithLabelScheduled(c clientset.Interface, ns string, label labels.Selector) (pods *api.PodList, err error) { +func WaitForPodsWithLabelScheduled(c clientset.Interface, ns string, label labels.Selector) (pods *v1.PodList, err error) { err = wait.PollImmediate(Poll, podScheduledBeforeTimeout, func() (bool, error) { pods, err = WaitForPodsWithLabel(c, ns, label) @@ -2740,9 +2741,9 @@ func WaitForPodsWithLabelScheduled(c clientset.Interface, ns string, label label } // Wait up to PodListTimeout for getting pods with certain label -func WaitForPodsWithLabel(c clientset.Interface, ns string, label labels.Selector) (pods *api.PodList, err error) { +func WaitForPodsWithLabel(c clientset.Interface, ns string, label labels.Selector) (pods *v1.PodList, err error) { for t := time.Now(); time.Since(t) < PodListTimeout; time.Sleep(Poll) { - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err = c.Core().Pods(ns).List(options) Expect(err).NotTo(HaveOccurred()) if len(pods.Items) > 0 { @@ -2756,7 +2757,7 @@ func WaitForPodsWithLabel(c clientset.Interface, ns string, label labels.Selecto } // DeleteRCAndPods a Replication Controller and all pods it spawned -func DeleteRCAndPods(clientset clientset.Interface, ns, name string) error { +func DeleteRCAndPods(clientset clientset.Interface, internalClientset internalclientset.Interface, ns, name string) error { By(fmt.Sprintf("deleting replication controller %s in namespace %s", name, ns)) rc, err := clientset.Core().ReplicationControllers(ns).Get(name) if err != nil { @@ -2766,7 +2767,7 @@ func DeleteRCAndPods(clientset clientset.Interface, ns, name string) error { } return err } - reaper, err := kubectl.ReaperForReplicationController(clientset.Core(), 10*time.Minute) + reaper, err := kubectl.ReaperForReplicationController(internalClientset.Core(), 10*time.Minute) if err != nil { if apierrs.IsNotFound(err) { Logf("RC %s was already deleted: %v", name, err) @@ -2823,7 +2824,7 @@ func DeleteRCAndWaitForGC(c clientset.Interface, ns, name string) error { defer ps.Stop() startTime := time.Now() falseVar := false - deleteOption := &api.DeleteOptions{OrphanDependents: &falseVar} + deleteOption := &v1.DeleteOptions{OrphanDependents: &falseVar} err = c.Core().ReplicationControllers(ns).Delete(name, deleteOption) if err != nil && apierrs.IsNotFound(err) { Logf("RC %s was already deleted: %v", name, err) @@ -2836,17 +2837,17 @@ func DeleteRCAndWaitForGC(c clientset.Interface, ns, name string) error { Logf("Deleting RC %s took: %v", name, deleteRCTime) var interval, timeout time.Duration switch { - case rc.Spec.Replicas < 100: + case *(rc.Spec.Replicas) < 100: interval = 100 * time.Millisecond - case rc.Spec.Replicas < 1000: + case *(rc.Spec.Replicas) < 1000: interval = 1 * time.Second default: interval = 10 * time.Second } - if rc.Spec.Replicas < 5000 { + if *(rc.Spec.Replicas) < 5000 { timeout = 10 * time.Minute } else { - timeout = time.Duration(rc.Spec.Replicas/gcThroughput) * time.Second + timeout = time.Duration(*(rc.Spec.Replicas)/gcThroughput) * time.Second // gcThroughput is pretty strict now, add a bit more to it timeout = timeout + 3*time.Minute } @@ -2865,7 +2866,7 @@ func DeleteRCAndWaitForGC(c clientset.Interface, ns, name string) error { // podStoreForRC creates a PodStore that monitors pods belong to the rc. It // waits until the reflector does a List() before returning. -func podStoreForRC(c clientset.Interface, rc *api.ReplicationController) (*testutils.PodStore, error) { +func podStoreForRC(c clientset.Interface, rc *v1.ReplicationController) (*testutils.PodStore, error) { labels := labels.SelectorFromSet(rc.Spec.Selector) ps := testutils.NewPodStore(c, rc.Namespace, labels, fields.Everything()) err := wait.Poll(1*time.Second, 2*time.Minute, func() (bool, error) { @@ -2904,7 +2905,7 @@ func waitForPodsGone(ps *testutils.PodStore, interval, timeout time.Duration) er } // Delete a ReplicaSet and all pods it spawned -func DeleteReplicaSet(clientset clientset.Interface, ns, name string) error { +func DeleteReplicaSet(clientset clientset.Interface, internalClientset internalclientset.Interface, ns, name string) error { By(fmt.Sprintf("deleting ReplicaSet %s in namespace %s", name, ns)) rc, err := clientset.Extensions().ReplicaSets(ns).Get(name) if err != nil { @@ -2914,7 +2915,7 @@ func DeleteReplicaSet(clientset clientset.Interface, ns, name string) error { } return err } - reaper, err := kubectl.ReaperFor(extensions.Kind("ReplicaSet"), clientset) + reaper, err := kubectl.ReaperFor(extensionsinternal.Kind("ReplicaSet"), internalClientset) if err != nil { if apierrs.IsNotFound(err) { Logf("ReplicaSet %s was already deleted: %v", name, err) @@ -2944,7 +2945,7 @@ func waitForReplicaSetPodsGone(c clientset.Interface, rs *extensions.ReplicaSet) return wait.PollImmediate(Poll, 2*time.Minute, func() (bool, error) { selector, err := unversioned.LabelSelectorAsSelector(rs.Spec.Selector) ExpectNoError(err) - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} if pods, err := c.Core().Pods(rs.Namespace).List(options); err == nil && len(pods.Items) == 0 { return true, nil } @@ -2989,7 +2990,7 @@ func WaitForDeploymentStatusValid(c clientset.Interface, d *extensions.Deploymen } } totalCreated := deploymentutil.GetReplicaCountForReplicaSets(allRSs) - maxCreated := deployment.Spec.Replicas + deploymentutil.MaxSurge(*deployment) + maxCreated := *(deployment.Spec.Replicas) + deploymentutil.MaxSurge(*deployment) if totalCreated > maxCreated { reason = fmt.Sprintf("total pods created: %d, more than the max allowed: %d", totalCreated, maxCreated) Logf(reason) @@ -3003,9 +3004,9 @@ func WaitForDeploymentStatusValid(c clientset.Interface, d *extensions.Deploymen } // When the deployment status and its underlying resources reach the desired state, we're done - if deployment.Status.Replicas == deployment.Spec.Replicas && - deployment.Status.UpdatedReplicas == deployment.Spec.Replicas && - deployment.Status.AvailableReplicas == deployment.Spec.Replicas { + if deployment.Status.Replicas == *(deployment.Spec.Replicas) && + deployment.Status.UpdatedReplicas == *(deployment.Spec.Replicas) && + deployment.Status.AvailableReplicas == *(deployment.Spec.Replicas) { return true, nil } @@ -3057,7 +3058,7 @@ func WaitForDeploymentStatus(c clientset.Interface, d *extensions.Deployment) er } } totalCreated := deploymentutil.GetReplicaCountForReplicaSets(allRSs) - maxCreated := deployment.Spec.Replicas + deploymentutil.MaxSurge(*deployment) + maxCreated := *(deployment.Spec.Replicas) + deploymentutil.MaxSurge(*deployment) if totalCreated > maxCreated { logReplicaSetsOfDeployment(deployment, allOldRSs, newRS) logPodsOfDeployment(c, deployment) @@ -3071,8 +3072,8 @@ func WaitForDeploymentStatus(c clientset.Interface, d *extensions.Deployment) er } // When the deployment status and its underlying resources reach the desired state, we're done - if deployment.Status.Replicas == deployment.Spec.Replicas && - deployment.Status.UpdatedReplicas == deployment.Spec.Replicas { + if deployment.Status.Replicas == *(deployment.Spec.Replicas) && + deployment.Status.UpdatedReplicas == *(deployment.Spec.Replicas) { return true, nil } return false, nil @@ -3196,7 +3197,7 @@ func CheckNewRSAnnotations(c clientset.Interface, ns, deploymentName string, exp func WaitForPodsReady(c clientset.Interface, ns, name string, minReadySeconds int) error { label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name})) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} return wait.Poll(Poll, 5*time.Minute, func() (bool, error) { pods, err := c.Core().Pods(ns).List(options) if err != nil { @@ -3262,7 +3263,7 @@ func WaitForDeploymentWithCondition(c clientset.Interface, ns, deploymentName, r func logPodsOfDeployment(c clientset.Interface, deployment *extensions.Deployment) { minReadySeconds := deployment.Spec.MinReadySeconds podList, err := deploymentutil.ListPods(deployment, - func(namespace string, options api.ListOptions) (*api.PodList, error) { + func(namespace string, options v1.ListOptions) (*v1.PodList, error) { return c.Core().Pods(namespace).List(options) }) if err != nil { @@ -3363,10 +3364,10 @@ func UpdateReplicaSetWithRetries(c clientset.Interface, namespace, name string, return rs, pollErr } -type updateRcFunc func(d *api.ReplicationController) +type updateRcFunc func(d *v1.ReplicationController) -func UpdateReplicationControllerWithRetries(c clientset.Interface, namespace, name string, applyUpdate updateRcFunc) (*api.ReplicationController, error) { - var rc *api.ReplicationController +func UpdateReplicationControllerWithRetries(c clientset.Interface, namespace, name string, applyUpdate updateRcFunc) (*v1.ReplicationController, error) { + var rc *v1.ReplicationController var updateErr error pollErr := wait.PollImmediate(10*time.Millisecond, 1*time.Minute, func() (bool, error) { var err error @@ -3437,7 +3438,7 @@ func UpdateJobWithRetries(c clientset.Interface, namespace, name string, applyUp } // NodeAddresses returns the first address of the given type of each node. -func NodeAddresses(nodelist *api.NodeList, addrType api.NodeAddressType) []string { +func NodeAddresses(nodelist *v1.NodeList, addrType v1.NodeAddressType) []string { hosts := []string{} for _, n := range nodelist.Items { for _, addr := range n.Status.Addresses { @@ -3461,7 +3462,7 @@ func NodeSSHHosts(c clientset.Interface) ([]string, error) { nodelist := waitListSchedulableNodesOrDie(c) // TODO(roberthbailey): Use the "preferred" address for the node, once such a thing is defined (#2462). - hosts := NodeAddresses(nodelist, api.NodeExternalIP) + hosts := NodeAddresses(nodelist, v1.NodeExternalIP) // Error if any node didn't have an external IP. if len(hosts) != len(nodelist.Items) { @@ -3521,11 +3522,11 @@ func LogSSHResult(result SSHResult) { Logf("ssh %s: exit code: %d", remote, result.Code) } -func IssueSSHCommandWithResult(cmd, provider string, node *api.Node) (*SSHResult, error) { +func IssueSSHCommandWithResult(cmd, provider string, node *v1.Node) (*SSHResult, error) { Logf("Getting external IP address for %s", node.Name) host := "" for _, a := range node.Status.Addresses { - if a.Type == api.NodeExternalIP { + if a.Type == v1.NodeExternalIP { host = a.Address + ":22" break } @@ -3547,7 +3548,7 @@ func IssueSSHCommandWithResult(cmd, provider string, node *api.Node) (*SSHResult return &result, nil } -func IssueSSHCommand(cmd, provider string, node *api.Node) error { +func IssueSSHCommand(cmd, provider string, node *v1.Node) error { result, err := IssueSSHCommandWithResult(cmd, provider, node) if result != nil { LogSSHResult(*result) @@ -3562,23 +3563,22 @@ func IssueSSHCommand(cmd, provider string, node *api.Node) error { } // NewHostExecPodSpec returns the pod spec of hostexec pod -func NewHostExecPodSpec(ns, name string) *api.Pod { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func NewHostExecPodSpec(ns, name string) *v1.Pod { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Namespace: ns, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "hostexec", Image: "gcr.io/google_containers/hostexec:1.2", - ImagePullPolicy: api.PullIfNotPresent, + ImagePullPolicy: v1.PullIfNotPresent, }, }, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, + HostNetwork: true, + SecurityContext: &v1.PodSecurityContext{}, }, } return pod @@ -3600,7 +3600,7 @@ func RunHostCmdOrDie(ns, name, cmd string) string { // LaunchHostExecPod launches a hostexec pod in the given namespace and waits // until it's Running -func LaunchHostExecPod(client clientset.Interface, ns, name string) *api.Pod { +func LaunchHostExecPod(client clientset.Interface, ns, name string) *v1.Pod { hostExecPod := NewHostExecPodSpec(ns, name) pod, err := client.Core().Pods(ns).Create(hostExecPod) ExpectNoError(err) @@ -3687,27 +3687,27 @@ func CheckPodsCondition(c clientset.Interface, ns string, podNames []string, tim // WaitForNodeToBeReady returns whether node name is ready within timeout. func WaitForNodeToBeReady(c clientset.Interface, name string, timeout time.Duration) bool { - return WaitForNodeToBe(c, name, api.NodeReady, true, timeout) + return WaitForNodeToBe(c, name, v1.NodeReady, true, timeout) } // WaitForNodeToBeNotReady returns whether node name is not ready (i.e. the // readiness condition is anything but ready, e.g false or unknown) within // timeout. func WaitForNodeToBeNotReady(c clientset.Interface, name string, timeout time.Duration) bool { - return WaitForNodeToBe(c, name, api.NodeReady, false, timeout) + return WaitForNodeToBe(c, name, v1.NodeReady, false, timeout) } -func isNodeConditionSetAsExpected(node *api.Node, conditionType api.NodeConditionType, wantTrue, silent bool) bool { +func isNodeConditionSetAsExpected(node *v1.Node, conditionType v1.NodeConditionType, wantTrue, silent bool) bool { // Check the node readiness condition (logging all). for _, cond := range node.Status.Conditions { // Ensure that the condition type and the status matches as desired. if cond.Type == conditionType { - if (cond.Status == api.ConditionTrue) == wantTrue { + if (cond.Status == v1.ConditionTrue) == wantTrue { return true } else { if !silent { Logf("Condition %s of node %s is %v instead of %t. Reason: %v, message: %v", - conditionType, node.Name, cond.Status == api.ConditionTrue, wantTrue, cond.Reason, cond.Message) + conditionType, node.Name, cond.Status == v1.ConditionTrue, wantTrue, cond.Reason, cond.Message) } return false } @@ -3719,15 +3719,15 @@ func isNodeConditionSetAsExpected(node *api.Node, conditionType api.NodeConditio return false } -func IsNodeConditionSetAsExpected(node *api.Node, conditionType api.NodeConditionType, wantTrue bool) bool { +func IsNodeConditionSetAsExpected(node *v1.Node, conditionType v1.NodeConditionType, wantTrue bool) bool { return isNodeConditionSetAsExpected(node, conditionType, wantTrue, false) } -func IsNodeConditionSetAsExpectedSilent(node *api.Node, conditionType api.NodeConditionType, wantTrue bool) bool { +func IsNodeConditionSetAsExpectedSilent(node *v1.Node, conditionType v1.NodeConditionType, wantTrue bool) bool { return isNodeConditionSetAsExpected(node, conditionType, wantTrue, true) } -func IsNodeConditionUnset(node *api.Node, conditionType api.NodeConditionType) bool { +func IsNodeConditionUnset(node *v1.Node, conditionType v1.NodeConditionType) bool { for _, cond := range node.Status.Conditions { if cond.Type == conditionType { return false @@ -3740,7 +3740,7 @@ func IsNodeConditionUnset(node *api.Node, conditionType api.NodeConditionType) b // within timeout. If wantTrue is true, it will ensure the node condition status // is ConditionTrue; if it's false, it ensures the node condition is in any state // other than ConditionTrue (e.g. not true or unknown). -func WaitForNodeToBe(c clientset.Interface, name string, conditionType api.NodeConditionType, wantTrue bool, timeout time.Duration) bool { +func WaitForNodeToBe(c clientset.Interface, name string, conditionType v1.NodeConditionType, wantTrue bool, timeout time.Duration) bool { Logf("Waiting up to %v for node %s condition %s to be %t", timeout, name, conditionType, wantTrue) for start := time.Now(); time.Since(start) < timeout; time.Sleep(Poll) { node, err := c.Core().Nodes().Get(name) @@ -3763,9 +3763,9 @@ func WaitForNodeToBe(c clientset.Interface, name string, conditionType api.NodeC // Currently we allow only for: // - not present CNI plugins on node // TODO: we should extend it for other reasons. -func allowedNotReadyReasons(nodes []*api.Node) bool { +func allowedNotReadyReasons(nodes []*v1.Node) bool { for _, node := range nodes { - index, condition := api.GetNodeCondition(&node.Status, api.NodeReady) + index, condition := v1.GetNodeCondition(&node.Status, v1.NodeReady) if index == -1 || !strings.Contains(condition.Message, "could not locate kubenet required CNI plugins") { return false @@ -3781,17 +3781,17 @@ func allowedNotReadyReasons(nodes []*api.Node) bool { func AllNodesReady(c clientset.Interface, timeout time.Duration) error { Logf("Waiting up to %v for all (but %d) nodes to be ready", timeout, TestContext.AllowedNotReadyNodes) - var notReady []*api.Node + var notReady []*v1.Node err := wait.PollImmediate(Poll, timeout, func() (bool, error) { notReady = nil // It should be OK to list unschedulable Nodes here. - nodes, err := c.Core().Nodes().List(api.ListOptions{}) + nodes, err := c.Core().Nodes().List(v1.ListOptions{}) if err != nil { return false, err } for i := range nodes.Items { node := &nodes.Items[i] - if !IsNodeConditionSetAsExpected(node, api.NodeReady, true) { + if !IsNodeConditionSetAsExpected(node, v1.NodeReady, true) { notReady = append(notReady, node) } } @@ -3822,28 +3822,28 @@ func AllNodesReady(c clientset.Interface, timeout time.Duration) error { func WaitForAllNodesHealthy(c clientset.Interface, timeout time.Duration) error { Logf("Waiting up to %v for all nodes to be ready", timeout) - var notReady []api.Node + var notReady []v1.Node var missingPodsPerNode map[string][]string err := wait.PollImmediate(Poll, timeout, func() (bool, error) { notReady = nil // It should be OK to list unschedulable Nodes here. - nodes, err := c.Core().Nodes().List(api.ListOptions{ResourceVersion: "0"}) + nodes, err := c.Core().Nodes().List(v1.ListOptions{ResourceVersion: "0"}) if err != nil { return false, err } for _, node := range nodes.Items { - if !IsNodeConditionSetAsExpected(&node, api.NodeReady, true) { + if !IsNodeConditionSetAsExpected(&node, v1.NodeReady, true) { notReady = append(notReady, node) } } - pods, err := c.Core().Pods(api.NamespaceAll).List(api.ListOptions{ResourceVersion: "0"}) + pods, err := c.Core().Pods(v1.NamespaceAll).List(v1.ListOptions{ResourceVersion: "0"}) if err != nil { return false, err } systemPodsPerNode := make(map[string][]string) for _, pod := range pods.Items { - if pod.Namespace == api.NamespaceSystem && pod.Status.Phase == api.PodRunning { + if pod.Namespace == api.NamespaceSystem && pod.Status.Phase == v1.PodRunning { if pod.Spec.NodeName != "" { systemPodsPerNode[pod.Spec.NodeName] = append(systemPodsPerNode[pod.Spec.NodeName], pod.Name) } @@ -3851,7 +3851,7 @@ func WaitForAllNodesHealthy(c clientset.Interface, timeout time.Duration) error } missingPodsPerNode = make(map[string][]string) for _, node := range nodes.Items { - if !system.IsMasterNode(&node) { + if !system.IsMasterNode(node.Name) { for _, requiredPod := range requiredPerNodePods { foundRequired := false for _, presentPod := range systemPodsPerNode[node.Name] { @@ -3886,8 +3886,8 @@ func WaitForAllNodesHealthy(c clientset.Interface, timeout time.Duration) error // Filters nodes in NodeList in place, removing nodes that do not // satisfy the given condition // TODO: consider merging with pkg/client/cache.NodeLister -func FilterNodes(nodeList *api.NodeList, fn func(node api.Node) bool) { - var l []api.Node +func FilterNodes(nodeList *v1.NodeList, fn func(node v1.Node) bool) { + var l []v1.Node for _, node := range nodeList.Items { if fn(node) { @@ -4001,9 +4001,9 @@ func WaitForApiserverUp(c clientset.Interface) error { // By cluster size we mean number of Nodes excluding Master Node. func WaitForClusterSize(c clientset.Interface, size int, timeout time.Duration) error { for start := time.Now(); time.Since(start) < timeout; time.Sleep(20 * time.Second) { - nodes, err := c.Core().Nodes().List(api.ListOptions{FieldSelector: fields.Set{ + nodes, err := c.Core().Nodes().List(v1.ListOptions{FieldSelector: fields.Set{ "spec.unschedulable": "false", - }.AsSelector()}) + }.AsSelector().String()}) if err != nil { Logf("Failed to list nodes: %v", err) continue @@ -4011,8 +4011,8 @@ func WaitForClusterSize(c clientset.Interface, size int, timeout time.Duration) numNodes := len(nodes.Items) // Filter out not-ready nodes. - FilterNodes(nodes, func(node api.Node) bool { - return IsNodeConditionSetAsExpected(&node, api.NodeReady, true) + FilterNodes(nodes, func(node v1.Node) bool { + return IsNodeConditionSetAsExpected(&node, v1.NodeReady, true) }) numReady := len(nodes.Items) @@ -4032,14 +4032,14 @@ func GenerateMasterRegexp(prefix string) string { // waitForMasters waits until the cluster has the desired number of ready masters in it. func WaitForMasters(masterPrefix string, c clientset.Interface, size int, timeout time.Duration) error { for start := time.Now(); time.Since(start) < timeout; time.Sleep(20 * time.Second) { - nodes, err := c.Core().Nodes().List(api.ListOptions{}) + nodes, err := c.Core().Nodes().List(v1.ListOptions{}) if err != nil { Logf("Failed to list nodes: %v", err) continue } // Filter out nodes that are not master replicas - FilterNodes(nodes, func(node api.Node) bool { + FilterNodes(nodes, func(node v1.Node) bool { res, err := regexp.Match(GenerateMasterRegexp(masterPrefix), ([]byte)(node.Name)) if err != nil { Logf("Failed to match regexp to node name: %v", err) @@ -4051,8 +4051,8 @@ func WaitForMasters(masterPrefix string, c clientset.Interface, size int, timeou numNodes := len(nodes.Items) // Filter out not-ready nodes. - FilterNodes(nodes, func(node api.Node) bool { - return IsNodeConditionSetAsExpected(&node, api.NodeReady, true) + FilterNodes(nodes, func(node v1.Node) bool { + return IsNodeConditionSetAsExpected(&node, v1.NodeReady, true) }) numReady := len(nodes.Items) @@ -4069,13 +4069,13 @@ func WaitForMasters(masterPrefix string, c clientset.Interface, size int, timeou // GetHostExternalAddress gets the node for a pod and returns the first External // address. Returns an error if the node the pod is on doesn't have an External // address. -func GetHostExternalAddress(client clientset.Interface, p *api.Pod) (externalAddress string, err error) { +func GetHostExternalAddress(client clientset.Interface, p *v1.Pod) (externalAddress string, err error) { node, err := client.Core().Nodes().Get(p.Spec.NodeName) if err != nil { return "", err } for _, address := range node.Status.Addresses { - if address.Type == api.NodeExternalIP { + if address.Type == v1.NodeExternalIP { if address.Address != "" { externalAddress = address.Address break @@ -4241,11 +4241,11 @@ func GetNodePortURL(client clientset.Interface, ns, name string, svcPort int) (s // This list of nodes must not include the master, which is marked // unschedulable, since the master doesn't run kube-proxy. Without // kube-proxy NodePorts won't work. - var nodes *api.NodeList + var nodes *v1.NodeList if wait.PollImmediate(Poll, SingleCallTimeout, func() (bool, error) { - nodes, err = client.Core().Nodes().List(api.ListOptions{FieldSelector: fields.Set{ + nodes, err = client.Core().Nodes().List(v1.ListOptions{FieldSelector: fields.Set{ "spec.unschedulable": "false", - }.AsSelector()}) + }.AsSelector().String()}) return err == nil, nil }) != nil { return "", err @@ -4255,7 +4255,7 @@ func GetNodePortURL(client clientset.Interface, ns, name string, svcPort int) (s } for _, node := range nodes.Items { for _, address := range node.Status.Addresses { - if address.Type == api.NodeExternalIP { + if address.Type == v1.NodeExternalIP { if address.Address != "" { return fmt.Sprintf("http://%v:%v", address.Address, nodePort), nil } @@ -4267,8 +4267,8 @@ func GetNodePortURL(client clientset.Interface, ns, name string, svcPort int) (s // ScaleRCByLabels scales an RC via ns/label lookup. If replicas == 0 it waits till // none are running, otherwise it does what a synchronous scale operation would do. -func ScaleRCByLabels(clientset clientset.Interface, ns string, l map[string]string, replicas uint) error { - listOpts := api.ListOptions{LabelSelector: labels.SelectorFromSet(labels.Set(l))} +func ScaleRCByLabels(clientset clientset.Interface, internalClientset internalclientset.Interface, ns string, l map[string]string, replicas uint) error { + listOpts := v1.ListOptions{LabelSelector: labels.SelectorFromSet(labels.Set(l)).String()} rcs, err := clientset.Core().ReplicationControllers(ns).List(listOpts) if err != nil { return err @@ -4279,7 +4279,7 @@ func ScaleRCByLabels(clientset clientset.Interface, ns string, l map[string]stri Logf("Scaling %v RCs with labels %v in ns %v to %v replicas.", len(rcs.Items), l, ns, replicas) for _, labelRC := range rcs.Items { name := labelRC.Name - if err := ScaleRC(clientset, ns, name, replicas, false); err != nil { + if err := ScaleRC(clientset, internalClientset, ns, name, replicas, false); err != nil { return err } rc, err := clientset.Core().ReplicationControllers(ns).Get(name) @@ -4424,7 +4424,7 @@ func UnblockNetwork(from string, to string) { } } -func isElementOf(podUID types.UID, pods *api.PodList) bool { +func isElementOf(podUID types.UID, pods *v1.PodList) bool { for _, pod := range pods.Items { if pod.UID == podUID { return true @@ -4442,7 +4442,7 @@ func CheckRSHashLabel(rs *extensions.ReplicaSet) error { return nil } -func CheckPodHashLabel(pods *api.PodList) error { +func CheckPodHashLabel(pods *v1.PodList) error { invalidPod := "" for _, pod := range pods.Items { if len(pod.Labels[extensions.DefaultDeploymentUniqueLabelKey]) == 0 { @@ -4499,25 +4499,25 @@ func NodeProxyRequest(c clientset.Interface, node, endpoint string) (restclient. } // GetKubeletPods retrieves the list of pods on the kubelet -func GetKubeletPods(c clientset.Interface, node string) (*api.PodList, error) { +func GetKubeletPods(c clientset.Interface, node string) (*v1.PodList, error) { return getKubeletPods(c, node, "pods") } // GetKubeletRunningPods retrieves the list of running pods on the kubelet. The pods // includes necessary information (e.g., UID, name, namespace for // pods/containers), but do not contain the full spec. -func GetKubeletRunningPods(c clientset.Interface, node string) (*api.PodList, error) { +func GetKubeletRunningPods(c clientset.Interface, node string) (*v1.PodList, error) { return getKubeletPods(c, node, "runningpods") } -func getKubeletPods(c clientset.Interface, node, resource string) (*api.PodList, error) { - result := &api.PodList{} +func getKubeletPods(c clientset.Interface, node, resource string) (*v1.PodList, error) { + result := &v1.PodList{} client, err := NodeProxyRequest(c, node, resource) if err != nil { - return &api.PodList{}, err + return &v1.PodList{}, err } if err = client.Into(result); err != nil { - return &api.PodList{}, err + return &v1.PodList{}, err } return result, nil } @@ -4529,21 +4529,21 @@ func getKubeletPods(c clientset.Interface, node, resource string) (*api.PodList, func LaunchWebserverPod(f *Framework, podName, nodeName string) (ip string) { containerName := fmt.Sprintf("%s-container", podName) port := 8080 - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: containerName, Image: "gcr.io/google_containers/porter:cd5cb5791ebaa8641955f0e8c2a9bed669b1eaab", - Env: []api.EnvVar{{Name: fmt.Sprintf("SERVE_PORT_%d", port), Value: "foo"}}, - Ports: []api.ContainerPort{{ContainerPort: int32(port)}}, + Env: []v1.EnvVar{{Name: fmt.Sprintf("SERVE_PORT_%d", port), Value: "foo"}}, + Ports: []v1.ContainerPort{{ContainerPort: int32(port)}}, }, }, NodeName: nodeName, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } podClient := f.ClientSet.Core().Pods(f.Namespace.Name) @@ -4562,12 +4562,12 @@ func LaunchWebserverPod(f *Framework, podName, nodeName string) (ip string) { // error will be returned if the host is not reachable from the pod. func CheckConnectivityToHost(f *Framework, nodeName, podName, host string, timeout int) error { contName := fmt.Sprintf("%s-container", podName) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: contName, Image: "gcr.io/google_containers/busybox:1.24", @@ -4575,7 +4575,7 @@ func CheckConnectivityToHost(f *Framework, nodeName, podName, host string, timeo }, }, NodeName: nodeName, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } podClient := f.ClientSet.Core().Pods(f.Namespace.Name) @@ -4608,7 +4608,7 @@ func CoreDump(dir string) { } } -func UpdatePodWithRetries(client clientset.Interface, ns, name string, update func(*api.Pod)) (*api.Pod, error) { +func UpdatePodWithRetries(client clientset.Interface, ns, name string, update func(*v1.Pod)) (*v1.Pod, error) { for i := 0; i < 3; i++ { pod, err := client.Core().Pods(ns).Get(name) if err != nil { @@ -4626,13 +4626,13 @@ func UpdatePodWithRetries(client clientset.Interface, ns, name string, update fu return nil, fmt.Errorf("Too many retries updating Pod %q", name) } -func GetPodsInNamespace(c clientset.Interface, ns string, ignoreLabels map[string]string) ([]*api.Pod, error) { - pods, err := c.Core().Pods(ns).List(api.ListOptions{}) +func GetPodsInNamespace(c clientset.Interface, ns string, ignoreLabels map[string]string) ([]*v1.Pod, error) { + pods, err := c.Core().Pods(ns).List(v1.ListOptions{}) if err != nil { - return []*api.Pod{}, err + return []*v1.Pod{}, err } ignoreSelector := labels.SelectorFromSet(ignoreLabels) - filtered := []*api.Pod{} + filtered := []*v1.Pod{} for _, p := range pods.Items { if len(ignoreLabels) != 0 && ignoreSelector.Matches(labels.Set(p.Labels)) { continue @@ -4681,18 +4681,18 @@ func retryCmd(command string, args ...string) (string, string, error) { } // GetPodsScheduled returns a number of currently scheduled and not scheduled Pods. -func GetPodsScheduled(masterNodes sets.String, pods *api.PodList) (scheduledPods, notScheduledPods []api.Pod) { +func GetPodsScheduled(masterNodes sets.String, pods *v1.PodList) (scheduledPods, notScheduledPods []v1.Pod) { for _, pod := range pods.Items { if !masterNodes.Has(pod.Spec.NodeName) { if pod.Spec.NodeName != "" { - _, scheduledCondition := api.GetPodCondition(&pod.Status, api.PodScheduled) + _, scheduledCondition := v1.GetPodCondition(&pod.Status, v1.PodScheduled) Expect(scheduledCondition != nil).To(Equal(true)) - Expect(scheduledCondition.Status).To(Equal(api.ConditionTrue)) + Expect(scheduledCondition.Status).To(Equal(v1.ConditionTrue)) scheduledPods = append(scheduledPods, pod) } else { - _, scheduledCondition := api.GetPodCondition(&pod.Status, api.PodScheduled) + _, scheduledCondition := v1.GetPodCondition(&pod.Status, v1.PodScheduled) Expect(scheduledCondition != nil).To(Equal(true)) - Expect(scheduledCondition.Status).To(Equal(api.ConditionFalse)) + Expect(scheduledCondition.Status).To(Equal(v1.ConditionFalse)) if scheduledCondition.Reason == "Unschedulable" { notScheduledPods = append(notScheduledPods, pod) @@ -4708,12 +4708,12 @@ func WaitForStableCluster(c clientset.Interface, masterNodes sets.String) int { timeout := 10 * time.Minute startTime := time.Now() - allPods, err := c.Core().Pods(api.NamespaceAll).List(api.ListOptions{}) + allPods, err := c.Core().Pods(v1.NamespaceAll).List(v1.ListOptions{}) ExpectNoError(err) // API server returns also Pods that succeeded. We need to filter them out. - currentPods := make([]api.Pod, 0, len(allPods.Items)) + currentPods := make([]v1.Pod, 0, len(allPods.Items)) for _, pod := range allPods.Items { - if pod.Status.Phase != api.PodSucceeded && pod.Status.Phase != api.PodFailed { + if pod.Status.Phase != v1.PodSucceeded && pod.Status.Phase != v1.PodFailed { currentPods = append(currentPods, pod) } @@ -4723,7 +4723,7 @@ func WaitForStableCluster(c clientset.Interface, masterNodes sets.String) int { for len(currentlyNotScheduledPods) != 0 { time.Sleep(2 * time.Second) - allPods, err := c.Core().Pods(api.NamespaceAll).List(api.ListOptions{}) + allPods, err := c.Core().Pods(v1.NamespaceAll).List(v1.ListOptions{}) ExpectNoError(err) scheduledPods, currentlyNotScheduledPods = GetPodsScheduled(masterNodes, allPods) @@ -4736,12 +4736,12 @@ func WaitForStableCluster(c clientset.Interface, masterNodes sets.String) int { } // GetMasterAndWorkerNodesOrDie will return a list masters and schedulable worker nodes -func GetMasterAndWorkerNodesOrDie(c clientset.Interface) (sets.String, *api.NodeList) { - nodes := &api.NodeList{} +func GetMasterAndWorkerNodesOrDie(c clientset.Interface) (sets.String, *v1.NodeList) { + nodes := &v1.NodeList{} masters := sets.NewString() - all, _ := c.Core().Nodes().List(api.ListOptions{}) + all, _ := c.Core().Nodes().List(v1.ListOptions{}) for _, n := range all.Items { - if system.IsMasterNode(&n) { + if system.IsMasterNode(n.Name) { masters.Insert(n.Name) } else if isNodeSchedulable(&n) && isNodeUntainted(&n) { nodes.Items = append(nodes.Items, n) @@ -4768,7 +4768,7 @@ func CreateFileForGoBinData(gobindataPath, outputFilename string) error { } func ListNamespaceEvents(c clientset.Interface, ns string) error { - ls, err := c.Core().Events(ns).List(api.ListOptions{}) + ls, err := c.Core().Events(ns).List(v1.ListOptions{}) if err != nil { return err } @@ -4857,7 +4857,7 @@ func getMaster(c clientset.Interface) Address { master := Address{} // Populate the internal IP. - eps, err := c.Core().Endpoints(api.NamespaceDefault).Get("kubernetes") + eps, err := c.Core().Endpoints(v1.NamespaceDefault).Get("kubernetes") if err != nil { Failf("Failed to get kubernetes endpoints: %v", err) } @@ -4898,11 +4898,11 @@ func GetMasterAddress(c clientset.Interface) string { // GetNodeExternalIP returns node external IP concatenated with port 22 for ssh // e.g. 1.2.3.4:22 -func GetNodeExternalIP(node *api.Node) string { +func GetNodeExternalIP(node *v1.Node) string { Logf("Getting external IP address for %s", node.Name) host := "" for _, a := range node.Status.Addresses { - if a.Type == api.NodeExternalIP { + if a.Type == v1.NodeExternalIP { host = a.Address + ":22" break } diff --git a/test/e2e/garbage_collector.go b/test/e2e/garbage_collector.go index 6952b0d28ea..2fc849d83a2 100644 --- a/test/e2e/garbage_collector.go +++ b/test/e2e/garbage_collector.go @@ -117,7 +117,7 @@ func gatherMetrics(f *framework.Framework) { var _ = framework.KubeDescribe("Garbage collector", func() { f := framework.NewDefaultFramework("gc") It("[Feature:GarbageCollector] should delete pods created by rc when not orphaning", func() { - clientSet := f.ClientSet_1_5 + clientSet := f.ClientSet rcClient := clientSet.Core().ReplicationControllers(f.Namespace.Name) podClient := clientSet.Core().Pods(f.Namespace.Name) rcName := "simpletest.rc" @@ -168,7 +168,7 @@ var _ = framework.KubeDescribe("Garbage collector", func() { }) It("[Feature:GarbageCollector] should orphan pods created by rc if delete options say so", func() { - clientSet := f.ClientSet_1_5 + clientSet := f.ClientSet rcClient := clientSet.Core().ReplicationControllers(f.Namespace.Name) podClient := clientSet.Core().Pods(f.Namespace.Name) rcName := "simpletest.rc" @@ -230,7 +230,7 @@ var _ = framework.KubeDescribe("Garbage collector", func() { }) It("[Feature:GarbageCollector] should orphan pods created by rc if deleteOptions.OrphanDependents is nil", func() { - clientSet := f.ClientSet_1_5 + clientSet := f.ClientSet rcClient := clientSet.Core().ReplicationControllers(f.Namespace.Name) podClient := clientSet.Core().Pods(f.Namespace.Name) rcName := "simpletest.rc" diff --git a/test/e2e/generated_clientset.go b/test/e2e/generated_clientset.go index 0e182eb88ee..65d6bd01e94 100644 --- a/test/e2e/generated_clientset.go +++ b/test/e2e/generated_clientset.go @@ -121,7 +121,7 @@ func observeObjectDeletion(w watch.Interface) (obj runtime.Object) { var _ = framework.KubeDescribe("Generated release_1_5 clientset", func() { f := framework.NewDefaultFramework("clientset") It("should create pods, delete pods, watch pods", func() { - podClient := f.ClientSet_1_5.Core().Pods(f.Namespace.Name) + podClient := f.ClientSet.Core().Pods(f.Namespace.Name) By("constructing the pod") name := "pod" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond()) @@ -240,7 +240,7 @@ var _ = framework.KubeDescribe("Generated release_1_5 clientset", func() { f := framework.NewDefaultFramework("clientset") It("should create v2alpha1 cronJobs, delete cronJobs, watch cronJobs", func() { var enabled bool - groupList, err := f.ClientSet_1_5.Discovery().ServerGroups() + groupList, err := f.ClientSet.Discovery().ServerGroups() ExpectNoError(err) for _, group := range groupList.Groups { if group.Name == v2alpha1.GroupName { @@ -256,7 +256,7 @@ var _ = framework.KubeDescribe("Generated release_1_5 clientset", func() { framework.Logf("%s is not enabled, test skipped", v2alpha1.SchemeGroupVersion) return } - cronJobClient := f.ClientSet_1_5.BatchV2alpha1().CronJobs(f.Namespace.Name) + cronJobClient := f.ClientSet.BatchV2alpha1().CronJobs(f.Namespace.Name) By("constructing the cronJob") name := "cronjob" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond()) diff --git a/test/e2e/gke_local_ssd.go b/test/e2e/gke_local_ssd.go index 8256018bc3b..cfa4ef56b72 100644 --- a/test/e2e/gke_local_ssd.go +++ b/test/e2e/gke_local_ssd.go @@ -20,8 +20,8 @@ import ( "fmt" "os/exec" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -65,28 +65,28 @@ func doTestWriteAndReadToLocalSsd(f *framework.Framework) { f.TestContainerOutput(msg, pod, 0, out) } -func testPodWithSsd(command string) *api.Pod { +func testPodWithSsd(command string) *v1.Pod { containerName := "test-container" volumeName := "test-ssd-volume" path := "/mnt/disks/ssd0" podName := "pod-" + string(uuid.NewUUID()) image := "ubuntu:14.04" - return &api.Pod{ + return &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: containerName, Image: image, Command: []string{"/bin/sh"}, Args: []string{"-c", command}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: path, @@ -94,12 +94,12 @@ func testPodWithSsd(command string) *api.Pod { }, }, }, - RestartPolicy: api.RestartPolicyNever, - Volumes: []api.Volume{ + RestartPolicy: v1.RestartPolicyNever, + Volumes: []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{ + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{ Path: path, }, }, diff --git a/test/e2e/ha_master.go b/test/e2e/ha_master.go index b351a8b4066..5c07a19dbee 100644 --- a/test/e2e/ha_master.go +++ b/test/e2e/ha_master.go @@ -26,7 +26,7 @@ import ( "time" . "github.com/onsi/ginkgo" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/test/e2e/framework" ) diff --git a/test/e2e/horizontal_pod_autoscaling.go b/test/e2e/horizontal_pod_autoscaling.go index 90e57f830f5..4e721e1b7a0 100644 --- a/test/e2e/horizontal_pod_autoscaling.go +++ b/test/e2e/horizontal_pod_autoscaling.go @@ -19,8 +19,8 @@ package e2e import ( "time" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/autoscaling" + "k8s.io/kubernetes/pkg/api/v1" + autoscaling "k8s.io/kubernetes/pkg/apis/autoscaling/v1" "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" @@ -177,7 +177,7 @@ func scaleDown(name, kind string, checkStability bool, rc *ResourceConsumer, f * func createCPUHorizontalPodAutoscaler(rc *ResourceConsumer, cpu, minReplicas, maxRepl int32) { hpa := &autoscaling.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: rc.name, Namespace: rc.framework.Namespace.Name, }, diff --git a/test/e2e/ingress_utils.go b/test/e2e/ingress_utils.go index bb9d2f0416c..70f707405a3 100644 --- a/test/e2e/ingress_utils.go +++ b/test/e2e/ingress_utils.go @@ -38,12 +38,13 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" compute "google.golang.org/api/compute/v1" "google.golang.org/api/googleapi" apierrs "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/apis/extensions" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" gcecloud "k8s.io/kubernetes/pkg/cloudprovider/providers/gce" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" @@ -280,16 +281,16 @@ func createSecret(kubeClient clientset.Interface, ing *extensions.Ingress) (host } cert := c.Bytes() key := k.Bytes() - secret := &api.Secret{ - ObjectMeta: api.ObjectMeta{ + secret := &v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Name: tls.SecretName, }, Data: map[string][]byte{ - api.TLSCertKey: cert, - api.TLSPrivateKeyKey: key, + v1.TLSCertKey: cert, + v1.TLSPrivateKeyKey: key, }, } - var s *api.Secret + var s *v1.Secret if s, err = kubeClient.Core().Secrets(ing.Namespace).Get(tls.SecretName); err == nil { // TODO: Retry the update. We don't really expect anything to conflict though. framework.Logf("Updating secret %v in ns %v with hosts %v for ingress %v", secret.Name, secret.Namespace, host, ing.Name) @@ -841,8 +842,8 @@ type GCEIngressController struct { rcPath string UID string staticIPName string - rc *api.ReplicationController - svc *api.Service + rc *v1.ReplicationController + svc *v1.Service c clientset.Interface cloud framework.CloudConfig } @@ -854,8 +855,8 @@ func newTestJig(c clientset.Interface) *testJig { // NginxIngressController manages implementation details of Ingress on Nginx. type NginxIngressController struct { ns string - rc *api.ReplicationController - pod *api.Pod + rc *v1.ReplicationController + pod *v1.Pod c clientset.Interface externalIP string } @@ -874,7 +875,7 @@ func (cont *NginxIngressController) init() { framework.Logf("waiting for pods with label %v", rc.Spec.Selector) sel := labels.SelectorFromSet(labels.Set(rc.Spec.Selector)) ExpectNoError(testutils.WaitForPodsWithLabelRunning(cont.c, cont.ns, sel)) - pods, err := cont.c.Core().Pods(cont.ns).List(api.ListOptions{LabelSelector: sel}) + pods, err := cont.c.Core().Pods(cont.ns).List(v1.ListOptions{LabelSelector: sel.String()}) ExpectNoError(err) if len(pods.Items) == 0 { framework.Failf("Failed to find nginx ingress controller pods with selector %v", sel) diff --git a/test/e2e/initial_resources.go b/test/e2e/initial_resources.go index 808e59c42c5..6d590bcdf29 100644 --- a/test/e2e/initial_resources.go +++ b/test/e2e/initial_resources.go @@ -22,7 +22,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/test/e2e/framework" ) @@ -51,13 +51,13 @@ var _ = framework.KubeDescribe("Initial Resources [Feature:InitialResources] [Fl }) }) -func runPod(f *framework.Framework, name, image string) *api.Pod { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func runPod(f *framework.Framework, name, image string) *v1.Pod { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: name, Image: image, diff --git a/test/e2e/job.go b/test/e2e/job.go index 327972de3a6..6bde390f701 100644 --- a/test/e2e/job.go +++ b/test/e2e/job.go @@ -21,8 +21,10 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/apis/batch" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + batchinternal "k8s.io/kubernetes/pkg/apis/batch" + batch "k8s.io/kubernetes/pkg/apis/batch/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/wait" @@ -49,7 +51,7 @@ var _ = framework.KubeDescribe("Job", func() { // Simplest case: all pods succeed promptly It("should run a job to completion when tasks succeed", func() { By("Creating a job") - job := newTestJob("succeed", "all-succeed", api.RestartPolicyNever, parallelism, completions) + job := newTestJob("succeed", "all-succeed", v1.RestartPolicyNever, parallelism, completions) job, err := createJob(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -68,7 +70,7 @@ var _ = framework.KubeDescribe("Job", func() { // up to 5 minutes between restarts, making test timeouts // due to successive failures too likely with a reasonable // test timeout. - job := newTestJob("failOnce", "fail-once-local", api.RestartPolicyOnFailure, parallelism, completions) + job := newTestJob("failOnce", "fail-once-local", v1.RestartPolicyOnFailure, parallelism, completions) job, err := createJob(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -86,7 +88,7 @@ var _ = framework.KubeDescribe("Job", func() { // Worst case analysis: 15 failures, each taking 1 minute to // run due to some slowness, 1 in 2^15 chance of happening, // causing test flake. Should be very rare. - job := newTestJob("randomlySucceedOrFail", "rand-non-local", api.RestartPolicyNever, parallelism, completions) + job := newTestJob("randomlySucceedOrFail", "rand-non-local", v1.RestartPolicyNever, parallelism, completions) job, err := createJob(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -97,7 +99,7 @@ var _ = framework.KubeDescribe("Job", func() { It("should keep restarting failed pods", func() { By("Creating a job") - job := newTestJob("fail", "all-fail", api.RestartPolicyNever, parallelism, completions) + job := newTestJob("fail", "all-fail", v1.RestartPolicyNever, parallelism, completions) job, err := createJob(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -115,7 +117,7 @@ var _ = framework.KubeDescribe("Job", func() { startParallelism := int32(1) endParallelism := int32(2) By("Creating a job") - job := newTestJob("notTerminate", "scale-up", api.RestartPolicyNever, startParallelism, completions) + job := newTestJob("notTerminate", "scale-up", v1.RestartPolicyNever, startParallelism, completions) job, err := createJob(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -124,7 +126,7 @@ var _ = framework.KubeDescribe("Job", func() { Expect(err).NotTo(HaveOccurred()) By("scale job up") - scaler, err := kubectl.ScalerFor(batch.Kind("Job"), f.ClientSet) + scaler, err := kubectl.ScalerFor(batchinternal.Kind("Job"), f.InternalClientset) Expect(err).NotTo(HaveOccurred()) waitForScale := kubectl.NewRetryParams(5*time.Second, 1*time.Minute) waitForReplicas := kubectl.NewRetryParams(5*time.Second, 5*time.Minute) @@ -140,7 +142,7 @@ var _ = framework.KubeDescribe("Job", func() { startParallelism := int32(2) endParallelism := int32(1) By("Creating a job") - job := newTestJob("notTerminate", "scale-down", api.RestartPolicyNever, startParallelism, completions) + job := newTestJob("notTerminate", "scale-down", v1.RestartPolicyNever, startParallelism, completions) job, err := createJob(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -149,7 +151,7 @@ var _ = framework.KubeDescribe("Job", func() { Expect(err).NotTo(HaveOccurred()) By("scale job down") - scaler, err := kubectl.ScalerFor(batch.Kind("Job"), f.ClientSet) + scaler, err := kubectl.ScalerFor(batchinternal.Kind("Job"), f.InternalClientset) Expect(err).NotTo(HaveOccurred()) waitForScale := kubectl.NewRetryParams(5*time.Second, 1*time.Minute) waitForReplicas := kubectl.NewRetryParams(5*time.Second, 5*time.Minute) @@ -163,7 +165,7 @@ var _ = framework.KubeDescribe("Job", func() { It("should delete a job", func() { By("Creating a job") - job := newTestJob("notTerminate", "foo", api.RestartPolicyNever, parallelism, completions) + job := newTestJob("notTerminate", "foo", v1.RestartPolicyNever, parallelism, completions) job, err := createJob(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) @@ -172,7 +174,7 @@ var _ = framework.KubeDescribe("Job", func() { Expect(err).NotTo(HaveOccurred()) By("delete a job") - reaper, err := kubectl.ReaperFor(batch.Kind("Job"), f.ClientSet) + reaper, err := kubectl.ReaperFor(batchinternal.Kind("Job"), f.InternalClientset) Expect(err).NotTo(HaveOccurred()) timeout := 1 * time.Minute err = reaper.Stop(f.Namespace.Name, job.Name, timeout, api.NewDeleteOptions(0)) @@ -186,7 +188,7 @@ var _ = framework.KubeDescribe("Job", func() { It("should fail a job", func() { By("Creating a job") - job := newTestJob("notTerminate", "foo", api.RestartPolicyNever, parallelism, completions) + job := newTestJob("notTerminate", "foo", v1.RestartPolicyNever, parallelism, completions) activeDeadlineSeconds := int64(10) job.Spec.ActiveDeadlineSeconds = &activeDeadlineSeconds job, err := createJob(f.ClientSet, f.Namespace.Name, job) @@ -211,35 +213,35 @@ var _ = framework.KubeDescribe("Job", func() { }) // newTestJob returns a job which does one of several testing behaviors. -func newTestJob(behavior, name string, rPol api.RestartPolicy, parallelism, completions int32) *batch.Job { +func newTestJob(behavior, name string, rPol v1.RestartPolicy, parallelism, completions int32) *batch.Job { job := &batch.Job{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, Spec: batch.JobSpec{ Parallelism: ¶llelism, Completions: &completions, ManualSelector: newBool(false), - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{jobSelectorKey: name}, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ RestartPolicy: rPol, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: "data", - VolumeSource: api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{}, + VolumeSource: v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{}, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "c", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { MountPath: "/data", Name: "data", @@ -293,14 +295,14 @@ func deleteJob(c clientset.Interface, ns, name string) error { func waitForAllPodsRunning(c clientset.Interface, ns, jobName string, parallelism int32) error { label := labels.SelectorFromSet(labels.Set(map[string]string{jobSelectorKey: jobName})) return wait.Poll(framework.Poll, jobTimeout, func() (bool, error) { - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := c.Core().Pods(ns).List(options) if err != nil { return false, err } count := int32(0) for _, p := range pods.Items { - if p.Status.Phase == api.PodRunning { + if p.Status.Phase == v1.PodRunning { count++ } } @@ -327,7 +329,7 @@ func waitForJobFail(c clientset.Interface, ns, jobName string, timeout time.Dura return false, err } for _, c := range curr.Status.Conditions { - if c.Type == batch.JobFailed && c.Status == api.ConditionTrue { + if c.Type == batch.JobFailed && c.Status == v1.ConditionTrue { return true, nil } } diff --git a/test/e2e/kibana_logging.go b/test/e2e/kibana_logging.go index 6695d04d8e5..9bf466e1cb6 100644 --- a/test/e2e/kibana_logging.go +++ b/test/e2e/kibana_logging.go @@ -20,6 +20,7 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/test/e2e/framework" @@ -69,7 +70,7 @@ func ClusterLevelLoggingWithKibana(f *framework.Framework) { // Wait for the Kibana pod(s) to enter the running state. By("Checking to make sure the Kibana pods are running") label := labels.SelectorFromSet(labels.Set(map[string]string{kibanaKey: kibanaValue})) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := f.ClientSet.Core().Pods(api.NamespaceSystem).List(options) Expect(err).NotTo(HaveOccurred()) for _, pod := range pods.Items { diff --git a/test/e2e/kube_proxy.go b/test/e2e/kube_proxy.go index ec9aa64a650..e3070240e90 100644 --- a/test/e2e/kube_proxy.go +++ b/test/e2e/kube_proxy.go @@ -24,7 +24,7 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/test/e2e/framework" "k8s.io/kubernetes/test/images/net/nat" @@ -47,7 +47,7 @@ var _ = framework.KubeDescribe("Network", func() { It("should set TCP CLOSE_WAIT timeout", func() { nodes := framework.GetReadySchedulableNodesOrDie(fr.ClientSet) - ips := collectAddresses(nodes, api.NodeInternalIP) + ips := collectAddresses(nodes, v1.NodeInternalIP) if len(nodes.Items) < 2 { framework.Skipf( @@ -56,7 +56,7 @@ var _ = framework.KubeDescribe("Network", func() { } type NodeInfo struct { - node *api.Node + node *v1.Node name string nodeIp string } @@ -75,15 +75,15 @@ var _ = framework.KubeDescribe("Network", func() { zero := int64(0) - clientPodSpec := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + clientPodSpec := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "e2e-net-client", Namespace: fr.Namespace.Name, Labels: map[string]string{"app": "e2e-net-client"}, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: clientNodeInfo.name, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "e2e-net-client", Image: kubeProxyE2eImage, @@ -97,15 +97,15 @@ var _ = framework.KubeDescribe("Network", func() { }, } - serverPodSpec := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + serverPodSpec := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "e2e-net-server", Namespace: fr.Namespace.Name, Labels: map[string]string{"app": "e2e-net-server"}, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: serverNodeInfo.name, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "e2e-net-server", Image: kubeProxyE2eImage, @@ -118,7 +118,7 @@ var _ = framework.KubeDescribe("Network", func() { testDaemonTcpPort, postFinTimeoutSeconds), }, - Ports: []api.ContainerPort{ + Ports: []v1.ContainerPort{ { Name: "tcp", ContainerPort: testDaemonTcpPort, diff --git a/test/e2e/kubectl.go b/test/e2e/kubectl.go index 8579c870e06..f48aaae6c3a 100644 --- a/test/e2e/kubectl.go +++ b/test/e2e/kubectl.go @@ -41,12 +41,12 @@ import ( "github.com/elazarl/goproxy" "github.com/ghodss/yaml" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/annotations" apierrs "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/labels" @@ -204,7 +204,7 @@ var _ = framework.KubeDescribe("Kubectl alpha client", func() { framework.RunKubectlOrDie("run", sjName, "--restart=OnFailure", "--generator=scheduledjob/v2alpha1", "--schedule="+schedule, "--image="+busyboxImage, nsFlag) By("verifying the ScheduledJob " + sjName + " was created") - sj, err := c.Batch().CronJobs(ns).Get(sjName) + sj, err := c.BatchV2alpha1().CronJobs(ns).Get(sjName) if err != nil { framework.Failf("Failed getting ScheduledJob %s: %v", sjName, err) } @@ -215,7 +215,7 @@ var _ = framework.KubeDescribe("Kubectl alpha client", func() { if containers == nil || len(containers) != 1 || containers[0].Image != busyboxImage { framework.Failf("Failed creating ScheduledJob %s for 1 pod with expected image %s: %#v", sjName, busyboxImage, containers) } - if sj.Spec.JobTemplate.Spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure { + if sj.Spec.JobTemplate.Spec.Template.Spec.RestartPolicy != v1.RestartPolicyOnFailure { framework.Failf("Failed creating a ScheduledJob with correct restart policy for --restart=OnFailure") } }) @@ -241,7 +241,7 @@ var _ = framework.KubeDescribe("Kubectl alpha client", func() { framework.RunKubectlOrDie("run", cjName, "--restart=OnFailure", "--generator=cronjob/v2alpha1", "--schedule="+schedule, "--image="+busyboxImage, nsFlag) By("verifying the CronJob " + cjName + " was created") - sj, err := c.Batch().CronJobs(ns).Get(cjName) + sj, err := c.BatchV2alpha1().CronJobs(ns).Get(cjName) if err != nil { framework.Failf("Failed getting CronJob %s: %v", cjName, err) } @@ -252,7 +252,7 @@ var _ = framework.KubeDescribe("Kubectl alpha client", func() { if containers == nil || len(containers) != 1 || containers[0].Image != busyboxImage { framework.Failf("Failed creating CronJob %s for 1 pod with expected image %s: %#v", cjName, busyboxImage, containers) } - if sj.Spec.JobTemplate.Spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure { + if sj.Spec.JobTemplate.Spec.Template.Spec.RestartPolicy != v1.RestartPolicyOnFailure { framework.Failf("Failed creating a CronJob with correct restart policy for --restart=OnFailure") } }) @@ -268,10 +268,10 @@ var _ = framework.KubeDescribe("Kubectl client", func() { return f.NewClusterVerification( framework.PodStateVerification{ Selectors: map[string]string{"app": "redis"}, - ValidPhases: []api.PodPhase{api.PodRunning /*api.PodPending*/}, + ValidPhases: []v1.PodPhase{v1.PodRunning /*v1.PodPending*/}, }) } - forEachPod := func(podFunc func(p api.Pod)) { + forEachPod := func(podFunc func(p v1.Pod)) { clusterState().ForEach(podFunc) } var c clientset.Interface @@ -289,7 +289,7 @@ var _ = framework.KubeDescribe("Kubectl client", func() { pods, err := clusterState().WaitFor(atLeast, framework.PodStartTimeout) if err != nil || len(pods) < atLeast { // TODO: Generalize integrating debug info into these tests so we always get debug info when we need it - framework.DumpAllNamespaceInfo(c, f.ClientSet_1_5, ns) + framework.DumpAllNamespaceInfo(f.ClientSet, ns) framework.Failf("Verified %v of %v pods , error : %v", len(pods), atLeast, err) } } @@ -519,8 +519,8 @@ var _ = framework.KubeDescribe("Kubectl client", func() { WithStdinData("abcd1234\n"). ExecOrDie() Expect(runOutput).ToNot(ContainSubstring("stdin closed")) - g := func(pods []*api.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) } - runTestPod, _, err := util.GetFirstPod(f.ClientSet.Core(), ns, labels.SelectorFromSet(map[string]string{"run": "run-test-3"}), 1*time.Minute, g) + g := func(pods []*v1.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) } + runTestPod, _, err := util.GetFirstPod(f.InternalClientset.Core(), ns, labels.SelectorFromSet(map[string]string{"run": "run-test-3"}), 1*time.Minute, g) if err != nil { os.Exit(1) } @@ -646,7 +646,7 @@ var _ = framework.KubeDescribe("Kubectl client", func() { waitForOrFailWithDebug(1) // Pod - forEachPod(func(pod api.Pod) { + forEachPod(func(pod v1.Pod) { output := framework.RunKubectlOrDie("describe", "pod", pod.Name, nsFlag) requiredStrings := [][]string{ {"Name:", "redis-master-"}, @@ -700,7 +700,7 @@ var _ = framework.KubeDescribe("Kubectl client", func() { // Node // It should be OK to list unschedulable Nodes here. - nodes, err := c.Core().Nodes().List(api.ListOptions{}) + nodes, err := c.Core().Nodes().List(v1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) node := nodes.Items[0] output = framework.RunKubectlOrDie("describe", "node", node.Name) @@ -748,7 +748,7 @@ var _ = framework.KubeDescribe("Kubectl client", func() { // It may take a while for the pods to get registered in some cases, wait to be sure. By("Waiting for Redis master to start.") waitForOrFailWithDebug(1) - forEachPod(func(pod api.Pod) { + forEachPod(func(pod v1.Pod) { framework.Logf("wait on redis-master startup in %v ", ns) framework.LookForStringInLog(ns, pod.Name, "redis-master", "The server is now ready to accept connections", framework.PodStartTimeout) }) @@ -873,7 +873,7 @@ var _ = framework.KubeDescribe("Kubectl client", func() { By("Waiting for Redis master to start.") waitForOrFailWithDebug(1) - forEachPod(func(pod api.Pod) { + forEachPod(func(pod v1.Pod) { By("checking for a matching strings") _, err := framework.LookForStringInLog(ns, pod.Name, containerName, "The server is now ready to accept connections", framework.PodStartTimeout) Expect(err).NotTo(HaveOccurred()) @@ -923,12 +923,12 @@ var _ = framework.KubeDescribe("Kubectl client", func() { By("Waiting for Redis master to start.") waitForOrFailWithDebug(1) By("patching all pods") - forEachPod(func(pod api.Pod) { + forEachPod(func(pod v1.Pod) { framework.RunKubectlOrDie("patch", "pod", pod.Name, nsFlag, "-p", "{\"metadata\":{\"annotations\":{\"x\":\"y\"}}}") }) By("checking annotations") - forEachPod(func(pod api.Pod) { + forEachPod(func(pod v1.Pod) { found := false for key, val := range pod.Annotations { if key == "x" && val == "y" { @@ -1082,7 +1082,7 @@ var _ = framework.KubeDescribe("Kubectl client", func() { By("rolling-update to same image controller") - runKubectlRetryOrDie("rolling-update", rcName, "--update-period=1s", "--image="+nginxImage, "--image-pull-policy="+string(api.PullIfNotPresent), nsFlag) + runKubectlRetryOrDie("rolling-update", rcName, "--update-period=1s", "--image="+nginxImage, "--image-pull-policy="+string(v1.PullIfNotPresent), nsFlag) framework.ValidateController(c, nginxImage, 1, rcName, "run="+rcName, noOpValidatorFn, ns) }) }) @@ -1166,7 +1166,7 @@ var _ = framework.KubeDescribe("Kubectl client", func() { if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage { framework.Failf("Failed creating job %s for 1 pod with expected image %s: %#v", jobName, nginxImage, containers) } - if job.Spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure { + if job.Spec.Template.Spec.RestartPolicy != v1.RestartPolicyOnFailure { framework.Failf("Failed creating a job with correct restart policy for --restart=OnFailure") } }) @@ -1199,7 +1199,7 @@ var _ = framework.KubeDescribe("Kubectl client", func() { if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage { framework.Failf("Failed creating pod %s with expected image %s", podName, nginxImage) } - if pod.Spec.RestartPolicy != api.RestartPolicyNever { + if pod.Spec.RestartPolicy != v1.RestartPolicyNever { framework.Failf("Failed creating a pod with correct restart policy for --restart=Never") } }) @@ -1333,10 +1333,10 @@ var _ = framework.KubeDescribe("Kubectl client", func() { framework.KubeDescribe("Kubectl taint", func() { It("should update the taint on a node", func() { - testTaint := api.Taint{ + testTaint := v1.Taint{ Key: fmt.Sprintf("kubernetes.io/e2e-taint-key-001-%s", string(uuid.NewUUID())), Value: "testing-taint-value", - Effect: api.TaintEffectNoSchedule, + Effect: v1.TaintEffectNoSchedule, } nodeName := getNodeThatCanRunPod(f) @@ -1364,10 +1364,10 @@ var _ = framework.KubeDescribe("Kubectl client", func() { }) It("should remove all the taints with the same key off a node", func() { - testTaint := api.Taint{ + testTaint := v1.Taint{ Key: fmt.Sprintf("kubernetes.io/e2e-taint-key-002-%s", string(uuid.NewUUID())), Value: "testing-taint-value", - Effect: api.TaintEffectNoSchedule, + Effect: v1.TaintEffectNoSchedule, } nodeName := getNodeThatCanRunPod(f) @@ -1385,10 +1385,10 @@ var _ = framework.KubeDescribe("Kubectl client", func() { } checkOutput(output, requiredStrings) - newTestTaint := api.Taint{ + newTestTaint := v1.Taint{ Key: testTaint.Key, Value: "another-testing-taint-value", - Effect: api.TaintEffectPreferNoSchedule, + Effect: v1.TaintEffectPreferNoSchedule, } By("adding another taint " + newTestTaint.ToString() + " to the node") runKubectlRetryOrDie("taint", "nodes", nodeName, newTestTaint.ToString()) @@ -1434,11 +1434,11 @@ var _ = framework.KubeDescribe("Kubectl client", func() { if len(quota.Spec.Hard) != 2 { framework.Failf("Expected two resources, got %v", quota.Spec.Hard) } - r, found := quota.Spec.Hard[api.ResourcePods] + r, found := quota.Spec.Hard[v1.ResourcePods] if expected := resource.MustParse("1000000"); !found || (&r).Cmp(expected) != 0 { framework.Failf("Expected pods=1000000, got %v", r) } - r, found = quota.Spec.Hard[api.ResourceServices] + r, found = quota.Spec.Hard[v1.ResourceServices] if expected := resource.MustParse("1000000"); !found || (&r).Cmp(expected) != 0 { framework.Failf("Expected services=1000000, got %v", r) } @@ -1461,14 +1461,14 @@ var _ = framework.KubeDescribe("Kubectl client", func() { if len(quota.Spec.Scopes) != 2 { framework.Failf("Expected two scopes, got %v", quota.Spec.Scopes) } - scopes := make(map[api.ResourceQuotaScope]struct{}) + scopes := make(map[v1.ResourceQuotaScope]struct{}) for _, scope := range quota.Spec.Scopes { scopes[scope] = struct{}{} } - if _, found := scopes[api.ResourceQuotaScopeBestEffort]; !found { + if _, found := scopes[v1.ResourceQuotaScopeBestEffort]; !found { framework.Failf("Expected BestEffort scope, got %v", quota.Spec.Scopes) } - if _, found := scopes[api.ResourceQuotaScopeNotTerminating]; !found { + if _, found := scopes[v1.ResourceQuotaScopeNotTerminating]; !found { framework.Failf("Expected NotTerminating scope, got %v", quota.Spec.Scopes) } }) @@ -1640,8 +1640,8 @@ func readBytesFromFile(filename string) []byte { return data } -func readReplicationControllerFromString(contents string) *api.ReplicationController { - rc := api.ReplicationController{} +func readReplicationControllerFromString(contents string) *v1.ReplicationController { + rc := v1.ReplicationController{} if err := yaml.Unmarshal([]byte(contents), &rc); err != nil { framework.Failf(err.Error()) } @@ -1662,12 +1662,12 @@ func modifyReplicationControllerConfiguration(contents string) io.Reader { return bytes.NewReader(data) } -func forEachReplicationController(c clientset.Interface, ns, selectorKey, selectorValue string, fn func(api.ReplicationController)) { - var rcs *api.ReplicationControllerList +func forEachReplicationController(c clientset.Interface, ns, selectorKey, selectorValue string, fn func(v1.ReplicationController)) { + var rcs *v1.ReplicationControllerList var err error for t := time.Now(); time.Since(t) < framework.PodListTimeout; time.Sleep(framework.Poll) { label := labels.SelectorFromSet(labels.Set(map[string]string{selectorKey: selectorValue})) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} rcs, err = c.Core().ReplicationControllers(ns).List(options) Expect(err).NotTo(HaveOccurred()) if len(rcs.Items) > 0 { @@ -1684,7 +1684,7 @@ func forEachReplicationController(c clientset.Interface, ns, selectorKey, select } } -func validateReplicationControllerConfiguration(rc api.ReplicationController) { +func validateReplicationControllerConfiguration(rc v1.ReplicationController) { if rc.Name == "redis-master" { if _, ok := rc.Annotations[annotations.LastAppliedConfigAnnotation]; !ok { framework.Failf("Annotation not found in modified configuration:\n%v\n", rc) diff --git a/test/e2e/kubelet.go b/test/e2e/kubelet.go index 981770cbaa0..02b2610414c 100644 --- a/test/e2e/kubelet.go +++ b/test/e2e/kubelet.go @@ -21,8 +21,8 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/pkg/util/wait" @@ -98,7 +98,7 @@ func waitTillNPodsRunningOnNodes(c clientset.Interface, nodeNames sets.String, p func updateNodeLabels(c clientset.Interface, nodeNames sets.String, toAdd, toRemove map[string]string) { const maxRetries = 5 for nodeName := range nodeNames { - var node *api.Node + var node *v1.Node var err error for i := 0; i < maxRetries; i++ { node, err = c.Core().Nodes().Get(nodeName) @@ -189,12 +189,13 @@ var _ = framework.KubeDescribe("kubelet", func() { rcName := fmt.Sprintf("cleanup%d-%s", totalPods, string(uuid.NewUUID())) Expect(framework.RunRC(testutils.RCConfig{ - Client: f.ClientSet, - Name: rcName, - Namespace: f.Namespace.Name, - Image: framework.GetPauseImageName(f.ClientSet), - Replicas: totalPods, - NodeSelector: nodeLabels, + Client: f.ClientSet, + InternalClient: f.InternalClientset, + Name: rcName, + Namespace: f.Namespace.Name, + Image: framework.GetPauseImageName(f.ClientSet), + Replicas: totalPods, + NodeSelector: nodeLabels, })).NotTo(HaveOccurred()) // Perform a sanity check so that we know all desired pods are // running on the nodes according to kubelet. The timeout is set to @@ -207,7 +208,7 @@ var _ = framework.KubeDescribe("kubelet", func() { } By("Deleting the RC") - framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, rcName) + framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, rcName) // Check that the pods really are gone by querying /runningpods on the // node. The /runningpods handler checks the container runtime (or its // cache) and returns a list of running pods. Some possible causes of diff --git a/test/e2e/kubelet_perf.go b/test/e2e/kubelet_perf.go index faace8a058d..99417ced1b5 100644 --- a/test/e2e/kubelet_perf.go +++ b/test/e2e/kubelet_perf.go @@ -22,7 +22,7 @@ import ( "time" "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/uuid" @@ -70,11 +70,12 @@ func runResourceTrackingTest(f *framework.Framework, podsPerNode int, nodeNames // TODO: Use a more realistic workload Expect(framework.RunRC(testutils.RCConfig{ - Client: f.ClientSet, - Name: rcName, - Namespace: f.Namespace.Name, - Image: framework.GetPauseImageName(f.ClientSet), - Replicas: totalPods, + Client: f.ClientSet, + InternalClient: f.InternalClientset, + Name: rcName, + Namespace: f.Namespace.Name, + Image: framework.GetPauseImageName(f.ClientSet), + Replicas: totalPods, })).NotTo(HaveOccurred()) // Log once and flush the stats. @@ -116,7 +117,7 @@ func runResourceTrackingTest(f *framework.Framework, podsPerNode int, nodeNames verifyCPULimits(expectedCPU, cpuSummary) By("Deleting the RC") - framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, rcName) + framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, rcName) } func verifyMemoryLimits(c clientset.Interface, expected framework.ResourceUsagePerContainer, actual framework.ResourceUsagePerNode) { diff --git a/test/e2e/limit_range.go b/test/e2e/limit_range.go index 9c7d1d8674b..7a52af3bc96 100644 --- a/test/e2e/limit_range.go +++ b/test/e2e/limit_range.go @@ -19,8 +19,8 @@ package e2e import ( "fmt" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" @@ -37,8 +37,8 @@ var _ = framework.KubeDescribe("LimitRange", func() { max := getResourceList("500m", "500Mi") defaultLimit := getResourceList("500m", "500Mi") defaultRequest := getResourceList("100m", "200Mi") - maxLimitRequestRatio := api.ResourceList{} - limitRange := newLimitRange("limit-range", api.LimitTypeContainer, + maxLimitRequestRatio := v1.ResourceList{} + limitRange := newLimitRange("limit-range", v1.LimitTypeContainer, min, max, defaultLimit, defaultRequest, maxLimitRequestRatio) @@ -47,13 +47,13 @@ var _ = framework.KubeDescribe("LimitRange", func() { By("Fetching the LimitRange to ensure it has proper values") limitRange, err = f.ClientSet.Core().LimitRanges(f.Namespace.Name).Get(limitRange.Name) - expected := api.ResourceRequirements{Requests: defaultRequest, Limits: defaultLimit} - actual := api.ResourceRequirements{Requests: limitRange.Spec.Limits[0].DefaultRequest, Limits: limitRange.Spec.Limits[0].Default} + expected := v1.ResourceRequirements{Requests: defaultRequest, Limits: defaultLimit} + actual := v1.ResourceRequirements{Requests: limitRange.Spec.Limits[0].DefaultRequest, Limits: limitRange.Spec.Limits[0].Default} err = equalResourceRequirement(expected, actual) Expect(err).NotTo(HaveOccurred()) By("Creating a Pod with no resource requirements") - pod := newTestPod(f, "pod-no-resources", api.ResourceList{}, api.ResourceList{}) + pod := newTestPod(f, "pod-no-resources", v1.ResourceList{}, v1.ResourceList{}) pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) Expect(err).NotTo(HaveOccurred()) @@ -80,7 +80,7 @@ var _ = framework.KubeDescribe("LimitRange", func() { // This is an interesting case, so it's worth a comment // If you specify a Limit, and no Request, the Limit will default to the Request // This means that the LimitRange.DefaultRequest will ONLY take affect if a container.resources.limit is not supplied - expected = api.ResourceRequirements{Requests: getResourceList("300m", "150Mi"), Limits: getResourceList("300m", "500Mi")} + expected = v1.ResourceRequirements{Requests: getResourceList("300m", "150Mi"), Limits: getResourceList("300m", "500Mi")} for i := range pod.Spec.Containers { err = equalResourceRequirement(expected, pod.Spec.Containers[i].Resources) if err != nil { @@ -91,19 +91,19 @@ var _ = framework.KubeDescribe("LimitRange", func() { } By("Failing to create a Pod with less than min resources") - pod = newTestPod(f, podName, getResourceList("10m", "50Mi"), api.ResourceList{}) + pod = newTestPod(f, podName, getResourceList("10m", "50Mi"), v1.ResourceList{}) pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) Expect(err).To(HaveOccurred()) By("Failing to create a Pod with more than max resources") - pod = newTestPod(f, podName, getResourceList("600m", "600Mi"), api.ResourceList{}) + pod = newTestPod(f, podName, getResourceList("600m", "600Mi"), v1.ResourceList{}) pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) Expect(err).To(HaveOccurred()) }) }) -func equalResourceRequirement(expected api.ResourceRequirements, actual api.ResourceRequirements) error { +func equalResourceRequirement(expected v1.ResourceRequirements, actual v1.ResourceRequirements) error { framework.Logf("Verifying requests: expected %v with actual %v", expected.Requests, actual.Requests) err := equalResourceList(expected.Requests, actual.Requests) if err != nil { @@ -117,7 +117,7 @@ func equalResourceRequirement(expected api.ResourceRequirements, actual api.Reso return nil } -func equalResourceList(expected api.ResourceList, actual api.ResourceList) error { +func equalResourceList(expected v1.ResourceList, actual v1.ResourceList) error { for k, v := range expected { if actualValue, found := actual[k]; !found || (v.Cmp(actualValue) != 0) { return fmt.Errorf("resource %v expected %v actual %v", k, v.String(), actualValue.String()) @@ -131,28 +131,28 @@ func equalResourceList(expected api.ResourceList, actual api.ResourceList) error return nil } -func getResourceList(cpu, memory string) api.ResourceList { - res := api.ResourceList{} +func getResourceList(cpu, memory string) v1.ResourceList { + res := v1.ResourceList{} if cpu != "" { - res[api.ResourceCPU] = resource.MustParse(cpu) + res[v1.ResourceCPU] = resource.MustParse(cpu) } if memory != "" { - res[api.ResourceMemory] = resource.MustParse(memory) + res[v1.ResourceMemory] = resource.MustParse(memory) } return res } // newLimitRange returns a limit range with specified data -func newLimitRange(name string, limitType api.LimitType, +func newLimitRange(name string, limitType v1.LimitType, min, max, defaultLimit, defaultRequest, - maxLimitRequestRatio api.ResourceList) *api.LimitRange { - return &api.LimitRange{ - ObjectMeta: api.ObjectMeta{ + maxLimitRequestRatio v1.ResourceList) *v1.LimitRange { + return &v1.LimitRange{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ + Spec: v1.LimitRangeSpec{ + Limits: []v1.LimitRangeItem{ { Type: limitType, Min: min, @@ -167,17 +167,17 @@ func newLimitRange(name string, limitType api.LimitType, } // newTestPod returns a pod that has the specified requests and limits -func newTestPod(f *framework.Framework, name string, requests api.ResourceList, limits api.ResourceList) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func newTestPod(f *framework.Framework, name string, requests v1.ResourceList, limits v1.ResourceList) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "pause", Image: framework.GetPauseImageName(f.ClientSet), - Resources: api.ResourceRequirements{ + Resources: v1.ResourceRequirements{ Requests: requests, Limits: limits, }, diff --git a/test/e2e/load.go b/test/e2e/load.go index 6c400054e5d..c6e57e6ac1e 100644 --- a/test/e2e/load.go +++ b/test/e2e/load.go @@ -27,8 +27,9 @@ import ( "sync" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/transport" "k8s.io/kubernetes/pkg/labels" @@ -62,7 +63,7 @@ const ( // To run this suite you must explicitly ask for it by setting the // -t/--test flag or ginkgo.focus flag. var _ = framework.KubeDescribe("Load capacity", func() { - var clientset internalclientset.Interface + var clientset clientset.Interface var nodeCount int var ns string var configs []*testutils.RCConfig @@ -140,7 +141,7 @@ var _ = framework.KubeDescribe("Load capacity", func() { totalPods := itArg.podsPerNode * nodeCount configs = generateRCConfigs(totalPods, itArg.image, itArg.command, namespaces) - var services []*api.Service + var services []*v1.Service // Read the environment variable to see if we want to create services createServices := os.Getenv("CREATE_SERVICES") if createServices == "true" { @@ -206,8 +207,9 @@ var _ = framework.KubeDescribe("Load capacity", func() { } }) -func createClients(numberOfClients int) ([]*internalclientset.Clientset, error) { - clients := make([]*internalclientset.Clientset, numberOfClients) +func createClients(numberOfClients int) ([]*clientset.Clientset, []*internalclientset.Clientset, error) { + clients := make([]*clientset.Clientset, numberOfClients) + internalClients := make([]*internalclientset.Clientset, numberOfClients) for i := 0; i < numberOfClients; i++ { config, err := framework.LoadConfig() Expect(err).NotTo(HaveOccurred()) @@ -223,11 +225,11 @@ func createClients(numberOfClients int) ([]*internalclientset.Clientset, error) // each client here. transportConfig, err := config.TransportConfig() if err != nil { - return nil, err + return nil, nil, err } tlsConfig, err := transport.TLSConfigFor(transportConfig) if err != nil { - return nil, err + return nil, nil, err } config.Transport = utilnet.SetTransportDefaults(&http.Transport{ Proxy: http.ProxyFromEnvironment, @@ -243,13 +245,18 @@ func createClients(numberOfClients int) ([]*internalclientset.Clientset, error) // Transport field. config.TLSClientConfig = restclient.TLSClientConfig{} - c, err := internalclientset.NewForConfig(config) + c, err := clientset.NewForConfig(config) if err != nil { - return nil, err + return nil, nil, err } clients[i] = c + internalClient, err := internalclientset.NewForConfig(config) + if err != nil { + return nil, nil, err + } + internalClients[i] = internalClient } - return clients, nil + return clients, internalClients, nil } func computeRCCounts(total int) (int, int, int) { @@ -266,7 +273,7 @@ func computeRCCounts(total int) (int, int, int) { return smallRCCount, mediumRCCount, bigRCCount } -func generateRCConfigs(totalPods int, image string, command []string, nss []*api.Namespace) []*testutils.RCConfig { +func generateRCConfigs(totalPods int, image string, command []string, nss []*v1.Namespace) []*testutils.RCConfig { configs := make([]*testutils.RCConfig, 0) smallRCCount, mediumRCCount, bigRCCount := computeRCCounts(totalPods) @@ -277,49 +284,51 @@ func generateRCConfigs(totalPods int, image string, command []string, nss []*api // Create a number of clients to better simulate real usecase // where not everyone is using exactly the same client. rcsPerClient := 20 - clients, err := createClients((len(configs) + rcsPerClient - 1) / rcsPerClient) + clients, internalClients, err := createClients((len(configs) + rcsPerClient - 1) / rcsPerClient) framework.ExpectNoError(err) for i := 0; i < len(configs); i++ { configs[i].Client = clients[i%len(clients)] + configs[i].InternalClient = internalClients[i%len(internalClients)] } return configs } func generateRCConfigsForGroup( - nss []*api.Namespace, groupName string, size, count int, image string, command []string) []*testutils.RCConfig { + nss []*v1.Namespace, groupName string, size, count int, image string, command []string) []*testutils.RCConfig { configs := make([]*testutils.RCConfig, 0, count) for i := 1; i <= count; i++ { config := &testutils.RCConfig{ - Client: nil, // this will be overwritten later - Name: groupName + "-" + strconv.Itoa(i), - Namespace: nss[i%len(nss)].Name, - Timeout: 10 * time.Minute, - Image: image, - Command: command, - Replicas: size, - CpuRequest: 10, // 0.01 core - MemRequest: 26214400, // 25MB + Client: nil, // this will be overwritten later + InternalClient: nil, // this will be overwritten later + Name: groupName + "-" + strconv.Itoa(i), + Namespace: nss[i%len(nss)].Name, + Timeout: 10 * time.Minute, + Image: image, + Command: command, + Replicas: size, + CpuRequest: 10, // 0.01 core + MemRequest: 26214400, // 25MB } configs = append(configs, config) } return configs } -func generateServicesForConfigs(configs []*testutils.RCConfig) []*api.Service { - services := make([]*api.Service, 0, len(configs)) +func generateServicesForConfigs(configs []*testutils.RCConfig) []*v1.Service { + services := make([]*v1.Service, 0, len(configs)) for _, config := range configs { serviceName := config.Name + "-svc" labels := map[string]string{"name": config.Name} - service := &api.Service{ - ObjectMeta: api.ObjectMeta{ + service := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: serviceName, Namespace: config.Namespace, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: labels, - Ports: []api.ServicePort{{ + Ports: []v1.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}, @@ -368,11 +377,11 @@ func scaleRC(wg *sync.WaitGroup, config *testutils.RCConfig, scalingTime time.Du sleepUpTo(scalingTime) newSize := uint(rand.Intn(config.Replicas) + config.Replicas/2) - framework.ExpectNoError(framework.ScaleRC(config.Client, config.Namespace, config.Name, newSize, true), + framework.ExpectNoError(framework.ScaleRC(config.Client, config.InternalClient, config.Namespace, config.Name, newSize, true), fmt.Sprintf("scaling rc %s for the first time", config.Name)) selector := labels.SelectorFromSet(labels.Set(map[string]string{"name": config.Name})) - options := api.ListOptions{ - LabelSelector: selector, + options := v1.ListOptions{ + LabelSelector: selector.String(), ResourceVersion: "0", } _, err := config.Client.Core().Pods(config.Namespace).List(options) @@ -396,16 +405,16 @@ func deleteRC(wg *sync.WaitGroup, config *testutils.RCConfig, deletingTime time. if framework.TestContext.GarbageCollectorEnabled { framework.ExpectNoError(framework.DeleteRCAndWaitForGC(config.Client, config.Namespace, config.Name), fmt.Sprintf("deleting rc %s", config.Name)) } else { - framework.ExpectNoError(framework.DeleteRCAndPods(config.Client, config.Namespace, config.Name), fmt.Sprintf("deleting rc %s", config.Name)) + framework.ExpectNoError(framework.DeleteRCAndPods(config.Client, config.InternalClient, config.Namespace, config.Name), fmt.Sprintf("deleting rc %s", config.Name)) } } -func CreateNamespaces(f *framework.Framework, namespaceCount int, namePrefix string) ([]*api.Namespace, error) { - namespaces := []*api.Namespace{} +func CreateNamespaces(f *framework.Framework, namespaceCount int, namePrefix string) ([]*v1.Namespace, error) { + namespaces := []*v1.Namespace{} for i := 1; i <= namespaceCount; i++ { namespace, err := f.CreateNamespace(fmt.Sprintf("%v-%d", namePrefix, i), nil) if err != nil { - return []*api.Namespace{}, err + return []*v1.Namespace{}, err } namespaces = append(namespaces, namespace) } diff --git a/test/e2e/logging_soak.go b/test/e2e/logging_soak.go index 87f1647011c..a95feea4e23 100644 --- a/test/e2e/logging_soak.go +++ b/test/e2e/logging_soak.go @@ -25,7 +25,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/test/e2e/framework" ) @@ -95,9 +95,9 @@ func RunLogPodsWithSleepOf(f *framework.Framework, sleep time.Duration, podname appName := "logging-soak" + podname podlables := f.CreatePodsPerNodeForSimpleApp( appName, - func(n api.Node) api.PodSpec { - return api.PodSpec{ - Containers: []api.Container{{ + func(n v1.Node) v1.PodSpec { + return v1.PodSpec{ + Containers: []v1.Container{{ Name: "logging-soak", Image: "gcr.io/google_containers/busybox:1.24", Args: []string{ @@ -107,7 +107,7 @@ func RunLogPodsWithSleepOf(f *framework.Framework, sleep time.Duration, podname }, }}, NodeName: n.Name, - RestartPolicy: api.RestartPolicyAlways, + RestartPolicy: v1.RestartPolicyAlways, } }, totalPods, @@ -116,10 +116,10 @@ func RunLogPodsWithSleepOf(f *framework.Framework, sleep time.Duration, podname logSoakVerification := f.NewClusterVerification( framework.PodStateVerification{ Selectors: podlables, - ValidPhases: []api.PodPhase{api.PodRunning, api.PodSucceeded}, + ValidPhases: []v1.PodPhase{v1.PodRunning, v1.PodSucceeded}, // we don't validate total log data, since there is no gaurantee all logs will be stored forever. // instead, we just validate that some logs are being created in std out. - Verify: func(p api.Pod) (bool, error) { + Verify: func(p v1.Pod) (bool, error) { s, err := framework.LookForStringInLog(f.Namespace.Name, p.Name, "logging-soak", "logs-123", 1*time.Second) return s != "", err }, diff --git a/test/e2e/mesos.go b/test/e2e/mesos.go index 1ffb07d0af2..bb65d1597d3 100644 --- a/test/e2e/mesos.go +++ b/test/e2e/mesos.go @@ -19,9 +19,9 @@ package e2e import ( "fmt" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -45,7 +45,7 @@ var _ = framework.KubeDescribe("Mesos", func() { nodeClient := f.ClientSet.Core().Nodes() rackA := labels.SelectorFromSet(map[string]string{"k8s.mesosphere.io/attribute-rack": "1"}) - options := api.ListOptions{LabelSelector: rackA} + options := v1.ListOptions{LabelSelector: rackA.String()} nodes, err := nodeClient.List(options) if err != nil { framework.Failf("Failed to query for node: %v", err) @@ -54,7 +54,7 @@ var _ = framework.KubeDescribe("Mesos", func() { var addr string for _, a := range nodes.Items[0].Status.Addresses { - if a.Type == api.NodeInternalIP { + if a.Type == v1.NodeInternalIP { addr = a.Address } } @@ -79,18 +79,18 @@ var _ = framework.KubeDescribe("Mesos", func() { // scheduled onto it. By("Trying to launch a pod with a label to get a node which can launch it.") podName := "with-label" - _, err := c.Core().Pods(ns).Create(&api.Pod{ + _, err := c.Core().Pods(ns).Create(&v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Annotations: map[string]string{ "k8s.mesosphere.io/roles": "public", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: podName, Image: framework.GetPauseImageName(f.ClientSet), @@ -110,7 +110,7 @@ var _ = framework.KubeDescribe("Mesos", func() { rack2 := labels.SelectorFromSet(map[string]string{ "k8s.mesosphere.io/attribute-rack": "2", }) - options := api.ListOptions{LabelSelector: rack2} + options := v1.ListOptions{LabelSelector: rack2.String()} nodes, err := nodeClient.List(options) framework.ExpectNoError(err) diff --git a/test/e2e/metrics_grabber_test.go b/test/e2e/metrics_grabber_test.go index 4e0c39dbe00..92658802b9d 100644 --- a/test/e2e/metrics_grabber_test.go +++ b/test/e2e/metrics_grabber_test.go @@ -19,8 +19,8 @@ package e2e import ( "strings" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/metrics" "k8s.io/kubernetes/test/e2e/framework" @@ -59,7 +59,7 @@ var _ = framework.KubeDescribe("MetricsGrabber", func() { It("should grab all metrics from a Scheduler.", func() { By("Proxying to Pod through the API server") // Check if master Node is registered - nodes, err := c.Core().Nodes().List(api.ListOptions{}) + nodes, err := c.Core().Nodes().List(v1.ListOptions{}) framework.ExpectNoError(err) var masterRegistered = false @@ -80,7 +80,7 @@ var _ = framework.KubeDescribe("MetricsGrabber", func() { It("should grab all metrics from a ControllerManager.", func() { By("Proxying to Pod through the API server") // Check if master Node is registered - nodes, err := c.Core().Nodes().List(api.ListOptions{}) + nodes, err := c.Core().Nodes().List(v1.ListOptions{}) framework.ExpectNoError(err) var masterRegistered = false diff --git a/test/e2e/monitoring.go b/test/e2e/monitoring.go index d4115d58f1f..f09640a5259 100644 --- a/test/e2e/monitoring.go +++ b/test/e2e/monitoring.go @@ -24,7 +24,8 @@ import ( influxdb "github.com/influxdata/influxdb/client" "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/test/e2e/framework" @@ -101,7 +102,7 @@ func verifyExpectedRcsExistAndGetExpectedPods(c clientset.Interface) ([]string, // is running (which would be an error except during a rolling update). for _, rcLabel := range rcLabels { selector := labels.Set{"k8s-app": rcLabel}.AsSelector() - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} deploymentList, err := c.Extensions().Deployments(api.NamespaceSystem).List(options) if err != nil { return nil, err @@ -121,7 +122,7 @@ func verifyExpectedRcsExistAndGetExpectedPods(c clientset.Interface) ([]string, // Check all the replication controllers. for _, rc := range rcList.Items { selector := labels.Set(rc.Spec.Selector).AsSelector() - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} podList, err := c.Core().Pods(api.NamespaceSystem).List(options) if err != nil { return nil, err @@ -136,7 +137,7 @@ func verifyExpectedRcsExistAndGetExpectedPods(c clientset.Interface) ([]string, // Do the same for all deployments. for _, rc := range deploymentList.Items { selector := labels.Set(rc.Spec.Selector.MatchLabels).AsSelector() - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} podList, err := c.Core().Pods(api.NamespaceSystem).List(options) if err != nil { return nil, err @@ -151,7 +152,7 @@ func verifyExpectedRcsExistAndGetExpectedPods(c clientset.Interface) ([]string, // And for pet sets. for _, ps := range psList.Items { selector := labels.Set(ps.Spec.Selector.MatchLabels).AsSelector() - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} podList, err := c.Core().Pods(api.NamespaceSystem).List(options) if err != nil { return nil, err @@ -168,7 +169,7 @@ func verifyExpectedRcsExistAndGetExpectedPods(c clientset.Interface) ([]string, } func expectedServicesExist(c clientset.Interface) error { - serviceList, err := c.Core().Services(api.NamespaceSystem).List(api.ListOptions{}) + serviceList, err := c.Core().Services(api.NamespaceSystem).List(v1.ListOptions{}) if err != nil { return err } @@ -187,7 +188,7 @@ func expectedServicesExist(c clientset.Interface) error { func getAllNodesInCluster(c clientset.Interface) ([]string, error) { // It should be OK to list unschedulable Nodes here. - nodeList, err := c.Core().Nodes().List(api.ListOptions{}) + nodeList, err := c.Core().Nodes().List(v1.ListOptions{}) if err != nil { return nil, err } @@ -281,7 +282,7 @@ func testMonitoringUsingHeapsterInfluxdb(c clientset.Interface) { func printDebugInfo(c clientset.Interface) { set := labels.Set{"k8s-app": "heapster"} - options := api.ListOptions{LabelSelector: set.AsSelector()} + options := v1.ListOptions{LabelSelector: set.AsSelector().String()} podList, err := c.Core().Pods(api.NamespaceSystem).List(options) if err != nil { framework.Logf("Error while listing pods %v", err) diff --git a/test/e2e/namespace.go b/test/e2e/namespace.go index d2e65901712..97c62323f6b 100644 --- a/test/e2e/namespace.go +++ b/test/e2e/namespace.go @@ -22,8 +22,8 @@ import ( "sync" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -60,7 +60,7 @@ func extinguish(f *framework.Framework, totalNS int, maxAllowedAfterDel int, max framework.ExpectNoError(wait.Poll(2*time.Second, time.Duration(maxSeconds)*time.Second, func() (bool, error) { var cnt = 0 - nsList, err := f.ClientSet.Core().Namespaces().List(api.ListOptions{}) + nsList, err := f.ClientSet.Core().Namespaces().List(v1.ListOptions{}) if err != nil { return false, err } @@ -89,12 +89,12 @@ func ensurePodsAreRemovedWhenNamespaceIsDeleted(f *framework.Framework) { Expect(err).NotTo(HaveOccurred()) By("Creating a pod in the namespace") - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "test-pod", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "nginx", Image: framework.GetPauseImageName(f.ClientSet), @@ -145,13 +145,13 @@ func ensureServicesAreRemovedWhenNamespaceIsDeleted(f *framework.Framework) { "foo": "bar", "baz": "blah", } - service := &api.Service{ - ObjectMeta: api.ObjectMeta{ + service := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: serviceName, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: labels, - Ports: []api.ServicePort{{ + Ports: []v1.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}, diff --git a/test/e2e/network_partition.go b/test/e2e/network_partition.go index 53d3ac10d0c..a8b6c851001 100644 --- a/test/e2e/network_partition.go +++ b/test/e2e/network_partition.go @@ -22,8 +22,9 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" @@ -40,7 +41,7 @@ import ( // At the end (even in case of errors), the network traffic is brought back to normal. // This function executes commands on a node so it will work only for some // environments. -func testUnderTemporaryNetworkFailure(c clientset.Interface, ns string, node *api.Node, testFunc func()) { +func testUnderTemporaryNetworkFailure(c clientset.Interface, ns string, node *v1.Node, testFunc func()) { host := framework.GetNodeExternalIP(node) master := framework.GetMasterAddress(c) By(fmt.Sprintf("block network traffic from node %s to the master", node.Name)) @@ -54,13 +55,13 @@ func testUnderTemporaryNetworkFailure(c clientset.Interface, ns string, node *ap }() framework.Logf("Waiting %v to ensure node %s is ready before beginning test...", resizeNodeReadyTimeout, node.Name) - if !framework.WaitForNodeToBe(c, node.Name, api.NodeReady, true, resizeNodeReadyTimeout) { + if !framework.WaitForNodeToBe(c, node.Name, v1.NodeReady, true, resizeNodeReadyTimeout) { framework.Failf("Node %s did not become ready within %v", node.Name, resizeNodeReadyTimeout) } framework.BlockNetwork(host, master) framework.Logf("Waiting %v for node %s to be not ready after simulated network failure", resizeNodeNotReadyTimeout, node.Name) - if !framework.WaitForNodeToBe(c, node.Name, api.NodeReady, false, resizeNodeNotReadyTimeout) { + if !framework.WaitForNodeToBe(c, node.Name, v1.NodeReady, false, resizeNodeNotReadyTimeout) { framework.Failf("Node %s did not become not-ready within %v", node.Name, resizeNodeNotReadyTimeout) } @@ -68,14 +69,14 @@ func testUnderTemporaryNetworkFailure(c clientset.Interface, ns string, node *ap // network traffic is unblocked in a deferred function } -func expectNodeReadiness(isReady bool, newNode chan *api.Node) { +func expectNodeReadiness(isReady bool, newNode chan *v1.Node) { timeout := false expected := false timer := time.After(nodeReadinessTimeout) for !expected && !timeout { select { case n := <-newNode: - if framework.IsNodeConditionSetAsExpected(n, api.NodeReady, isReady) { + if framework.IsNodeConditionSetAsExpected(n, v1.NodeReady, isReady) { expected = true } else { framework.Logf("Observed node ready status is NOT %v as expected", isReady) @@ -89,24 +90,24 @@ func expectNodeReadiness(isReady bool, newNode chan *api.Node) { } } -func podOnNode(podName, nodeName string, image string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func podOnNode(podName, nodeName string, image string) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{ "name": podName, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: podName, Image: image, - Ports: []api.ContainerPort{{ContainerPort: 9376}}, + Ports: []v1.ContainerPort{{ContainerPort: 9376}}, }, }, NodeName: nodeName, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } } @@ -158,16 +159,16 @@ var _ = framework.KubeDescribe("Network Partition [Disruptive] [Slow]", func() { It("All pods on the unreachable node should be marked as NotReady upon the node turn NotReady "+ "AND all pods should be mark back to Ready when the node get back to Ready before pod eviction timeout", func() { By("choose a node - we will block all network traffic on this node") - var podOpts api.ListOptions - nodeOpts := api.ListOptions{} + var podOpts v1.ListOptions + nodeOpts := v1.ListOptions{} nodes, err := c.Core().Nodes().List(nodeOpts) Expect(err).NotTo(HaveOccurred()) - framework.FilterNodes(nodes, func(node api.Node) bool { - if !framework.IsNodeConditionSetAsExpected(&node, api.NodeReady, true) { + framework.FilterNodes(nodes, func(node v1.Node) bool { + if !framework.IsNodeConditionSetAsExpected(&node, v1.NodeReady, true) { return false } - podOpts = api.ListOptions{FieldSelector: fields.OneTermEqualSelector(api.PodHostField, node.Name)} - pods, err := c.Core().Pods(api.NamespaceAll).List(podOpts) + podOpts = v1.ListOptions{FieldSelector: fields.OneTermEqualSelector(api.PodHostField, node.Name).String()} + pods, err := c.Core().Pods(v1.NamespaceAll).List(podOpts) if err != nil || len(pods.Items) <= 0 { return false } @@ -177,7 +178,7 @@ var _ = framework.KubeDescribe("Network Partition [Disruptive] [Slow]", func() { framework.Failf("No eligible node were found: %d", len(nodes.Items)) } node := nodes.Items[0] - podOpts = api.ListOptions{FieldSelector: fields.OneTermEqualSelector(api.PodHostField, node.Name)} + podOpts = v1.ListOptions{FieldSelector: fields.OneTermEqualSelector(api.PodHostField, node.Name).String()} if err = framework.WaitForMatchPodsCondition(c, podOpts, "Running and Ready", podReadyTimeout, testutils.PodRunningReady); err != nil { framework.Failf("Pods on node %s are not ready and running within %v: %v", node.Name, podReadyTimeout, err) } @@ -185,25 +186,25 @@ var _ = framework.KubeDescribe("Network Partition [Disruptive] [Slow]", func() { By("Set up watch on node status") nodeSelector := fields.OneTermEqualSelector("metadata.name", node.Name) stopCh := make(chan struct{}) - newNode := make(chan *api.Node) + newNode := make(chan *v1.Node) var controller *cache.Controller _, controller = cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - options.FieldSelector = nodeSelector + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + options.FieldSelector = nodeSelector.String() obj, err := f.ClientSet.Core().Nodes().List(options) return runtime.Object(obj), err }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - options.FieldSelector = nodeSelector + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + options.FieldSelector = nodeSelector.String() return f.ClientSet.Core().Nodes().Watch(options) }, }, - &api.Node{}, + &v1.Node{}, 0, cache.ResourceEventHandlerFuncs{ UpdateFunc: func(oldObj, newObj interface{}) { - n, ok := newObj.(*api.Node) + n, ok := newObj.(*v1.Node) Expect(ok).To(Equal(true)) newNode <- n @@ -262,7 +263,7 @@ var _ = framework.KubeDescribe("Network Partition [Disruptive] [Slow]", func() { By("choose a node with at least one pod - we will block some network traffic on this node") label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name})) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := c.Core().Pods(ns).List(options) // list pods after all have been scheduled Expect(err).NotTo(HaveOccurred()) nodeName := pods.Items[0].Spec.NodeName @@ -327,7 +328,7 @@ var _ = framework.KubeDescribe("Network Partition [Disruptive] [Slow]", func() { By("choose a node with at least one pod - we will block some network traffic on this node") label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name})) - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := c.Core().Pods(ns).List(options) // list pods after all have been scheduled Expect(err).NotTo(HaveOccurred()) nodeName := pods.Items[0].Spec.NodeName @@ -385,8 +386,8 @@ var _ = framework.KubeDescribe("Network Partition [Disruptive] [Slow]", func() { }) It("should come back up if node goes down [Slow] [Disruptive]", func() { - petMounts := []api.VolumeMount{{Name: "datadir", MountPath: "/data/"}} - podMounts := []api.VolumeMount{{Name: "home", MountPath: "/home"}} + petMounts := []v1.VolumeMount{{Name: "datadir", MountPath: "/data/"}} + podMounts := []v1.VolumeMount{{Name: "home", MountPath: "/home"}} ps := newStatefulSet(psName, ns, headlessSvcName, 3, petMounts, podMounts, labels) _, err := c.Apps().StatefulSets(ns).Create(ps) Expect(err).NotTo(HaveOccurred()) @@ -399,16 +400,16 @@ var _ = framework.KubeDescribe("Network Partition [Disruptive] [Slow]", func() { restartNodes(f, nodeNames) By("waiting for pods to be running again") - pst.waitForRunningAndReady(ps.Spec.Replicas, ps) + pst.waitForRunningAndReady(*ps.Spec.Replicas, ps) }) It("should not reschedule pets if there is a network partition [Slow] [Disruptive]", func() { - ps := newStatefulSet(psName, ns, headlessSvcName, 3, []api.VolumeMount{}, []api.VolumeMount{}, labels) + ps := newStatefulSet(psName, ns, headlessSvcName, 3, []v1.VolumeMount{}, []v1.VolumeMount{}, labels) _, err := c.Apps().StatefulSets(ns).Create(ps) Expect(err).NotTo(HaveOccurred()) pst := statefulSetTester{c: c} - pst.waitForRunningAndReady(ps.Spec.Replicas, ps) + pst.waitForRunningAndReady(*ps.Spec.Replicas, ps) pod := pst.getPodList(ps).Items[0] node, err := c.Core().Nodes().Get(pod.Spec.NodeName) @@ -429,7 +430,7 @@ var _ = framework.KubeDescribe("Network Partition [Disruptive] [Slow]", func() { } By("waiting for pods to be running again") - pst.waitForRunningAndReady(ps.Spec.Replicas, ps) + pst.waitForRunningAndReady(*ps.Spec.Replicas, ps) }) }) @@ -438,7 +439,7 @@ var _ = framework.KubeDescribe("Network Partition [Disruptive] [Slow]", func() { parallelism := int32(2) completions := int32(4) - job := newTestJob("notTerminate", "network-partition", api.RestartPolicyNever, parallelism, completions) + job := newTestJob("notTerminate", "network-partition", v1.RestartPolicyNever, parallelism, completions) job, err := createJob(f.ClientSet, f.Namespace.Name, job) Expect(err).NotTo(HaveOccurred()) label := labels.SelectorFromSet(labels.Set(map[string]string{jobSelectorKey: job.Name})) @@ -448,7 +449,7 @@ var _ = framework.KubeDescribe("Network Partition [Disruptive] [Slow]", func() { Expect(err).NotTo(HaveOccurred()) By("choose a node with at least one pod - we will block some network traffic on this node") - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := c.Core().Pods(ns).List(options) // list pods after all have been scheduled Expect(err).NotTo(HaveOccurred()) nodeName := pods.Items[0].Spec.NodeName diff --git a/test/e2e/networking_perf.go b/test/e2e/networking_perf.go index e0dfab64ef5..55b67b3071b 100644 --- a/test/e2e/networking_perf.go +++ b/test/e2e/networking_perf.go @@ -24,7 +24,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/test/e2e/framework" ) @@ -59,9 +59,9 @@ var _ = framework.KubeDescribe("Networking IPerf [Experimental] [Slow] [Feature: 8001, 8002, appName, - func(n api.Node) api.PodSpec { - return api.PodSpec{ - Containers: []api.Container{{ + func(n v1.Node) v1.PodSpec { + return v1.PodSpec{ + Containers: []v1.Container{{ Name: "iperf-server", Image: "gcr.io/google_containers/iperf:e2e", Args: []string{ @@ -69,10 +69,10 @@ var _ = framework.KubeDescribe("Networking IPerf [Experimental] [Slow] [Feature: "-c", "/usr/local/bin/iperf -s -p 8001 ", }, - Ports: []api.ContainerPort{{ContainerPort: 8001}}, + Ports: []v1.ContainerPort{{ContainerPort: 8001}}, }}, NodeName: n.Name, - RestartPolicy: api.RestartPolicyOnFailure, + RestartPolicy: v1.RestartPolicyOnFailure, } }, // this will be used to generate the -service name which all iperf clients point at. @@ -86,9 +86,9 @@ var _ = framework.KubeDescribe("Networking IPerf [Experimental] [Slow] [Feature: iperfClientPodLabels := f.CreatePodsPerNodeForSimpleApp( "iperf-e2e-cli", - func(n api.Node) api.PodSpec { - return api.PodSpec{ - Containers: []api.Container{ + func(n v1.Node) v1.PodSpec { + return v1.PodSpec{ + Containers: []v1.Container{ { Name: "iperf-client", Image: "gcr.io/google_containers/iperf:e2e", @@ -99,7 +99,7 @@ var _ = framework.KubeDescribe("Networking IPerf [Experimental] [Slow] [Feature: }, }, }, - RestartPolicy: api.RestartPolicyOnFailure, // let them successfully die. + RestartPolicy: v1.RestartPolicyOnFailure, // let them successfully die. } }, numClient, @@ -121,7 +121,7 @@ var _ = framework.KubeDescribe("Networking IPerf [Experimental] [Slow] [Feature: iperfClusterVerification := f.NewClusterVerification( framework.PodStateVerification{ Selectors: iperfClientPodLabels, - ValidPhases: []api.PodPhase{api.PodSucceeded}, + ValidPhases: []v1.PodPhase{v1.PodSucceeded}, }, ) @@ -133,7 +133,7 @@ var _ = framework.KubeDescribe("Networking IPerf [Experimental] [Slow] [Feature: } else { // For each builds up a collection of IPerfRecords iperfClusterVerification.ForEach( - func(p api.Pod) { + func(p v1.Pod) { resultS, err := framework.LookForStringInLog(f.Namespace.Name, p.Name, "iperf-client", "0-", 1*time.Second) if err == nil { framework.Logf(resultS) diff --git a/test/e2e/node_problem_detector.go b/test/e2e/node_problem_detector.go index 7c602742d58..d59227ed8c5 100644 --- a/test/e2e/node_problem_detector.go +++ b/test/e2e/node_problem_detector.go @@ -23,8 +23,9 @@ import ( "time" "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - coreclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + coreclientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/system" @@ -54,7 +55,7 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { name = "node-problem-detector-" + uid configName = "node-problem-detector-config-" + uid // There is no namespace for Node, event recorder will set default namespace for node events. - eventNamespace = api.NamespaceDefault + eventNamespace = v1.NamespaceDefault }) // Test kernel monitor. We may add other tests if we have more problem daemons in the future. @@ -63,7 +64,7 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { // Use test condition to avoid conflict with real node problem detector // TODO(random-liu): Now node condition could be arbitrary string, consider wether we need to // add TestCondition when switching to predefined condition list. - condition = api.NodeConditionType("TestCondition") + condition = v1.NodeConditionType("TestCondition") lookback = time.Hour // Assume the test won't take more than 1 hour, in fact it usually only takes 90 seconds. startPattern = "test reboot" @@ -88,8 +89,8 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { permMessage = "permanent error" ) var source, config, tmpDir string - var node *api.Node - var eventListOptions api.ListOptions + var node *v1.Node + var eventListOptions v1.ListOptions injectCommand := func(timestamp time.Time, log string, num int) string { var commands []string for i := 0; i < num; i++ { @@ -132,11 +133,11 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { ] }` By("Get a non master node to run the pod") - nodes, err := c.Core().Nodes().List(api.ListOptions{}) + nodes, err := c.Core().Nodes().List(v1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) node = nil for _, n := range nodes.Items { - if !system.IsMasterNode(&n) { + if !system.IsMasterNode(n.Name) { node = &n break } @@ -146,70 +147,71 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { selector := fields.Set{ "involvedObject.kind": "Node", "involvedObject.name": node.Name, - "involvedObject.namespace": api.NamespaceAll, + "involvedObject.namespace": v1.NamespaceAll, "source": source, - }.AsSelector() - eventListOptions = api.ListOptions{FieldSelector: selector} + }.AsSelector().String() + eventListOptions = v1.ListOptions{FieldSelector: selector} By("Create the test log file") tmpDir = "/tmp/" + name cmd := fmt.Sprintf("mkdir %s; > %s/%s", tmpDir, tmpDir, logFile) Expect(framework.IssueSSHCommand(cmd, framework.TestContext.Provider, node)).To(Succeed()) By("Create config map for the node problem detector") - _, err = c.Core().ConfigMaps(ns).Create(&api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ + _, err = c.Core().ConfigMaps(ns).Create(&v1.ConfigMap{ + ObjectMeta: v1.ObjectMeta{ Name: configName, }, Data: map[string]string{configFile: config}, }) Expect(err).NotTo(HaveOccurred()) By("Create the node problem detector") - _, err = c.Core().Pods(ns).Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + _, err = c.Core().Pods(ns).Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeName: node.Name, - SecurityContext: &api.PodSecurityContext{HostNetwork: true}, - Volumes: []api.Volume{ + HostNetwork: true, + SecurityContext: &v1.PodSecurityContext{}, + Volumes: []v1.Volume{ { Name: configVolume, - VolumeSource: api.VolumeSource{ - ConfigMap: &api.ConfigMapVolumeSource{ - LocalObjectReference: api.LocalObjectReference{Name: configName}, + VolumeSource: v1.VolumeSource{ + ConfigMap: &v1.ConfigMapVolumeSource{ + LocalObjectReference: v1.LocalObjectReference{Name: configName}, }, }, }, { Name: logVolume, - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: tmpDir}, + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{Path: tmpDir}, }, }, { Name: localtimeVolume, - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: etcLocaltime}, + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{Path: etcLocaltime}, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: name, Image: image, Command: []string{"/node-problem-detector", "--kernel-monitor=" + filepath.Join(configDir, configFile)}, - ImagePullPolicy: api.PullAlways, - Env: []api.EnvVar{ + ImagePullPolicy: v1.PullAlways, + Env: []v1.EnvVar{ { Name: "NODE_NAME", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ + ValueFrom: &v1.EnvVarSource{ + FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "spec.nodeName", }, }, }, }, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: logVolume, MountPath: logDir, @@ -248,13 +250,13 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { events int conditionReason string conditionMessage string - conditionType api.ConditionStatus + conditionType v1.ConditionStatus }{ { description: "should generate default node condition", conditionReason: defaultReason, conditionMessage: defaultMessage, - conditionType: api.ConditionFalse, + conditionType: v1.ConditionFalse, }, { description: "should not generate events for too old log", @@ -263,7 +265,7 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { messageNum: 3, conditionReason: defaultReason, conditionMessage: defaultMessage, - conditionType: api.ConditionFalse, + conditionType: v1.ConditionFalse, }, { description: "should not change node condition for too old log", @@ -272,7 +274,7 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { messageNum: 1, conditionReason: defaultReason, conditionMessage: defaultMessage, - conditionType: api.ConditionFalse, + conditionType: v1.ConditionFalse, }, { description: "should generate event for old log within lookback duration", @@ -282,7 +284,7 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { events: 3, conditionReason: defaultReason, conditionMessage: defaultMessage, - conditionType: api.ConditionFalse, + conditionType: v1.ConditionFalse, }, { description: "should change node condition for old log within lookback duration", @@ -292,7 +294,7 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { events: 3, // event number should not change conditionReason: permReason, conditionMessage: permMessage, - conditionType: api.ConditionTrue, + conditionType: v1.ConditionTrue, }, { description: "should reset node condition if the node is reboot", @@ -302,7 +304,7 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { events: 3, // event number should not change conditionReason: defaultReason, conditionMessage: defaultMessage, - conditionType: api.ConditionFalse, + conditionType: v1.ConditionFalse, }, { description: "should generate event for new log", @@ -312,7 +314,7 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { events: 6, conditionReason: defaultReason, conditionMessage: defaultMessage, - conditionType: api.ConditionFalse, + conditionType: v1.ConditionFalse, }, { description: "should change node condition for new log", @@ -322,7 +324,7 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { events: 6, // event number should not change conditionReason: permReason, conditionMessage: permMessage, - conditionType: api.ConditionTrue, + conditionType: v1.ConditionTrue, }, } { By(test.description) @@ -360,13 +362,13 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { framework.Logf("Node Problem Detector logs:\n %s", log) } By("Delete the node problem detector") - c.Core().Pods(ns).Delete(name, api.NewDeleteOptions(0)) + c.Core().Pods(ns).Delete(name, v1.NewDeleteOptions(0)) By("Wait for the node problem detector to disappear") Expect(framework.WaitForPodToDisappear(c, ns, name, labels.Everything(), pollInterval, pollTimeout)).To(Succeed()) By("Delete the config map") c.Core().ConfigMaps(ns).Delete(configName, nil) By("Clean up the events") - Expect(c.Core().Events(eventNamespace).DeleteCollection(api.NewDeleteOptions(0), eventListOptions)).To(Succeed()) + Expect(c.Core().Events(eventNamespace).DeleteCollection(v1.NewDeleteOptions(0), eventListOptions)).To(Succeed()) By("Clean up the node condition") patch := []byte(fmt.Sprintf(`{"status":{"conditions":[{"$patch":"delete","type":"%s"}]}}`, condition)) c.Core().RESTClient().Patch(api.StrategicMergePatchType).Resource("nodes").Name(node.Name).SubResource("status").Body(patch).Do() @@ -377,7 +379,7 @@ var _ = framework.KubeDescribe("NodeProblemDetector", func() { }) // verifyEvents verifies there are num specific events generated -func verifyEvents(e coreclientset.EventInterface, options api.ListOptions, num int, reason, message string) error { +func verifyEvents(e coreclientset.EventInterface, options v1.ListOptions, num int, reason, message string) error { events, err := e.List(options) if err != nil { return err @@ -396,7 +398,7 @@ func verifyEvents(e coreclientset.EventInterface, options api.ListOptions, num i } // verifyNoEvents verifies there is no event generated -func verifyNoEvents(e coreclientset.EventInterface, options api.ListOptions) error { +func verifyNoEvents(e coreclientset.EventInterface, options v1.ListOptions) error { events, err := e.List(options) if err != nil { return err @@ -408,12 +410,12 @@ func verifyNoEvents(e coreclientset.EventInterface, options api.ListOptions) err } // verifyCondition verifies specific node condition is generated, if reason and message are empty, they will not be checked -func verifyCondition(n coreclientset.NodeInterface, nodeName string, condition api.NodeConditionType, status api.ConditionStatus, reason, message string) error { +func verifyCondition(n coreclientset.NodeInterface, nodeName string, condition v1.NodeConditionType, status v1.ConditionStatus, reason, message string) error { node, err := n.Get(nodeName) if err != nil { return err } - _, c := api.GetNodeCondition(&node.Status, condition) + _, c := v1.GetNodeCondition(&node.Status, condition) if c == nil { return fmt.Errorf("node condition %q not found", condition) } diff --git a/test/e2e/nodeoutofdisk.go b/test/e2e/nodeoutofdisk.go index 9c95861b640..eafbeb22b8e 100644 --- a/test/e2e/nodeoutofdisk.go +++ b/test/e2e/nodeoutofdisk.go @@ -22,9 +22,9 @@ import ( "time" cadvisorapi "github.com/google/cadvisor/info/v1" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -136,10 +136,10 @@ var _ = framework.KubeDescribe("NodeOutOfDisk [Serial] [Flaky] [Disruptive]", fu "involvedObject.kind": "Pod", "involvedObject.name": pendingPodName, "involvedObject.namespace": ns, - "source": api.DefaultSchedulerName, + "source": v1.DefaultSchedulerName, "reason": "FailedScheduling", - }.AsSelector() - options := api.ListOptions{FieldSelector: selector} + }.AsSelector().String() + options := v1.ListOptions{FieldSelector: selector} schedEvents, err := c.Core().Events(ns).List(options) framework.ExpectNoError(err) @@ -171,19 +171,19 @@ var _ = framework.KubeDescribe("NodeOutOfDisk [Serial] [Flaky] [Disruptive]", fu func createOutOfDiskPod(c clientset.Interface, ns, name string, milliCPU int64) { podClient := c.Core().Pods(ns) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "pause", Image: framework.GetPauseImageName(c), - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ // Request enough CPU to fit only two pods on a given node. - api.ResourceCPU: *resource.NewMilliQuantity(milliCPU, resource.DecimalSI), + v1.ResourceCPU: *resource.NewMilliQuantity(milliCPU, resource.DecimalSI), }, }, }, @@ -197,11 +197,11 @@ func createOutOfDiskPod(c clientset.Interface, ns, name string, milliCPU int64) // availCpu calculates the available CPU on a given node by subtracting the CPU requested by // all the pods from the total available CPU capacity on the node. -func availCpu(c clientset.Interface, node *api.Node) (int64, error) { - podClient := c.Core().Pods(api.NamespaceAll) +func availCpu(c clientset.Interface, node *v1.Node) (int64, error) { + podClient := c.Core().Pods(v1.NamespaceAll) - selector := fields.Set{"spec.nodeName": node.Name}.AsSelector() - options := api.ListOptions{FieldSelector: selector} + selector := fields.Set{"spec.nodeName": node.Name}.AsSelector().String() + options := v1.ListOptions{FieldSelector: selector} pods, err := podClient.List(options) if err != nil { return 0, fmt.Errorf("failed to retrieve all the pods on node %s: %v", node.Name, err) @@ -217,7 +217,7 @@ func availCpu(c clientset.Interface, node *api.Node) (int64, error) { // availSize returns the available disk space on a given node by querying node stats which // is in turn obtained internally from cadvisor. -func availSize(c clientset.Interface, node *api.Node) (uint64, error) { +func availSize(c clientset.Interface, node *v1.Node) (uint64, error) { statsResource := fmt.Sprintf("api/v1/proxy/nodes/%s/stats/", node.Name) framework.Logf("Querying stats for node %s using url %s", node.Name, statsResource) res, err := c.Core().RESTClient().Get().AbsPath(statsResource).Timeout(time.Minute).Do().Raw() @@ -235,7 +235,7 @@ func availSize(c clientset.Interface, node *api.Node) (uint64, error) { // fillDiskSpace fills the available disk space on a given node by creating a large file. The disk // space on the node is filled in such a way that the available space after filling the disk is just // below the lowDiskSpaceThreshold mark. -func fillDiskSpace(c clientset.Interface, node *api.Node) { +func fillDiskSpace(c clientset.Interface, node *v1.Node) { avail, err := availSize(c, node) framework.ExpectNoError(err, "Node %s: couldn't obtain available disk size %v", node.Name, err) @@ -247,7 +247,7 @@ func fillDiskSpace(c clientset.Interface, node *api.Node) { cmd := fmt.Sprintf("fallocate -l %d test.img", fillSize) framework.ExpectNoError(framework.IssueSSHCommand(cmd, framework.TestContext.Provider, node)) - ood := framework.WaitForNodeToBe(c, node.Name, api.NodeOutOfDisk, true, nodeOODTimeOut) + ood := framework.WaitForNodeToBe(c, node.Name, v1.NodeOutOfDisk, true, nodeOODTimeOut) Expect(ood).To(BeTrue(), "Node %s did not run out of disk within %v", node.Name, nodeOODTimeOut) avail, err = availSize(c, node) @@ -256,11 +256,11 @@ func fillDiskSpace(c clientset.Interface, node *api.Node) { } // recoverDiskSpace recovers disk space, filled by creating a large file, on a given node. -func recoverDiskSpace(c clientset.Interface, node *api.Node) { +func recoverDiskSpace(c clientset.Interface, node *v1.Node) { By(fmt.Sprintf("Recovering disk space on node %s", node.Name)) cmd := "rm -f test.img" framework.ExpectNoError(framework.IssueSSHCommand(cmd, framework.TestContext.Provider, node)) - ood := framework.WaitForNodeToBe(c, node.Name, api.NodeOutOfDisk, false, nodeOODTimeOut) + ood := framework.WaitForNodeToBe(c, node.Name, v1.NodeOutOfDisk, false, nodeOODTimeOut) Expect(ood).To(BeTrue(), "Node %s's out of disk condition status did not change to false within %v", node.Name, nodeOODTimeOut) } diff --git a/test/e2e/opaque_resource.go b/test/e2e/opaque_resource.go index 28750309158..af40015f1ea 100644 --- a/test/e2e/opaque_resource.go +++ b/test/e2e/opaque_resource.go @@ -24,6 +24,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/runtime" @@ -38,16 +39,16 @@ import ( var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", func() { f := framework.NewDefaultFramework("opaque-resource") - opaqueResName := api.OpaqueIntResourceName("foo") - var node *api.Node + opaqueResName := v1.OpaqueIntResourceName("foo") + var node *v1.Node BeforeEach(func() { if node == nil { // Priming invocation; select the first non-master node. - nodes, err := f.ClientSet.Core().Nodes().List(api.ListOptions{}) + nodes, err := f.ClientSet.Core().Nodes().List(v1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) for _, n := range nodes.Items { - if !system.IsMasterNode(&n) { + if !system.IsMasterNode(n.Name) { node = &n break } @@ -63,8 +64,8 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun It("should not break pods that do not consume opaque integer resources.", func() { By("Creating a vanilla pod") - requests := api.ResourceList{api.ResourceCPU: resource.MustParse("0.1")} - limits := api.ResourceList{api.ResourceCPU: resource.MustParse("0.2")} + requests := v1.ResourceList{v1.ResourceCPU: resource.MustParse("0.1")} + limits := v1.ResourceList{v1.ResourceCPU: resource.MustParse("0.2")} pod := newTestPod(f, "without-oir", requests, limits) By("Observing an event that indicates the pod was scheduled") @@ -72,8 +73,8 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun _, err := f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) return err } - predicate := func(e *api.Event) bool { - return e.Type == api.EventTypeNormal && + predicate := func(e *v1.Event) bool { + return e.Type == v1.EventTypeNormal && e.Reason == "Scheduled" && // Here we don't check for the bound node name since it can land on // any one (this pod doesn't require any of the opaque resource.) @@ -86,13 +87,13 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun It("should schedule pods that do consume opaque integer resources.", func() { By("Creating a pod that requires less of the opaque resource than is allocatable on a node.") - requests := api.ResourceList{ - api.ResourceCPU: resource.MustParse("0.1"), - opaqueResName: resource.MustParse("1"), + requests := v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("0.1"), + opaqueResName: resource.MustParse("1"), } - limits := api.ResourceList{ - api.ResourceCPU: resource.MustParse("0.2"), - opaqueResName: resource.MustParse("2"), + limits := v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("0.2"), + opaqueResName: resource.MustParse("2"), } pod := newTestPod(f, "min-oir", requests, limits) @@ -101,8 +102,8 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun _, err := f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) return err } - predicate := func(e *api.Event) bool { - return e.Type == api.EventTypeNormal && + predicate := func(e *v1.Event) bool { + return e.Type == v1.EventTypeNormal && e.Reason == "Scheduled" && strings.Contains(e.Message, fmt.Sprintf("Successfully assigned %v to %v", pod.Name, node.Name)) } @@ -113,15 +114,15 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun It("should not schedule pods that exceed the available amount of opaque integer resource.", func() { By("Creating a pod that requires more of the opaque resource than is allocatable on any node") - requests := api.ResourceList{opaqueResName: resource.MustParse("6")} - limits := api.ResourceList{} + requests := v1.ResourceList{opaqueResName: resource.MustParse("6")} + limits := v1.ResourceList{} By("Observing an event that indicates the pod was not scheduled") action := func() error { _, err := f.ClientSet.Core().Pods(f.Namespace.Name).Create(newTestPod(f, "over-max-oir", requests, limits)) return err } - predicate := func(e *api.Event) bool { + predicate := func(e *v1.Event) bool { return e.Type == "Warning" && e.Reason == "FailedScheduling" && strings.Contains(e.Message, "failed to fit in any node") @@ -133,20 +134,20 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun It("should account opaque integer resources in pods with multiple containers.", func() { By("Creating a pod with two containers that together require less of the opaque resource than is allocatable on a node") - requests := api.ResourceList{opaqueResName: resource.MustParse("1")} - limits := api.ResourceList{} + requests := v1.ResourceList{opaqueResName: resource.MustParse("1")} + limits := v1.ResourceList{} image := framework.GetPauseImageName(f.ClientSet) // This pod consumes 2 "foo" resources. - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "mult-container-oir", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "pause", Image: image, - Resources: api.ResourceRequirements{ + Resources: v1.ResourceRequirements{ Requests: requests, Limits: limits, }, @@ -154,7 +155,7 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun { Name: "pause-sidecar", Image: image, - Resources: api.ResourceRequirements{ + Resources: v1.ResourceRequirements{ Requests: requests, Limits: limits, }, @@ -168,8 +169,8 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun _, err := f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) return err } - predicate := func(e *api.Event) bool { - return e.Type == api.EventTypeNormal && + predicate := func(e *v1.Event) bool { + return e.Type == v1.EventTypeNormal && e.Reason == "Scheduled" && strings.Contains(e.Message, fmt.Sprintf("Successfully assigned %v to %v", pod.Name, node.Name)) } @@ -178,19 +179,19 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun Expect(success).To(Equal(true)) By("Creating a pod with two containers that together require more of the opaque resource than is allocatable on any node") - requests = api.ResourceList{opaqueResName: resource.MustParse("3")} - limits = api.ResourceList{} + requests = v1.ResourceList{opaqueResName: resource.MustParse("3")} + limits = v1.ResourceList{} // This pod consumes 6 "foo" resources. - pod = &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod = &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "mult-container-over-max-oir", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "pause", Image: image, - Resources: api.ResourceRequirements{ + Resources: v1.ResourceRequirements{ Requests: requests, Limits: limits, }, @@ -198,7 +199,7 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun { Name: "pause-sidecar", Image: image, - Resources: api.ResourceRequirements{ + Resources: v1.ResourceRequirements{ Requests: requests, Limits: limits, }, @@ -212,7 +213,7 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun _, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) return err } - predicate = func(e *api.Event) bool { + predicate = func(e *v1.Event) bool { return e.Type == "Warning" && e.Reason == "FailedScheduling" && strings.Contains(e.Message, "failed to fit in any node") @@ -224,12 +225,12 @@ var _ = framework.KubeDescribe("Opaque resources [Feature:OpaqueResources]", fun }) // Adds the opaque resource to a node. -func addOpaqueResource(f *framework.Framework, nodeName string, opaqueResName api.ResourceName) { +func addOpaqueResource(f *framework.Framework, nodeName string, opaqueResName v1.ResourceName) { action := func() error { patch := []byte(fmt.Sprintf(`[{"op": "add", "path": "/status/capacity/%s", "value": "5"}]`, escapeForJSONPatch(opaqueResName))) return f.ClientSet.Core().RESTClient().Patch(api.JSONPatchType).Resource("nodes").Name(nodeName).SubResource("status").Body(patch).Do().Error() } - predicate := func(n *api.Node) bool { + predicate := func(n *v1.Node) bool { capacity, foundCap := n.Status.Capacity[opaqueResName] allocatable, foundAlloc := n.Status.Allocatable[opaqueResName] return foundCap && capacity.MilliValue() == int64(5000) && @@ -241,13 +242,13 @@ func addOpaqueResource(f *framework.Framework, nodeName string, opaqueResName ap } // Removes the opaque resource from a node. -func removeOpaqueResource(f *framework.Framework, nodeName string, opaqueResName api.ResourceName) { +func removeOpaqueResource(f *framework.Framework, nodeName string, opaqueResName v1.ResourceName) { action := func() error { patch := []byte(fmt.Sprintf(`[{"op": "remove", "path": "/status/capacity/%s"}]`, escapeForJSONPatch(opaqueResName))) f.ClientSet.Core().RESTClient().Patch(api.JSONPatchType).Resource("nodes").Name(nodeName).SubResource("status").Body(patch).Do() return nil // Ignore error -- the opaque resource may not exist. } - predicate := func(n *api.Node) bool { + predicate := func(n *v1.Node) bool { _, foundCap := n.Status.Capacity[opaqueResName] _, foundAlloc := n.Status.Allocatable[opaqueResName] return !foundCap && !foundAlloc @@ -257,7 +258,7 @@ func removeOpaqueResource(f *framework.Framework, nodeName string, opaqueResName Expect(success).To(Equal(true)) } -func escapeForJSONPatch(resName api.ResourceName) string { +func escapeForJSONPatch(resName v1.ResourceName) string { // Escape forward slashes in the resource name per the JSON Pointer spec. // See https://tools.ietf.org/html/rfc6901#section-3 return strings.Replace(string(resName), "/", "~1", -1) @@ -265,7 +266,7 @@ func escapeForJSONPatch(resName api.ResourceName) string { // Returns true if a node update matching the predicate was emitted from the // system after performing the supplied action. -func observeNodeUpdateAfterAction(f *framework.Framework, nodeName string, nodePredicate func(*api.Node) bool, action func() error) (bool, error) { +func observeNodeUpdateAfterAction(f *framework.Framework, nodeName string, nodePredicate func(*v1.Node) bool, action func() error) (bool, error) { observedMatchingNode := false nodeSelector := fields.OneTermEqualSelector("metadata.name", nodeName) informerStartedChan := make(chan struct{}) @@ -273,24 +274,24 @@ func observeNodeUpdateAfterAction(f *framework.Framework, nodeName string, nodeP _, controller := cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - options.FieldSelector = nodeSelector + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + options.FieldSelector = nodeSelector.String() ls, err := f.ClientSet.Core().Nodes().List(options) return ls, err }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - options.FieldSelector = nodeSelector + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + options.FieldSelector = nodeSelector.String() w, err := f.ClientSet.Core().Nodes().Watch(options) // Signal parent goroutine that watching has begun. informerStartedGuard.Do(func() { close(informerStartedChan) }) return w, err }, }, - &api.Node{}, + &v1.Node{}, 0, cache.ResourceEventHandlerFuncs{ UpdateFunc: func(oldObj, newObj interface{}) { - n, ok := newObj.(*api.Node) + n, ok := newObj.(*v1.Node) Expect(ok).To(Equal(true)) if nodePredicate(n) { observedMatchingNode = true @@ -323,26 +324,26 @@ func observeNodeUpdateAfterAction(f *framework.Framework, nodeName string, nodeP // Returns true if an event matching the predicate was emitted from the system // after performing the supplied action. -func observeEventAfterAction(f *framework.Framework, eventPredicate func(*api.Event) bool, action func() error) (bool, error) { +func observeEventAfterAction(f *framework.Framework, eventPredicate func(*v1.Event) bool, action func() error) (bool, error) { observedMatchingEvent := false // Create an informer to list/watch events from the test framework namespace. _, controller := cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { ls, err := f.ClientSet.Core().Events(f.Namespace.Name).List(options) return ls, err }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { w, err := f.ClientSet.Core().Events(f.Namespace.Name).Watch(options) return w, err }, }, - &api.Event{}, + &v1.Event{}, 0, cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { - e, ok := obj.(*api.Event) + e, ok := obj.(*v1.Event) By(fmt.Sprintf("Considering event: \nType = [%s], Reason = [%s], Message = [%s]", e.Type, e.Reason, e.Message)) Expect(ok).To(Equal(true)) if ok && eventPredicate(e) { diff --git a/test/e2e/pd.go b/test/e2e/pd.go index 7f1a70c14d2..5173612fa8f 100644 --- a/test/e2e/pd.go +++ b/test/e2e/pd.go @@ -30,11 +30,11 @@ import ( "github.com/aws/aws-sdk-go/service/ec2" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" awscloud "k8s.io/kubernetes/pkg/cloudprovider/providers/aws" gcecloud "k8s.io/kubernetes/pkg/cloudprovider/providers/gce" "k8s.io/kubernetes/pkg/types" @@ -54,8 +54,8 @@ const ( var _ = framework.KubeDescribe("Pod Disks", func() { var ( - podClient unversionedcore.PodInterface - nodeClient unversionedcore.NodeInterface + podClient v1core.PodInterface + nodeClient v1core.NodeInterface host0Name types.NodeName host1Name types.NodeName ) @@ -91,8 +91,8 @@ var _ = framework.KubeDescribe("Pod Disks", func() { // Teardown pods, PD. Ignore errors. // Teardown should do nothing unless test failed. By("cleaning up PD-RW test environment") - podClient.Delete(host0Pod.Name, api.NewDeleteOptions(0)) - podClient.Delete(host1Pod.Name, api.NewDeleteOptions(0)) + podClient.Delete(host0Pod.Name, v1.NewDeleteOptions(0)) + podClient.Delete(host1Pod.Name, v1.NewDeleteOptions(0)) detachAndDeletePDs(diskName, []types.NodeName{host0Name, host1Name}) }() @@ -113,7 +113,7 @@ var _ = framework.KubeDescribe("Pod Disks", func() { By("deleting host0Pod") // Delete pod with 0 grace period - framework.ExpectNoError(podClient.Delete(host0Pod.Name, api.NewDeleteOptions(0)), "Failed to delete host0Pod") + framework.ExpectNoError(podClient.Delete(host0Pod.Name, v1.NewDeleteOptions(0)), "Failed to delete host0Pod") By("submitting host1Pod to kubernetes") _, err = podClient.Create(host1Pod) @@ -131,7 +131,7 @@ var _ = framework.KubeDescribe("Pod Disks", func() { framework.ExpectNoError(waitForPDInVolumesInUse(nodeClient, diskName, host0Name, nodeStatusTimeout, false /* shouldExist */)) By("deleting host1Pod") - framework.ExpectNoError(podClient.Delete(host1Pod.Name, api.NewDeleteOptions(0)), "Failed to delete host1Pod") + framework.ExpectNoError(podClient.Delete(host1Pod.Name, v1.NewDeleteOptions(0)), "Failed to delete host1Pod") By("Test completed successfully, waiting for PD to safely detach") waitForPDDetach(diskName, host0Name) @@ -155,8 +155,8 @@ var _ = framework.KubeDescribe("Pod Disks", func() { // Teardown pods, PD. Ignore errors. // Teardown should do nothing unless test failed. By("cleaning up PD-RW test environment") - podClient.Delete(host0Pod.Name, &api.DeleteOptions{}) - podClient.Delete(host1Pod.Name, &api.DeleteOptions{}) + podClient.Delete(host0Pod.Name, &v1.DeleteOptions{}) + podClient.Delete(host1Pod.Name, &v1.DeleteOptions{}) detachAndDeletePDs(diskName, []types.NodeName{host0Name, host1Name}) }() @@ -177,7 +177,7 @@ var _ = framework.KubeDescribe("Pod Disks", func() { By("deleting host0Pod") // Delete pod with default grace period 30s - framework.ExpectNoError(podClient.Delete(host0Pod.Name, &api.DeleteOptions{}), "Failed to delete host0Pod") + framework.ExpectNoError(podClient.Delete(host0Pod.Name, &v1.DeleteOptions{}), "Failed to delete host0Pod") By("submitting host1Pod to kubernetes") _, err = podClient.Create(host1Pod) @@ -195,7 +195,7 @@ var _ = framework.KubeDescribe("Pod Disks", func() { framework.ExpectNoError(waitForPDInVolumesInUse(nodeClient, diskName, host0Name, nodeStatusTimeout, false /* shouldExist */)) By("deleting host1Pod") - framework.ExpectNoError(podClient.Delete(host1Pod.Name, &api.DeleteOptions{}), "Failed to delete host1Pod") + framework.ExpectNoError(podClient.Delete(host1Pod.Name, &v1.DeleteOptions{}), "Failed to delete host1Pod") By("Test completed successfully, waiting for PD to safely detach") waitForPDDetach(diskName, host0Name) @@ -219,9 +219,9 @@ var _ = framework.KubeDescribe("Pod Disks", func() { By("cleaning up PD-RO test environment") // Teardown pods, PD. Ignore errors. // Teardown should do nothing unless test failed. - podClient.Delete(rwPod.Name, api.NewDeleteOptions(0)) - podClient.Delete(host0ROPod.Name, api.NewDeleteOptions(0)) - podClient.Delete(host1ROPod.Name, api.NewDeleteOptions(0)) + podClient.Delete(rwPod.Name, v1.NewDeleteOptions(0)) + podClient.Delete(host0ROPod.Name, v1.NewDeleteOptions(0)) + podClient.Delete(host1ROPod.Name, v1.NewDeleteOptions(0)) detachAndDeletePDs(diskName, []types.NodeName{host0Name, host1Name}) }() @@ -230,7 +230,7 @@ var _ = framework.KubeDescribe("Pod Disks", func() { framework.ExpectNoError(err, "Failed to create rwPod") framework.ExpectNoError(f.WaitForPodRunningSlow(rwPod.Name)) // Delete pod with 0 grace period - framework.ExpectNoError(podClient.Delete(rwPod.Name, api.NewDeleteOptions(0)), "Failed to delete host0Pod") + framework.ExpectNoError(podClient.Delete(rwPod.Name, v1.NewDeleteOptions(0)), "Failed to delete host0Pod") framework.ExpectNoError(waitForPDDetach(diskName, host0Name)) By("submitting host0ROPod to kubernetes") @@ -246,10 +246,10 @@ var _ = framework.KubeDescribe("Pod Disks", func() { framework.ExpectNoError(f.WaitForPodRunningSlow(host1ROPod.Name)) By("deleting host0ROPod") - framework.ExpectNoError(podClient.Delete(host0ROPod.Name, api.NewDeleteOptions(0)), "Failed to delete host0ROPod") + framework.ExpectNoError(podClient.Delete(host0ROPod.Name, v1.NewDeleteOptions(0)), "Failed to delete host0ROPod") By("deleting host1ROPod") - framework.ExpectNoError(podClient.Delete(host1ROPod.Name, api.NewDeleteOptions(0)), "Failed to delete host1ROPod") + framework.ExpectNoError(podClient.Delete(host1ROPod.Name, v1.NewDeleteOptions(0)), "Failed to delete host1ROPod") By("Test completed successfully, waiting for PD to safely detach") waitForPDDetach(diskName, host0Name) @@ -271,9 +271,9 @@ var _ = framework.KubeDescribe("Pod Disks", func() { By("cleaning up PD-RO test environment") // Teardown pods, PD. Ignore errors. // Teardown should do nothing unless test failed. - podClient.Delete(rwPod.Name, &api.DeleteOptions{}) - podClient.Delete(host0ROPod.Name, &api.DeleteOptions{}) - podClient.Delete(host1ROPod.Name, &api.DeleteOptions{}) + podClient.Delete(rwPod.Name, &v1.DeleteOptions{}) + podClient.Delete(host0ROPod.Name, &v1.DeleteOptions{}) + podClient.Delete(host1ROPod.Name, &v1.DeleteOptions{}) detachAndDeletePDs(diskName, []types.NodeName{host0Name, host1Name}) }() @@ -282,7 +282,7 @@ var _ = framework.KubeDescribe("Pod Disks", func() { framework.ExpectNoError(err, "Failed to create rwPod") framework.ExpectNoError(f.WaitForPodRunningSlow(rwPod.Name)) // Delete pod with default grace period 30s - framework.ExpectNoError(podClient.Delete(rwPod.Name, &api.DeleteOptions{}), "Failed to delete host0Pod") + framework.ExpectNoError(podClient.Delete(rwPod.Name, &v1.DeleteOptions{}), "Failed to delete host0Pod") framework.ExpectNoError(waitForPDDetach(diskName, host0Name)) By("submitting host0ROPod to kubernetes") @@ -298,10 +298,10 @@ var _ = framework.KubeDescribe("Pod Disks", func() { framework.ExpectNoError(f.WaitForPodRunningSlow(host1ROPod.Name)) By("deleting host0ROPod") - framework.ExpectNoError(podClient.Delete(host0ROPod.Name, &api.DeleteOptions{}), "Failed to delete host0ROPod") + framework.ExpectNoError(podClient.Delete(host0ROPod.Name, &v1.DeleteOptions{}), "Failed to delete host0ROPod") By("deleting host1ROPod") - framework.ExpectNoError(podClient.Delete(host1ROPod.Name, &api.DeleteOptions{}), "Failed to delete host1ROPod") + framework.ExpectNoError(podClient.Delete(host1ROPod.Name, &v1.DeleteOptions{}), "Failed to delete host1ROPod") By("Test completed successfully, waiting for PD to safely detach") waitForPDDetach(diskName, host0Name) @@ -315,14 +315,14 @@ var _ = framework.KubeDescribe("Pod Disks", func() { diskName, err := createPDWithRetry() framework.ExpectNoError(err, "Error creating PD") numContainers := 4 - var host0Pod *api.Pod + var host0Pod *v1.Pod defer func() { By("cleaning up PD-RW test environment") // Teardown pods, PD. Ignore errors. // Teardown should do nothing unless test failed. if host0Pod != nil { - podClient.Delete(host0Pod.Name, api.NewDeleteOptions(0)) + podClient.Delete(host0Pod.Name, v1.NewDeleteOptions(0)) } detachAndDeletePDs(diskName, []types.NodeName{host0Name}) }() @@ -354,7 +354,7 @@ var _ = framework.KubeDescribe("Pod Disks", func() { verifyPDContentsViaContainer(f, host0Pod.Name, containerName, fileAndContentToVerify) By("deleting host0Pod") - framework.ExpectNoError(podClient.Delete(host0Pod.Name, api.NewDeleteOptions(0)), "Failed to delete host0Pod") + framework.ExpectNoError(podClient.Delete(host0Pod.Name, v1.NewDeleteOptions(0)), "Failed to delete host0Pod") } By("Test completed successfully, waiting for PD to safely detach") @@ -370,14 +370,14 @@ var _ = framework.KubeDescribe("Pod Disks", func() { By("creating PD2") disk2Name, err := createPDWithRetry() framework.ExpectNoError(err, "Error creating PD2") - var host0Pod *api.Pod + var host0Pod *v1.Pod defer func() { By("cleaning up PD-RW test environment") // Teardown pods, PD. Ignore errors. // Teardown should do nothing unless test failed. if host0Pod != nil { - podClient.Delete(host0Pod.Name, api.NewDeleteOptions(0)) + podClient.Delete(host0Pod.Name, v1.NewDeleteOptions(0)) } detachAndDeletePDs(disk1Name, []types.NodeName{host0Name}) detachAndDeletePDs(disk2Name, []types.NodeName{host0Name}) @@ -413,7 +413,7 @@ var _ = framework.KubeDescribe("Pod Disks", func() { verifyPDContentsViaContainer(f, host0Pod.Name, containerName, fileAndContentToVerify) By("deleting host0Pod") - framework.ExpectNoError(podClient.Delete(host0Pod.Name, api.NewDeleteOptions(0)), "Failed to delete host0Pod") + framework.ExpectNoError(podClient.Delete(host0Pod.Name, v1.NewDeleteOptions(0)), "Failed to delete host0Pod") } By("Test completed successfully, waiting for PD to safely detach") @@ -590,8 +590,8 @@ func detachPD(nodeName types.NodeName, pdName string) error { } } -func testPDPod(diskNames []string, targetNode types.NodeName, readOnly bool, numContainers int) *api.Pod { - containers := make([]api.Container, numContainers) +func testPDPod(diskNames []string, targetNode types.NodeName, readOnly bool, numContainers int) *v1.Pod { + containers := make([]v1.Container, numContainers) for i := range containers { containers[i].Name = "mycontainer" if numContainers > 1 { @@ -602,37 +602,37 @@ func testPDPod(diskNames []string, targetNode types.NodeName, readOnly bool, num containers[i].Command = []string{"sleep", "6000"} - containers[i].VolumeMounts = make([]api.VolumeMount, len(diskNames)) + containers[i].VolumeMounts = make([]v1.VolumeMount, len(diskNames)) for k := range diskNames { containers[i].VolumeMounts[k].Name = fmt.Sprintf("testpd%v", k+1) containers[i].VolumeMounts[k].MountPath = fmt.Sprintf("/testpd%v", k+1) } - containers[i].Resources.Limits = api.ResourceList{} - containers[i].Resources.Limits[api.ResourceCPU] = *resource.NewQuantity(int64(0), resource.DecimalSI) + containers[i].Resources.Limits = v1.ResourceList{} + containers[i].Resources.Limits[v1.ResourceCPU] = *resource.NewQuantity(int64(0), resource.DecimalSI) } - pod := &api.Pod{ + pod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "pd-test-" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ Containers: containers, NodeName: string(targetNode), }, } if framework.TestContext.Provider == "gce" || framework.TestContext.Provider == "gke" { - pod.Spec.Volumes = make([]api.Volume, len(diskNames)) + pod.Spec.Volumes = make([]v1.Volume, len(diskNames)) for k, diskName := range diskNames { pod.Spec.Volumes[k].Name = fmt.Sprintf("testpd%v", k+1) - pod.Spec.Volumes[k].VolumeSource = api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + pod.Spec.Volumes[k].VolumeSource = v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: diskName, FSType: "ext4", ReadOnly: readOnly, @@ -640,11 +640,11 @@ func testPDPod(diskNames []string, targetNode types.NodeName, readOnly bool, num } } } else if framework.TestContext.Provider == "aws" { - pod.Spec.Volumes = make([]api.Volume, len(diskNames)) + pod.Spec.Volumes = make([]v1.Volume, len(diskNames)) for k, diskName := range diskNames { pod.Spec.Volumes[k].Name = fmt.Sprintf("testpd%v", k+1) - pod.Spec.Volumes[k].VolumeSource = api.VolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{ + pod.Spec.Volumes[k].VolumeSource = v1.VolumeSource{ + AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: diskName, FSType: "ext4", ReadOnly: readOnly, @@ -711,7 +711,7 @@ func detachAndDeletePDs(diskName string, hosts []types.NodeName) { } func waitForPDInVolumesInUse( - nodeClient unversionedcore.NodeInterface, + nodeClient v1core.NodeInterface, diskName string, nodeName types.NodeName, timeout time.Duration, diff --git a/test/e2e/persistent_volumes.go b/test/e2e/persistent_volumes.go index 80c47db1c8a..9f65df8ec1b 100644 --- a/test/e2e/persistent_volumes.go +++ b/test/e2e/persistent_volumes.go @@ -22,12 +22,12 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "k8s.io/kubernetes/pkg/api" apierrs "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/volume/util/volumehelper" "k8s.io/kubernetes/test/e2e/framework" @@ -97,7 +97,7 @@ func pvPvcCleanup(c clientset.Interface, ns string, pvols pvmap, claims pvcmap) // Delete the PVC and wait for the PV to become Available again. Validate that the PV // has recycled (assumption here about reclaimPolicy). Caller tells this func which // phase value to expect for the pv bound to the to-be-deleted claim. -func deletePVCandValidatePV(c clientset.Interface, ns string, pvc *api.PersistentVolumeClaim, pv *api.PersistentVolume, expctPVPhase api.PersistentVolumePhase) { +func deletePVCandValidatePV(c clientset.Interface, ns string, pvc *v1.PersistentVolumeClaim, pv *v1.PersistentVolume, expctPVPhase v1.PersistentVolumePhase) { pvname := pvc.Spec.VolumeName framework.Logf("Deleting PVC %v to trigger recycling of PV %v", pvc.Name, pvname) @@ -118,11 +118,11 @@ func deletePVCandValidatePV(c clientset.Interface, ns string, pvc *api.Persisten pv, err = c.Core().PersistentVolumes().Get(pv.Name) Expect(err).NotTo(HaveOccurred()) cr := pv.Spec.ClaimRef - if expctPVPhase == api.VolumeAvailable { + if expctPVPhase == v1.VolumeAvailable { if cr != nil { // may be ok if cr != nil Expect(len(cr.UID)).To(BeZero()) } - } else if expctPVPhase == api.VolumeBound { + } else if expctPVPhase == v1.VolumeBound { Expect(cr).NotTo(BeNil()) Expect(len(cr.UID)).NotTo(BeZero()) } @@ -137,7 +137,7 @@ func deletePVCandValidatePV(c clientset.Interface, ns string, pvc *api.Persisten func deletePVCandValidatePVGroup(c clientset.Interface, ns string, pvols pvmap, claims pvcmap) { var boundPVs, deletedPVCs int - var expctPVPhase api.PersistentVolumePhase + var expctPVPhase v1.PersistentVolumePhase for pvName := range pvols { pv, err := c.Core().PersistentVolumes().Get(pvName) @@ -156,11 +156,11 @@ func deletePVCandValidatePVGroup(c clientset.Interface, ns string, pvols pvmap, // what Phase do we expect the PV that was bound to the claim to // be in after that claim is deleted? - expctPVPhase = api.VolumeAvailable + expctPVPhase = v1.VolumeAvailable if len(claims) > len(pvols) { // there are excess pvcs so expect the previously bound // PV to become bound again - expctPVPhase = api.VolumeBound + expctPVPhase = v1.VolumeBound } deletePVCandValidatePV(c, ns, pvc, pv, expctPVPhase) @@ -172,7 +172,7 @@ func deletePVCandValidatePVGroup(c clientset.Interface, ns string, pvols pvmap, } // create the PV resource. Fails test on error. -func createPV(c clientset.Interface, pv *api.PersistentVolume) *api.PersistentVolume { +func createPV(c clientset.Interface, pv *v1.PersistentVolume) *v1.PersistentVolume { pv, err := c.Core().PersistentVolumes().Create(pv) Expect(err).NotTo(HaveOccurred()) @@ -180,7 +180,7 @@ func createPV(c clientset.Interface, pv *api.PersistentVolume) *api.PersistentVo } // create the PVC resource. Fails test on error. -func createPVC(c clientset.Interface, ns string, pvc *api.PersistentVolumeClaim) *api.PersistentVolumeClaim { +func createPVC(c clientset.Interface, ns string, pvc *v1.PersistentVolumeClaim) *v1.PersistentVolumeClaim { pvc, err := c.Core().PersistentVolumeClaims(ns).Create(pvc) Expect(err).NotTo(HaveOccurred()) @@ -193,9 +193,9 @@ func createPVC(c clientset.Interface, ns string, pvc *api.PersistentVolumeClaim) // Note: in the pre-bind case the real PVC name, which is generated, is not // known until after the PVC is instantiated. This is why the pvc is created // before the pv. -func createPVCPV(c clientset.Interface, serverIP, ns string, preBind bool) (*api.PersistentVolume, *api.PersistentVolumeClaim) { +func createPVCPV(c clientset.Interface, serverIP, ns string, preBind bool) (*v1.PersistentVolume, *v1.PersistentVolumeClaim) { - var bindTo *api.PersistentVolumeClaim + var bindTo *v1.PersistentVolumeClaim var preBindMsg string // make the pvc definition first @@ -227,7 +227,7 @@ func createPVCPV(c clientset.Interface, serverIP, ns string, preBind bool) (*api // Note: in the pre-bind case the real PV name, which is generated, is not // known until after the PV is instantiated. This is why the pv is created // before the pvc. -func createPVPVC(c clientset.Interface, serverIP, ns string, preBind bool) (*api.PersistentVolume, *api.PersistentVolumeClaim) { +func createPVPVC(c clientset.Interface, serverIP, ns string, preBind bool) (*v1.PersistentVolume, *v1.PersistentVolumeClaim) { preBindMsg := "" if preBind { @@ -256,8 +256,8 @@ func createPVPVC(c clientset.Interface, serverIP, ns string, preBind bool) (*api func createPVsPVCs(numpvs, numpvcs int, c clientset.Interface, ns, serverIP string) (pvmap, pvcmap) { var i int - var pv *api.PersistentVolume - var pvc *api.PersistentVolumeClaim + var pv *v1.PersistentVolume + var pvc *v1.PersistentVolumeClaim pvMap := make(pvmap, numpvs) pvcMap := make(pvcmap, numpvcs) @@ -292,16 +292,16 @@ func createPVsPVCs(numpvs, numpvcs int, c clientset.Interface, ns, serverIP stri } // Wait for the pv and pvc to bind to each other. -func waitOnPVandPVC(c clientset.Interface, ns string, pv *api.PersistentVolume, pvc *api.PersistentVolumeClaim) { +func waitOnPVandPVC(c clientset.Interface, ns string, pv *v1.PersistentVolume, pvc *v1.PersistentVolumeClaim) { // Wait for newly created PVC to bind to the PV framework.Logf("Waiting for PV %v to bind to PVC %v", pv.Name, pvc.Name) - err := framework.WaitForPersistentVolumeClaimPhase(api.ClaimBound, c, ns, pvc.Name, 3*time.Second, 300*time.Second) + err := framework.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, c, ns, pvc.Name, 3*time.Second, 300*time.Second) Expect(err).NotTo(HaveOccurred()) // Wait for PersistentVolume.Status.Phase to be Bound, which it should be // since the PVC is already bound. - err = framework.WaitForPersistentVolumePhase(api.VolumeBound, c, pv.Name, 3*time.Second, 300*time.Second) + err = framework.WaitForPersistentVolumePhase(v1.VolumeBound, c, pv.Name, 3*time.Second, 300*time.Second) Expect(err).NotTo(HaveOccurred()) // Re-get the pv and pvc objects @@ -335,7 +335,7 @@ func waitAndVerifyBinds(c clientset.Interface, ns string, pvols pvmap, claims pv } for pvName := range pvols { - err := framework.WaitForPersistentVolumePhase(api.VolumeBound, c, pvName, 3*time.Second, 180*time.Second) + err := framework.WaitForPersistentVolumePhase(v1.VolumeBound, c, pvName, 3*time.Second, 180*time.Second) if err != nil && len(pvols) > len(claims) { framework.Logf("WARN: pv %v is not bound after max wait", pvName) framework.Logf(" This may be ok since there are more pvs than pvcs") @@ -352,7 +352,7 @@ func waitAndVerifyBinds(c clientset.Interface, ns string, pvols pvmap, claims pv _, found := claims[pvcKey] Expect(found).To(BeTrue()) - err = framework.WaitForPersistentVolumeClaimPhase(api.ClaimBound, c, ns, cr.Name, 3*time.Second, 180*time.Second) + err = framework.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, c, ns, cr.Name, 3*time.Second, 180*time.Second) Expect(err).NotTo(HaveOccurred()) actualBinds++ } @@ -364,7 +364,7 @@ func waitAndVerifyBinds(c clientset.Interface, ns string, pvols pvmap, claims pv } // Test the pod's exit code to be zero. -func testPodSuccessOrFail(c clientset.Interface, ns string, pod *api.Pod) { +func testPodSuccessOrFail(c clientset.Interface, ns string, pod *v1.Pod) { By("Pod should terminate with exitcode 0 (success)") err := framework.WaitForPodSuccessInNamespace(c, pod.Name, ns) @@ -373,7 +373,7 @@ func testPodSuccessOrFail(c clientset.Interface, ns string, pod *api.Pod) { } // Delete the passed in pod. -func deletePod(f *framework.Framework, c clientset.Interface, ns string, pod *api.Pod) { +func deletePod(f *framework.Framework, c clientset.Interface, ns string, pod *v1.Pod) { framework.Logf("Deleting pod %v", pod.Name) err := c.Core().Pods(ns).Delete(pod.Name, nil) @@ -408,7 +408,7 @@ func createWaitAndDeletePod(f *framework.Framework, c clientset.Interface, ns st // Validate PV/PVC, create and verify writer pod, delete the PVC, and validate the PV's // phase. Note: the PV is deleted in the AfterEach, not here. -func completeTest(f *framework.Framework, c clientset.Interface, ns string, pv *api.PersistentVolume, pvc *api.PersistentVolumeClaim) { +func completeTest(f *framework.Framework, c clientset.Interface, ns string, pv *v1.PersistentVolume, pvc *v1.PersistentVolumeClaim) { // 1. verify that the PV and PVC have binded correctly By("Validating the PV-PVC binding") @@ -421,7 +421,7 @@ func completeTest(f *framework.Framework, c clientset.Interface, ns string, pv * // 3. delete the PVC, wait for PV to become "Available" By("Deleting the PVC to invoke the recycler") - deletePVCandValidatePV(c, ns, pvc, pv, api.VolumeAvailable) + deletePVCandValidatePV(c, ns, pvc, pv, v1.VolumeAvailable) } // Validate pairs of PVs and PVCs, create and verify writer pod, delete PVC and validate @@ -460,11 +460,11 @@ var _ = framework.KubeDescribe("PersistentVolumes", func() { var ns string var NFSconfig VolumeTestConfig var serverIP string - var nfsServerPod *api.Pod + var nfsServerPod *v1.Pod // config for the nfs-server pod in the default namespace NFSconfig = VolumeTestConfig{ - namespace: api.NamespaceDefault, + namespace: v1.NamespaceDefault, prefix: "nfs", serverImage: "gcr.io/google_containers/volume-nfs:0.7", serverPorts: []int{2049}, @@ -496,8 +496,8 @@ var _ = framework.KubeDescribe("PersistentVolumes", func() { Context("with Single PV - PVC pairs", func() { - var pv *api.PersistentVolume - var pvc *api.PersistentVolumeClaim + var pv *v1.PersistentVolume + var pvc *v1.PersistentVolumeClaim // Note: this is the only code where the pv is deleted. AfterEach(func() { @@ -627,41 +627,41 @@ func makePvcKey(ns, name string) types.NamespacedName { // (instantiated) and thus the PV's ClaimRef cannot be completely filled-in in // this func. Therefore, the ClaimRef's name is added later in // createPVCPV. -func makePersistentVolume(serverIP string, pvc *api.PersistentVolumeClaim) *api.PersistentVolume { +func makePersistentVolume(serverIP string, pvc *v1.PersistentVolumeClaim) *v1.PersistentVolume { // Specs are expected to match this test's PersistentVolumeClaim - var claimRef *api.ObjectReference + var claimRef *v1.ObjectReference if pvc != nil { - claimRef = &api.ObjectReference{ + claimRef = &v1.ObjectReference{ Name: pvc.Name, Namespace: pvc.Namespace, } } - return &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ + return &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "nfs-", Annotations: map[string]string{ volumehelper.VolumeGidAnnotationKey: "777", }, }, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimRecycle, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("2Gi"), + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimRecycle, + Capacity: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("2Gi"), }, - PersistentVolumeSource: api.PersistentVolumeSource{ - NFS: &api.NFSVolumeSource{ + PersistentVolumeSource: v1.PersistentVolumeSource{ + NFS: &v1.NFSVolumeSource{ Server: serverIP, Path: "/exports", ReadOnly: false, }, }, - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, }, ClaimRef: claimRef, }, @@ -672,23 +672,23 @@ func makePersistentVolume(serverIP string, pvc *api.PersistentVolumeClaim) *api. // Note: if this PVC is intended to be pre-bound to a PV, whose name is not // known until the PV is instantiated, then the func createPVPVC will add // pvc.Spec.VolumeName to this claim. -func makePersistentVolumeClaim(ns string) *api.PersistentVolumeClaim { +func makePersistentVolumeClaim(ns string) *v1.PersistentVolumeClaim { // Specs are expected to match this test's PersistentVolume - return &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + return &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "pvc-", Namespace: ns, }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("1Gi"), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("1Gi"), }, }, }, @@ -697,44 +697,44 @@ func makePersistentVolumeClaim(ns string) *api.PersistentVolumeClaim { // Returns a pod definition based on the namespace. The pod references the PVC's // name. -func makeWritePod(ns string, pvcName string) *api.Pod { +func makeWritePod(ns string, pvcName string) *v1.Pod { // Prepare pod that mounts the NFS volume again and // checks that /mnt/index.html was scrubbed there var isPrivileged bool = true - return &api.Pod{ + return &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "write-pod-", Namespace: ns, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "write-pod", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"/bin/sh"}, Args: []string{"-c", "touch /mnt/SUCCESS && (id -G | grep -E '\\b777\\b')"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "nfs-pvc", MountPath: "/mnt", }, }, - SecurityContext: &api.SecurityContext{ + SecurityContext: &v1.SecurityContext{ Privileged: &isPrivileged, }, }, }, - RestartPolicy: api.RestartPolicyOnFailure, - Volumes: []api.Volume{ + RestartPolicy: v1.RestartPolicyOnFailure, + Volumes: []v1.Volume{ { Name: "nfs-pvc", - VolumeSource: api.VolumeSource{ - PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ + VolumeSource: v1.VolumeSource{ + PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: pvcName, }, }, diff --git a/test/e2e/petset.go b/test/e2e/petset.go index ad2a47ee40c..cc6b6486297 100644 --- a/test/e2e/petset.go +++ b/test/e2e/petset.go @@ -32,8 +32,9 @@ import ( apierrs "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/apps" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + apps "k8s.io/kubernetes/pkg/apis/apps/v1beta1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller/petset" "k8s.io/kubernetes/pkg/labels" klabels "k8s.io/kubernetes/pkg/labels" @@ -89,12 +90,12 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { "baz": "blah", } headlessSvcName := "test" - var petMounts, podMounts []api.VolumeMount + var petMounts, podMounts []v1.VolumeMount var ps *apps.StatefulSet BeforeEach(func() { - petMounts = []api.VolumeMount{{Name: "datadir", MountPath: "/data/"}} - podMounts = []api.VolumeMount{{Name: "home", MountPath: "/home"}} + petMounts = []v1.VolumeMount{{Name: "datadir", MountPath: "/data/"}} + podMounts = []v1.VolumeMount{{Name: "home", MountPath: "/home"}} ps = newStatefulSet(psName, ns, headlessSvcName, 2, petMounts, podMounts, labels) By("Creating service " + headlessSvcName + " in namespace " + ns) @@ -113,7 +114,7 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { It("should provide basic identity", func() { By("Creating statefulset " + psName + " in namespace " + ns) - ps.Spec.Replicas = 3 + *(ps.Spec.Replicas) = 3 setInitializedAnnotation(ps, "false") _, err := c.Apps().StatefulSets(ns).Create(ps) @@ -148,7 +149,7 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { It("should handle healthy pet restarts during scale", func() { By("Creating statefulset " + psName + " in namespace " + ns) - ps.Spec.Replicas = 2 + *(ps.Spec.Replicas) = 2 setInitializedAnnotation(ps, "false") _, err := c.Apps().StatefulSets(ns).Create(ps) @@ -183,14 +184,14 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { It("should allow template updates", func() { By("Creating stateful set " + psName + " in namespace " + ns) - ps.Spec.Replicas = 2 + *(ps.Spec.Replicas) = 2 ps, err := c.Apps().StatefulSets(ns).Create(ps) Expect(err).NotTo(HaveOccurred()) pst := statefulSetTester{c: c} - pst.waitForRunningAndReady(ps.Spec.Replicas, ps) + pst.waitForRunningAndReady(*ps.Spec.Replicas, ps) newImage := newNginxImage oldImage := ps.Spec.Template.Spec.Containers[0].Image @@ -206,10 +207,10 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { pst.deletePetAtIndex(updateIndex, ps) By("Waiting for all stateful pods to be running again") - pst.waitForRunningAndReady(ps.Spec.Replicas, ps) + pst.waitForRunningAndReady(*ps.Spec.Replicas, ps) By(fmt.Sprintf("Verifying stateful pod at index %d is updated", updateIndex)) - verify := func(pod *api.Pod) { + verify := func(pod *v1.Pod) { podImage := pod.Spec.Containers[0].Image Expect(podImage).To(Equal(newImage), fmt.Sprintf("Expected stateful pod image %s updated to %s", podImage, newImage)) } @@ -218,7 +219,7 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { It("Scaling down before scale up is finished should wait until current pod will be running and ready before it will be removed", func() { By("Creating stateful set " + psName + " in namespace " + ns + ", and pausing scale operations after each pod") - testProbe := &api.Probe{Handler: api.Handler{HTTPGet: &api.HTTPGetAction{ + testProbe := &v1.Probe{Handler: v1.Handler{HTTPGet: &v1.HTTPGetAction{ Path: "/index.html", Port: intstr.IntOrString{IntVal: 80}}}} ps := newStatefulSet(psName, ns, headlessSvcName, 1, nil, nil, labels) @@ -247,8 +248,8 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { expectedPodName := ps.Name + "-1" expectedPod, err := f.ClientSet.Core().Pods(ns).Get(expectedPodName) Expect(err).NotTo(HaveOccurred()) - watcher, err := f.ClientSet.Core().Pods(ns).Watch(api.SingleObject( - api.ObjectMeta{ + watcher, err := f.ClientSet.Core().Pods(ns).Watch(v1.SingleObject( + v1.ObjectMeta{ Name: expectedPod.Name, ResourceVersion: expectedPod.ResourceVersion, }, @@ -258,16 +259,16 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { By("Verifying the 2nd pod is removed only when it becomes running and ready") pst.restoreProbe(ps, testProbe) _, err = watch.Until(statefulsetTimeout, watcher, func(event watch.Event) (bool, error) { - pod := event.Object.(*api.Pod) + pod := event.Object.(*v1.Pod) if event.Type == watch.Deleted && pod.Name == expectedPodName { return false, fmt.Errorf("Pod %v was deleted before enter running", pod.Name) } framework.Logf("Observed event %v for pod %v. Phase %v, Pod is ready %v", - event.Type, pod.Name, pod.Status.Phase, api.IsPodReady(pod)) + event.Type, pod.Name, pod.Status.Phase, v1.IsPodReady(pod)) if pod.Name != expectedPodName { return false, nil } - if pod.Status.Phase == api.PodRunning && api.IsPodReady(pod) { + if pod.Status.Phase == v1.PodRunning && v1.IsPodReady(pod) { return true, nil } return false, nil @@ -278,13 +279,13 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { It("Scaling should happen in predictable order and halt if any pet is unhealthy", func() { psLabels := klabels.Set(labels) By("Initializing watcher for selector " + psLabels.String()) - watcher, err := f.ClientSet.Core().Pods(ns).Watch(api.ListOptions{ - LabelSelector: psLabels.AsSelector(), + watcher, err := f.ClientSet.Core().Pods(ns).Watch(v1.ListOptions{ + LabelSelector: psLabels.AsSelector().String(), }) Expect(err).NotTo(HaveOccurred()) By("Creating stateful set " + psName + " in namespace " + ns) - testProbe := &api.Probe{Handler: api.Handler{HTTPGet: &api.HTTPGetAction{ + testProbe := &v1.Probe{Handler: v1.Handler{HTTPGet: &v1.HTTPGetAction{ Path: "/index.html", Port: intstr.IntOrString{IntVal: 80}}}} ps := newStatefulSet(psName, ns, headlessSvcName, 1, nil, nil, psLabels) @@ -294,11 +295,11 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { By("Waiting until all stateful set " + psName + " replicas will be running in namespace " + ns) pst := &statefulSetTester{c: c} - pst.waitForRunningAndReady(ps.Spec.Replicas, ps) + pst.waitForRunningAndReady(*ps.Spec.Replicas, ps) By("Confirming that stateful set scale up will halt with unhealthy pet") pst.breakProbe(ps, testProbe) - pst.waitForRunningAndNotReady(ps.Spec.Replicas, ps) + pst.waitForRunningAndNotReady(*ps.Spec.Replicas, ps) pst.updateReplicas(ps, 3) pst.confirmPetCount(1, ps, 10*time.Second) @@ -312,7 +313,7 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { if event.Type != watch.Added { return false, nil } - pod := event.Object.(*api.Pod) + pod := event.Object.(*v1.Pod) if pod.Name == expectedOrder[0] { expectedOrder = expectedOrder[1:] } @@ -322,8 +323,8 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { Expect(err).NotTo(HaveOccurred()) By("Scale down will halt with unhealthy pet") - watcher, err = f.ClientSet.Core().Pods(ns).Watch(api.ListOptions{ - LabelSelector: psLabels.AsSelector(), + watcher, err = f.ClientSet.Core().Pods(ns).Watch(v1.ListOptions{ + LabelSelector: psLabels.AsSelector().String(), }) Expect(err).NotTo(HaveOccurred()) @@ -342,7 +343,7 @@ var _ = framework.KubeDescribe("StatefulSet [Slow]", func() { if event.Type != watch.Deleted { return false, nil } - pod := event.Object.(*api.Pod) + pod := event.Object.(*v1.Pod) if pod.Name == expectedOrder[0] { expectedOrder = expectedOrder[1:] } @@ -430,17 +431,17 @@ var _ = framework.KubeDescribe("Stateful Set recreate [Slow]", func() { node := nodes.Items[0] By("creating pod with conflicting port in namespace " + f.Namespace.Name) - conflictingPort := api.ContainerPort{HostPort: 21017, ContainerPort: 21017, Name: "conflict"} - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + conflictingPort := v1.ContainerPort{HostPort: 21017, ContainerPort: 21017, Name: "conflict"} + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "nginx", Image: "gcr.io/google_containers/nginx-slim:0.7", - Ports: []api.ContainerPort{conflictingPort}, + Ports: []v1.ContainerPort{conflictingPort}, }, }, NodeName: node.Name, @@ -464,11 +465,11 @@ var _ = framework.KubeDescribe("Stateful Set recreate [Slow]", func() { var initialPetPodUID types.UID By("waiting until pet pod " + petPodName + " will be recreated and deleted at least once in namespace " + f.Namespace.Name) - w, err := f.ClientSet.Core().Pods(f.Namespace.Name).Watch(api.SingleObject(api.ObjectMeta{Name: petPodName})) + w, err := f.ClientSet.Core().Pods(f.Namespace.Name).Watch(v1.SingleObject(v1.ObjectMeta{Name: petPodName})) framework.ExpectNoError(err) // we need to get UID from pod in any state and wait until stateful set controller will remove pod atleast once _, err = watch.Until(petPodTimeout, w, func(event watch.Event) (bool, error) { - pod := event.Object.(*api.Pod) + pod := event.Object.(*v1.Pod) switch event.Type { case watch.Deleted: framework.Logf("Observed delete event for pet pod %v in namespace %v", pod.Name, pod.Namespace) @@ -487,7 +488,7 @@ var _ = framework.KubeDescribe("Stateful Set recreate [Slow]", func() { } By("removing pod with conflicting port in namespace " + f.Namespace.Name) - err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(pod.Name, api.NewDeleteOptions(0)) + err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(pod.Name, v1.NewDeleteOptions(0)) framework.ExpectNoError(err) By("waiting when pet pod " + petPodName + " will be recreated in namespace " + f.Namespace.Name + " and will be in running state") @@ -497,7 +498,7 @@ var _ = framework.KubeDescribe("Stateful Set recreate [Slow]", func() { if err != nil { return err } - if petPod.Status.Phase != api.PodRunning { + if petPod.Status.Phase != v1.PodRunning { return fmt.Errorf("Pod %v is not in running phase: %v", petPod.Name, petPod.Status.Phase) } else if petPod.UID == initialPetPodUID { return fmt.Errorf("Pod %v wasn't recreated: %v == %v", petPod.Name, petPod.UID, initialPetPodUID) @@ -508,7 +509,7 @@ var _ = framework.KubeDescribe("Stateful Set recreate [Slow]", func() { }) func dumpDebugInfo(c clientset.Interface, ns string) { - pl, _ := c.Core().Pods(ns).List(api.ListOptions{LabelSelector: labels.Everything()}) + pl, _ := c.Core().Pods(ns).List(v1.ListOptions{LabelSelector: labels.Everything().String()}) for _, p := range pl.Items { desc, _ := framework.RunKubectl("describe", "po", p.Name, fmt.Sprintf("--namespace=%v", ns)) framework.Logf("\nOutput of kubectl describe %v:\n%v", p.Name, desc) @@ -557,7 +558,7 @@ func (c *clusterAppTester) run() { if restartCluster { By("Restarting stateful set " + ps.Name) c.tester.restart(ps) - c.tester.waitForRunningAndReady(ps.Spec.Replicas, ps) + c.tester.waitForRunningAndReady(*ps.Spec.Replicas, ps) } } @@ -746,9 +747,9 @@ func (p *statefulSetTester) createStatefulSet(manifestPath, ns string) *apps.Sta framework.Logf(fmt.Sprintf("creating " + ps.Name + " service")) framework.RunKubectlOrDie("create", "-f", mkpath("service.yaml"), fmt.Sprintf("--namespace=%v", ns)) - framework.Logf(fmt.Sprintf("creating statefulset %v/%v with %d replicas and selector %+v", ps.Namespace, ps.Name, ps.Spec.Replicas, ps.Spec.Selector)) + framework.Logf(fmt.Sprintf("creating statefulset %v/%v with %d replicas and selector %+v", ps.Namespace, ps.Name, *(ps.Spec.Replicas), ps.Spec.Selector)) framework.RunKubectlOrDie("create", "-f", mkpath("petset.yaml"), fmt.Sprintf("--namespace=%v", ns)) - p.waitForRunningAndReady(ps.Spec.Replicas, ps) + p.waitForRunningAndReady(*ps.Spec.Replicas, ps) return ps } @@ -797,7 +798,7 @@ func (p *statefulSetTester) checkHostname(ps *apps.StatefulSet) error { func (p *statefulSetTester) saturate(ps *apps.StatefulSet) { // TODO: Watch events and check that creation timestamps don't overlap var i int32 - for i = 0; i < ps.Spec.Replicas; i++ { + for i = 0; i < *(ps.Spec.Replicas); i++ { framework.Logf("Waiting for pet at index " + fmt.Sprintf("%v", i+1) + " to enter Running") p.waitForRunningAndReady(i+1, ps) framework.Logf("Marking pet at index " + fmt.Sprintf("%v", i) + " healthy") @@ -808,12 +809,12 @@ func (p *statefulSetTester) saturate(ps *apps.StatefulSet) { func (p *statefulSetTester) deletePetAtIndex(index int, ps *apps.StatefulSet) { name := getPodNameAtIndex(index, ps) noGrace := int64(0) - if err := p.c.Core().Pods(ps.Namespace).Delete(name, &api.DeleteOptions{GracePeriodSeconds: &noGrace}); err != nil { + if err := p.c.Core().Pods(ps.Namespace).Delete(name, &v1.DeleteOptions{GracePeriodSeconds: &noGrace}); err != nil { framework.Failf("Failed to delete pet %v for StatefulSet %v/%v: %v", name, ps.Namespace, ps.Name, err) } } -type verifyPodFunc func(*api.Pod) +type verifyPodFunc func(*v1.Pod) func (p *statefulSetTester) verifyPodAtIndex(index int, ps *apps.StatefulSet, verify verifyPodFunc) { name := getPodNameAtIndex(index, ps) @@ -831,9 +832,9 @@ func getPodNameAtIndex(index int, ps *apps.StatefulSet) string { func (p *statefulSetTester) scale(ps *apps.StatefulSet, count int32) error { name := ps.Name ns := ps.Namespace - p.update(ns, name, func(ps *apps.StatefulSet) { ps.Spec.Replicas = count }) + p.update(ns, name, func(ps *apps.StatefulSet) { *(ps.Spec.Replicas) = count }) - var petList *api.PodList + var petList *v1.PodList pollErr := wait.PollImmediate(statefulsetPoll, statefulsetTimeout, func() (bool, error) { petList = p.getPodList(ps) if int32(len(petList.Items)) == count { @@ -844,8 +845,8 @@ func (p *statefulSetTester) scale(ps *apps.StatefulSet, count int32) error { if pollErr != nil { unhealthy := []string{} for _, pet := range petList.Items { - delTs, phase, readiness := pet.DeletionTimestamp, pet.Status.Phase, api.IsPodReady(&pet) - if delTs != nil || phase != api.PodRunning || !readiness { + delTs, phase, readiness := pet.DeletionTimestamp, pet.Status.Phase, v1.IsPodReady(&pet) + if delTs != nil || phase != v1.PodRunning || !readiness { unhealthy = append(unhealthy, fmt.Sprintf("%v: deletion %v, phase %v, readiness %v", pet.Name, delTs, phase, readiness)) } } @@ -855,13 +856,13 @@ func (p *statefulSetTester) scale(ps *apps.StatefulSet, count int32) error { } func (p *statefulSetTester) updateReplicas(ps *apps.StatefulSet, count int32) { - p.update(ps.Namespace, ps.Name, func(ps *apps.StatefulSet) { ps.Spec.Replicas = count }) + p.update(ps.Namespace, ps.Name, func(ps *apps.StatefulSet) { ps.Spec.Replicas = &count }) } func (p *statefulSetTester) restart(ps *apps.StatefulSet) { - oldReplicas := ps.Spec.Replicas + oldReplicas := *(ps.Spec.Replicas) ExpectNoError(p.scale(ps, 0)) - p.update(ps.Namespace, ps.Name, func(ps *apps.StatefulSet) { ps.Spec.Replicas = oldReplicas }) + p.update(ps.Namespace, ps.Name, func(ps *apps.StatefulSet) { *(ps.Spec.Replicas) = oldReplicas }) } func (p *statefulSetTester) update(ns, name string, update func(ps *apps.StatefulSet)) { @@ -882,10 +883,10 @@ func (p *statefulSetTester) update(ns, name string, update func(ps *apps.Statefu framework.Failf("too many retries draining statefulset %q", name) } -func (p *statefulSetTester) getPodList(ps *apps.StatefulSet) *api.PodList { +func (p *statefulSetTester) getPodList(ps *apps.StatefulSet) *v1.PodList { selector, err := unversioned.LabelSelectorAsSelector(ps.Spec.Selector) ExpectNoError(err) - podList, err := p.c.Core().Pods(ps.Namespace).List(api.ListOptions{LabelSelector: selector}) + podList, err := p.c.Core().Pods(ps.Namespace).List(v1.ListOptions{LabelSelector: selector.String()}) ExpectNoError(err) return podList } @@ -916,10 +917,10 @@ func (p *statefulSetTester) waitForRunning(numPets int32, ps *apps.StatefulSet, return false, fmt.Errorf("Too many pods scheduled, expected %d got %d", numPets, len(podList.Items)) } for _, p := range podList.Items { - isReady := api.IsPodReady(&p) + isReady := v1.IsPodReady(&p) desiredReadiness := shouldBeReady == isReady - framework.Logf("Waiting for pod %v to enter %v - Ready=%v, currently %v - Ready=%v", p.Name, api.PodRunning, shouldBeReady, p.Status.Phase, isReady) - if p.Status.Phase != api.PodRunning || !desiredReadiness { + framework.Logf("Waiting for pod %v to enter %v - Ready=%v, currently %v - Ready=%v", p.Name, v1.PodRunning, shouldBeReady, p.Status.Phase, isReady) + if p.Status.Phase != v1.PodRunning || !desiredReadiness { return false, nil } } @@ -938,7 +939,7 @@ func (p *statefulSetTester) waitForRunningAndNotReady(numPets int32, ps *apps.St p.waitForRunning(numPets, ps, false) } -func (p *statefulSetTester) breakProbe(ps *apps.StatefulSet, probe *api.Probe) error { +func (p *statefulSetTester) breakProbe(ps *apps.StatefulSet, probe *v1.Probe) error { path := probe.HTTPGet.Path if path == "" { return fmt.Errorf("Path expected to be not empty: %v", path) @@ -947,7 +948,7 @@ func (p *statefulSetTester) breakProbe(ps *apps.StatefulSet, probe *api.Probe) e return p.execInPets(ps, cmd) } -func (p *statefulSetTester) restoreProbe(ps *apps.StatefulSet, probe *api.Probe) error { +func (p *statefulSetTester) restoreProbe(ps *apps.StatefulSet, probe *v1.Probe) error { path := probe.HTTPGet.Path if path == "" { return fmt.Errorf("Path expected to be not empty: %v", path) @@ -960,7 +961,7 @@ func (p *statefulSetTester) setHealthy(ps *apps.StatefulSet) { podList := p.getPodList(ps) markedHealthyPod := "" for _, pod := range podList.Items { - if pod.Status.Phase != api.PodRunning { + if pod.Status.Phase != v1.PodRunning { framework.Failf("Found pod in %v cannot set health", pod.Status.Phase) } if isInitialized(pod) { @@ -969,7 +970,7 @@ func (p *statefulSetTester) setHealthy(ps *apps.StatefulSet) { if markedHealthyPod != "" { framework.Failf("Found multiple non-healthy pets: %v and %v", pod.Name, markedHealthyPod) } - p, err := framework.UpdatePodWithRetries(p.c, pod.Namespace, pod.Name, func(up *api.Pod) { + p, err := framework.UpdatePodWithRetries(p.c, pod.Namespace, pod.Name, func(up *v1.Pod) { up.Annotations[petset.StatefulSetInitAnnotation] = "true" }) ExpectNoError(err) @@ -1001,7 +1002,7 @@ func (p *statefulSetTester) waitForStatus(ps *apps.StatefulSet, expectedReplicas func deleteAllStatefulSets(c clientset.Interface, ns string) { pst := &statefulSetTester{c: c} - psList, err := c.Apps().StatefulSets(ns).List(api.ListOptions{LabelSelector: labels.Everything()}) + psList, err := c.Apps().StatefulSets(ns).List(v1.ListOptions{LabelSelector: labels.Everything().String()}) ExpectNoError(err) // Scale down each statefulset, then delete it completely. @@ -1023,7 +1024,7 @@ func deleteAllStatefulSets(c clientset.Interface, ns string) { pvNames := sets.NewString() // TODO: Don't assume all pvcs in the ns belong to a statefulset pvcPollErr := wait.PollImmediate(statefulsetPoll, statefulsetTimeout, func() (bool, error) { - pvcList, err := c.Core().PersistentVolumeClaims(ns).List(api.ListOptions{LabelSelector: labels.Everything()}) + pvcList, err := c.Core().PersistentVolumeClaims(ns).List(v1.ListOptions{LabelSelector: labels.Everything().String()}) if err != nil { framework.Logf("WARNING: Failed to list pvcs, retrying %v", err) return false, nil @@ -1043,7 +1044,7 @@ func deleteAllStatefulSets(c clientset.Interface, ns string) { } pollErr := wait.PollImmediate(statefulsetPoll, statefulsetTimeout, func() (bool, error) { - pvList, err := c.Core().PersistentVolumes().List(api.ListOptions{LabelSelector: labels.Everything()}) + pvList, err := c.Core().PersistentVolumes().List(v1.ListOptions{LabelSelector: labels.Everything().String()}) if err != nil { framework.Logf("WARNING: Failed to list pvs, retrying %v", err) return false, nil @@ -1089,7 +1090,7 @@ func pollReadWithTimeout(pet petTester, petNumber int, key, expectedVal string) return err } -func isInitialized(pod api.Pod) bool { +func isInitialized(pod v1.Pod) bool { initialized, ok := pod.Annotations[petset.StatefulSetInitAnnotation] if !ok { return false @@ -1105,40 +1106,40 @@ func dec(i int64, exponent int) *inf.Dec { return inf.NewDec(i, inf.Scale(-exponent)) } -func newPVC(name string) api.PersistentVolumeClaim { - return api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ +func newPVC(name string) v1.PersistentVolumeClaim { + return v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: name, Annotations: map[string]string{ "volume.alpha.kubernetes.io/storage-class": "anything", }, }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceStorage: *resource.NewQuantity(1, resource.BinarySI), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceStorage: *resource.NewQuantity(1, resource.BinarySI), }, }, }, } } -func newStatefulSet(name, ns, governingSvcName string, replicas int32, petMounts []api.VolumeMount, podMounts []api.VolumeMount, labels map[string]string) *apps.StatefulSet { +func newStatefulSet(name, ns, governingSvcName string, replicas int32, petMounts []v1.VolumeMount, podMounts []v1.VolumeMount, labels map[string]string) *apps.StatefulSet { mounts := append(petMounts, podMounts...) - claims := []api.PersistentVolumeClaim{} + claims := []v1.PersistentVolumeClaim{} for _, m := range petMounts { claims = append(claims, newPVC(m.Name)) } - vols := []api.Volume{} + vols := []v1.Volume{} for _, m := range podMounts { - vols = append(vols, api.Volume{ + vols = append(vols, v1.Volume{ Name: m.Name, - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{ + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{ Path: fmt.Sprintf("/tmp/%v", m.Name), }, }, @@ -1150,7 +1151,7 @@ func newStatefulSet(name, ns, governingSvcName string, replicas int32, petMounts Kind: "StatefulSet", APIVersion: "apps/v1beta1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: name, Namespace: ns, }, @@ -1158,14 +1159,14 @@ func newStatefulSet(name, ns, governingSvcName string, replicas int32, petMounts Selector: &unversioned.LabelSelector{ MatchLabels: labels, }, - Replicas: replicas, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Replicas: func(i int32) *int32 { return &i }(replicas), + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: labels, Annotations: map[string]string{}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "nginx", Image: nginxImage, diff --git a/test/e2e/pod_gc.go b/test/e2e/pod_gc.go index 91c93b910d3..8121f5d1de0 100644 --- a/test/e2e/pod_gc.go +++ b/test/e2e/pod_gc.go @@ -22,7 +22,7 @@ import ( . "github.com/onsi/ginkgo" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -38,7 +38,7 @@ var _ = framework.KubeDescribe("Pod garbage collector [Feature:PodGarbageCollect for count < 1000 { pod, err := createTerminatingPod(f) pod.ResourceVersion = "" - pod.Status.Phase = api.PodFailed + pod.Status.Phase = v1.PodFailed pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).UpdateStatus(pod) if err != nil { framework.Failf("err failing pod: %v", err) @@ -55,13 +55,13 @@ var _ = framework.KubeDescribe("Pod garbage collector [Feature:PodGarbageCollect // The gc controller polls every 30s and fires off a goroutine per // pod to terminate. var err error - var pods *api.PodList + var pods *v1.PodList timeout := 2 * time.Minute gcThreshold := 100 By(fmt.Sprintf("Waiting for gc controller to gc all but %d pods", gcThreshold)) pollErr := wait.Poll(1*time.Minute, timeout, func() (bool, error) { - pods, err = f.ClientSet.Core().Pods(f.Namespace.Name).List(api.ListOptions{}) + pods, err = f.ClientSet.Core().Pods(f.Namespace.Name).List(v1.ListOptions{}) if err != nil { framework.Logf("Failed to list pod %v", err) return false, nil @@ -78,17 +78,17 @@ var _ = framework.KubeDescribe("Pod garbage collector [Feature:PodGarbageCollect }) }) -func createTerminatingPod(f *framework.Framework) (*api.Pod, error) { +func createTerminatingPod(f *framework.Framework) (*v1.Pod, error) { uuid := uuid.NewUUID() - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: string(uuid), Annotations: map[string]string{ "scheduler.alpha.kubernetes.io/name": "please don't schedule my pods", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: string(uuid), Image: "gcr.io/google_containers/busybox:1.24", diff --git a/test/e2e/pods.go b/test/e2e/pods.go index fee5a4c9b47..ee4779f8b00 100644 --- a/test/e2e/pods.go +++ b/test/e2e/pods.go @@ -24,7 +24,7 @@ import ( "strconv" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/pkg/util/wait" @@ -45,16 +45,16 @@ var _ = framework.KubeDescribe("Pods Delete Grace Period", func() { By("creating the pod") name := "pod-submit-remove-" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: map[string]string{ "name": "foo", "time": value, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "nginx", Image: "gcr.io/google_containers/nginx-slim:0.7", @@ -65,12 +65,12 @@ var _ = framework.KubeDescribe("Pods Delete Grace Period", func() { By("setting up watch") selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value})) - options := api.ListOptions{LabelSelector: selector} + options := v1.ListOptions{LabelSelector: selector.String()} pods, err := podClient.List(options) Expect(err).NotTo(HaveOccurred(), "failed to query for pod") Expect(len(pods.Items)).To(Equal(0)) - options = api.ListOptions{ - LabelSelector: selector, + options = v1.ListOptions{ + LabelSelector: selector.String(), ResourceVersion: pods.ListMeta.ResourceVersion, } w, err := podClient.Watch(options) @@ -81,7 +81,7 @@ var _ = framework.KubeDescribe("Pods Delete Grace Period", func() { By("verifying the pod is in kubernetes") selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value})) - options = api.ListOptions{LabelSelector: selector} + options = v1.ListOptions{LabelSelector: selector.String()} pods, err = podClient.List(options) Expect(err).NotTo(HaveOccurred(), "failed to query for pod") Expect(len(pods.Items)).To(Equal(1)) @@ -159,13 +159,13 @@ var _ = framework.KubeDescribe("Pods Delete Grace Period", func() { By("verifying pod deletion was observed") deleted := false timeout := false - var lastPod *api.Pod + var lastPod *v1.Pod timer := time.After(30 * time.Second) for !deleted && !timeout { select { case event, _ := <-w.ResultChan(): if event.Type == watch.Deleted { - lastPod = event.Object.(*api.Pod) + lastPod = event.Object.(*v1.Pod) deleted = true } case <-timer: @@ -180,7 +180,7 @@ var _ = framework.KubeDescribe("Pods Delete Grace Period", func() { Expect(lastPod.Spec.TerminationGracePeriodSeconds).ToNot(BeZero()) selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value})) - options = api.ListOptions{LabelSelector: selector} + options = v1.ListOptions{LabelSelector: selector.String()} pods, err = podClient.List(options) Expect(err).NotTo(HaveOccurred(), "failed to query for pods") Expect(len(pods.Items)).To(Equal(0)) diff --git a/test/e2e/portforward.go b/test/e2e/portforward.go index e3e6331ca8e..3a8974c0578 100644 --- a/test/e2e/portforward.go +++ b/test/e2e/portforward.go @@ -28,7 +28,7 @@ import ( "syscall" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/version" "k8s.io/kubernetes/test/e2e/framework" @@ -46,18 +46,18 @@ var ( portForwardPortToStdOutV = version.MustParse("v1.3.0-alpha.4") ) -func pfPod(expectedClientData, chunks, chunkSize, chunkIntervalMillis string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func pfPod(expectedClientData, chunks, chunkSize, chunkIntervalMillis string) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{"name": podName}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "portforwardtester", Image: "gcr.io/google_containers/portforwardtester:1.0", - Env: []api.EnvVar{ + Env: []v1.EnvVar{ { Name: "BIND_PORT", Value: "80", @@ -81,7 +81,7 @@ func pfPod(expectedClientData, chunks, chunkSize, chunkIntervalMillis string) *a }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } } diff --git a/test/e2e/pre_stop.go b/test/e2e/pre_stop.go index 38dd3e5a9e9..6c2eab0a30d 100644 --- a/test/e2e/pre_stop.go +++ b/test/e2e/pre_stop.go @@ -21,8 +21,8 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -36,16 +36,16 @@ type State struct { func testPreStop(c clientset.Interface, ns string) { // This is the server that will receive the preStop notification - podDescr := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + podDescr := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "server", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "server", Image: "gcr.io/google_containers/nettest:1.7", - Ports: []api.ContainerPort{{ContainerPort: 8080}}, + Ports: []v1.ContainerPort{{ContainerPort: 8080}}, }, }, }, @@ -69,19 +69,19 @@ func testPreStop(c clientset.Interface, ns string) { podOut, err := c.Core().Pods(ns).Get(podDescr.Name) framework.ExpectNoError(err, "getting pod info") - preStopDescr := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + preStopDescr := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "tester", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "tester", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"sleep", "600"}, - Lifecycle: &api.Lifecycle{ - PreStop: &api.Handler{ - Exec: &api.ExecAction{ + Lifecycle: &v1.Lifecycle{ + PreStop: &v1.Handler{ + Exec: &v1.ExecAction{ Command: []string{ "wget", "-O-", "--post-data=" + val, fmt.Sprintf("http://%s:8080/write", podOut.Status.PodIP), }, diff --git a/test/e2e/proxy.go b/test/e2e/proxy.go index bb6e335d771..2637841aaa0 100644 --- a/test/e2e/proxy.go +++ b/test/e2e/proxy.go @@ -24,10 +24,10 @@ import ( "sync" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/net" "k8s.io/kubernetes/test/e2e/framework" @@ -49,7 +49,7 @@ const ( ) var _ = framework.KubeDescribe("Proxy", func() { - version := registered.GroupOrDie(api.GroupName).GroupVersion.Version + version := registered.GroupOrDie(v1.GroupName).GroupVersion.Version Context("version "+version, func() { options := framework.FrameworkOptions{ ClientQPS: -1.0, @@ -71,13 +71,13 @@ var _ = framework.KubeDescribe("Proxy", func() { It("should proxy through a service and a pod [Conformance]", func() { start := time.Now() labels := map[string]string{"proxy-service-target": "true"} - service, err := f.ClientSet.Core().Services(f.Namespace.Name).Create(&api.Service{ - ObjectMeta: api.ObjectMeta{ + service, err := f.ClientSet.Core().Services(f.Namespace.Name).Create(&v1.Service{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "proxy-service-", }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: labels, - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ { Name: "portname1", Port: 80, @@ -107,14 +107,15 @@ var _ = framework.KubeDescribe("Proxy", func() { // a simple server which serves the values of the // environmental variables below. By("starting an echo server on multiple ports") - pods := []*api.Pod{} + pods := []*v1.Pod{} cfg := testutils.RCConfig{ - Client: f.ClientSet, - Image: "gcr.io/google_containers/porter:cd5cb5791ebaa8641955f0e8c2a9bed669b1eaab", - Name: service.Name, - Namespace: f.Namespace.Name, - Replicas: 1, - PollInterval: time.Second, + Client: f.ClientSet, + InternalClient: f.InternalClientset, + Image: "gcr.io/google_containers/porter:cd5cb5791ebaa8641955f0e8c2a9bed669b1eaab", + Name: service.Name, + Namespace: f.Namespace.Name, + Replicas: 1, + PollInterval: time.Second, Env: map[string]string{ "SERVE_PORT_80": `test`, "SERVE_PORT_1080": `test`, @@ -132,9 +133,9 @@ var _ = framework.KubeDescribe("Proxy", func() { "tlsdest1": 460, "tlsdest2": 462, }, - ReadinessProbe: &api.Probe{ - Handler: api.Handler{ - HTTPGet: &api.HTTPGetAction{ + ReadinessProbe: &v1.Probe{ + Handler: v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Port: intstr.FromInt(80), }, }, @@ -146,7 +147,7 @@ var _ = framework.KubeDescribe("Proxy", func() { CreatedPods: &pods, } Expect(framework.RunRC(cfg)).NotTo(HaveOccurred()) - defer framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, cfg.Name) + defer framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, cfg.Name) Expect(f.WaitForAnEndpoint(service.Name)).NotTo(HaveOccurred()) @@ -260,7 +261,7 @@ var _ = framework.KubeDescribe("Proxy", func() { } if len(errs) != 0 { - body, err := f.ClientSet.Core().Pods(f.Namespace.Name).GetLogs(pods[0].Name, &api.PodLogOptions{}).Do().Raw() + body, err := f.ClientSet.Core().Pods(f.Namespace.Name).GetLogs(pods[0].Name, &v1.PodLogOptions{}).Do().Raw() if err != nil { framework.Logf("Error getting logs for pod %s: %v", pods[0].Name, err) } else { diff --git a/test/e2e/rc.go b/test/e2e/rc.go index 126311c18ad..6f2b8bc560b 100644 --- a/test/e2e/rc.go +++ b/test/e2e/rc.go @@ -20,8 +20,8 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/controller/replication" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/uuid" @@ -51,21 +51,21 @@ var _ = framework.KubeDescribe("ReplicationController", func() { }) }) -func newRC(rsName string, replicas int32, rcPodLabels map[string]string, imageName string, image string) *api.ReplicationController { +func newRC(rsName string, replicas int32, rcPodLabels map[string]string, imageName string, image string) *v1.ReplicationController { zero := int64(0) - return &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ + return &v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{ Name: rsName, }, - Spec: api.ReplicationControllerSpec{ - Replicas: replicas, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Spec: v1.ReplicationControllerSpec{ + Replicas: func(i int32) *int32 { return &i }(replicas), + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: rcPodLabels, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ TerminationGracePeriodSeconds: &zero, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: imageName, Image: image, @@ -89,25 +89,25 @@ func ServeImageOrFail(f *framework.Framework, test string, image string) { // The source for the Docker containter kubernetes/serve_hostname is // in contrib/for-demos/serve_hostname By(fmt.Sprintf("Creating replication controller %s", name)) - controller, err := f.ClientSet.Core().ReplicationControllers(f.Namespace.Name).Create(&api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ + controller, err := f.ClientSet.Core().ReplicationControllers(f.Namespace.Name).Create(&v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.ReplicationControllerSpec{ - Replicas: replicas, + Spec: v1.ReplicationControllerSpec{ + Replicas: func(i int32) *int32 { return &i }(replicas), Selector: map[string]string{ "name": name, }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"name": name}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: name, Image: image, - Ports: []api.ContainerPort{{ContainerPort: 9376}}, + Ports: []v1.ContainerPort{{ContainerPort: 9376}}, }, }, }, @@ -118,7 +118,7 @@ func ServeImageOrFail(f *framework.Framework, test string, image string) { // Cleanup the replication controller when we are done. defer func() { // Resize the replication controller to zero to get rid of pods. - if err := framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, controller.Name); err != nil { + if err := framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, controller.Name); err != nil { framework.Logf("Failed to cleanup replication controller %v: %v.", controller.Name, err) } }() @@ -169,7 +169,7 @@ func rcConditionCheck(f *framework.Framework) { if err != nil { return false, err } - podQuota := quota.Status.Hard[api.ResourcePods] + podQuota := quota.Status.Hard[v1.ResourcePods] quantity := resource.MustParse("2") return (&podQuota).Cmp(quantity) == 0, nil }) @@ -197,7 +197,7 @@ func rcConditionCheck(f *framework.Framework) { } conditions = rc.Status.Conditions - cond := replication.GetCondition(rc.Status, api.ReplicationControllerReplicaFailure) + cond := replication.GetCondition(rc.Status, v1.ReplicationControllerReplicaFailure) return cond != nil, nil }) if err == wait.ErrWaitTimeout { @@ -206,8 +206,9 @@ func rcConditionCheck(f *framework.Framework) { Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("Scaling down rc %q to satisfy pod quota", name)) - rc, err = framework.UpdateReplicationControllerWithRetries(c, namespace, name, func(update *api.ReplicationController) { - update.Spec.Replicas = 2 + rc, err = framework.UpdateReplicationControllerWithRetries(c, namespace, name, func(update *v1.ReplicationController) { + x := int32(2) + update.Spec.Replicas = &x }) Expect(err).NotTo(HaveOccurred()) @@ -225,7 +226,7 @@ func rcConditionCheck(f *framework.Framework) { } conditions = rc.Status.Conditions - cond := replication.GetCondition(rc.Status, api.ReplicationControllerReplicaFailure) + cond := replication.GetCondition(rc.Status, v1.ReplicationControllerReplicaFailure) return cond == nil, nil }) if err == wait.ErrWaitTimeout { diff --git a/test/e2e/reboot.go b/test/e2e/reboot.go index 73b842cac8f..313dbeb9e73 100644 --- a/test/e2e/reboot.go +++ b/test/e2e/reboot.go @@ -22,7 +22,8 @@ import ( "time" "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/sets" @@ -64,7 +65,7 @@ var _ = framework.KubeDescribe("Reboot [Disruptive] [Feature:Reboot]", func() { // events for the kube-system namespace on failures namespaceName := api.NamespaceSystem By(fmt.Sprintf("Collecting events from namespace %q.", namespaceName)) - events, err := f.ClientSet.Core().Events(namespaceName).List(api.ListOptions{}) + events, err := f.ClientSet.Core().Events(namespaceName).List(v1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) for _, e := range events.Items { @@ -160,7 +161,7 @@ func testReboot(c clientset.Interface, rebootCmd string) { } } -func printStatusAndLogsForNotReadyPods(c clientset.Interface, ns string, podNames []string, pods []*api.Pod) { +func printStatusAndLogsForNotReadyPods(c clientset.Interface, ns string, podNames []string, pods []*v1.Pod) { printFn := func(id, log string, err error, previous bool) { prefix := "Retrieving log for container" if previous { diff --git a/test/e2e/replica_set.go b/test/e2e/replica_set.go index 8e9b62e84af..c0678a7bd76 100644 --- a/test/e2e/replica_set.go +++ b/test/e2e/replica_set.go @@ -20,10 +20,10 @@ import ( "fmt" "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/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/controller/replicaset" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/uuid" @@ -37,18 +37,18 @@ import ( func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string) *extensions.ReplicaSet { zero := int64(0) return &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: rsName, }, Spec: extensions.ReplicaSetSpec{ - Replicas: replicas, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Replicas: func(i int32) *int32 { return &i }(replicas), + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: rsPodLabels, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ TerminationGracePeriodSeconds: &zero, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: imageName, Image: image, @@ -60,14 +60,14 @@ func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageNa } } -func newPodQuota(name, number string) *api.ResourceQuota { - return &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ +func newPodQuota(name, number string) *v1.ResourceQuota { + return &v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourcePods: resource.MustParse(number), + Spec: v1.ResourceQuotaSpec{ + Hard: v1.ResourceList{ + v1.ResourcePods: resource.MustParse(number), }, }, } @@ -103,24 +103,24 @@ func ReplicaSetServeImageOrFail(f *framework.Framework, test string, image strin // in contrib/for-demos/serve_hostname By(fmt.Sprintf("Creating ReplicaSet %s", name)) rs, err := f.ClientSet.Extensions().ReplicaSets(f.Namespace.Name).Create(&extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, Spec: extensions.ReplicaSetSpec{ - Replicas: replicas, + Replicas: func(i int32) *int32 { return &i }(replicas), Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{ "name": name, }}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"name": name}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: name, Image: image, - Ports: []api.ContainerPort{{ContainerPort: 9376}}, + Ports: []v1.ContainerPort{{ContainerPort: 9376}}, }, }, }, @@ -131,7 +131,7 @@ func ReplicaSetServeImageOrFail(f *framework.Framework, test string, image strin // Cleanup the ReplicaSet when we are done. defer func() { // Resize the ReplicaSet to zero to get rid of pods. - if err := framework.DeleteReplicaSet(f.ClientSet, f.Namespace.Name, rs.Name); err != nil { + if err := framework.DeleteReplicaSet(f.ClientSet, f.InternalClientset, f.Namespace.Name, rs.Name); err != nil { framework.Logf("Failed to cleanup ReplicaSet %v: %v.", rs.Name, err) } }() @@ -184,7 +184,7 @@ func rsConditionCheck(f *framework.Framework) { return false, err } quantity := resource.MustParse("2") - podQuota := quota.Status.Hard[api.ResourcePods] + podQuota := quota.Status.Hard[v1.ResourcePods] return (&podQuota).Cmp(quantity) == 0, nil }) if err == wait.ErrWaitTimeout { @@ -222,7 +222,8 @@ func rsConditionCheck(f *framework.Framework) { By(fmt.Sprintf("Scaling down replica set %q to satisfy pod quota", name)) rs, err = framework.UpdateReplicaSetWithRetries(c, namespace, name, func(update *extensions.ReplicaSet) { - update.Spec.Replicas = 2 + x := int32(2) + update.Spec.Replicas = &x }) Expect(err).NotTo(HaveOccurred()) diff --git a/test/e2e/rescheduler.go b/test/e2e/rescheduler.go index 962fba7888e..c1f3cde243a 100644 --- a/test/e2e/rescheduler.go +++ b/test/e2e/rescheduler.go @@ -21,6 +21,7 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/test/e2e/framework" testutils "k8s.io/kubernetes/test/utils" @@ -42,28 +43,28 @@ var _ = framework.KubeDescribe("Rescheduler [Serial]", func() { nodeCount := len(nodes.Items) Expect(nodeCount).NotTo(BeZero()) - cpu := nodes.Items[0].Status.Capacity[api.ResourceCPU] + cpu := nodes.Items[0].Status.Capacity[v1.ResourceCPU] totalMillicores = int((&cpu).MilliValue()) * nodeCount }) It("should ensure that critical pod is scheduled in case there is no resources available", func() { By("reserving all available cpu") err := reserveAllCpu(f, "reserve-all-cpu", totalMillicores) - defer framework.DeleteRCAndPods(f.ClientSet, ns, "reserve-all-cpu") + defer framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, ns, "reserve-all-cpu") framework.ExpectNoError(err) By("creating a new instance of Dashboard and waiting for Dashboard to be scheduled") label := labels.SelectorFromSet(labels.Set(map[string]string{"k8s-app": "kubernetes-dashboard"})) - listOpts := api.ListOptions{LabelSelector: label} + listOpts := v1.ListOptions{LabelSelector: label.String()} deployments, err := f.ClientSet.Extensions().Deployments(api.NamespaceSystem).List(listOpts) framework.ExpectNoError(err) Expect(len(deployments.Items)).Should(Equal(1)) deployment := deployments.Items[0] - replicas := uint(deployment.Spec.Replicas) + replicas := uint(*(deployment.Spec.Replicas)) - err = framework.ScaleDeployment(f.ClientSet, api.NamespaceSystem, deployment.Name, replicas+1, true) - defer framework.ExpectNoError(framework.ScaleDeployment(f.ClientSet, api.NamespaceSystem, deployment.Name, replicas, true)) + err = framework.ScaleDeployment(f.ClientSet, f.InternalClientset, api.NamespaceSystem, deployment.Name, replicas+1, true) + defer framework.ExpectNoError(framework.ScaleDeployment(f.ClientSet, f.InternalClientset, api.NamespaceSystem, deployment.Name, replicas, true)) framework.ExpectNoError(err) }) @@ -74,7 +75,7 @@ func reserveAllCpu(f *framework.Framework, id string, millicores int) error { replicas := millicores / 100 ReserveCpu(f, id, 1, 100) - framework.ExpectNoError(framework.ScaleRC(f.ClientSet, f.Namespace.Name, id, uint(replicas), false)) + framework.ExpectNoError(framework.ScaleRC(f.ClientSet, f.InternalClientset, f.Namespace.Name, id, uint(replicas), false)) for start := time.Now(); time.Since(start) < timeout; time.Sleep(10 * time.Second) { pods, err := framework.GetPodsInNamespace(f.ClientSet, f.Namespace.Name, framework.ImagePullerLabels) @@ -100,9 +101,9 @@ func reserveAllCpu(f *framework.Framework, id string, millicores int) error { return fmt.Errorf("Pod name %s: Gave up waiting %v for %d pods to come up", id, timeout, replicas) } -func podRunningOrUnschedulable(pod *api.Pod) bool { - _, cond := api.GetPodCondition(&pod.Status, api.PodScheduled) - if cond != nil && cond.Status == api.ConditionFalse && cond.Reason == "Unschedulable" { +func podRunningOrUnschedulable(pod *v1.Pod) bool { + _, cond := v1.GetPodCondition(&pod.Status, v1.PodScheduled) + if cond != nil && cond.Status == v1.ConditionFalse && cond.Reason == "Unschedulable" { return true } running, _ := testutils.PodRunningReady(pod) diff --git a/test/e2e/resize_nodes.go b/test/e2e/resize_nodes.go index 43d0bfb7abd..65e54c9d9ef 100644 --- a/test/e2e/resize_nodes.go +++ b/test/e2e/resize_nodes.go @@ -25,8 +25,9 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/test/e2e/framework" @@ -136,17 +137,17 @@ func WaitForGroupSize(group string, size int32) error { return fmt.Errorf("timeout waiting %v for node instance group size to be %d", timeout, size) } -func svcByName(name string, port int) *api.Service { - return &api.Service{ - ObjectMeta: api.ObjectMeta{ +func svcByName(name string, port int) *v1.Service { + return &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.ServiceSpec{ - Type: api.ServiceTypeNodePort, + Spec: v1.ServiceSpec{ + Type: v1.ServiceTypeNodePort, Selector: map[string]string{ "name": name, }, - Ports: []api.ServicePort{{ + Ports: []v1.ServicePort{{ Port: int32(port), TargetPort: intstr.FromInt(port), }}, @@ -159,18 +160,18 @@ func newSVCByName(c clientset.Interface, ns, name string) error { return err } -func rcByNamePort(name string, replicas int32, image string, port int, protocol api.Protocol, - labels map[string]string, gracePeriod *int64) *api.ReplicationController { +func rcByNamePort(name string, replicas int32, image string, port int, protocol v1.Protocol, + labels map[string]string, gracePeriod *int64) *v1.ReplicationController { - return rcByNameContainer(name, replicas, image, labels, api.Container{ + return rcByNameContainer(name, replicas, image, labels, v1.Container{ Name: name, Image: image, - Ports: []api.ContainerPort{{ContainerPort: int32(port), Protocol: protocol}}, + Ports: []v1.ContainerPort{{ContainerPort: int32(port), Protocol: protocol}}, }, gracePeriod) } -func rcByNameContainer(name string, replicas int32, image string, labels map[string]string, c api.Container, - gracePeriod *int64) *api.ReplicationController { +func rcByNameContainer(name string, replicas int32, image string, labels map[string]string, c v1.Container, + gracePeriod *int64) *v1.ReplicationController { zeroGracePeriod := int64(0) @@ -179,25 +180,25 @@ func rcByNameContainer(name string, replicas int32, image string, labels map[str if gracePeriod == nil { gracePeriod = &zeroGracePeriod } - return &api.ReplicationController{ + return &v1.ReplicationController{ TypeMeta: unversioned.TypeMeta{ Kind: "ReplicationController", - APIVersion: registered.GroupOrDie(api.GroupName).GroupVersion.String(), + APIVersion: registered.GroupOrDie(v1.GroupName).GroupVersion.String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.ReplicationControllerSpec{ - Replicas: replicas, + Spec: v1.ReplicationControllerSpec{ + Replicas: func(i int32) *int32 { return &i }(replicas), Selector: map[string]string{ "name": name, }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: labels, }, - Spec: api.PodSpec{ - Containers: []api.Container{c}, + Spec: v1.PodSpec{ + Containers: []v1.Container{c}, TerminationGracePeriodSeconds: gracePeriod, }, }, @@ -206,10 +207,10 @@ func rcByNameContainer(name string, replicas int32, image string, labels map[str } // newRCByName creates a replication controller with a selector by name of name. -func newRCByName(c clientset.Interface, ns, name string, replicas int32, gracePeriod *int64) (*api.ReplicationController, error) { +func newRCByName(c clientset.Interface, ns, name string, replicas int32, gracePeriod *int64) (*v1.ReplicationController, error) { By(fmt.Sprintf("creating replication controller %s", name)) return c.Core().ReplicationControllers(ns).Create(rcByNamePort( - name, replicas, serveHostnameImage, 9376, api.ProtocolTCP, map[string]string{}, gracePeriod)) + name, replicas, serveHostnameImage, 9376, v1.ProtocolTCP, map[string]string{}, gracePeriod)) } func resizeRC(c clientset.Interface, ns, name string, replicas int32) error { @@ -217,7 +218,7 @@ func resizeRC(c clientset.Interface, ns, name string, replicas int32) error { if err != nil { return err } - rc.Spec.Replicas = replicas + *(rc.Spec.Replicas) = replicas _, err = c.Core().ReplicationControllers(rc.Namespace).Update(rc) return err } diff --git a/test/e2e/resource_quota.go b/test/e2e/resource_quota.go index ccfe7412372..2996e55b5fd 100644 --- a/test/e2e/resource_quota.go +++ b/test/e2e/resource_quota.go @@ -20,9 +20,9 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -47,8 +47,8 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status is calculated") - usedResources := api.ResourceList{} - usedResources[api.ResourceQuotas] = resource.MustParse("1") + usedResources := v1.ResourceList{} + usedResources[v1.ResourceQuotas] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) }) @@ -61,20 +61,20 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status is calculated") - usedResources := api.ResourceList{} - usedResources[api.ResourceQuotas] = resource.MustParse("1") + usedResources := v1.ResourceList{} + usedResources[v1.ResourceQuotas] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) By("Creating a Service") - service := newTestServiceForQuota("test-service", api.ServiceTypeClusterIP) + service := newTestServiceForQuota("test-service", v1.ServiceTypeClusterIP) service, err = f.ClientSet.Core().Services(f.Namespace.Name).Create(service) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status captures service creation") - usedResources = api.ResourceList{} - usedResources[api.ResourceQuotas] = resource.MustParse("1") - usedResources[api.ResourceServices] = resource.MustParse("1") + usedResources = v1.ResourceList{} + usedResources[v1.ResourceQuotas] = resource.MustParse("1") + usedResources[v1.ResourceServices] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) @@ -83,14 +83,14 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status released usage") - usedResources[api.ResourceServices] = resource.MustParse("0") + usedResources[v1.ResourceServices] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) }) It("should create a ResourceQuota and capture the life of a secret.", func() { By("Discovering how many secrets are in namespace by default") - secrets, err := f.ClientSet.Core().Secrets(f.Namespace.Name).List(api.ListOptions{}) + secrets, err := f.ClientSet.Core().Secrets(f.Namespace.Name).List(v1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) defaultSecrets := fmt.Sprintf("%d", len(secrets.Items)) hardSecrets := fmt.Sprintf("%d", len(secrets.Items)+1) @@ -98,14 +98,14 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { By("Creating a ResourceQuota") quotaName := "test-quota" resourceQuota := newTestResourceQuota(quotaName) - resourceQuota.Spec.Hard[api.ResourceSecrets] = resource.MustParse(hardSecrets) + resourceQuota.Spec.Hard[v1.ResourceSecrets] = resource.MustParse(hardSecrets) resourceQuota, err = createResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuota) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status is calculated") - usedResources := api.ResourceList{} - usedResources[api.ResourceQuotas] = resource.MustParse("1") - usedResources[api.ResourceSecrets] = resource.MustParse(defaultSecrets) + usedResources := v1.ResourceList{} + usedResources[v1.ResourceQuotas] = resource.MustParse("1") + usedResources[v1.ResourceSecrets] = resource.MustParse(defaultSecrets) err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) @@ -115,8 +115,8 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status captures secret creation") - usedResources = api.ResourceList{} - usedResources[api.ResourceSecrets] = resource.MustParse(hardSecrets) + usedResources = v1.ResourceList{} + usedResources[v1.ResourceSecrets] = resource.MustParse(hardSecrets) // we expect there to be two secrets because each namespace will receive // a service account token secret by default err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) @@ -127,7 +127,7 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status released usage") - usedResources[api.ResourceSecrets] = resource.MustParse(defaultSecrets) + usedResources[v1.ResourceSecrets] = resource.MustParse(defaultSecrets) err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) }) @@ -140,42 +140,42 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status is calculated") - usedResources := api.ResourceList{} - usedResources[api.ResourceQuotas] = resource.MustParse("1") + usedResources := v1.ResourceList{} + usedResources[v1.ResourceQuotas] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) By("Creating a Pod that fits quota") podName := "test-pod" - requests := api.ResourceList{} - requests[api.ResourceCPU] = resource.MustParse("500m") - requests[api.ResourceMemory] = resource.MustParse("252Mi") - pod := newTestPodForQuota(f, podName, requests, api.ResourceList{}) + requests := v1.ResourceList{} + requests[v1.ResourceCPU] = resource.MustParse("500m") + requests[v1.ResourceMemory] = resource.MustParse("252Mi") + pod := newTestPodForQuota(f, podName, requests, v1.ResourceList{}) pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) Expect(err).NotTo(HaveOccurred()) podToUpdate := pod By("Ensuring ResourceQuota status captures the pod usage") - usedResources[api.ResourceQuotas] = resource.MustParse("1") - usedResources[api.ResourcePods] = resource.MustParse("1") - usedResources[api.ResourceCPU] = requests[api.ResourceCPU] - usedResources[api.ResourceMemory] = requests[api.ResourceMemory] + usedResources[v1.ResourceQuotas] = resource.MustParse("1") + usedResources[v1.ResourcePods] = resource.MustParse("1") + usedResources[v1.ResourceCPU] = requests[v1.ResourceCPU] + usedResources[v1.ResourceMemory] = requests[v1.ResourceMemory] err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) By("Not allowing a pod to be created that exceeds remaining quota") - requests = api.ResourceList{} - requests[api.ResourceCPU] = resource.MustParse("600m") - requests[api.ResourceMemory] = resource.MustParse("100Mi") - pod = newTestPodForQuota(f, "fail-pod", requests, api.ResourceList{}) + requests = v1.ResourceList{} + requests[v1.ResourceCPU] = resource.MustParse("600m") + requests[v1.ResourceMemory] = resource.MustParse("100Mi") + pod = newTestPodForQuota(f, "fail-pod", requests, v1.ResourceList{}) pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) Expect(err).To(HaveOccurred()) By("Ensuring a pod cannot update its resource requirements") // a pod cannot dynamically update its resource requirements. - requests = api.ResourceList{} - requests[api.ResourceCPU] = resource.MustParse("100m") - requests[api.ResourceMemory] = resource.MustParse("100Mi") + requests = v1.ResourceList{} + requests[v1.ResourceCPU] = resource.MustParse("100m") + requests[v1.ResourceMemory] = resource.MustParse("100Mi") podToUpdate.Spec.Containers[0].Resources.Requests = requests _, err = f.ClientSet.Core().Pods(f.Namespace.Name).Update(podToUpdate) Expect(err).To(HaveOccurred()) @@ -185,14 +185,14 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Deleting the pod") - err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(podName, api.NewDeleteOptions(0)) + err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(podName, v1.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status released the pod usage") - usedResources[api.ResourceQuotas] = resource.MustParse("1") - usedResources[api.ResourcePods] = resource.MustParse("0") - usedResources[api.ResourceCPU] = resource.MustParse("0") - usedResources[api.ResourceMemory] = resource.MustParse("0") + usedResources[v1.ResourceQuotas] = resource.MustParse("1") + usedResources[v1.ResourcePods] = resource.MustParse("0") + usedResources[v1.ResourceCPU] = resource.MustParse("0") + usedResources[v1.ResourceMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) }) @@ -205,8 +205,8 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status is calculated") - usedResources := api.ResourceList{} - usedResources[api.ResourceQuotas] = resource.MustParse("1") + usedResources := v1.ResourceList{} + usedResources[v1.ResourceQuotas] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) @@ -216,9 +216,9 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status captures configMap creation") - usedResources = api.ResourceList{} - usedResources[api.ResourceQuotas] = resource.MustParse("1") - usedResources[api.ResourceConfigMaps] = resource.MustParse("1") + usedResources = v1.ResourceList{} + usedResources[v1.ResourceQuotas] = resource.MustParse("1") + usedResources[v1.ResourceConfigMaps] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) @@ -227,7 +227,7 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status released usage") - usedResources[api.ResourceConfigMaps] = resource.MustParse("0") + usedResources[v1.ResourceConfigMaps] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) }) @@ -240,9 +240,9 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status is calculated") - usedResources := api.ResourceList{} - usedResources[api.ResourceQuotas] = resource.MustParse("1") - usedResources[api.ResourceReplicationControllers] = resource.MustParse("0") + usedResources := v1.ResourceList{} + usedResources[v1.ResourceQuotas] = resource.MustParse("1") + usedResources[v1.ResourceReplicationControllers] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) @@ -252,8 +252,8 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status captures replication controller creation") - usedResources = api.ResourceList{} - usedResources[api.ResourceReplicationControllers] = resource.MustParse("1") + usedResources = v1.ResourceList{} + usedResources[v1.ResourceReplicationControllers] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) @@ -262,7 +262,7 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status released usage") - usedResources[api.ResourceReplicationControllers] = resource.MustParse("0") + usedResources[v1.ResourceReplicationControllers] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) }) @@ -275,10 +275,10 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status is calculated") - usedResources := api.ResourceList{} - usedResources[api.ResourceQuotas] = resource.MustParse("1") - usedResources[api.ResourcePersistentVolumeClaims] = resource.MustParse("0") - usedResources[api.ResourceRequestsStorage] = resource.MustParse("0") + usedResources := v1.ResourceList{} + usedResources[v1.ResourceQuotas] = resource.MustParse("1") + usedResources[v1.ResourcePersistentVolumeClaims] = resource.MustParse("0") + usedResources[v1.ResourceRequestsStorage] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) @@ -288,9 +288,9 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status captures persistent volume claimcreation") - usedResources = api.ResourceList{} - usedResources[api.ResourcePersistentVolumeClaims] = resource.MustParse("1") - usedResources[api.ResourceRequestsStorage] = resource.MustParse("1Gi") + usedResources = v1.ResourceList{} + usedResources[v1.ResourcePersistentVolumeClaims] = resource.MustParse("1") + usedResources[v1.ResourceRequestsStorage] = resource.MustParse("1Gi") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) @@ -299,8 +299,8 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status released usage") - usedResources[api.ResourcePersistentVolumeClaims] = resource.MustParse("0") - usedResources[api.ResourceRequestsStorage] = resource.MustParse("0") + usedResources[v1.ResourcePersistentVolumeClaims] = resource.MustParse("0") + usedResources[v1.ResourceRequestsStorage] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) Expect(err).NotTo(HaveOccurred()) }) @@ -308,18 +308,18 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { It("should verify ResourceQuota with terminating scopes.", func() { By("Creating a ResourceQuota with terminating scope") quotaTerminatingName := "quota-terminating" - resourceQuotaTerminating, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope(quotaTerminatingName, api.ResourceQuotaScopeTerminating)) + resourceQuotaTerminating, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope(quotaTerminatingName, v1.ResourceQuotaScopeTerminating)) Expect(err).NotTo(HaveOccurred()) By("Ensuring ResourceQuota status is calculated") - usedResources := api.ResourceList{} - usedResources[api.ResourcePods] = resource.MustParse("0") + usedResources := v1.ResourceList{} + usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) Expect(err).NotTo(HaveOccurred()) By("Creating a ResourceQuota with not terminating scope") quotaNotTerminatingName := "quota-not-terminating" - resourceQuotaNotTerminating, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope(quotaNotTerminatingName, api.ResourceQuotaScopeNotTerminating)) + resourceQuotaNotTerminating, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope(quotaNotTerminatingName, v1.ResourceQuotaScopeNotTerminating)) Expect(err).NotTo(HaveOccurred()) By("Ensuring ResourceQuota status is calculated") @@ -328,44 +328,44 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { By("Creating a long running pod") podName := "test-pod" - requests := api.ResourceList{} - requests[api.ResourceCPU] = resource.MustParse("500m") - requests[api.ResourceMemory] = resource.MustParse("200Mi") - limits := api.ResourceList{} - limits[api.ResourceCPU] = resource.MustParse("1") - limits[api.ResourceMemory] = resource.MustParse("400Mi") + requests := v1.ResourceList{} + requests[v1.ResourceCPU] = resource.MustParse("500m") + requests[v1.ResourceMemory] = resource.MustParse("200Mi") + limits := v1.ResourceList{} + limits[v1.ResourceCPU] = resource.MustParse("1") + limits[v1.ResourceMemory] = resource.MustParse("400Mi") pod := newTestPodForQuota(f, podName, requests, limits) pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota with not terminating scope captures the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("1") - usedResources[api.ResourceRequestsCPU] = requests[api.ResourceCPU] - usedResources[api.ResourceRequestsMemory] = requests[api.ResourceMemory] - usedResources[api.ResourceLimitsCPU] = limits[api.ResourceCPU] - usedResources[api.ResourceLimitsMemory] = limits[api.ResourceMemory] + usedResources[v1.ResourcePods] = resource.MustParse("1") + usedResources[v1.ResourceRequestsCPU] = requests[v1.ResourceCPU] + usedResources[v1.ResourceRequestsMemory] = requests[v1.ResourceMemory] + usedResources[v1.ResourceLimitsCPU] = limits[v1.ResourceCPU] + usedResources[v1.ResourceLimitsMemory] = limits[v1.ResourceMemory] err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotTerminating.Name, usedResources) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota with terminating scope ignored the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("0") - usedResources[api.ResourceRequestsCPU] = resource.MustParse("0") - usedResources[api.ResourceRequestsMemory] = resource.MustParse("0") - usedResources[api.ResourceLimitsCPU] = resource.MustParse("0") - usedResources[api.ResourceLimitsMemory] = resource.MustParse("0") + usedResources[v1.ResourcePods] = resource.MustParse("0") + usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") + usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") + usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") + usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) Expect(err).NotTo(HaveOccurred()) By("Deleting the pod") - err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(podName, api.NewDeleteOptions(0)) + err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(podName, v1.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status released the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("0") - usedResources[api.ResourceRequestsCPU] = resource.MustParse("0") - usedResources[api.ResourceRequestsMemory] = resource.MustParse("0") - usedResources[api.ResourceLimitsCPU] = resource.MustParse("0") - usedResources[api.ResourceLimitsMemory] = resource.MustParse("0") + usedResources[v1.ResourcePods] = resource.MustParse("0") + usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") + usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") + usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") + usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotTerminating.Name, usedResources) Expect(err).NotTo(HaveOccurred()) @@ -378,50 +378,50 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota with terminating scope captures the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("1") - usedResources[api.ResourceRequestsCPU] = requests[api.ResourceCPU] - usedResources[api.ResourceRequestsMemory] = requests[api.ResourceMemory] - usedResources[api.ResourceLimitsCPU] = limits[api.ResourceCPU] - usedResources[api.ResourceLimitsMemory] = limits[api.ResourceMemory] + usedResources[v1.ResourcePods] = resource.MustParse("1") + usedResources[v1.ResourceRequestsCPU] = requests[v1.ResourceCPU] + usedResources[v1.ResourceRequestsMemory] = requests[v1.ResourceMemory] + usedResources[v1.ResourceLimitsCPU] = limits[v1.ResourceCPU] + usedResources[v1.ResourceLimitsMemory] = limits[v1.ResourceMemory] err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota with not terminating scope ignored the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("0") - usedResources[api.ResourceRequestsCPU] = resource.MustParse("0") - usedResources[api.ResourceRequestsMemory] = resource.MustParse("0") - usedResources[api.ResourceLimitsCPU] = resource.MustParse("0") - usedResources[api.ResourceLimitsMemory] = resource.MustParse("0") + usedResources[v1.ResourcePods] = resource.MustParse("0") + usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") + usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") + usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") + usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotTerminating.Name, usedResources) Expect(err).NotTo(HaveOccurred()) By("Deleting the pod") - err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(podName, api.NewDeleteOptions(0)) + err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(podName, v1.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status released the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("0") - usedResources[api.ResourceRequestsCPU] = resource.MustParse("0") - usedResources[api.ResourceRequestsMemory] = resource.MustParse("0") - usedResources[api.ResourceLimitsCPU] = resource.MustParse("0") - usedResources[api.ResourceLimitsMemory] = resource.MustParse("0") + usedResources[v1.ResourcePods] = resource.MustParse("0") + usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") + usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") + usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") + usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) Expect(err).NotTo(HaveOccurred()) }) It("should verify ResourceQuota with best effort scope.", func() { By("Creating a ResourceQuota with best effort scope") - resourceQuotaBestEffort, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope("quota-besteffort", api.ResourceQuotaScopeBestEffort)) + resourceQuotaBestEffort, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope("quota-besteffort", v1.ResourceQuotaScopeBestEffort)) Expect(err).NotTo(HaveOccurred()) By("Ensuring ResourceQuota status is calculated") - usedResources := api.ResourceList{} - usedResources[api.ResourcePods] = resource.MustParse("0") + usedResources := v1.ResourceList{} + usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) Expect(err).NotTo(HaveOccurred()) By("Creating a ResourceQuota with not best effort scope") - resourceQuotaNotBestEffort, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope("quota-not-besteffort", api.ResourceQuotaScopeNotBestEffort)) + resourceQuotaNotBestEffort, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope("quota-not-besteffort", v1.ResourceQuotaScopeNotBestEffort)) Expect(err).NotTo(HaveOccurred()) By("Ensuring ResourceQuota status is calculated") @@ -429,111 +429,111 @@ var _ = framework.KubeDescribe("ResourceQuota", func() { Expect(err).NotTo(HaveOccurred()) By("Creating a best-effort pod") - pod := newTestPodForQuota(f, podName, api.ResourceList{}, api.ResourceList{}) + pod := newTestPodForQuota(f, podName, v1.ResourceList{}, v1.ResourceList{}) pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota with best effort scope captures the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("1") + usedResources[v1.ResourcePods] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota with not best effort ignored the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("0") + usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotBestEffort.Name, usedResources) Expect(err).NotTo(HaveOccurred()) By("Deleting the pod") - err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(pod.Name, api.NewDeleteOptions(0)) + err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(pod.Name, v1.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status released the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("0") + usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) Expect(err).NotTo(HaveOccurred()) By("Creating a not best-effort pod") - requests := api.ResourceList{} - requests[api.ResourceCPU] = resource.MustParse("500m") - requests[api.ResourceMemory] = resource.MustParse("200Mi") - limits := api.ResourceList{} - limits[api.ResourceCPU] = resource.MustParse("1") - limits[api.ResourceMemory] = resource.MustParse("400Mi") + requests := v1.ResourceList{} + requests[v1.ResourceCPU] = resource.MustParse("500m") + requests[v1.ResourceMemory] = resource.MustParse("200Mi") + limits := v1.ResourceList{} + limits[v1.ResourceCPU] = resource.MustParse("1") + limits[v1.ResourceMemory] = resource.MustParse("400Mi") pod = newTestPodForQuota(f, "burstable-pod", requests, limits) pod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Create(pod) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota with not best effort scope captures the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("1") + usedResources[v1.ResourcePods] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotBestEffort.Name, usedResources) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota with best effort scope ignored the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("0") + usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) Expect(err).NotTo(HaveOccurred()) By("Deleting the pod") - err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(pod.Name, api.NewDeleteOptions(0)) + err = f.ClientSet.Core().Pods(f.Namespace.Name).Delete(pod.Name, v1.NewDeleteOptions(0)) Expect(err).NotTo(HaveOccurred()) By("Ensuring resource quota status released the pod usage") - usedResources[api.ResourcePods] = resource.MustParse("0") + usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotBestEffort.Name, usedResources) Expect(err).NotTo(HaveOccurred()) }) }) // newTestResourceQuotaWithScope returns a quota that enforces default constraints for testing with scopes -func newTestResourceQuotaWithScope(name string, scope api.ResourceQuotaScope) *api.ResourceQuota { - hard := api.ResourceList{} - hard[api.ResourcePods] = resource.MustParse("5") +func newTestResourceQuotaWithScope(name string, scope v1.ResourceQuotaScope) *v1.ResourceQuota { + hard := v1.ResourceList{} + hard[v1.ResourcePods] = resource.MustParse("5") switch scope { - case api.ResourceQuotaScopeTerminating, api.ResourceQuotaScopeNotTerminating: - hard[api.ResourceRequestsCPU] = resource.MustParse("1") - hard[api.ResourceRequestsMemory] = resource.MustParse("500Mi") - hard[api.ResourceLimitsCPU] = resource.MustParse("2") - hard[api.ResourceLimitsMemory] = resource.MustParse("1Gi") + case v1.ResourceQuotaScopeTerminating, v1.ResourceQuotaScopeNotTerminating: + hard[v1.ResourceRequestsCPU] = resource.MustParse("1") + hard[v1.ResourceRequestsMemory] = resource.MustParse("500Mi") + hard[v1.ResourceLimitsCPU] = resource.MustParse("2") + hard[v1.ResourceLimitsMemory] = resource.MustParse("1Gi") } - return &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{Name: name}, - Spec: api.ResourceQuotaSpec{Hard: hard, Scopes: []api.ResourceQuotaScope{scope}}, + return &v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{Name: name}, + Spec: v1.ResourceQuotaSpec{Hard: hard, Scopes: []v1.ResourceQuotaScope{scope}}, } } // newTestResourceQuota returns a quota that enforces default constraints for testing -func newTestResourceQuota(name string) *api.ResourceQuota { - hard := api.ResourceList{} - hard[api.ResourcePods] = resource.MustParse("5") - hard[api.ResourceServices] = resource.MustParse("10") - hard[api.ResourceServicesNodePorts] = resource.MustParse("1") - hard[api.ResourceServicesLoadBalancers] = resource.MustParse("1") - hard[api.ResourceReplicationControllers] = resource.MustParse("10") - hard[api.ResourceQuotas] = resource.MustParse("1") - hard[api.ResourceCPU] = resource.MustParse("1") - hard[api.ResourceMemory] = resource.MustParse("500Mi") - hard[api.ResourceConfigMaps] = resource.MustParse("2") - hard[api.ResourceSecrets] = resource.MustParse("10") - hard[api.ResourcePersistentVolumeClaims] = resource.MustParse("10") - hard[api.ResourceRequestsStorage] = resource.MustParse("10Gi") - return &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{Name: name}, - Spec: api.ResourceQuotaSpec{Hard: hard}, +func newTestResourceQuota(name string) *v1.ResourceQuota { + hard := v1.ResourceList{} + hard[v1.ResourcePods] = resource.MustParse("5") + hard[v1.ResourceServices] = resource.MustParse("10") + hard[v1.ResourceServicesNodePorts] = resource.MustParse("1") + hard[v1.ResourceServicesLoadBalancers] = resource.MustParse("1") + hard[v1.ResourceReplicationControllers] = resource.MustParse("10") + hard[v1.ResourceQuotas] = resource.MustParse("1") + hard[v1.ResourceCPU] = resource.MustParse("1") + hard[v1.ResourceMemory] = resource.MustParse("500Mi") + hard[v1.ResourceConfigMaps] = resource.MustParse("2") + hard[v1.ResourceSecrets] = resource.MustParse("10") + hard[v1.ResourcePersistentVolumeClaims] = resource.MustParse("10") + hard[v1.ResourceRequestsStorage] = resource.MustParse("10Gi") + return &v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{Name: name}, + Spec: v1.ResourceQuotaSpec{Hard: hard}, } } // newTestPodForQuota returns a pod that has the specified requests and limits -func newTestPodForQuota(f *framework.Framework, name string, requests api.ResourceList, limits api.ResourceList) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func newTestPodForQuota(f *framework.Framework, name string, requests v1.ResourceList, limits v1.ResourceList) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "pause", Image: framework.GetPauseImageName(f.ClientSet), - Resources: api.ResourceRequirements{ + Resources: v1.ResourceRequirements{ Requests: requests, Limits: limits, }, @@ -544,20 +544,20 @@ func newTestPodForQuota(f *framework.Framework, name string, requests api.Resour } // newTestPersistentVolumeClaimForQuota returns a simple persistent volume claim -func newTestPersistentVolumeClaimForQuota(name string) *api.PersistentVolumeClaim { - return &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ +func newTestPersistentVolumeClaimForQuota(name string) *v1.PersistentVolumeClaim { + return &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - api.ReadWriteMany, + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, + v1.ReadOnlyMany, + v1.ReadWriteMany, }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("1Gi"), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse("1Gi"), }, }, }, @@ -565,22 +565,22 @@ func newTestPersistentVolumeClaimForQuota(name string) *api.PersistentVolumeClai } // newTestReplicationControllerForQuota returns a simple replication controller -func newTestReplicationControllerForQuota(name, image string, replicas int32) *api.ReplicationController { - return &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ +func newTestReplicationControllerForQuota(name, image string, replicas int32) *v1.ReplicationController { + return &v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.ReplicationControllerSpec{ - Replicas: replicas, + Spec: v1.ReplicationControllerSpec{ + Replicas: func(i int32) *int32 { return &i }(replicas), Selector: map[string]string{ "name": name, }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"name": name}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: name, Image: image, @@ -593,14 +593,14 @@ func newTestReplicationControllerForQuota(name, image string, replicas int32) *a } // newTestServiceForQuota returns a simple service -func newTestServiceForQuota(name string, serviceType api.ServiceType) *api.Service { - return &api.Service{ - ObjectMeta: api.ObjectMeta{ +func newTestServiceForQuota(name string, serviceType v1.ServiceType) *v1.Service { + return &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Type: serviceType, - Ports: []api.ServicePort{{ + Ports: []v1.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}, @@ -608,9 +608,9 @@ func newTestServiceForQuota(name string, serviceType api.ServiceType) *api.Servi } } -func newTestConfigMapForQuota(name string) *api.ConfigMap { - return &api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ +func newTestConfigMapForQuota(name string) *v1.ConfigMap { + return &v1.ConfigMap{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, Data: map[string]string{ @@ -619,9 +619,9 @@ func newTestConfigMapForQuota(name string) *api.ConfigMap { } } -func newTestSecretForQuota(name string) *api.Secret { - return &api.Secret{ - ObjectMeta: api.ObjectMeta{ +func newTestSecretForQuota(name string) *v1.Secret { + return &v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, Data: map[string][]byte{ @@ -633,7 +633,7 @@ func newTestSecretForQuota(name string) *api.Secret { } // createResourceQuota in the specified namespace -func createResourceQuota(c clientset.Interface, namespace string, resourceQuota *api.ResourceQuota) (*api.ResourceQuota, error) { +func createResourceQuota(c clientset.Interface, namespace string, resourceQuota *v1.ResourceQuota) (*v1.ResourceQuota, error) { return c.Core().ResourceQuotas(namespace).Create(resourceQuota) } @@ -643,7 +643,7 @@ func deleteResourceQuota(c clientset.Interface, namespace, name string) error { } // wait for resource quota status to show the expected used resources value -func waitForResourceQuota(c clientset.Interface, ns, quotaName string, used api.ResourceList) error { +func waitForResourceQuota(c clientset.Interface, ns, quotaName string, used v1.ResourceList) error { return wait.Poll(framework.Poll, resourceQuotaTimeout, func() (bool, error) { resourceQuota, err := c.Core().ResourceQuotas(ns).Get(quotaName) if err != nil { diff --git a/test/e2e/restart.go b/test/e2e/restart.go index bea33956afb..860ef7e833b 100644 --- a/test/e2e/restart.go +++ b/test/e2e/restart.go @@ -21,6 +21,7 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/fields" kubepod "k8s.io/kubernetes/pkg/kubelet/pod" "k8s.io/kubernetes/pkg/labels" @@ -32,15 +33,15 @@ import ( . "github.com/onsi/gomega" ) -func isNotRestartAlwaysMirrorPod(p *api.Pod) bool { +func isNotRestartAlwaysMirrorPod(p *v1.Pod) bool { if !kubepod.IsMirrorPod(p) { return false } - return p.Spec.RestartPolicy != api.RestartPolicyAlways + return p.Spec.RestartPolicy != v1.RestartPolicyAlways } -func filterIrrelevantPods(pods []*api.Pod) []*api.Pod { - var results []*api.Pod +func filterIrrelevantPods(pods []*v1.Pod) []*v1.Pod { + var results []*v1.Pod for _, p := range pods { if isNotRestartAlwaysMirrorPod(p) { // Mirror pods with restart policy == Never will not get @@ -128,7 +129,7 @@ var _ = framework.KubeDescribe("Restart [Disruptive]", func() { // returning their names if it can do so before timeout. func waitForNPods(ps *testutils.PodStore, expect int, timeout time.Duration) ([]string, error) { // Loop until we find expect pods or timeout is passed. - var pods []*api.Pod + var pods []*v1.Pod var errLast error found := wait.Poll(framework.Poll, timeout, func() (bool, error) { allPods := ps.List() diff --git a/test/e2e/scheduler_predicates.go b/test/e2e/scheduler_predicates.go index d0d9b7471cf..ac507c5a805 100644 --- a/test/e2e/scheduler_predicates.go +++ b/test/e2e/scheduler_predicates.go @@ -23,7 +23,8 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -44,12 +45,12 @@ type pausePodConfig struct { Name string Affinity string Annotations, Labels, NodeSelector map[string]string - Resources *api.ResourceRequirements + Resources *v1.ResourceRequirements } var _ = framework.KubeDescribe("SchedulerPredicates [Serial]", func() { var cs clientset.Interface - var nodeList *api.NodeList + var nodeList *v1.NodeList var systemPodsNo int var totalPodCapacity int64 var RCName string @@ -59,9 +60,9 @@ var _ = framework.KubeDescribe("SchedulerPredicates [Serial]", func() { AfterEach(func() { rc, err := cs.Core().ReplicationControllers(ns).Get(RCName) - if err == nil && rc.Spec.Replicas != 0 { + if err == nil && *(rc.Spec.Replicas) != 0 { By("Cleaning up the replication controller") - err := framework.DeleteRCAndPods(f.ClientSet, ns, RCName) + err := framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, ns, RCName) framework.ExpectNoError(err) } }) @@ -69,7 +70,7 @@ var _ = framework.KubeDescribe("SchedulerPredicates [Serial]", func() { BeforeEach(func() { cs = f.ClientSet ns = f.Namespace.Name - nodeList = &api.NodeList{} + nodeList = &v1.NodeList{} framework.WaitForAllNodesHealthy(cs, time.Minute) masterNodes, nodeList = framework.GetMasterAndWorkerNodesOrDie(cs) @@ -156,11 +157,11 @@ var _ = framework.KubeDescribe("SchedulerPredicates [Serial]", func() { } framework.WaitForStableCluster(cs, masterNodes) - pods, err := cs.Core().Pods(api.NamespaceAll).List(api.ListOptions{}) + pods, err := cs.Core().Pods(v1.NamespaceAll).List(v1.ListOptions{}) framework.ExpectNoError(err) for _, pod := range pods.Items { _, found := nodeToCapacityMap[pod.Spec.NodeName] - if found && pod.Status.Phase != api.PodSucceeded && pod.Status.Phase != api.PodFailed { + if found && pod.Status.Phase != v1.PodSucceeded && pod.Status.Phase != v1.PodFailed { framework.Logf("Pod %v requesting resource cpu=%vm on Node %v", pod.Name, getRequestedCPU(pod), pod.Spec.NodeName) nodeToCapacityMap[pod.Spec.NodeName] -= getRequestedCPU(pod) } @@ -189,11 +190,11 @@ var _ = framework.KubeDescribe("SchedulerPredicates [Serial]", func() { *initPausePod(f, pausePodConfig{ Name: "", Labels: map[string]string{"name": ""}, - Resources: &api.ResourceRequirements{ - Limits: api.ResourceList{ + Resources: &v1.ResourceRequirements{ + Limits: v1.ResourceList{ "cpu": *resource.NewMilliQuantity(milliCpuPerPod, "DecimalSI"), }, - Requests: api.ResourceList{ + Requests: v1.ResourceList{ "cpu": *resource.NewMilliQuantity(milliCpuPerPod, "DecimalSI"), }, }, @@ -203,8 +204,8 @@ var _ = framework.KubeDescribe("SchedulerPredicates [Serial]", func() { createPausePod(f, pausePodConfig{ Name: podName, Labels: map[string]string{"name": "additional"}, - Resources: &api.ResourceRequirements{ - Limits: api.ResourceList{ + Resources: &v1.ResourceRequirements{ + Limits: v1.ResourceList{ "cpu": *resource.NewMilliQuantity(milliCpuPerPod, "DecimalSI"), }, }, @@ -511,8 +512,8 @@ var _ = framework.KubeDescribe("SchedulerPredicates [Serial]", func() { // cannot be scheduled onto it. By("Launching two pods on two distinct nodes to get two node names") CreateHostPortPods(f, "host-port", 2, true) - defer framework.DeleteRCAndPods(f.ClientSet, ns, "host-port") - podList, err := cs.Core().Pods(ns).List(api.ListOptions{}) + defer framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, ns, "host-port") + podList, err := cs.Core().Pods(ns).List(v1.ListOptions{}) ExpectNoError(err) Expect(len(podList.Items)).To(Equal(2)) nodeNames := []string{podList.Items[0].Spec.NodeName, podList.Items[1].Spec.NodeName} @@ -671,10 +672,10 @@ var _ = framework.KubeDescribe("SchedulerPredicates [Serial]", func() { nodeName := getNodeThatCanRunPodWithoutToleration(f) By("Trying to apply a random taint on the found node.") - testTaint := api.Taint{ + testTaint := v1.Taint{ Key: fmt.Sprintf("kubernetes.io/e2e-taint-key-%s", string(uuid.NewUUID())), Value: "testing-taint-value", - Effect: api.TaintEffectNoSchedule, + Effect: v1.TaintEffectNoSchedule, } framework.AddOrUpdateTaintOnNode(cs, nodeName, testTaint) framework.ExpectNodeHasTaint(cs, nodeName, testTaint) @@ -723,10 +724,10 @@ var _ = framework.KubeDescribe("SchedulerPredicates [Serial]", func() { nodeName := getNodeThatCanRunPodWithoutToleration(f) By("Trying to apply a random taint on the found node.") - testTaint := api.Taint{ + testTaint := v1.Taint{ Key: fmt.Sprintf("kubernetes.io/e2e-taint-key-%s", string(uuid.NewUUID())), Value: "testing-taint-value", - Effect: api.TaintEffectNoSchedule, + Effect: v1.TaintEffectNoSchedule, } framework.AddOrUpdateTaintOnNode(cs, nodeName, testTaint) framework.ExpectNodeHasTaint(cs, nodeName, testTaint) @@ -757,25 +758,25 @@ var _ = framework.KubeDescribe("SchedulerPredicates [Serial]", func() { }) }) -func initPausePod(f *framework.Framework, conf pausePodConfig) *api.Pod { +func initPausePod(f *framework.Framework, conf pausePodConfig) *v1.Pod { if conf.Affinity != "" { if conf.Annotations == nil { conf.Annotations = map[string]string{ - api.AffinityAnnotationKey: conf.Affinity, + v1.AffinityAnnotationKey: conf.Affinity, } } else { - conf.Annotations[api.AffinityAnnotationKey] = conf.Affinity + conf.Annotations[v1.AffinityAnnotationKey] = conf.Affinity } } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: conf.Name, Labels: conf.Labels, Annotations: conf.Annotations, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ NodeSelector: conf.NodeSelector, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: podName, Image: framework.GetPauseImageName(f.ClientSet), @@ -789,13 +790,13 @@ func initPausePod(f *framework.Framework, conf pausePodConfig) *api.Pod { return pod } -func createPausePod(f *framework.Framework, conf pausePodConfig) *api.Pod { +func createPausePod(f *framework.Framework, conf pausePodConfig) *v1.Pod { pod, err := f.ClientSet.Core().Pods(f.Namespace.Name).Create(initPausePod(f, conf)) framework.ExpectNoError(err) return pod } -func runPausePod(f *framework.Framework, conf pausePodConfig) *api.Pod { +func runPausePod(f *framework.Framework, conf pausePodConfig) *v1.Pod { pod := createPausePod(f, conf) framework.ExpectNoError(framework.WaitForPodRunningInNamespace(f.ClientSet, pod)) pod, err := f.ClientSet.Core().Pods(f.Namespace.Name).Get(conf.Name) @@ -811,13 +812,13 @@ func runPodAndGetNodeName(f *framework.Framework, conf pausePodConfig) string { pod := runPausePod(f, conf) By("Explicitly delete pod here to free the resource it takes.") - err := f.ClientSet.Core().Pods(f.Namespace.Name).Delete(pod.Name, api.NewDeleteOptions(0)) + err := f.ClientSet.Core().Pods(f.Namespace.Name).Delete(pod.Name, v1.NewDeleteOptions(0)) framework.ExpectNoError(err) return pod.Spec.NodeName } -func createPodWithNodeAffinity(f *framework.Framework) *api.Pod { +func createPodWithNodeAffinity(f *framework.Framework) *v1.Pod { return createPausePod(f, pausePodConfig{ Name: "with-nodeaffinity-" + string(uuid.NewUUID()), Affinity: `{ @@ -836,7 +837,7 @@ func createPodWithNodeAffinity(f *framework.Framework) *api.Pod { }) } -func createPodWithPodAffinity(f *framework.Framework, topologyKey string) *api.Pod { +func createPodWithPodAffinity(f *framework.Framework, topologyKey string) *v1.Pod { return createPausePod(f, pausePodConfig{ Name: "with-podantiaffinity-" + string(uuid.NewUUID()), Affinity: `{ @@ -869,23 +870,23 @@ func createPodWithPodAffinity(f *framework.Framework, topologyKey string) *api.P } // Returns a number of currently scheduled and not scheduled Pods. -func getPodsScheduled(pods *api.PodList) (scheduledPods, notScheduledPods []api.Pod) { +func getPodsScheduled(pods *v1.PodList) (scheduledPods, notScheduledPods []v1.Pod) { for _, pod := range pods.Items { if !masterNodes.Has(pod.Spec.NodeName) { if pod.Spec.NodeName != "" { - _, scheduledCondition := api.GetPodCondition(&pod.Status, api.PodScheduled) + _, scheduledCondition := v1.GetPodCondition(&pod.Status, v1.PodScheduled) // We can't assume that the scheduledCondition is always set if Pod is assigned to Node, // as e.g. DaemonController doesn't set it when assigning Pod to a Node. Currently // Kubelet sets this condition when it gets a Pod without it, but if we were expecting // that it would always be not nil, this would cause a rare race condition. if scheduledCondition != nil { - Expect(scheduledCondition.Status).To(Equal(api.ConditionTrue)) + Expect(scheduledCondition.Status).To(Equal(v1.ConditionTrue)) } scheduledPods = append(scheduledPods, pod) } else { - _, scheduledCondition := api.GetPodCondition(&pod.Status, api.PodScheduled) + _, scheduledCondition := v1.GetPodCondition(&pod.Status, v1.PodScheduled) if scheduledCondition != nil { - Expect(scheduledCondition.Status).To(Equal(api.ConditionFalse)) + Expect(scheduledCondition.Status).To(Equal(v1.ConditionFalse)) } if scheduledCondition.Reason == "Unschedulable" { notScheduledPods = append(notScheduledPods, pod) @@ -896,7 +897,7 @@ func getPodsScheduled(pods *api.PodList) (scheduledPods, notScheduledPods []api. return } -func getRequestedCPU(pod api.Pod) int64 { +func getRequestedCPU(pod v1.Pod) int64 { var result int64 for _, container := range pod.Spec.Containers { result += container.Resources.Requests.Cpu().MilliValue() @@ -913,7 +914,7 @@ func waitForScheduler() { // TODO: upgrade calls in PodAffinity tests when we're able to run them func verifyResult(c clientset.Interface, expectedScheduled int, expectedNotScheduled int, ns string) { - allPods, err := c.Core().Pods(ns).List(api.ListOptions{}) + allPods, err := c.Core().Pods(ns).List(v1.ListOptions{}) framework.ExpectNoError(err) scheduledPods, notScheduledPods := framework.GetPodsScheduled(masterNodes, allPods) diff --git a/test/e2e/security_context.go b/test/e2e/security_context.go index 18b26799a76..95bd93fed2b 100644 --- a/test/e2e/security_context.go +++ b/test/e2e/security_context.go @@ -25,7 +25,7 @@ package e2e import ( "fmt" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -33,26 +33,25 @@ import ( . "github.com/onsi/gomega" ) -func scTestPod(hostIPC bool, hostPID bool) *api.Pod { +func scTestPod(hostIPC bool, hostPID bool) *v1.Pod { podName := "security-context-" + string(uuid.NewUUID()) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{"name": podName}, Annotations: map[string]string{}, }, - Spec: api.PodSpec{ - SecurityContext: &api.PodSecurityContext{ - HostIPC: hostIPC, - HostPID: hostPID, - }, - Containers: []api.Container{ + Spec: v1.PodSpec{ + HostIPC: hostIPC, + HostPID: hostPID, + SecurityContext: &v1.PodSecurityContext{}, + Containers: []v1.Container{ { Name: "test-container", Image: "gcr.io/google_containers/busybox:1.24", }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } @@ -86,7 +85,7 @@ var _ = framework.KubeDescribe("Security Context [Feature:SecurityContext]", fun var uid int64 = 1001 var overrideUid int64 = 1002 pod.Spec.SecurityContext.RunAsUser = &uid - pod.Spec.Containers[0].SecurityContext = new(api.SecurityContext) + pod.Spec.Containers[0].SecurityContext = new(v1.SecurityContext) pod.Spec.Containers[0].SecurityContext.RunAsUser = &overrideUid pod.Spec.Containers[0].Command = []string{"sh", "-c", "id -u"} @@ -110,33 +109,33 @@ var _ = framework.KubeDescribe("Security Context [Feature:SecurityContext]", fun It("should support seccomp alpha unconfined annotation on the container [Feature:Seccomp]", func() { // TODO: port to SecurityContext as soon as seccomp is out of alpha pod := scTestPod(false, false) - pod.Annotations[api.SeccompContainerAnnotationKeyPrefix+"test-container"] = "unconfined" - pod.Annotations[api.SeccompPodAnnotationKey] = "docker/default" + pod.Annotations[v1.SeccompContainerAnnotationKeyPrefix+"test-container"] = "unconfined" + pod.Annotations[v1.SeccompPodAnnotationKey] = "docker/default" pod.Spec.Containers[0].Command = []string{"grep", "ecc", "/proc/self/status"} - f.TestContainerOutput(api.SeccompPodAnnotationKey, pod, 0, []string{"0"}) // seccomp disabled + f.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{"0"}) // seccomp disabled }) It("should support seccomp alpha unconfined annotation on the pod [Feature:Seccomp]", func() { // TODO: port to SecurityContext as soon as seccomp is out of alpha pod := scTestPod(false, false) - pod.Annotations[api.SeccompPodAnnotationKey] = "unconfined" + pod.Annotations[v1.SeccompPodAnnotationKey] = "unconfined" pod.Spec.Containers[0].Command = []string{"grep", "ecc", "/proc/self/status"} - f.TestContainerOutput(api.SeccompPodAnnotationKey, pod, 0, []string{"0"}) // seccomp disabled + f.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{"0"}) // seccomp disabled }) It("should support seccomp alpha docker/default annotation [Feature:Seccomp]", func() { // TODO: port to SecurityContext as soon as seccomp is out of alpha pod := scTestPod(false, false) - pod.Annotations[api.SeccompContainerAnnotationKeyPrefix+"test-container"] = "docker/default" + pod.Annotations[v1.SeccompContainerAnnotationKeyPrefix+"test-container"] = "docker/default" pod.Spec.Containers[0].Command = []string{"grep", "ecc", "/proc/self/status"} - f.TestContainerOutput(api.SeccompPodAnnotationKey, pod, 0, []string{"2"}) // seccomp filtered + f.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{"2"}) // seccomp filtered }) It("should support seccomp default which is unconfined [Feature:Seccomp]", func() { // TODO: port to SecurityContext as soon as seccomp is out of alpha pod := scTestPod(false, false) pod.Spec.Containers[0].Command = []string{"grep", "ecc", "/proc/self/status"} - f.TestContainerOutput(api.SeccompPodAnnotationKey, pod, 0, []string{"0"}) // seccomp disabled + f.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{"0"}) // seccomp disabled }) }) @@ -146,23 +145,23 @@ func testPodSELinuxLabeling(f *framework.Framework, hostIPC bool, hostPID bool) pod := scTestPod(hostIPC, hostPID) volumeName := "test-volume" mountPath := "/mounted_volume" - pod.Spec.Containers[0].VolumeMounts = []api.VolumeMount{ + pod.Spec.Containers[0].VolumeMounts = []v1.VolumeMount{ { Name: volumeName, MountPath: mountPath, }, } - pod.Spec.Volumes = []api.Volume{ + pod.Spec.Volumes = []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{ - Medium: api.StorageMediumDefault, + VolumeSource: v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{ + Medium: v1.StorageMediumDefault, }, }, }, } - pod.Spec.SecurityContext.SELinuxOptions = &api.SELinuxOptions{ + pod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{ Level: "s0:c0,c1", } pod.Spec.Containers[0].Command = []string{"sleep", "6000"} @@ -190,17 +189,17 @@ func testPodSELinuxLabeling(f *framework.Framework, hostIPC bool, hostPID bool) By(fmt.Sprintf("confirming a container with the same label can read the file under --volume-dir=%s", framework.TestContext.KubeVolumeDir)) pod = scTestPod(hostIPC, hostPID) pod.Spec.NodeName = foundPod.Spec.NodeName - volumeMounts := []api.VolumeMount{ + volumeMounts := []v1.VolumeMount{ { Name: volumeName, MountPath: mountPath, }, } - volumes := []api.Volume{ + volumes := []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{ + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{ Path: volumeHostPath, }, }, @@ -209,7 +208,7 @@ func testPodSELinuxLabeling(f *framework.Framework, hostIPC bool, hostPID bool) pod.Spec.Containers[0].VolumeMounts = volumeMounts pod.Spec.Volumes = volumes pod.Spec.Containers[0].Command = []string{"cat", testFilePath} - pod.Spec.SecurityContext.SELinuxOptions = &api.SELinuxOptions{ + pod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{ Level: "s0:c0,c1", } @@ -220,7 +219,7 @@ func testPodSELinuxLabeling(f *framework.Framework, hostIPC bool, hostPID bool) pod.Spec.Volumes = volumes pod.Spec.Containers[0].VolumeMounts = volumeMounts pod.Spec.Containers[0].Command = []string{"sleep", "6000"} - pod.Spec.SecurityContext.SELinuxOptions = &api.SELinuxOptions{ + pod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{ Level: "s0:c2,c3", } _, err = client.Create(pod) diff --git a/test/e2e/service.go b/test/e2e/service.go index 95e06bbc36f..914766295db 100644 --- a/test/e2e/service.go +++ b/test/e2e/service.go @@ -30,10 +30,11 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/service" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/api/v1/service" + "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/controller/endpoint" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/types" @@ -83,10 +84,12 @@ var _ = framework.KubeDescribe("Services", func() { f := framework.NewDefaultFramework("services") var cs clientset.Interface + var internalClientset internalclientset.Interface serviceLBNames := []string{} BeforeEach(func() { cs = f.ClientSet + internalClientset = f.InternalClientset }) AfterEach(func() { @@ -104,7 +107,7 @@ var _ = framework.KubeDescribe("Services", func() { // TODO: We get coverage of TCP/UDP and multi-port services through the DNS test. We should have a simpler test for multi-port TCP here. It("should provide secure master service [Conformance]", func() { - _, err := cs.Core().Services(api.NamespaceDefault).Get("kubernetes") + _, err := cs.Core().Services(v1.NamespaceDefault).Get("kubernetes") Expect(err).NotTo(HaveOccurred()) }) @@ -123,13 +126,13 @@ var _ = framework.KubeDescribe("Services", func() { Expect(err).NotTo(HaveOccurred()) }() - service := &api.Service{ - ObjectMeta: api.ObjectMeta{ + service := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: serviceName, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: labels, - Ports: []api.ServicePort{{ + Ports: []v1.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}, @@ -151,11 +154,11 @@ var _ = framework.KubeDescribe("Services", func() { name1 := "pod1" name2 := "pod2" - createPodOrFail(cs, ns, name1, labels, []api.ContainerPort{{ContainerPort: 80}}) + createPodOrFail(cs, ns, name1, labels, []v1.ContainerPort{{ContainerPort: 80}}) names[name1] = true validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{name1: {80}}) - createPodOrFail(cs, ns, name2, labels, []api.ContainerPort{{ContainerPort: 80}}) + createPodOrFail(cs, ns, name2, labels, []v1.ContainerPort{{ContainerPort: 80}}) names[name2] = true validateEndpointsOrFail(cs, ns, serviceName, PortsByPodName{name1: {80}, name2: {80}}) @@ -185,13 +188,13 @@ var _ = framework.KubeDescribe("Services", func() { svc2port := "svc2" By("creating service " + serviceName + " in namespace " + ns) - service := &api.Service{ - ObjectMeta: api.ObjectMeta{ + service := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: serviceName, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: labels, - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ { Name: "portname1", Port: 80, @@ -219,13 +222,13 @@ var _ = framework.KubeDescribe("Services", func() { } }() - containerPorts1 := []api.ContainerPort{ + containerPorts1 := []v1.ContainerPort{ { Name: svc1port, ContainerPort: int32(port1), }, } - containerPorts2 := []api.ContainerPort{ + containerPorts2 := []v1.ContainerPort{ { Name: svc2port, ContainerPort: int32(port2), @@ -261,7 +264,7 @@ var _ = framework.KubeDescribe("Services", func() { jig := NewServiceTestJig(cs, serviceName) servicePort := 8080 tcpService := jig.CreateTCPServiceWithPort(ns, nil, int32(servicePort)) - jig.SanityCheckService(tcpService, api.ServiceTypeClusterIP) + jig.SanityCheckService(tcpService, v1.ServiceTypeClusterIP) defer func() { framework.Logf("Cleaning up the sourceip test service") err := cs.Core().Services(ns).Delete(serviceName, nil) @@ -311,10 +314,10 @@ var _ = framework.KubeDescribe("Services", func() { numPods, servicePort := 3, 80 By("creating service1 in namespace " + ns) - podNames1, svc1IP, err := startServeHostnameService(cs, ns, "service1", servicePort, numPods) + podNames1, svc1IP, err := startServeHostnameService(cs, internalClientset, ns, "service1", servicePort, numPods) Expect(err).NotTo(HaveOccurred()) By("creating service2 in namespace " + ns) - podNames2, svc2IP, err := startServeHostnameService(cs, ns, "service2", servicePort, numPods) + podNames2, svc2IP, err := startServeHostnameService(cs, internalClientset, ns, "service2", servicePort, numPods) Expect(err).NotTo(HaveOccurred()) hosts, err := framework.NodeSSHHosts(cs) @@ -332,7 +335,7 @@ var _ = framework.KubeDescribe("Services", func() { // Stop service 1 and make sure it is gone. By("stopping service1") - framework.ExpectNoError(stopServeHostnameService(f.ClientSet, ns, "service1")) + framework.ExpectNoError(stopServeHostnameService(f.ClientSet, f.InternalClientset, ns, "service1")) By("verifying service1 is not up") framework.ExpectNoError(verifyServeHostnameServiceDown(cs, host, svc1IP, servicePort)) @@ -341,7 +344,7 @@ var _ = framework.KubeDescribe("Services", func() { // Start another service and verify both are up. By("creating service3 in namespace " + ns) - podNames3, svc3IP, err := startServeHostnameService(cs, ns, "service3", servicePort, numPods) + podNames3, svc3IP, err := startServeHostnameService(cs, internalClientset, ns, "service3", servicePort, numPods) Expect(err).NotTo(HaveOccurred()) if svc2IP == svc3IP { @@ -365,12 +368,12 @@ var _ = framework.KubeDescribe("Services", func() { svc1 := "service1" svc2 := "service2" - defer func() { framework.ExpectNoError(stopServeHostnameService(f.ClientSet, ns, svc1)) }() - podNames1, svc1IP, err := startServeHostnameService(cs, ns, svc1, servicePort, numPods) + defer func() { framework.ExpectNoError(stopServeHostnameService(f.ClientSet, f.InternalClientset, ns, svc1)) }() + podNames1, svc1IP, err := startServeHostnameService(cs, internalClientset, ns, svc1, servicePort, numPods) Expect(err).NotTo(HaveOccurred()) - defer func() { framework.ExpectNoError(stopServeHostnameService(f.ClientSet, ns, svc2)) }() - podNames2, svc2IP, err := startServeHostnameService(cs, ns, svc2, servicePort, numPods) + defer func() { framework.ExpectNoError(stopServeHostnameService(f.ClientSet, f.InternalClientset, ns, svc2)) }() + podNames2, svc2IP, err := startServeHostnameService(cs, internalClientset, ns, svc2, servicePort, numPods) Expect(err).NotTo(HaveOccurred()) if svc1IP == svc2IP { @@ -414,8 +417,10 @@ var _ = framework.KubeDescribe("Services", func() { ns := f.Namespace.Name numPods, servicePort := 3, 80 - defer func() { framework.ExpectNoError(stopServeHostnameService(f.ClientSet, ns, "service1")) }() - podNames1, svc1IP, err := startServeHostnameService(cs, ns, "service1", servicePort, numPods) + defer func() { + framework.ExpectNoError(stopServeHostnameService(f.ClientSet, f.InternalClientset, ns, "service1")) + }() + podNames1, svc1IP, err := startServeHostnameService(cs, internalClientset, ns, "service1", servicePort, numPods) Expect(err).NotTo(HaveOccurred()) hosts, err := framework.NodeSSHHosts(cs) @@ -439,8 +444,10 @@ var _ = framework.KubeDescribe("Services", func() { framework.ExpectNoError(verifyServeHostnameServiceUp(cs, ns, host, podNames1, svc1IP, servicePort)) // Create a new service and check if it's not reusing IP. - defer func() { framework.ExpectNoError(stopServeHostnameService(f.ClientSet, ns, "service2")) }() - podNames2, svc2IP, err := startServeHostnameService(cs, ns, "service2", servicePort, numPods) + defer func() { + framework.ExpectNoError(stopServeHostnameService(f.ClientSet, f.InternalClientset, ns, "service2")) + }() + podNames2, svc2IP, err := startServeHostnameService(cs, internalClientset, ns, "service2", servicePort, numPods) Expect(err).NotTo(HaveOccurred()) if svc1IP == svc2IP { @@ -461,10 +468,10 @@ var _ = framework.KubeDescribe("Services", func() { nodeIP := pickNodeIP(jig.Client) // for later By("creating service " + serviceName + " with type=NodePort in namespace " + ns) - service := jig.CreateTCPServiceOrFail(ns, func(svc *api.Service) { - svc.Spec.Type = api.ServiceTypeNodePort + service := jig.CreateTCPServiceOrFail(ns, func(svc *v1.Service) { + svc.Spec.Type = v1.ServiceTypeNodePort }) - jig.SanityCheckService(service, api.ServiceTypeNodePort) + jig.SanityCheckService(service, v1.ServiceTypeNodePort) nodePort := int(service.Spec.Ports[0].NodePort) By("creating pod to be part of service " + serviceName) @@ -521,11 +528,11 @@ var _ = framework.KubeDescribe("Services", func() { By("creating a TCP service " + serviceName + " with type=ClusterIP in namespace " + ns1) tcpService := jig.CreateTCPServiceOrFail(ns1, nil) - jig.SanityCheckService(tcpService, api.ServiceTypeClusterIP) + jig.SanityCheckService(tcpService, v1.ServiceTypeClusterIP) By("creating a UDP service " + serviceName + " with type=ClusterIP in namespace " + ns2) udpService := jig.CreateUDPServiceOrFail(ns2, nil) - jig.SanityCheckService(udpService, api.ServiceTypeClusterIP) + jig.SanityCheckService(udpService, v1.ServiceTypeClusterIP) By("verifying that TCP and UDP use the same port") if tcpService.Spec.Ports[0].Port != udpService.Spec.Ports[0].Port { @@ -543,18 +550,18 @@ var _ = framework.KubeDescribe("Services", func() { // Change the services to NodePort. By("changing the TCP service to type=NodePort") - tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) { - s.Spec.Type = api.ServiceTypeNodePort + tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *v1.Service) { + s.Spec.Type = v1.ServiceTypeNodePort }) - jig.SanityCheckService(tcpService, api.ServiceTypeNodePort) + jig.SanityCheckService(tcpService, v1.ServiceTypeNodePort) tcpNodePort := int(tcpService.Spec.Ports[0].NodePort) framework.Logf("TCP node port: %d", tcpNodePort) By("changing the UDP service to type=NodePort") - udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) { - s.Spec.Type = api.ServiceTypeNodePort + udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *v1.Service) { + s.Spec.Type = v1.ServiceTypeNodePort }) - jig.SanityCheckService(udpService, api.ServiceTypeNodePort) + jig.SanityCheckService(udpService, v1.ServiceTypeNodePort) udpNodePort := int(udpService.Spec.Ports[0].NodePort) framework.Logf("UDP node port: %d", udpNodePort) @@ -587,15 +594,15 @@ var _ = framework.KubeDescribe("Services", func() { } By("changing the TCP service to type=LoadBalancer") - tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) { + tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *v1.Service) { s.Spec.LoadBalancerIP = requestedIP // will be "" if not applicable - s.Spec.Type = api.ServiceTypeLoadBalancer + s.Spec.Type = v1.ServiceTypeLoadBalancer }) if loadBalancerSupportsUDP { By("changing the UDP service to type=LoadBalancer") - udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer + udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *v1.Service) { + s.Spec.Type = v1.ServiceTypeLoadBalancer }) } serviceLBNames = append(serviceLBNames, getLoadBalancerName(tcpService)) @@ -606,7 +613,7 @@ var _ = framework.KubeDescribe("Services", func() { By("waiting for the TCP service to have a load balancer") // Wait for the load balancer to be created asynchronously tcpService = jig.WaitForLoadBalancerOrFail(ns1, tcpService.Name, loadBalancerCreateTimeout) - jig.SanityCheckService(tcpService, api.ServiceTypeLoadBalancer) + jig.SanityCheckService(tcpService, v1.ServiceTypeLoadBalancer) if int(tcpService.Spec.Ports[0].NodePort) != tcpNodePort { framework.Failf("TCP Spec.Ports[0].NodePort changed (%d -> %d) when not expected", tcpNodePort, tcpService.Spec.Ports[0].NodePort) } @@ -637,7 +644,7 @@ var _ = framework.KubeDescribe("Services", func() { By("waiting for the UDP service to have a load balancer") // 2nd one should be faster since they ran in parallel. udpService = jig.WaitForLoadBalancerOrFail(ns2, udpService.Name, loadBalancerCreateTimeout) - jig.SanityCheckService(udpService, api.ServiceTypeLoadBalancer) + jig.SanityCheckService(udpService, v1.ServiceTypeLoadBalancer) if int(udpService.Spec.Ports[0].NodePort) != udpNodePort { framework.Failf("UDP Spec.Ports[0].NodePort changed (%d -> %d) when not expected", udpNodePort, udpService.Spec.Ports[0].NodePort) } @@ -668,7 +675,7 @@ var _ = framework.KubeDescribe("Services", func() { By("changing the TCP service's NodePort") tcpService = jig.ChangeServiceNodePortOrFail(ns1, tcpService.Name, tcpNodePort) - jig.SanityCheckService(tcpService, api.ServiceTypeLoadBalancer) + jig.SanityCheckService(tcpService, v1.ServiceTypeLoadBalancer) tcpNodePortOld := tcpNodePort tcpNodePort = int(tcpService.Spec.Ports[0].NodePort) if tcpNodePort == tcpNodePortOld { @@ -682,9 +689,9 @@ var _ = framework.KubeDescribe("Services", func() { By("changing the UDP service's NodePort") udpService = jig.ChangeServiceNodePortOrFail(ns2, udpService.Name, udpNodePort) if loadBalancerSupportsUDP { - jig.SanityCheckService(udpService, api.ServiceTypeLoadBalancer) + jig.SanityCheckService(udpService, v1.ServiceTypeLoadBalancer) } else { - jig.SanityCheckService(udpService, api.ServiceTypeNodePort) + jig.SanityCheckService(udpService, v1.ServiceTypeNodePort) } udpNodePortOld := udpNodePort udpNodePort = int(udpService.Spec.Ports[0].NodePort) @@ -719,10 +726,10 @@ var _ = framework.KubeDescribe("Services", func() { // Change the services' main ports. By("changing the TCP service's port") - tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) { + tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *v1.Service) { s.Spec.Ports[0].Port++ }) - jig.SanityCheckService(tcpService, api.ServiceTypeLoadBalancer) + jig.SanityCheckService(tcpService, v1.ServiceTypeLoadBalancer) svcPortOld := svcPort svcPort = int(tcpService.Spec.Ports[0].Port) if svcPort == svcPortOld { @@ -736,13 +743,13 @@ var _ = framework.KubeDescribe("Services", func() { } By("changing the UDP service's port") - udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) { + udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *v1.Service) { s.Spec.Ports[0].Port++ }) if loadBalancerSupportsUDP { - jig.SanityCheckService(udpService, api.ServiceTypeLoadBalancer) + jig.SanityCheckService(udpService, v1.ServiceTypeLoadBalancer) } else { - jig.SanityCheckService(udpService, api.ServiceTypeNodePort) + jig.SanityCheckService(udpService, v1.ServiceTypeNodePort) } if int(udpService.Spec.Ports[0].Port) != svcPort { framework.Failf("UDP Spec.Ports[0].Port (%d) did not change", udpService.Spec.Ports[0].Port) @@ -773,23 +780,23 @@ var _ = framework.KubeDescribe("Services", func() { // Change the services back to ClusterIP. By("changing TCP service back to type=ClusterIP") - tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) { - s.Spec.Type = api.ServiceTypeClusterIP + tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *v1.Service) { + s.Spec.Type = v1.ServiceTypeClusterIP s.Spec.Ports[0].NodePort = 0 }) // Wait for the load balancer to be destroyed asynchronously tcpService = jig.WaitForLoadBalancerDestroyOrFail(ns1, tcpService.Name, tcpIngressIP, svcPort, loadBalancerCreateTimeout) - jig.SanityCheckService(tcpService, api.ServiceTypeClusterIP) + jig.SanityCheckService(tcpService, v1.ServiceTypeClusterIP) By("changing UDP service back to type=ClusterIP") - udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) { - s.Spec.Type = api.ServiceTypeClusterIP + udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *v1.Service) { + s.Spec.Type = v1.ServiceTypeClusterIP s.Spec.Ports[0].NodePort = 0 }) if loadBalancerSupportsUDP { // Wait for the load balancer to be destroyed asynchronously udpService = jig.WaitForLoadBalancerDestroyOrFail(ns2, udpService.Name, udpIngressIP, svcPort, loadBalancerCreateTimeout) - jig.SanityCheckService(udpService, api.ServiceTypeClusterIP) + jig.SanityCheckService(udpService, v1.ServiceTypeClusterIP) } By("checking the TCP NodePort is closed") @@ -821,24 +828,24 @@ var _ = framework.KubeDescribe("Services", func() { }() By("creating service " + serviceName + " with same NodePort but different protocols in namespace " + ns) - service := &api.Service{ - ObjectMeta: api.ObjectMeta{ + service := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: t.ServiceName, Namespace: t.Namespace, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: t.Labels, - Type: api.ServiceTypeNodePort, - Ports: []api.ServicePort{ + Type: v1.ServiceTypeNodePort, + Ports: []v1.ServicePort{ { Name: "tcp-port", Port: 53, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, { Name: "udp-port", Port: 53, - Protocol: api.ProtocolUDP, + Protocol: v1.ProtocolUDP, }, }, }, @@ -872,11 +879,11 @@ var _ = framework.KubeDescribe("Services", func() { By("creating service " + serviceName1 + " with type NodePort in namespace " + ns) service := t.BuildServiceSpec() - service.Spec.Type = api.ServiceTypeNodePort + service.Spec.Type = v1.ServiceTypeNodePort result, err := t.CreateService(service) Expect(err).NotTo(HaveOccurred()) - if result.Spec.Type != api.ServiceTypeNodePort { + if result.Spec.Type != v1.ServiceTypeNodePort { framework.Failf("got unexpected Spec.Type for new service: %v", result) } if len(result.Spec.Ports) != 1 { @@ -890,7 +897,7 @@ var _ = framework.KubeDescribe("Services", func() { By("creating service " + serviceName2 + " with conflicting NodePort") service2 := t.BuildServiceSpec() service2.Name = serviceName2 - service2.Spec.Type = api.ServiceTypeNodePort + service2.Spec.Type = v1.ServiceTypeNodePort service2.Spec.Ports[0].NodePort = port.NodePort result2, err := t.CreateService(service2) if err == nil { @@ -923,13 +930,13 @@ var _ = framework.KubeDescribe("Services", func() { }() service := t.BuildServiceSpec() - service.Spec.Type = api.ServiceTypeNodePort + service.Spec.Type = v1.ServiceTypeNodePort By("creating service " + serviceName + " with type NodePort in namespace " + ns) service, err := t.CreateService(service) Expect(err).NotTo(HaveOccurred()) - if service.Spec.Type != api.ServiceTypeNodePort { + if service.Spec.Type != v1.ServiceTypeNodePort { framework.Failf("got unexpected Spec.Type for new service: %v", service) } if len(service.Spec.Ports) != 1 { @@ -952,7 +959,7 @@ var _ = framework.KubeDescribe("Services", func() { } } By(fmt.Sprintf("changing service "+serviceName+" to out-of-range NodePort %d", outOfRangeNodePort)) - result, err := updateService(cs, ns, serviceName, func(s *api.Service) { + result, err := updateService(cs, ns, serviceName, func(s *v1.Service) { s.Spec.Ports[0].NodePort = int32(outOfRangeNodePort) }) if err == nil { @@ -967,7 +974,7 @@ var _ = framework.KubeDescribe("Services", func() { By(fmt.Sprintf("creating service "+serviceName+" with out-of-range NodePort %d", outOfRangeNodePort)) service = t.BuildServiceSpec() - service.Spec.Type = api.ServiceTypeNodePort + service.Spec.Type = v1.ServiceTypeNodePort service.Spec.Ports[0].NodePort = int32(outOfRangeNodePort) service, err = t.CreateService(service) if err == nil { @@ -991,13 +998,13 @@ var _ = framework.KubeDescribe("Services", func() { }() service := t.BuildServiceSpec() - service.Spec.Type = api.ServiceTypeNodePort + service.Spec.Type = v1.ServiceTypeNodePort By("creating service " + serviceName + " with type NodePort in namespace " + ns) service, err := t.CreateService(service) Expect(err).NotTo(HaveOccurred()) - if service.Spec.Type != api.ServiceTypeNodePort { + if service.Spec.Type != v1.ServiceTypeNodePort { framework.Failf("got unexpected Spec.Type for new service: %v", service) } if len(service.Spec.Ports) != 1 { @@ -1033,7 +1040,7 @@ var _ = framework.KubeDescribe("Services", func() { By(fmt.Sprintf("creating service "+serviceName+" with same NodePort %d", nodePort)) service = t.BuildServiceSpec() - service.Spec.Type = api.ServiceTypeNodePort + service.Spec.Type = v1.ServiceTypeNodePort service.Spec.Ports[0].NodePort = nodePort service, err = t.CreateService(service) Expect(err).NotTo(HaveOccurred()) @@ -1054,13 +1061,13 @@ var _ = framework.KubeDescribe("Services", func() { service := t.BuildServiceSpec() service.Annotations = map[string]string{endpoint.TolerateUnreadyEndpointsAnnotation: "true"} - rcSpec := rcByNameContainer(t.name, 1, t.image, t.Labels, api.Container{ + rcSpec := rcByNameContainer(t.name, 1, t.image, t.Labels, v1.Container{ Name: t.name, Image: t.image, - Ports: []api.ContainerPort{{ContainerPort: int32(80), Protocol: api.ProtocolTCP}}, - ReadinessProbe: &api.Probe{ - Handler: api.Handler{ - Exec: &api.ExecAction{ + Ports: []v1.ContainerPort{{ContainerPort: int32(80), Protocol: v1.ProtocolTCP}}, + ReadinessProbe: &v1.Probe{ + Handler: v1.Handler{ + Exec: &v1.ExecAction{ Command: []string{"/bin/false"}, }, }, @@ -1139,7 +1146,7 @@ var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", framework.Failf("Service HealthCheck NodePort was not allocated") } defer func() { - jig.ChangeServiceType(svc.Namespace, svc.Name, api.ServiceTypeClusterIP, loadBalancerCreateTimeout) + jig.ChangeServiceType(svc.Namespace, svc.Name, v1.ServiceTypeClusterIP, loadBalancerCreateTimeout) // Make sure we didn't leak the health check node port. for name, ips := range jig.getEndpointNodes(svc) { @@ -1201,7 +1208,7 @@ var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", svc := jig.createOnlyLocalLoadBalancerService(namespace, serviceName, loadBalancerCreateTimeout, false) serviceLBNames = append(serviceLBNames, getLoadBalancerName(svc)) defer func() { - jig.ChangeServiceType(svc.Namespace, svc.Name, api.ServiceTypeClusterIP, loadBalancerCreateTimeout) + jig.ChangeServiceType(svc.Namespace, svc.Name, v1.ServiceTypeClusterIP, loadBalancerCreateTimeout) Expect(cs.Core().Services(svc.Namespace).Delete(svc.Name, nil)).NotTo(HaveOccurred()) }() @@ -1210,9 +1217,9 @@ var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", framework.Failf("Service HealthCheck NodePort was not allocated") } - ips := collectAddresses(nodes, api.NodeExternalIP) + ips := collectAddresses(nodes, v1.NodeExternalIP) if len(ips) == 0 { - ips = collectAddresses(nodes, api.NodeLegacyHostIP) + ips = collectAddresses(nodes, v1.NodeLegacyHostIP) } ingressIP := getIngressPoint(&svc.Status.LoadBalancer.Ingress[0]) @@ -1224,7 +1231,7 @@ var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", endpointNodeName := nodes.Items[i].Name By("creating a pod to be part of the service " + serviceName + " on node " + endpointNodeName) - jig.RunOrFail(namespace, func(rc *api.ReplicationController) { + jig.RunOrFail(namespace, func(rc *v1.ReplicationController) { rc.Name = serviceName if endpointNodeName != "" { rc.Spec.Template.Spec.NodeName = endpointNodeName @@ -1248,7 +1255,7 @@ var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", // Make sure the loadbalancer picked up the helth check change jig.TestReachableHTTP(ingressIP, svcTCPPort, kubeProxyLagTimeout) } - framework.ExpectNoError(framework.DeleteRCAndPods(f.ClientSet, namespace, serviceName)) + framework.ExpectNoError(framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, namespace, serviceName)) } }) @@ -1261,7 +1268,7 @@ var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", svc := jig.createOnlyLocalLoadBalancerService(namespace, serviceName, loadBalancerCreateTimeout, true) serviceLBNames = append(serviceLBNames, getLoadBalancerName(svc)) defer func() { - jig.ChangeServiceType(svc.Namespace, svc.Name, api.ServiceTypeClusterIP, loadBalancerCreateTimeout) + jig.ChangeServiceType(svc.Namespace, svc.Name, v1.ServiceTypeClusterIP, loadBalancerCreateTimeout) Expect(cs.Core().Services(svc.Namespace).Delete(svc.Name, nil)).NotTo(HaveOccurred()) }() @@ -1310,7 +1317,7 @@ var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", svc := jig.createOnlyLocalLoadBalancerService(namespace, serviceName, loadBalancerCreateTimeout, true) serviceLBNames = append(serviceLBNames, getLoadBalancerName(svc)) defer func() { - jig.ChangeServiceType(svc.Namespace, svc.Name, api.ServiceTypeClusterIP, loadBalancerCreateTimeout) + jig.ChangeServiceType(svc.Namespace, svc.Name, v1.ServiceTypeClusterIP, loadBalancerCreateTimeout) Expect(cs.Core().Services(svc.Namespace).Delete(svc.Name, nil)).NotTo(HaveOccurred()) }() @@ -1318,7 +1325,7 @@ var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", healthCheckNodePort := int(service.GetServiceHealthCheckNodePort(svc)) By("turning ESIPP off") - svc = jig.UpdateServiceOrFail(svc.Namespace, svc.Name, func(svc *api.Service) { + svc = jig.UpdateServiceOrFail(svc.Namespace, svc.Name, func(svc *v1.Service) { svc.ObjectMeta.Annotations[service.BetaAnnotationExternalTraffic] = service.AnnotationValueExternalTrafficGlobal }) @@ -1332,7 +1339,7 @@ var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", if _, ok := endpointNodeMap[n.Name]; ok { continue } - noEndpointNodeMap[n.Name] = getNodeAddresses(&n, api.NodeExternalIP) + noEndpointNodeMap[n.Name] = getNodeAddresses(&n, v1.NodeExternalIP) } svcTCPPort := int(svc.Spec.Ports[0].Port) @@ -1382,7 +1389,7 @@ var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", // creation will fail. By("turning ESIPP annotation back on") - svc = jig.UpdateServiceOrFail(svc.Namespace, svc.Name, func(svc *api.Service) { + svc = jig.UpdateServiceOrFail(svc.Namespace, svc.Name, func(svc *v1.Service) { svc.ObjectMeta.Annotations[service.BetaAnnotationExternalTraffic] = service.AnnotationValueExternalTrafficLocal // Request the same healthCheckNodePort as before, to test the user-requested allocation path @@ -1407,8 +1414,8 @@ var _ = framework.KubeDescribe("ESIPP [Slow][Feature:ExternalTrafficLocalOnly]", // updateService fetches a service, calls the update function on it, // and then attempts to send the updated service. It retries up to 2 // times in the face of timeouts and conflicts. -func updateService(c clientset.Interface, namespace, serviceName string, update func(*api.Service)) (*api.Service, error) { - var service *api.Service +func updateService(c clientset.Interface, namespace, serviceName string, update func(*v1.Service)) (*v1.Service, error) { + var service *v1.Service var err error for i := 0; i < 3; i++ { service, err = c.Core().Services(namespace).Get(serviceName) @@ -1427,7 +1434,7 @@ func updateService(c clientset.Interface, namespace, serviceName string, update return service, err } -func getContainerPortsByPodUID(endpoints *api.Endpoints) PortsByPodUID { +func getContainerPortsByPodUID(endpoints *v1.Endpoints) PortsByPodUID { m := PortsByPodUID{} for _, ss := range endpoints.Subsets { for _, port := range ss.Ports { @@ -1526,7 +1533,7 @@ func validateEndpointsOrFail(c clientset.Interface, namespace, serviceName strin i++ } - if pods, err := c.Core().Pods(api.NamespaceAll).List(api.ListOptions{}); err == nil { + if pods, err := c.Core().Pods(v1.NamespaceAll).List(v1.ListOptions{}); err == nil { for _, pod := range pods.Items { framework.Logf("Pod %s\t%s\t%s\t%s", pod.Namespace, pod.Name, pod.Spec.NodeName, pod.DeletionTimestamp) } @@ -1537,16 +1544,16 @@ func validateEndpointsOrFail(c clientset.Interface, namespace, serviceName strin } // newExecPodSpec returns the pod spec of exec pod -func newExecPodSpec(ns, generateName string) *api.Pod { +func newExecPodSpec(ns, generateName string) *v1.Pod { immediate := int64(0) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ GenerateName: generateName, Namespace: ns, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ TerminationGracePeriodSeconds: &immediate, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "exec", Image: "gcr.io/google_containers/busybox:1.24", @@ -1571,7 +1578,7 @@ func createExecPodOrFail(client clientset.Interface, ns, generateName string) st if err != nil { return false, nil } - return retrievedPod.Status.Phase == api.PodRunning, nil + return retrievedPod.Status.Phase == v1.PodRunning, nil }) Expect(err).NotTo(HaveOccurred()) return created.Name @@ -1590,28 +1597,28 @@ func createExecPodOnNode(client clientset.Interface, ns, nodeName, generateName if err != nil { return false, nil } - return retrievedPod.Status.Phase == api.PodRunning, nil + return retrievedPod.Status.Phase == v1.PodRunning, nil }) Expect(err).NotTo(HaveOccurred()) return created.Name } -func createPodOrFail(c clientset.Interface, ns, name string, labels map[string]string, containerPorts []api.ContainerPort) { +func createPodOrFail(c clientset.Interface, ns, name string, labels map[string]string, containerPorts []v1.ContainerPort) { By(fmt.Sprintf("creating pod %s in namespace %s", name, ns)) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: labels, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "pause", Image: framework.GetPauseImageName(c), Ports: containerPorts, // Add a dummy environment variable to work around a docker issue. // https://github.com/docker/docker/issues/14203 - Env: []api.EnvVar{{Name: "FOO", Value: " "}}, + Env: []v1.EnvVar{{Name: "FOO", Value: " "}}, }, }, }, @@ -1626,7 +1633,7 @@ func deletePodOrFail(c clientset.Interface, ns, name string) { Expect(err).NotTo(HaveOccurred()) } -func getNodeAddresses(node *api.Node, addressType api.NodeAddressType) (ips []string) { +func getNodeAddresses(node *v1.Node, addressType v1.NodeAddressType) (ips []string) { for j := range node.Status.Addresses { nodeAddress := &node.Status.Addresses[j] if nodeAddress.Type == addressType { @@ -1636,7 +1643,7 @@ func getNodeAddresses(node *api.Node, addressType api.NodeAddressType) (ips []st return } -func collectAddresses(nodes *api.NodeList, addressType api.NodeAddressType) []string { +func collectAddresses(nodes *v1.NodeList, addressType v1.NodeAddressType) []string { ips := []string{} for i := range nodes.Items { ips = append(ips, getNodeAddresses(&nodes.Items[i], addressType)...) @@ -1647,9 +1654,9 @@ func collectAddresses(nodes *api.NodeList, addressType api.NodeAddressType) []st func getNodePublicIps(c clientset.Interface) ([]string, error) { nodes := framework.GetReadySchedulableNodesOrDie(c) - ips := collectAddresses(nodes, api.NodeExternalIP) + ips := collectAddresses(nodes, v1.NodeExternalIP) if len(ips) == 0 { - ips = collectAddresses(nodes, api.NodeLegacyHostIP) + ips = collectAddresses(nodes, v1.NodeLegacyHostIP) } return ips, nil } @@ -1840,16 +1847,16 @@ func testNotReachableUDP(ip string, port int, request string) (bool, error) { } // Creates a replication controller that serves its hostname and a service on top of it. -func startServeHostnameService(c clientset.Interface, ns, name string, port, replicas int) ([]string, string, error) { +func startServeHostnameService(c clientset.Interface, internalClient internalclientset.Interface, ns, name string, port, replicas int) ([]string, string, error) { podNames := make([]string, replicas) By("creating service " + name + " in namespace " + ns) - _, err := c.Core().Services(ns).Create(&api.Service{ - ObjectMeta: api.ObjectMeta{ + _, err := c.Core().Services(ns).Create(&v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{{ + Spec: v1.ServiceSpec{ + Ports: []v1.ServicePort{{ Port: int32(port), TargetPort: intstr.FromInt(9376), Protocol: "TCP", @@ -1863,10 +1870,11 @@ func startServeHostnameService(c clientset.Interface, ns, name string, port, rep return podNames, "", err } - var createdPods []*api.Pod + var createdPods []*v1.Pod maxContainerFailures := 0 config := testutils.RCConfig{ Client: c, + InternalClient: internalClient, Image: "gcr.io/google_containers/serve_hostname:v1.4", Name: name, Namespace: ns, @@ -1901,8 +1909,8 @@ func startServeHostnameService(c clientset.Interface, ns, name string, port, rep return podNames, serviceIP, nil } -func stopServeHostnameService(clientset clientset.Interface, ns, name string) error { - if err := framework.DeleteRCAndPods(clientset, ns, name); err != nil { +func stopServeHostnameService(clientset clientset.Interface, internalClientset internalclientset.Interface, ns, name string) error { + if err := framework.DeleteRCAndPods(clientset, internalClientset, ns, name); err != nil { return err } if err := clientset.Core().Services(ns).Delete(name, nil); err != nil { @@ -2043,19 +2051,19 @@ func NewServiceTestJig(client clientset.Interface, name string) *ServiceTestJig return j } -// newServiceTemplate returns the default api.Service template for this jig, but +// newServiceTemplate returns the default v1.Service template for this jig, but // does not actually create the Service. The default Service has the same name // as the jig and exposes the given port. -func (j *ServiceTestJig) newServiceTemplate(namespace string, proto api.Protocol, port int32) *api.Service { - service := &api.Service{ - ObjectMeta: api.ObjectMeta{ +func (j *ServiceTestJig) newServiceTemplate(namespace string, proto v1.Protocol, port int32) *v1.Service { + service := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Namespace: namespace, Name: j.Name, Labels: j.Labels, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: j.Labels, - Ports: []api.ServicePort{ + Ports: []v1.ServicePort{ { Protocol: proto, Port: port, @@ -2069,8 +2077,8 @@ func (j *ServiceTestJig) newServiceTemplate(namespace string, proto api.Protocol // CreateTCPServiceWithPort creates a new TCP Service with given port based on the // jig's defaults. Callers can provide a function to tweak the Service object before // it is created. -func (j *ServiceTestJig) CreateTCPServiceWithPort(namespace string, tweak func(svc *api.Service), port int32) *api.Service { - svc := j.newServiceTemplate(namespace, api.ProtocolTCP, port) +func (j *ServiceTestJig) CreateTCPServiceWithPort(namespace string, tweak func(svc *v1.Service), port int32) *v1.Service { + svc := j.newServiceTemplate(namespace, v1.ProtocolTCP, port) if tweak != nil { tweak(svc) } @@ -2084,8 +2092,8 @@ func (j *ServiceTestJig) CreateTCPServiceWithPort(namespace string, tweak func(s // CreateTCPServiceOrFail creates a new TCP Service based on the jig's // defaults. Callers can provide a function to tweak the Service object before // it is created. -func (j *ServiceTestJig) CreateTCPServiceOrFail(namespace string, tweak func(svc *api.Service)) *api.Service { - svc := j.newServiceTemplate(namespace, api.ProtocolTCP, 80) +func (j *ServiceTestJig) CreateTCPServiceOrFail(namespace string, tweak func(svc *v1.Service)) *v1.Service { + svc := j.newServiceTemplate(namespace, v1.ProtocolTCP, 80) if tweak != nil { tweak(svc) } @@ -2099,8 +2107,8 @@ func (j *ServiceTestJig) CreateTCPServiceOrFail(namespace string, tweak func(svc // CreateUDPServiceOrFail creates a new UDP Service based on the jig's // defaults. Callers can provide a function to tweak the Service object before // it is created. -func (j *ServiceTestJig) CreateUDPServiceOrFail(namespace string, tweak func(svc *api.Service)) *api.Service { - svc := j.newServiceTemplate(namespace, api.ProtocolUDP, 80) +func (j *ServiceTestJig) CreateUDPServiceOrFail(namespace string, tweak func(svc *v1.Service)) *v1.Service { + svc := j.newServiceTemplate(namespace, v1.ProtocolUDP, 80) if tweak != nil { tweak(svc) } @@ -2111,9 +2119,9 @@ func (j *ServiceTestJig) CreateUDPServiceOrFail(namespace string, tweak func(svc return result } -func (j *ServiceTestJig) ChangeServiceType(namespace, name string, newType api.ServiceType, timeout time.Duration) { +func (j *ServiceTestJig) ChangeServiceType(namespace, name string, newType v1.ServiceType, timeout time.Duration) { ingressIP := "" - svc := j.UpdateServiceOrFail(namespace, name, func(s *api.Service) { + svc := j.UpdateServiceOrFail(namespace, name, func(s *v1.Service) { for _, ing := range s.Status.LoadBalancer.Ingress { if ing.IP != "" { ingressIP = ing.IP @@ -2130,35 +2138,35 @@ func (j *ServiceTestJig) ChangeServiceType(namespace, name string, newType api.S // createOnlyLocalNodePortService creates a loadbalancer service and sanity checks its // nodePort. If createPod is true, it also creates an RC with 1 replica of // the standard netexec container used everywhere in this test. -func (j *ServiceTestJig) createOnlyLocalNodePortService(namespace, serviceName string, createPod bool) *api.Service { +func (j *ServiceTestJig) createOnlyLocalNodePortService(namespace, serviceName string, createPod bool) *v1.Service { By("creating a service " + namespace + "/" + serviceName + " with type=NodePort and annotation for local-traffic-only") - svc := j.CreateTCPServiceOrFail(namespace, func(svc *api.Service) { - svc.Spec.Type = api.ServiceTypeNodePort + svc := j.CreateTCPServiceOrFail(namespace, func(svc *v1.Service) { + svc.Spec.Type = v1.ServiceTypeNodePort svc.ObjectMeta.Annotations = map[string]string{ service.BetaAnnotationExternalTraffic: service.AnnotationValueExternalTrafficLocal} - svc.Spec.Ports = []api.ServicePort{{Protocol: "TCP", Port: 80}} + svc.Spec.Ports = []v1.ServicePort{{Protocol: "TCP", Port: 80}} }) if createPod { By("creating a pod to be part of the service " + serviceName) j.RunOrFail(namespace, nil) } - j.SanityCheckService(svc, api.ServiceTypeNodePort) + j.SanityCheckService(svc, v1.ServiceTypeNodePort) return svc } // createOnlyLocalLoadBalancerService creates a loadbalancer service and waits for it to // acquire an ingress IP. If createPod is true, it also creates an RC with 1 // replica of the standard netexec container used everywhere in this test. -func (j *ServiceTestJig) createOnlyLocalLoadBalancerService(namespace, serviceName string, timeout time.Duration, createPod bool) *api.Service { +func (j *ServiceTestJig) createOnlyLocalLoadBalancerService(namespace, serviceName string, timeout time.Duration, createPod bool) *v1.Service { By("creating a service " + namespace + "/" + serviceName + " with type=LoadBalancer and annotation for local-traffic-only") - svc := j.CreateTCPServiceOrFail(namespace, func(svc *api.Service) { - svc.Spec.Type = api.ServiceTypeLoadBalancer + svc := j.CreateTCPServiceOrFail(namespace, func(svc *v1.Service) { + svc.Spec.Type = v1.ServiceTypeLoadBalancer // We need to turn affinity off for our LB distribution tests - svc.Spec.SessionAffinity = api.ServiceAffinityNone + svc.Spec.SessionAffinity = v1.ServiceAffinityNone svc.ObjectMeta.Annotations = map[string]string{ service.BetaAnnotationExternalTraffic: service.AnnotationValueExternalTrafficLocal} - svc.Spec.Ports = []api.ServicePort{{Protocol: "TCP", Port: 80}} + svc.Spec.Ports = []v1.ServicePort{{Protocol: "TCP", Port: 80}} }) if createPod { @@ -2167,13 +2175,13 @@ func (j *ServiceTestJig) createOnlyLocalLoadBalancerService(namespace, serviceNa } By("waiting for loadbalancer for service " + namespace + "/" + serviceName) svc = j.WaitForLoadBalancerOrFail(namespace, serviceName, timeout) - j.SanityCheckService(svc, api.ServiceTypeLoadBalancer) + j.SanityCheckService(svc, v1.ServiceTypeLoadBalancer) return svc } // getEndpointNodes returns a map of nodenames:external-ip on which the // endpoints of the given Service are running. -func (j *ServiceTestJig) getEndpointNodes(svc *api.Service) map[string][]string { +func (j *ServiceTestJig) getEndpointNodes(svc *v1.Service) map[string][]string { nodes := j.getNodes(maxNodesForEndpointsTests) endpoints, err := j.Client.Core().Endpoints(svc.Namespace).Get(svc.Name) if err != nil { @@ -2193,7 +2201,7 @@ func (j *ServiceTestJig) getEndpointNodes(svc *api.Service) map[string][]string nodeMap := map[string][]string{} for _, n := range nodes.Items { if epNodes.Has(n.Name) { - nodeMap[n.Name] = getNodeAddresses(&n, api.NodeExternalIP) + nodeMap[n.Name] = getNodeAddresses(&n, v1.NodeExternalIP) } } return nodeMap @@ -2201,7 +2209,7 @@ func (j *ServiceTestJig) getEndpointNodes(svc *api.Service) map[string][]string // getNodes returns the first maxNodesForTest nodes. Useful in large clusters // where we don't eg: want to create an endpoint per node. -func (j *ServiceTestJig) getNodes(maxNodesForTest int) (nodes *api.NodeList) { +func (j *ServiceTestJig) getNodes(maxNodesForTest int) (nodes *v1.NodeList) { nodes = framework.GetReadySchedulableNodesOrDie(j.Client) if len(nodes.Items) <= maxNodesForTest { maxNodesForTest = len(nodes.Items) @@ -2233,12 +2241,12 @@ func (j *ServiceTestJig) waitForEndpointOnNode(namespace, serviceName, nodeName framework.ExpectNoError(err) } -func (j *ServiceTestJig) SanityCheckService(svc *api.Service, svcType api.ServiceType) { +func (j *ServiceTestJig) SanityCheckService(svc *v1.Service, svcType v1.ServiceType) { if svc.Spec.Type != svcType { framework.Failf("unexpected Spec.Type (%s) for service, expected %s", svc.Spec.Type, svcType) } expectNodePorts := false - if svcType != api.ServiceTypeClusterIP { + if svcType != v1.ServiceTypeClusterIP { expectNodePorts = true } for i, port := range svc.Spec.Ports { @@ -2253,7 +2261,7 @@ func (j *ServiceTestJig) SanityCheckService(svc *api.Service, svcType api.Servic } } expectIngress := false - if svcType == api.ServiceTypeLoadBalancer { + if svcType == v1.ServiceTypeLoadBalancer { expectIngress = true } hasIngress := len(svc.Status.LoadBalancer.Ingress) != 0 @@ -2272,7 +2280,7 @@ func (j *ServiceTestJig) SanityCheckService(svc *api.Service, svcType api.Servic // UpdateService fetches a service, calls the update function on it, and // then attempts to send the updated service. It tries up to 3 times in the // face of timeouts and conflicts. -func (j *ServiceTestJig) UpdateService(namespace, name string, update func(*api.Service)) (*api.Service, error) { +func (j *ServiceTestJig) UpdateService(namespace, name string, update func(*v1.Service)) (*v1.Service, error) { for i := 0; i < 3; i++ { service, err := j.Client.Core().Services(namespace).Get(name) if err != nil { @@ -2293,7 +2301,7 @@ func (j *ServiceTestJig) UpdateService(namespace, name string, update func(*api. // UpdateServiceOrFail fetches a service, calls the update function on it, and // then attempts to send the updated service. It tries up to 3 times in the // face of timeouts and conflicts. -func (j *ServiceTestJig) UpdateServiceOrFail(namespace, name string, update func(*api.Service)) *api.Service { +func (j *ServiceTestJig) UpdateServiceOrFail(namespace, name string, update func(*v1.Service)) *v1.Service { svc, err := j.UpdateService(namespace, name, update) if err != nil { framework.Failf(err.Error()) @@ -2301,14 +2309,14 @@ func (j *ServiceTestJig) UpdateServiceOrFail(namespace, name string, update func return svc } -func (j *ServiceTestJig) ChangeServiceNodePortOrFail(namespace, name string, initial int) *api.Service { +func (j *ServiceTestJig) ChangeServiceNodePortOrFail(namespace, name string, initial int) *v1.Service { var err error - var service *api.Service + var service *v1.Service for i := 1; i < ServiceNodePortRange.Size; i++ { offs1 := initial - ServiceNodePortRange.Base offs2 := (offs1 + i) % ServiceNodePortRange.Size newPort := ServiceNodePortRange.Base + offs2 - service, err = j.UpdateService(namespace, name, func(s *api.Service) { + service, err = j.UpdateService(namespace, name, func(s *v1.Service) { s.Spec.Ports[0].NodePort = int32(newPort) }) if err != nil && strings.Contains(err.Error(), "provided port is already allocated") { @@ -2324,8 +2332,8 @@ func (j *ServiceTestJig) ChangeServiceNodePortOrFail(namespace, name string, ini return service } -func (j *ServiceTestJig) WaitForLoadBalancerOrFail(namespace, name string, timeout time.Duration) *api.Service { - var service *api.Service +func (j *ServiceTestJig) WaitForLoadBalancerOrFail(namespace, name string, timeout time.Duration) *v1.Service { + var service *v1.Service framework.Logf("Waiting up to %v for service %q to have a LoadBalancer", timeout, name) pollFunc := func() (bool, error) { svc, err := j.Client.Core().Services(namespace).Get(name) @@ -2344,7 +2352,7 @@ func (j *ServiceTestJig) WaitForLoadBalancerOrFail(namespace, name string, timeo return service } -func (j *ServiceTestJig) WaitForLoadBalancerDestroyOrFail(namespace, name string, ip string, port int, timeout time.Duration) *api.Service { +func (j *ServiceTestJig) WaitForLoadBalancerDestroyOrFail(namespace, name string, ip string, port int, timeout time.Duration) *v1.Service { // TODO: once support ticket 21807001 is resolved, reduce this timeout back to something reasonable defer func() { if err := framework.EnsureLoadBalancerResourcesDeleted(ip, strconv.Itoa(port)); err != nil { @@ -2352,7 +2360,7 @@ func (j *ServiceTestJig) WaitForLoadBalancerDestroyOrFail(namespace, name string } }() - var service *api.Service + var service *v1.Service framework.Logf("Waiting up to %v for service %q to have no LoadBalancer", timeout, name) pollFunc := func() (bool, error) { svc, err := j.Client.Core().Services(namespace).Get(name) @@ -2425,7 +2433,7 @@ func (j *ServiceTestJig) TestHTTPHealthCheckNodePort(host string, port int, requ return pass, fail, statusMsg } -func getIngressPoint(ing *api.LoadBalancerIngress) string { +func getIngressPoint(ing *v1.LoadBalancerIngress) string { host := ing.IP if host == "" { host = ing.Hostname @@ -2433,33 +2441,33 @@ func getIngressPoint(ing *api.LoadBalancerIngress) string { return host } -// newRCTemplate returns the default api.ReplicationController object for +// newRCTemplate returns the default v1.ReplicationController object for // this jig, but does not actually create the RC. The default RC has the same // name as the jig and runs the "netexec" container. -func (j *ServiceTestJig) newRCTemplate(namespace string) *api.ReplicationController { - rc := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ +func (j *ServiceTestJig) newRCTemplate(namespace string) *v1.ReplicationController { + rc := &v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{ Namespace: namespace, Name: j.Name, Labels: j.Labels, }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, + Spec: v1.ReplicationControllerSpec{ + Replicas: func(i int) *int32 { x := int32(i); return &x }(1), Selector: j.Labels, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: j.Labels, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "netexec", Image: "gcr.io/google_containers/netexec:1.7", Args: []string{"--http-port=80", "--udp-port=80"}, - ReadinessProbe: &api.Probe{ + ReadinessProbe: &v1.Probe{ PeriodSeconds: 3, - Handler: api.Handler{ - HTTPGet: &api.HTTPGetAction{ + Handler: v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Port: intstr.FromInt(80), Path: "/hostName", }, @@ -2478,7 +2486,7 @@ func (j *ServiceTestJig) newRCTemplate(namespace string) *api.ReplicationControl // RunOrFail creates a ReplicationController and Pod(s) and waits for the // Pod(s) to be running. Callers can provide a function to tweak the RC object // before it is created. -func (j *ServiceTestJig) RunOrFail(namespace string, tweak func(rc *api.ReplicationController)) *api.ReplicationController { +func (j *ServiceTestJig) RunOrFail(namespace string, tweak func(rc *v1.ReplicationController)) *v1.ReplicationController { rc := j.newRCTemplate(namespace) if tweak != nil { tweak(rc) @@ -2487,7 +2495,7 @@ func (j *ServiceTestJig) RunOrFail(namespace string, tweak func(rc *api.Replicat if err != nil { framework.Failf("Failed to created RC %q: %v", rc.Name, err) } - pods, err := j.waitForPodsCreated(namespace, int(rc.Spec.Replicas)) + pods, err := j.waitForPodsCreated(namespace, int(*(rc.Spec.Replicas))) if err != nil { framework.Failf("Failed to create pods: %v", err) } @@ -2503,7 +2511,7 @@ func (j *ServiceTestJig) waitForPodsCreated(namespace string, replicas int) ([]s label := labels.SelectorFromSet(labels.Set(j.Labels)) framework.Logf("Waiting up to %v for %d pods to be created", timeout, replicas) for start := time.Now(); time.Since(start) < timeout; time.Sleep(2 * time.Second) { - options := api.ListOptions{LabelSelector: label} + options := v1.ListOptions{LabelSelector: label.String()} pods, err := j.Client.Core().Pods(namespace).List(options) if err != nil { return nil, err @@ -2568,15 +2576,15 @@ func NewServerTest(client clientset.Interface, namespace string, serviceName str } // Build default config for a service (which can then be changed) -func (t *ServiceTestFixture) BuildServiceSpec() *api.Service { - service := &api.Service{ - ObjectMeta: api.ObjectMeta{ +func (t *ServiceTestFixture) BuildServiceSpec() *v1.Service { + service := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: t.ServiceName, Namespace: t.Namespace, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: t.Labels, - Ports: []api.ServicePort{{ + Ports: []v1.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}, @@ -2587,8 +2595,8 @@ func (t *ServiceTestFixture) BuildServiceSpec() *api.Service { // CreateWebserverRC creates rc-backed pods with the well-known webserver // configuration and records it for cleanup. -func (t *ServiceTestFixture) CreateWebserverRC(replicas int32) *api.ReplicationController { - rcSpec := rcByNamePort(t.name, replicas, t.image, 80, api.ProtocolTCP, t.Labels, nil) +func (t *ServiceTestFixture) CreateWebserverRC(replicas int32) *v1.ReplicationController { + rcSpec := rcByNamePort(t.name, replicas, t.image, 80, v1.ProtocolTCP, t.Labels, nil) rcAct, err := t.createRC(rcSpec) if err != nil { framework.Failf("Failed to create rc %s: %v", rcSpec.Name, err) @@ -2600,7 +2608,7 @@ func (t *ServiceTestFixture) CreateWebserverRC(replicas int32) *api.ReplicationC } // createRC creates a replication controller and records it for cleanup. -func (t *ServiceTestFixture) createRC(rc *api.ReplicationController) (*api.ReplicationController, error) { +func (t *ServiceTestFixture) createRC(rc *v1.ReplicationController) (*v1.ReplicationController, error) { rc, err := t.Client.Core().ReplicationControllers(t.Namespace).Create(rc) if err == nil { t.rcs[rc.Name] = true @@ -2609,7 +2617,7 @@ func (t *ServiceTestFixture) createRC(rc *api.ReplicationController) (*api.Repli } // Create a service, and record it for cleanup -func (t *ServiceTestFixture) CreateService(service *api.Service) (*api.Service, error) { +func (t *ServiceTestFixture) CreateService(service *v1.Service) (*v1.Service, error) { result, err := t.Client.Core().Services(t.Namespace).Create(service) if err == nil { t.services[service.Name] = true @@ -2635,7 +2643,8 @@ func (t *ServiceTestFixture) Cleanup() []error { if err != nil { errs = append(errs, err) } - old.Spec.Replicas = 0 + x := int32(0) + old.Spec.Replicas = &x if _, err := t.Client.Core().ReplicationControllers(t.Namespace).Update(old); err != nil { errs = append(errs, err) } @@ -2659,21 +2668,21 @@ func (t *ServiceTestFixture) Cleanup() []error { } // newEchoServerPodSpec returns the pod spec of echo server pod -func newEchoServerPodSpec(podName string) *api.Pod { +func newEchoServerPodSpec(podName string) *v1.Pod { port := 8080 - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "echoserver", Image: "gcr.io/google_containers/echoserver:1.4", - Ports: []api.ContainerPort{{ContainerPort: int32(port)}}, + Ports: []v1.ContainerPort{{ContainerPort: int32(port)}}, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } return pod @@ -2735,7 +2744,7 @@ func execSourceipTest(f *framework.Framework, c clientset.Interface, ns, nodeNam return execPod.Status.PodIP, outputs[1] } -func getLoadBalancerName(service *api.Service) string { +func getLoadBalancerName(service *v1.Service) string { //GCE requires that the name of a load balancer starts with a lower case letter. ret := "a" + string(service.UID) ret = strings.Replace(ret, "-", "", -1) diff --git a/test/e2e/service_accounts.go b/test/e2e/service_accounts.go index ffa1ce81bed..47c63e00f68 100644 --- a/test/e2e/service_accounts.go +++ b/test/e2e/service_accounts.go @@ -20,8 +20,8 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/version" @@ -39,7 +39,7 @@ var _ = framework.KubeDescribe("ServiceAccounts", func() { It("should ensure a single API token exists", func() { // wait for the service account to reference a single secret - var secrets []api.ObjectReference + var secrets []v1.ObjectReference framework.ExpectNoError(wait.Poll(time.Millisecond*500, time.Second*10, func() (bool, error) { By("waiting for a single token reference") sa, err := f.ClientSet.Core().ServiceAccounts(f.Namespace.Name).Get("default") @@ -178,9 +178,9 @@ var _ = framework.KubeDescribe("ServiceAccounts", func() { framework.Logf("Error getting secret %s: %v", secretRef.Name, err) continue } - if secret.Type == api.SecretTypeServiceAccountToken { - tokenContent = string(secret.Data[api.ServiceAccountTokenKey]) - rootCAContent = string(secret.Data[api.ServiceAccountRootCAKey]) + if secret.Type == v1.SecretTypeServiceAccountToken { + tokenContent = string(secret.Data[v1.ServiceAccountTokenKey]) + rootCAContent = string(secret.Data[v1.ServiceAccountRootCAKey]) return true, nil } } @@ -189,52 +189,52 @@ var _ = framework.KubeDescribe("ServiceAccounts", func() { return false, nil })) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "pod-service-account-" + string(uuid.NewUUID()) + "-", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "token-test", Image: "gcr.io/google_containers/mounttest:0.7", Args: []string{ - fmt.Sprintf("--file_content=%s/%s", serviceaccount.DefaultAPITokenMountPath, api.ServiceAccountTokenKey), + fmt.Sprintf("--file_content=%s/%s", serviceaccount.DefaultAPITokenMountPath, v1.ServiceAccountTokenKey), }, }, { Name: "root-ca-test", Image: "gcr.io/google_containers/mounttest:0.7", Args: []string{ - fmt.Sprintf("--file_content=%s/%s", serviceaccount.DefaultAPITokenMountPath, api.ServiceAccountRootCAKey), + fmt.Sprintf("--file_content=%s/%s", serviceaccount.DefaultAPITokenMountPath, v1.ServiceAccountRootCAKey), }, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } supportsTokenNamespace, _ := framework.ServerVersionGTE(serviceAccountTokenNamespaceVersion, f.ClientSet.Discovery()) if supportsTokenNamespace { - pod.Spec.Containers = append(pod.Spec.Containers, api.Container{ + pod.Spec.Containers = append(pod.Spec.Containers, v1.Container{ Name: "namespace-test", Image: "gcr.io/google_containers/mounttest:0.7", Args: []string{ - fmt.Sprintf("--file_content=%s/%s", serviceaccount.DefaultAPITokenMountPath, api.ServiceAccountNamespaceKey), + fmt.Sprintf("--file_content=%s/%s", serviceaccount.DefaultAPITokenMountPath, v1.ServiceAccountNamespaceKey), }, }) } f.TestContainerOutput("consume service account token", pod, 0, []string{ - fmt.Sprintf(`content of file "%s/%s": %s`, serviceaccount.DefaultAPITokenMountPath, api.ServiceAccountTokenKey, tokenContent), + fmt.Sprintf(`content of file "%s/%s": %s`, serviceaccount.DefaultAPITokenMountPath, v1.ServiceAccountTokenKey, tokenContent), }) f.TestContainerOutput("consume service account root CA", pod, 1, []string{ - fmt.Sprintf(`content of file "%s/%s": %s`, serviceaccount.DefaultAPITokenMountPath, api.ServiceAccountRootCAKey, rootCAContent), + fmt.Sprintf(`content of file "%s/%s": %s`, serviceaccount.DefaultAPITokenMountPath, v1.ServiceAccountRootCAKey, rootCAContent), }) if supportsTokenNamespace { f.TestContainerOutput("consume service account namespace", pod, 2, []string{ - fmt.Sprintf(`content of file "%s/%s": %s`, serviceaccount.DefaultAPITokenMountPath, api.ServiceAccountNamespaceKey, f.Namespace.Name), + fmt.Sprintf(`content of file "%s/%s": %s`, serviceaccount.DefaultAPITokenMountPath, v1.ServiceAccountNamespaceKey, f.Namespace.Name), }) } }) diff --git a/test/e2e/service_latency.go b/test/e2e/service_latency.go index b8856f9dd97..03f5ab3879a 100644 --- a/test/e2e/service_latency.go +++ b/test/e2e/service_latency.go @@ -22,7 +22,7 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/runtime" @@ -118,12 +118,13 @@ var _ = framework.KubeDescribe("Service endpoints latency", func() { func runServiceLatencies(f *framework.Framework, inParallel, total int) (output []time.Duration, err error) { cfg := testutils.RCConfig{ - Client: f.ClientSet, - Image: framework.GetPauseImageName(f.ClientSet), - Name: "svc-latency-rc", - Namespace: f.Namespace.Name, - Replicas: 1, - PollInterval: time.Second, + Client: f.ClientSet, + InternalClient: f.InternalClientset, + Image: framework.GetPauseImageName(f.ClientSet), + Name: "svc-latency-rc", + Namespace: f.Namespace.Name, + Replicas: 1, + PollInterval: time.Second, } if err := framework.RunRC(cfg); err != nil { return nil, err @@ -179,7 +180,7 @@ func runServiceLatencies(f *framework.Framework, inParallel, total int) (output type endpointQuery struct { endpointsName string - endpoints *api.Endpoints + endpoints *v1.Endpoints result chan<- struct{} } @@ -188,7 +189,7 @@ type endpointQueries struct { stop chan struct{} requestChan chan *endpointQuery - seenChan chan *api.Endpoints + seenChan chan *v1.Endpoints } func newQuerier() *endpointQueries { @@ -197,7 +198,7 @@ func newQuerier() *endpointQueries { stop: make(chan struct{}, 100), requestChan: make(chan *endpointQuery), - seenChan: make(chan *api.Endpoints, 100), + seenChan: make(chan *v1.Endpoints, 100), } go eq.join() return eq @@ -257,7 +258,7 @@ func (eq *endpointQueries) join() { } // request blocks until the requested endpoint is seen. -func (eq *endpointQueries) request(endpointsName string) *api.Endpoints { +func (eq *endpointQueries) request(endpointsName string) *v1.Endpoints { result := make(chan struct{}) req := &endpointQuery{ endpointsName: endpointsName, @@ -269,7 +270,7 @@ func (eq *endpointQueries) request(endpointsName string) *api.Endpoints { } // marks e as added; does not block. -func (eq *endpointQueries) added(e *api.Endpoints) { +func (eq *endpointQueries) added(e *v1.Endpoints) { eq.seenChan <- e } @@ -277,26 +278,26 @@ func (eq *endpointQueries) added(e *api.Endpoints) { func startEndpointWatcher(f *framework.Framework, q *endpointQueries) { _, controller := cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { obj, err := f.ClientSet.Core().Endpoints(f.Namespace.Name).List(options) return runtime.Object(obj), err }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return f.ClientSet.Core().Endpoints(f.Namespace.Name).Watch(options) }, }, - &api.Endpoints{}, + &v1.Endpoints{}, 0, cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { - if e, ok := obj.(*api.Endpoints); ok { + if e, ok := obj.(*v1.Endpoints); ok { if len(e.Subsets) > 0 && len(e.Subsets[0].Addresses) > 0 { q.added(e) } } }, UpdateFunc: func(old, cur interface{}) { - if e, ok := cur.(*api.Endpoints); ok { + if e, ok := cur.(*v1.Endpoints); ok { if len(e.Subsets) > 0 && len(e.Subsets[0].Addresses) > 0 { q.added(e) } @@ -315,15 +316,15 @@ func startEndpointWatcher(f *framework.Framework, q *endpointQueries) { func singleServiceLatency(f *framework.Framework, name string, q *endpointQueries) (time.Duration, error) { // Make a service that points to that pod. - svc := &api.Service{ - ObjectMeta: api.ObjectMeta{ + svc := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "latency-svc-", }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{{Protocol: api.ProtocolTCP, Port: 80}}, + Spec: v1.ServiceSpec{ + Ports: []v1.ServicePort{{Protocol: v1.ProtocolTCP, Port: 80}}, Selector: map[string]string{"name": name}, - Type: api.ServiceTypeClusterIP, - SessionAffinity: api.ServiceAffinityNone, + Type: v1.ServiceTypeClusterIP, + SessionAffinity: v1.ServiceAffinityNone, }, } startTime := time.Now() diff --git a/test/e2e/serviceloadbalancers.go b/test/e2e/serviceloadbalancers.go index 2936ffc5918..d210036022a 100644 --- a/test/e2e/serviceloadbalancers.go +++ b/test/e2e/serviceloadbalancers.go @@ -22,7 +22,8 @@ import ( "net/http" "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/wait" @@ -111,7 +112,7 @@ func (h *haproxyControllerTester) start(namespace string) (err error) { // Find the pods of the rc we just created. labelSelector := labels.SelectorFromSet( labels.Set(map[string]string{"name": h.rcName})) - options := api.ListOptions{LabelSelector: labelSelector} + options := v1.ListOptions{LabelSelector: labelSelector.String()} pods, err := h.client.Core().Pods(h.rcNamespace).List(options) if err != nil { return err @@ -262,8 +263,8 @@ func simpleGET(c *http.Client, url, host string) (string, error) { } // rcFromManifest reads a .json/yaml file and returns the rc in it. -func rcFromManifest(fileName string) *api.ReplicationController { - var controller api.ReplicationController +func rcFromManifest(fileName string) *v1.ReplicationController { + var controller v1.ReplicationController framework.Logf("Parsing rc from %v", fileName) data := framework.ReadOrDie(fileName) @@ -275,8 +276,8 @@ func rcFromManifest(fileName string) *api.ReplicationController { } // svcFromManifest reads a .json/yaml file and returns the rc in it. -func svcFromManifest(fileName string) *api.Service { - var svc api.Service +func svcFromManifest(fileName string) *v1.Service { + var svc v1.Service framework.Logf("Parsing service from %v", fileName) data := framework.ReadOrDie(fileName) diff --git a/test/e2e/third-party.go b/test/e2e/third-party.go index bfd40d34bc2..caa52c71c58 100644 --- a/test/e2e/third-party.go +++ b/test/e2e/third-party.go @@ -24,8 +24,9 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/extensions" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" @@ -45,7 +46,7 @@ var data = `{ type Foo struct { unversioned.TypeMeta `json:",inline"` - api.ObjectMeta `json:"metadata,omitempty" description:"standard object metadata"` + v1.ObjectMeta `json:"metadata,omitempty" description:"standard object metadata"` SomeField string `json:"someField"` OtherField int `json:"otherField"` @@ -64,7 +65,7 @@ var _ = Describe("ThirdParty resources [Flaky] [Disruptive]", func() { f := framework.NewDefaultFramework("thirdparty") rsrc := &extensions.ThirdPartyResource{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "foo.company.com", }, Versions: []extensions.APIVersion{ @@ -120,7 +121,7 @@ var _ = Describe("ThirdParty resources [Flaky] [Disruptive]", func() { TypeMeta: unversioned.TypeMeta{ Kind: "Foo", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", }, SomeField: "bar", diff --git a/test/e2e/ubernetes_lite.go b/test/e2e/ubernetes_lite.go index 9e8a9061d25..504bae4f3f5 100644 --- a/test/e2e/ubernetes_lite.go +++ b/test/e2e/ubernetes_lite.go @@ -22,9 +22,9 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/sets" @@ -61,16 +61,16 @@ var _ = framework.KubeDescribe("Multi-AZ Clusters", func() { func SpreadServiceOrFail(f *framework.Framework, replicaCount int, image string) { // First create the service serviceName := "test-service" - serviceSpec := &api.Service{ - ObjectMeta: api.ObjectMeta{ + serviceSpec := &v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: serviceName, Namespace: f.Namespace.Name, }, - Spec: api.ServiceSpec{ + Spec: v1.ServiceSpec{ Selector: map[string]string{ "service": serviceName, }, - Ports: []api.ServicePort{{ + Ports: []v1.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}, @@ -80,13 +80,13 @@ func SpreadServiceOrFail(f *framework.Framework, replicaCount int, image string) Expect(err).NotTo(HaveOccurred()) // Now create some pods behind the service - podSpec := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + podSpec := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: serviceName, Labels: map[string]string{"service": serviceName}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "test", Image: framework.GetPauseImageName(f.ClientSet), @@ -113,7 +113,7 @@ func SpreadServiceOrFail(f *framework.Framework, replicaCount int, image string) } // Find the name of the zone in which a Node is running -func getZoneNameForNode(node api.Node) (string, error) { +func getZoneNameForNode(node v1.Node) (string, error) { for key, value := range node.Labels { if key == unversioned.LabelZoneFailureDomain { return value, nil @@ -126,7 +126,7 @@ func getZoneNameForNode(node api.Node) (string, error) { // Find the names of all zones in which we have nodes in this cluster. func getZoneNames(c clientset.Interface) ([]string, error) { zoneNames := sets.NewString() - nodes, err := c.Core().Nodes().List(api.ListOptions{}) + nodes, err := c.Core().Nodes().List(v1.ListOptions{}) if err != nil { return nil, err } @@ -148,7 +148,7 @@ func getZoneCount(c clientset.Interface) (int, error) { } // Find the name of the zone in which the pod is scheduled -func getZoneNameForPod(c clientset.Interface, pod api.Pod) (string, error) { +func getZoneNameForPod(c clientset.Interface, pod v1.Pod) (string, error) { By(fmt.Sprintf("Getting zone name for pod %s, on node %s", pod.Name, pod.Spec.NodeName)) node, err := c.Core().Nodes().Get(pod.Spec.NodeName) Expect(err).NotTo(HaveOccurred()) @@ -157,7 +157,7 @@ func getZoneNameForPod(c clientset.Interface, pod api.Pod) (string, error) { // Determine whether a set of pods are approximately evenly spread // across a given set of zones -func checkZoneSpreading(c clientset.Interface, pods *api.PodList, zoneNames []string) (bool, error) { +func checkZoneSpreading(c clientset.Interface, pods *v1.PodList, zoneNames []string) (bool, error) { podsPerZone := make(map[string]int) for _, zoneName := range zoneNames { podsPerZone[zoneName] = 0 @@ -190,26 +190,26 @@ func checkZoneSpreading(c clientset.Interface, pods *api.PodList, zoneNames []st func SpreadRCOrFail(f *framework.Framework, replicaCount int32, image string) { name := "ubelite-spread-rc-" + string(uuid.NewUUID()) By(fmt.Sprintf("Creating replication controller %s", name)) - controller, err := f.ClientSet.Core().ReplicationControllers(f.Namespace.Name).Create(&api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ + controller, err := f.ClientSet.Core().ReplicationControllers(f.Namespace.Name).Create(&v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{ Namespace: f.Namespace.Name, Name: name, }, - Spec: api.ReplicationControllerSpec{ - Replicas: replicaCount, + Spec: v1.ReplicationControllerSpec{ + Replicas: &replicaCount, Selector: map[string]string{ "name": name, }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"name": name}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: name, Image: image, - Ports: []api.ContainerPort{{ContainerPort: 9376}}, + Ports: []v1.ContainerPort{{ContainerPort: 9376}}, }, }, }, @@ -220,7 +220,7 @@ func SpreadRCOrFail(f *framework.Framework, replicaCount int32, image string) { // Cleanup the replication controller when we are done. defer func() { // Resize the replication controller to zero to get rid of pods. - if err := framework.DeleteRCAndPods(f.ClientSet, f.Namespace.Name, controller.Name); err != nil { + if err := framework.DeleteRCAndPods(f.ClientSet, f.InternalClientset, f.Namespace.Name, controller.Name); err != nil { framework.Logf("Failed to cleanup replication controller %v: %v.", controller.Name, err) } }() diff --git a/test/e2e/volume_provisioning.go b/test/e2e/volume_provisioning.go index 18a6981c92b..dc5606b7f33 100644 --- a/test/e2e/volume_provisioning.go +++ b/test/e2e/volume_provisioning.go @@ -19,12 +19,12 @@ package e2e import ( "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/storage" - storageutil "k8s.io/kubernetes/pkg/apis/storage/util" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" + storageutil "k8s.io/kubernetes/pkg/apis/storage/v1beta1/util" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" @@ -39,8 +39,8 @@ const ( expectedSize = "2Gi" ) -func testDynamicProvisioning(client clientset.Interface, claim *api.PersistentVolumeClaim) { - err := framework.WaitForPersistentVolumeClaimPhase(api.ClaimBound, client, claim.Namespace, claim.Name, framework.Poll, framework.ClaimProvisionTimeout) +func testDynamicProvisioning(client clientset.Interface, claim *v1.PersistentVolumeClaim) { + err := framework.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, client, claim.Namespace, claim.Name, framework.Poll, framework.ClaimProvisionTimeout) Expect(err).NotTo(HaveOccurred()) By("checking the claim") @@ -54,16 +54,16 @@ func testDynamicProvisioning(client clientset.Interface, claim *api.PersistentVo // Check sizes expectedCapacity := resource.MustParse(expectedSize) - pvCapacity := pv.Spec.Capacity[api.ResourceName(api.ResourceStorage)] + pvCapacity := pv.Spec.Capacity[v1.ResourceName(v1.ResourceStorage)] Expect(pvCapacity.Value()).To(Equal(expectedCapacity.Value())) requestedCapacity := resource.MustParse(requestedSize) - claimCapacity := claim.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)] + claimCapacity := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] Expect(claimCapacity.Value()).To(Equal(requestedCapacity.Value())) // Check PV properties - Expect(pv.Spec.PersistentVolumeReclaimPolicy).To(Equal(api.PersistentVolumeReclaimDelete)) - expectedAccessModes := []api.PersistentVolumeAccessMode{api.ReadWriteOnce} + Expect(pv.Spec.PersistentVolumeReclaimPolicy).To(Equal(v1.PersistentVolumeReclaimDelete)) + expectedAccessModes := []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce} Expect(pv.Spec.AccessModes).To(Equal(expectedAccessModes)) Expect(pv.Spec.ClaimRef.Name).To(Equal(claim.ObjectMeta.Name)) Expect(pv.Spec.ClaimRef.Namespace).To(Equal(claim.ObjectMeta.Namespace)) @@ -153,19 +153,19 @@ var _ = framework.KubeDescribe("Dynamic provisioning", func() { }) }) -func newClaim(ns string, alpha bool) *api.PersistentVolumeClaim { - claim := api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ +func newClaim(ns string, alpha bool) *v1.PersistentVolumeClaim { + claim := v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "pvc-", Namespace: ns, }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, + Spec: v1.PersistentVolumeClaimSpec{ + AccessModes: []v1.PersistentVolumeAccessMode{ + v1.ReadWriteOnce, }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse(requestedSize), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceName(v1.ResourceStorage): resource.MustParse(requestedSize), }, }, }, @@ -187,22 +187,22 @@ func newClaim(ns string, alpha bool) *api.PersistentVolumeClaim { // runInPodWithVolume runs a command in a pod with given claim mounted to /mnt directory. func runInPodWithVolume(c clientset.Interface, ns, claimName, command string) { - pod := &api.Pod{ + pod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "pvc-volume-tester-", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "volume-tester", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"/bin/sh"}, Args: []string{"-c", command}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "my-volume", MountPath: "/mnt/test", @@ -210,12 +210,12 @@ func runInPodWithVolume(c clientset.Interface, ns, claimName, command string) { }, }, }, - RestartPolicy: api.RestartPolicyNever, - Volumes: []api.Volume{ + RestartPolicy: v1.RestartPolicyNever, + Volumes: []v1.Volume{ { Name: "my-volume", - VolumeSource: api.VolumeSource{ - PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ + VolumeSource: v1.VolumeSource{ + PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: claimName, ReadOnly: false, }, @@ -248,7 +248,7 @@ func newStorageClass() *storage.StorageClass { TypeMeta: unversioned.TypeMeta{ Kind: "StorageClass", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "fast", }, Provisioner: pluginName, diff --git a/test/e2e/volumes.go b/test/e2e/volumes.go index 9432bb4a035..14634aaf220 100644 --- a/test/e2e/volumes.go +++ b/test/e2e/volumes.go @@ -46,10 +46,10 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" apierrs "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/test/e2e/framework" "github.com/golang/glog" @@ -78,31 +78,31 @@ type VolumeTestConfig struct { // Starts a container specified by config.serverImage and exports all // config.serverPorts from it. The returned pod should be used to get the server // IP address and create appropriate VolumeSource. -func startVolumeServer(client clientset.Interface, config VolumeTestConfig) *api.Pod { +func startVolumeServer(client clientset.Interface, config VolumeTestConfig) *v1.Pod { podClient := client.Core().Pods(config.namespace) portCount := len(config.serverPorts) - serverPodPorts := make([]api.ContainerPort, portCount) + serverPodPorts := make([]v1.ContainerPort, portCount) for i := 0; i < portCount; i++ { portName := fmt.Sprintf("%s-%d", config.prefix, i) - serverPodPorts[i] = api.ContainerPort{ + serverPodPorts[i] = v1.ContainerPort{ Name: portName, ContainerPort: int32(config.serverPorts[i]), - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, } } volumeCount := len(config.volumes) - volumes := make([]api.Volume, volumeCount) - mounts := make([]api.VolumeMount, volumeCount) + volumes := make([]v1.Volume, volumeCount) + mounts := make([]v1.VolumeMount, volumeCount) i := 0 for src, dst := range config.volumes { mountName := fmt.Sprintf("path%d", i) volumes[i].Name = mountName - volumes[i].VolumeSource.HostPath = &api.HostPathVolumeSource{ + volumes[i].VolumeSource.HostPath = &v1.HostPathVolumeSource{ Path: src, } @@ -116,24 +116,24 @@ func startVolumeServer(client clientset.Interface, config VolumeTestConfig) *api By(fmt.Sprint("creating ", config.prefix, " server pod")) privileged := new(bool) *privileged = true - serverPod := &api.Pod{ + serverPod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.prefix + "-server", Labels: map[string]string{ "role": config.prefix + "-server", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: config.prefix + "-server", Image: config.serverImage, - SecurityContext: &api.SecurityContext{ + SecurityContext: &v1.SecurityContext{ Privileged: privileged, }, Args: config.serverArgs, @@ -194,21 +194,21 @@ func volumeTestCleanup(f *framework.Framework, config VolumeTestConfig) { // Start a client pod using given VolumeSource (exported by startVolumeServer()) // and check that the pod sees the data from the server pod. -func testVolumeClient(client clientset.Interface, config VolumeTestConfig, volume api.VolumeSource, fsGroup *int64, expectedContent string) { +func testVolumeClient(client clientset.Interface, config VolumeTestConfig, volume v1.VolumeSource, fsGroup *int64, expectedContent string) { By(fmt.Sprint("starting ", config.prefix, " client")) - clientPod := &api.Pod{ + clientPod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.prefix + "-client", Labels: map[string]string{ "role": config.prefix + "-client", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: config.prefix + "-client", Image: "gcr.io/google_containers/busybox:1.24", @@ -221,7 +221,7 @@ func testVolumeClient(client clientset.Interface, config VolumeTestConfig, volum "-c", "while true ; do cat /opt/index.html ; sleep 2 ; ls -altrh /opt/ ; sleep 2 ; done ", }, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: config.prefix + "-volume", MountPath: "/opt/", @@ -229,12 +229,12 @@ func testVolumeClient(client clientset.Interface, config VolumeTestConfig, volum }, }, }, - SecurityContext: &api.PodSecurityContext{ - SELinuxOptions: &api.SELinuxOptions{ + SecurityContext: &v1.PodSecurityContext{ + SELinuxOptions: &v1.SELinuxOptions{ Level: "s0:c0,c1", }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: config.prefix + "-volume", VolumeSource: volume, @@ -268,29 +268,29 @@ func testVolumeClient(client clientset.Interface, config VolumeTestConfig, volum // Insert index.html with given content into given volume. It does so by // starting and auxiliary pod which writes the file there. // The volume must be writable. -func injectHtml(client clientset.Interface, config VolumeTestConfig, volume api.VolumeSource, content string) { +func injectHtml(client clientset.Interface, config VolumeTestConfig, volume v1.VolumeSource, content string) { By(fmt.Sprint("starting ", config.prefix, " injector")) podClient := client.Core().Pods(config.namespace) - injectPod := &api.Pod{ + injectPod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.prefix + "-injector", Labels: map[string]string{ "role": config.prefix + "-injector", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: config.prefix + "-injector", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"/bin/sh"}, Args: []string{"-c", "echo '" + content + "' > /mnt/index.html && chmod o+rX /mnt /mnt/index.html"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: config.prefix + "-volume", MountPath: "/mnt", @@ -298,13 +298,13 @@ func injectHtml(client clientset.Interface, config VolumeTestConfig, volume api. }, }, }, - SecurityContext: &api.PodSecurityContext{ - SELinuxOptions: &api.SELinuxOptions{ + SecurityContext: &v1.PodSecurityContext{ + SELinuxOptions: &v1.SELinuxOptions{ Level: "s0:c0,c1", }, }, - RestartPolicy: api.RestartPolicyNever, - Volumes: []api.Volume{ + RestartPolicy: v1.RestartPolicyNever, + Volumes: []v1.Volume{ { Name: config.prefix + "-volume", VolumeSource: volume, @@ -354,7 +354,7 @@ var _ = framework.KubeDescribe("Volumes [Feature:Volumes]", func() { clean := true // filled in BeforeEach var cs clientset.Interface - var namespace *api.Namespace + var namespace *v1.Namespace BeforeEach(func() { cs = f.ClientSet @@ -383,8 +383,8 @@ var _ = framework.KubeDescribe("Volumes [Feature:Volumes]", func() { serverIP := pod.Status.PodIP framework.Logf("NFS server IP address: %v", serverIP) - volume := api.VolumeSource{ - NFS: &api.NFSVolumeSource{ + volume := v1.VolumeSource{ + NFS: &v1.NFSVolumeSource{ Server: serverIP, Path: "/", ReadOnly: true, @@ -418,26 +418,26 @@ var _ = framework.KubeDescribe("Volumes [Feature:Volumes]", func() { framework.Logf("Gluster server IP address: %v", serverIP) // create Endpoints for the server - endpoints := api.Endpoints{ + endpoints := v1.Endpoints{ TypeMeta: unversioned.TypeMeta{ Kind: "Endpoints", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.prefix + "-server", }, - Subsets: []api.EndpointSubset{ + Subsets: []v1.EndpointSubset{ { - Addresses: []api.EndpointAddress{ + Addresses: []v1.EndpointAddress{ { IP: serverIP, }, }, - Ports: []api.EndpointPort{ + Ports: []v1.EndpointPort{ { Name: "gluster", Port: 24007, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, }, }, @@ -456,8 +456,8 @@ var _ = framework.KubeDescribe("Volumes [Feature:Volumes]", func() { framework.Failf("Failed to create endpoints for Gluster server: %v", err) } - volume := api.VolumeSource{ - Glusterfs: &api.GlusterfsVolumeSource{ + volume := v1.VolumeSource{ + Glusterfs: &v1.GlusterfsVolumeSource{ EndpointsName: config.prefix + "-server", // 'test_vol' comes from test/images/volumes-tester/gluster/run_gluster.sh Path: "test_vol", @@ -500,8 +500,8 @@ var _ = framework.KubeDescribe("Volumes [Feature:Volumes]", func() { serverIP := pod.Status.PodIP framework.Logf("iSCSI server IP address: %v", serverIP) - volume := api.VolumeSource{ - ISCSI: &api.ISCSIVolumeSource{ + volume := v1.VolumeSource{ + ISCSI: &v1.ISCSIVolumeSource{ TargetPortal: serverIP + ":3260", // from test/images/volumes-tester/iscsi/initiatorname.iscsi IQN: "iqn.2003-01.org.linux-iscsi.f21.x8664:sn.4b0aae584f7c", @@ -544,12 +544,12 @@ var _ = framework.KubeDescribe("Volumes [Feature:Volumes]", func() { framework.Logf("Ceph server IP address: %v", serverIP) // create secrets for the server - secret := api.Secret{ + secret := v1.Secret{ TypeMeta: unversioned.TypeMeta{ Kind: "Secret", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.prefix + "-secret", }, Data: map[string][]byte{ @@ -571,13 +571,13 @@ var _ = framework.KubeDescribe("Volumes [Feature:Volumes]", func() { framework.Failf("Failed to create secrets for Ceph RBD: %v", err) } - volume := api.VolumeSource{ - RBD: &api.RBDVolumeSource{ + volume := v1.VolumeSource{ + RBD: &v1.RBDVolumeSource{ CephMonitors: []string{serverIP}, RBDPool: "rbd", RBDImage: "foo", RadosUser: "admin", - SecretRef: &api.LocalObjectReference{ + SecretRef: &v1.LocalObjectReference{ Name: config.prefix + "-secret", }, FSType: "ext2", @@ -615,12 +615,12 @@ var _ = framework.KubeDescribe("Volumes [Feature:Volumes]", func() { time.Sleep(20 * time.Second) // create ceph secret - secret := &api.Secret{ + secret := &v1.Secret{ TypeMeta: unversioned.TypeMeta{ Kind: "Secret", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.prefix + "-secret", }, // Must use the ceph keyring at contrib/for-tests/volumes-ceph/ceph/init.sh @@ -644,11 +644,11 @@ var _ = framework.KubeDescribe("Volumes [Feature:Volumes]", func() { framework.Failf("unable to create test secret %s: %v", secret.Name, err) } - volume := api.VolumeSource{ - CephFS: &api.CephFSVolumeSource{ + volume := v1.VolumeSource{ + CephFS: &v1.CephFSVolumeSource{ Monitors: []string{serverIP + ":6789"}, User: "kube", - SecretRef: &api.LocalObjectReference{Name: config.prefix + "-secret"}, + SecretRef: &v1.LocalObjectReference{Name: config.prefix + "-secret"}, ReadOnly: true, }, } @@ -714,8 +714,8 @@ var _ = framework.KubeDescribe("Volumes [Feature:Volumes]", func() { volumeTestCleanup(f, config) } }() - volume := api.VolumeSource{ - Cinder: &api.CinderVolumeSource{ + volume := v1.VolumeSource{ + Cinder: &v1.CinderVolumeSource{ VolumeID: volumeID, FSType: "ext3", ReadOnly: false, @@ -758,8 +758,8 @@ var _ = framework.KubeDescribe("Volumes [Feature:Volumes]", func() { volumeTestCleanup(f, config) } }() - volume := api.VolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{ + volume := v1.VolumeSource{ + GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: volumeName, FSType: "ext3", ReadOnly: false, diff --git a/test/e2e_node/BUILD b/test/e2e_node/BUILD index 07ce0e6a3f6..c4f899b61ab 100644 --- a/test/e2e_node/BUILD +++ b/test/e2e_node/BUILD @@ -26,6 +26,7 @@ go_library( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apis/componentconfig:go_default_library", "//pkg/apis/componentconfig/v1alpha1:go_default_library", "//pkg/kubelet/api/v1alpha1/stats:go_default_library", @@ -73,12 +74,12 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/client/cache:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/kubelet:go_default_library", "//pkg/kubelet/api/v1alpha1/stats:go_default_library", "//pkg/kubelet/cm:go_default_library", diff --git a/test/e2e_node/apparmor_test.go b/test/e2e_node/apparmor_test.go index 7e33a2d97a5..eab18a64010 100644 --- a/test/e2e_node/apparmor_test.go +++ b/test/e2e_node/apparmor_test.go @@ -28,7 +28,7 @@ import ( "k8s.io/client-go/pkg/api/errors" "k8s.io/client-go/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/security/apparmor" "k8s.io/kubernetes/pkg/watch" "k8s.io/kubernetes/test/e2e/framework" @@ -138,7 +138,7 @@ func loadTestProfiles() error { return nil } -func runAppArmorTest(f *framework.Framework, shouldRun bool, profile string) api.PodStatus { +func runAppArmorTest(f *framework.Framework, shouldRun bool, profile string) v1.PodStatus { pod := createPodWithAppArmor(f, profile) if shouldRun { // The pod needs to start before it stops, so wait for the longer start timeout. @@ -146,7 +146,7 @@ func runAppArmorTest(f *framework.Framework, shouldRun bool, profile string) api f.ClientSet, pod.Name, f.Namespace.Name, "", framework.PodStartTimeout)) } else { // Pod should remain in the pending state. Wait for the Reason to be set to "AppArmor". - w, err := f.PodClient().Watch(api.SingleObject(api.ObjectMeta{Name: pod.Name})) + w, err := f.PodClient().Watch(v1.SingleObject(v1.ObjectMeta{Name: pod.Name})) framework.ExpectNoError(err) _, err = watch.Until(framework.PodStartTimeout, w, func(e watch.Event) (bool, error) { switch e.Type { @@ -154,7 +154,7 @@ func runAppArmorTest(f *framework.Framework, shouldRun bool, profile string) api return false, errors.NewNotFound(unversioned.GroupResource{Resource: "pods"}, pod.Name) } switch t := e.Object.(type) { - case *api.Pod: + case *v1.Pod: if t.Status.Reason == "AppArmor" { return true, nil } @@ -168,29 +168,29 @@ func runAppArmorTest(f *framework.Framework, shouldRun bool, profile string) api return p.Status } -func createPodWithAppArmor(f *framework.Framework, profile string) *api.Pod { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func createPodWithAppArmor(f *framework.Framework, profile string) *v1.Pod { + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: fmt.Sprintf("test-apparmor-%s", strings.Replace(profile, "/", "-", -1)), Annotations: map[string]string{ apparmor.ContainerAnnotationKeyPrefix + "test": profile, }, }, - Spec: api.PodSpec{ - Containers: []api.Container{{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ Name: "test", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"touch", "foo"}, }}, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } return f.PodClient().Create(pod) } -func expectSoftRejection(status api.PodStatus) { +func expectSoftRejection(status v1.PodStatus) { args := []interface{}{"PodStatus: %+v", status} - Expect(status.Phase).To(Equal(api.PodPending), args...) + Expect(status.Phase).To(Equal(v1.PodPending), args...) Expect(status.Reason).To(Equal("AppArmor"), args...) Expect(status.Message).To(ContainSubstring("AppArmor"), args...) Expect(status.ContainerStatuses[0].State.Waiting.Reason).To(Equal("Blocked"), args...) diff --git a/test/e2e_node/cgroup_manager_test.go b/test/e2e_node/cgroup_manager_test.go index 3d4de84085e..ef1bb5ce2c2 100644 --- a/test/e2e_node/cgroup_manager_test.go +++ b/test/e2e_node/cgroup_manager_test.go @@ -17,8 +17,8 @@ limitations under the License. package e2e_node import ( - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/cm" "k8s.io/kubernetes/pkg/kubelet/qos" "k8s.io/kubernetes/pkg/util/uuid" @@ -30,27 +30,27 @@ import ( // getResourceList returns a ResourceList with the // specified cpu and memory resource values -func getResourceList(cpu, memory string) api.ResourceList { - res := api.ResourceList{} +func getResourceList(cpu, memory string) v1.ResourceList { + res := v1.ResourceList{} if cpu != "" { - res[api.ResourceCPU] = resource.MustParse(cpu) + res[v1.ResourceCPU] = resource.MustParse(cpu) } if memory != "" { - res[api.ResourceMemory] = resource.MustParse(memory) + res[v1.ResourceMemory] = resource.MustParse(memory) } return res } // getResourceRequirements returns a ResourceRequirements object -func getResourceRequirements(requests, limits api.ResourceList) api.ResourceRequirements { - res := api.ResourceRequirements{} +func getResourceRequirements(requests, limits v1.ResourceList) v1.ResourceRequirements { + res := v1.ResourceRequirements{} res.Requests = requests res.Limits = limits return res } // makePodToVerifyCgroups returns a pod that verifies the existence of the specified cgroups. -func makePodToVerifyCgroups(cgroupNames []cm.CgroupName) *api.Pod { +func makePodToVerifyCgroups(cgroupNames []cm.CgroupName) *v1.Pod { // convert the names to their literal cgroupfs forms... cgroupFsNames := []string{} for _, cgroupName := range cgroupNames { @@ -68,18 +68,18 @@ func makePodToVerifyCgroups(cgroupNames []cm.CgroupName) *api.Pod { command += localCommand } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Image: "gcr.io/google_containers/busybox:1.24", Name: "container" + string(uuid.NewUUID()), Command: []string{"sh", "-c", command}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "sysfscgroup", MountPath: "/tmp", @@ -87,11 +87,11 @@ func makePodToVerifyCgroups(cgroupNames []cm.CgroupName) *api.Pod { }, }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: "sysfscgroup", - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/sys/fs/cgroup"}, + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{Path: "/sys/fs/cgroup"}, }, }, }, @@ -101,23 +101,23 @@ func makePodToVerifyCgroups(cgroupNames []cm.CgroupName) *api.Pod { } // makePodToVerifyCgroupRemoved verfies the specified cgroup does not exist. -func makePodToVerifyCgroupRemoved(cgroupName cm.CgroupName) *api.Pod { +func makePodToVerifyCgroupRemoved(cgroupName cm.CgroupName) *v1.Pod { cgroupFsName := string(cgroupName) if framework.TestContext.KubeletConfig.CgroupDriver == "systemd" { cgroupFsName = cm.ConvertCgroupNameToSystemd(cm.CgroupName(cgroupName), true) } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod" + string(uuid.NewUUID()), }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyOnFailure, - Containers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyOnFailure, + Containers: []v1.Container{ { Image: "gcr.io/google_containers/busybox:1.24", Name: "container" + string(uuid.NewUUID()), Command: []string{"sh", "-c", "for i in `seq 1 10`; do if [ ! -d /tmp/memory/" + cgroupFsName + " ] && [ ! -d /tmp/cpu/" + cgroupFsName + " ]; then exit 0; else sleep 10; fi; done; exit 1"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "sysfscgroup", MountPath: "/tmp", @@ -125,11 +125,11 @@ func makePodToVerifyCgroupRemoved(cgroupName cm.CgroupName) *api.Pod { }, }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: "sysfscgroup", - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/sys/fs/cgroup"}, + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{Path: "/sys/fs/cgroup"}, }, }, }, @@ -162,17 +162,17 @@ var _ = framework.KubeDescribe("Kubelet Cgroup Manager", func() { return } var ( - guaranteedPod *api.Pod + guaranteedPod *v1.Pod podUID string ) By("Creating a Guaranteed pod in Namespace", func() { - guaranteedPod = f.PodClient().Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + guaranteedPod = f.PodClient().Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod" + string(uuid.NewUUID()), Namespace: f.Namespace.Name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Image: framework.GetPauseImageName(f.ClientSet), Name: "container" + string(uuid.NewUUID()), @@ -192,7 +192,7 @@ var _ = framework.KubeDescribe("Kubelet Cgroup Manager", func() { }) By("Checking if the pod cgroup was deleted", func() { gp := int64(1) - Expect(f.PodClient().Delete(guaranteedPod.Name, &api.DeleteOptions{GracePeriodSeconds: &gp})).NotTo(HaveOccurred()) + Expect(f.PodClient().Delete(guaranteedPod.Name, &v1.DeleteOptions{GracePeriodSeconds: &gp})).NotTo(HaveOccurred()) pod := makePodToVerifyCgroupRemoved(cm.CgroupName("pod" + podUID)) f.PodClient().Create(pod) err := framework.WaitForPodSuccessInNamespace(f.ClientSet, pod.Name, f.Namespace.Name) @@ -207,16 +207,16 @@ var _ = framework.KubeDescribe("Kubelet Cgroup Manager", func() { } var ( podUID string - bestEffortPod *api.Pod + bestEffortPod *v1.Pod ) By("Creating a BestEffort pod in Namespace", func() { - bestEffortPod = f.PodClient().Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + bestEffortPod = f.PodClient().Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod" + string(uuid.NewUUID()), Namespace: f.Namespace.Name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Image: framework.GetPauseImageName(f.ClientSet), Name: "container" + string(uuid.NewUUID()), @@ -236,7 +236,7 @@ var _ = framework.KubeDescribe("Kubelet Cgroup Manager", func() { }) By("Checking if the pod cgroup was deleted", func() { gp := int64(1) - Expect(f.PodClient().Delete(bestEffortPod.Name, &api.DeleteOptions{GracePeriodSeconds: &gp})).NotTo(HaveOccurred()) + Expect(f.PodClient().Delete(bestEffortPod.Name, &v1.DeleteOptions{GracePeriodSeconds: &gp})).NotTo(HaveOccurred()) pod := makePodToVerifyCgroupRemoved(cm.CgroupName("BestEffort/pod" + podUID)) f.PodClient().Create(pod) err := framework.WaitForPodSuccessInNamespace(f.ClientSet, pod.Name, f.Namespace.Name) @@ -251,16 +251,16 @@ var _ = framework.KubeDescribe("Kubelet Cgroup Manager", func() { } var ( podUID string - burstablePod *api.Pod + burstablePod *v1.Pod ) By("Creating a Burstable pod in Namespace", func() { - burstablePod = f.PodClient().Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + burstablePod = f.PodClient().Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod" + string(uuid.NewUUID()), Namespace: f.Namespace.Name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Image: framework.GetPauseImageName(f.ClientSet), Name: "container" + string(uuid.NewUUID()), @@ -280,7 +280,7 @@ var _ = framework.KubeDescribe("Kubelet Cgroup Manager", func() { }) By("Checking if the pod cgroup was deleted", func() { gp := int64(1) - Expect(f.PodClient().Delete(burstablePod.Name, &api.DeleteOptions{GracePeriodSeconds: &gp})).NotTo(HaveOccurred()) + Expect(f.PodClient().Delete(burstablePod.Name, &v1.DeleteOptions{GracePeriodSeconds: &gp})).NotTo(HaveOccurred()) pod := makePodToVerifyCgroupRemoved(cm.CgroupName("Burstable/pod" + podUID)) f.PodClient().Create(pod) err := framework.WaitForPodSuccessInNamespace(f.ClientSet, pod.Name, f.Namespace.Name) diff --git a/test/e2e_node/container.go b/test/e2e_node/container.go index 647f0e9e0e1..55daf5e8022 100644 --- a/test/e2e_node/container.go +++ b/test/e2e_node/container.go @@ -19,8 +19,8 @@ package e2e_node import ( "fmt" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" ) @@ -28,29 +28,29 @@ import ( // One pod one container // TODO: This should be migrated to the e2e framework. type ConformanceContainer struct { - Container api.Container - RestartPolicy api.RestartPolicy - Volumes []api.Volume + Container v1.Container + RestartPolicy v1.RestartPolicy + Volumes []v1.Volume ImagePullSecrets []string PodClient *framework.PodClient podName string - PodSecurityContext *api.PodSecurityContext + PodSecurityContext *v1.PodSecurityContext } func (cc *ConformanceContainer) Create() { cc.podName = cc.Container.Name + string(uuid.NewUUID()) - imagePullSecrets := []api.LocalObjectReference{} + imagePullSecrets := []v1.LocalObjectReference{} for _, s := range cc.ImagePullSecrets { - imagePullSecrets = append(imagePullSecrets, api.LocalObjectReference{Name: s}) + imagePullSecrets = append(imagePullSecrets, v1.LocalObjectReference{Name: s}) } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: cc.podName, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ RestartPolicy: cc.RestartPolicy, - Containers: []api.Container{ + Containers: []v1.Container{ cc.Container, }, SecurityContext: cc.PodSecurityContext, @@ -62,7 +62,7 @@ func (cc *ConformanceContainer) Create() { } func (cc *ConformanceContainer) Delete() error { - return cc.PodClient.Delete(cc.podName, api.NewDeleteOptions(0)) + return cc.PodClient.Delete(cc.podName, v1.NewDeleteOptions(0)) } func (cc *ConformanceContainer) IsReady() (bool, error) { @@ -70,25 +70,25 @@ func (cc *ConformanceContainer) IsReady() (bool, error) { if err != nil { return false, err } - return api.IsPodReady(pod), nil + return v1.IsPodReady(pod), nil } -func (cc *ConformanceContainer) GetPhase() (api.PodPhase, error) { +func (cc *ConformanceContainer) GetPhase() (v1.PodPhase, error) { pod, err := cc.PodClient.Get(cc.podName) if err != nil { - return api.PodUnknown, err + return v1.PodUnknown, err } return pod.Status.Phase, nil } -func (cc *ConformanceContainer) GetStatus() (api.ContainerStatus, error) { +func (cc *ConformanceContainer) GetStatus() (v1.ContainerStatus, error) { pod, err := cc.PodClient.Get(cc.podName) if err != nil { - return api.ContainerStatus{}, err + return v1.ContainerStatus{}, err } statuses := pod.Status.ContainerStatuses if len(statuses) != 1 || statuses[0].Name != cc.Container.Name { - return api.ContainerStatus{}, fmt.Errorf("unexpected container statuses %v", statuses) + return v1.ContainerStatus{}, fmt.Errorf("unexpected container statuses %v", statuses) } return statuses[0], nil } @@ -113,7 +113,7 @@ const ( ContainerStateUnknown ContainerState = "Unknown" ) -func GetContainerState(state api.ContainerState) ContainerState { +func GetContainerState(state v1.ContainerState) ContainerState { if state.Waiting != nil { return ContainerStateWaiting } diff --git a/test/e2e_node/container_manager_test.go b/test/e2e_node/container_manager_test.go index d9d400efc48..3f8cbaf8342 100644 --- a/test/e2e_node/container_manager_test.go +++ b/test/e2e_node/container_manager_test.go @@ -26,8 +26,8 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -95,12 +95,12 @@ var _ = framework.KubeDescribe("Kubelet Container Manager [Serial]", func() { var err error podClient := f.PodClient() podName := "besteffort" + string(uuid.NewUUID()) - podClient.Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + podClient.Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Image: "gcr.io/google_containers/serve_hostname:v1.4", Name: podName, @@ -139,17 +139,17 @@ var _ = framework.KubeDescribe("Kubelet Container Manager [Serial]", func() { It("guaranteed container's oom-score-adj should be -998", func() { podClient := f.PodClient() podName := "guaranteed" + string(uuid.NewUUID()) - podClient.Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + podClient.Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Image: "gcr.io/google_containers/nginx-slim:0.7", Name: podName, - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Limits: v1.ResourceList{ "cpu": resource.MustParse("100m"), "memory": resource.MustParse("50Mi"), }, @@ -180,17 +180,17 @@ var _ = framework.KubeDescribe("Kubelet Container Manager [Serial]", func() { It("burstable container's oom-score-adj should be between [2, 1000)", func() { podClient := f.PodClient() podName := "burstable" + string(uuid.NewUUID()) - podClient.Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + podClient.Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Image: "gcr.io/google_containers/test-webserver:e2e", Name: podName, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("100m"), "memory": resource.MustParse("50Mi"), }, diff --git a/test/e2e_node/density_test.go b/test/e2e_node/density_test.go index 7bd7b34f1cf..ccb06252b5e 100644 --- a/test/e2e_node/density_test.go +++ b/test/e2e_node/density_test.go @@ -25,8 +25,8 @@ import ( "sync" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" kubemetrics "k8s.io/kubernetes/pkg/kubelet/metrics" @@ -429,7 +429,7 @@ func runDensitySeqTest(f *framework.Framework, rc *ResourceCollector, testArg de // createBatchPodWithRateControl creates a batch of pods concurrently, uses one goroutine for each creation. // between creations there is an interval for throughput control -func createBatchPodWithRateControl(f *framework.Framework, pods []*api.Pod, interval time.Duration) map[string]unversioned.Time { +func createBatchPodWithRateControl(f *framework.Framework, pods []*v1.Pod, interval time.Duration) map[string]unversioned.Time { createTimes := make(map[string]unversioned.Time) for _, pod := range pods { createTimes[pod.ObjectMeta.Name] = unversioned.Now() @@ -479,12 +479,12 @@ func verifyPodStartupLatency(expect, actual framework.LatencyMetric) error { func newInformerWatchPod(f *framework.Framework, mutex *sync.Mutex, watchTimes map[string]unversioned.Time, podType string) *cache.Controller { ns := f.Namespace.Name - checkPodRunning := func(p *api.Pod) { + checkPodRunning := func(p *v1.Pod) { mutex.Lock() defer mutex.Unlock() defer GinkgoRecover() - if p.Status.Phase == api.PodRunning { + if p.Status.Phase == v1.PodRunning { if _, found := watchTimes[p.Name]; !found { watchTimes[p.Name] = unversioned.Now() } @@ -493,26 +493,26 @@ func newInformerWatchPod(f *framework.Framework, mutex *sync.Mutex, watchTimes m _, controller := cache.NewInformer( &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - options.LabelSelector = labels.SelectorFromSet(labels.Set{"type": podType}) + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + options.LabelSelector = labels.SelectorFromSet(labels.Set{"type": podType}).String() obj, err := f.ClientSet.Core().Pods(ns).List(options) return runtime.Object(obj), err }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - options.LabelSelector = labels.SelectorFromSet(labels.Set{"type": podType}) + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + options.LabelSelector = labels.SelectorFromSet(labels.Set{"type": podType}).String() return f.ClientSet.Core().Pods(ns).Watch(options) }, }, - &api.Pod{}, + &v1.Pod{}, 0, cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { - p, ok := obj.(*api.Pod) + p, ok := obj.(*v1.Pod) Expect(ok).To(Equal(true)) go checkPodRunning(p) }, UpdateFunc: func(oldObj, newObj interface{}) { - p, ok := newObj.(*api.Pod) + p, ok := newObj.(*v1.Pod) Expect(ok).To(Equal(true)) go checkPodRunning(p) }, @@ -522,7 +522,7 @@ func newInformerWatchPod(f *framework.Framework, mutex *sync.Mutex, watchTimes m } // createBatchPodSequential creats pods back-to-back in sequence. -func createBatchPodSequential(f *framework.Framework, pods []*api.Pod) (time.Duration, []framework.PodLatencyData) { +func createBatchPodSequential(f *framework.Framework, pods []*v1.Pod) (time.Duration, []framework.PodLatencyData) { batchStartTime := unversioned.Now() e2eLags := make([]framework.PodLatencyData, 0) for _, pod := range pods { diff --git a/test/e2e_node/disk_eviction_test.go b/test/e2e_node/disk_eviction_test.go index 6200a36c8d6..b272352a5e6 100644 --- a/test/e2e_node/disk_eviction_test.go +++ b/test/e2e_node/disk_eviction_test.go @@ -21,13 +21,13 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" ) const ( @@ -72,13 +72,13 @@ var _ = framework.KubeDescribe("Kubelet Eviction Manager [Serial] [Disruptive]", idlePodName = "idle" + string(uuid.NewUUID()) verifyPodName = "verify" + string(uuid.NewUUID()) createIdlePod(idlePodName, podClient) - podClient.Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + podClient.Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: busyPodName, }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Image: "gcr.io/google_containers/busybox:1.24", Name: busyPodName, @@ -96,9 +96,9 @@ var _ = framework.KubeDescribe("Kubelet Eviction Manager [Serial] [Disruptive]", if !isImageSupported() || !evictionOptionIsSet() { // Skip the after each return } - podClient.DeleteSync(busyPodName, &api.DeleteOptions{}, podDisappearTimeout) - podClient.DeleteSync(idlePodName, &api.DeleteOptions{}, podDisappearTimeout) - podClient.DeleteSync(verifyPodName, &api.DeleteOptions{}, podDisappearTimeout) + podClient.DeleteSync(busyPodName, &v1.DeleteOptions{}, podDisappearTimeout) + podClient.DeleteSync(idlePodName, &v1.DeleteOptions{}, podDisappearTimeout) + podClient.DeleteSync(verifyPodName, &v1.DeleteOptions{}, podDisappearTimeout) // Wait for 2 container gc loop to ensure that the containers are deleted. The containers // created in this test consume a lot of disk, we don't want them to trigger disk eviction @@ -140,7 +140,7 @@ var _ = framework.KubeDescribe("Kubelet Eviction Manager [Serial] [Disruptive]", return err } - if podData.Status.Phase != api.PodRunning { + if podData.Status.Phase != v1.PodRunning { err = verifyPodEviction(podData) if err != nil { return err @@ -174,7 +174,7 @@ var _ = framework.KubeDescribe("Kubelet Eviction Manager [Serial] [Disruptive]", if err != nil { return err } - if podData.Status.Phase != api.PodRunning { + if podData.Status.Phase != v1.PodRunning { return fmt.Errorf("waiting for the new pod to be running") } @@ -186,13 +186,13 @@ var _ = framework.KubeDescribe("Kubelet Eviction Manager [Serial] [Disruptive]", }) func createIdlePod(podName string, podClient *framework.PodClient) { - podClient.Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + podClient.Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Image: framework.GetPauseImageNameForHostArch(), Name: podName, @@ -202,8 +202,8 @@ func createIdlePod(podName string, podClient *framework.PodClient) { }) } -func verifyPodEviction(podData *api.Pod) error { - if podData.Status.Phase != api.PodFailed { +func verifyPodEviction(podData *v1.Pod) error { + if podData.Status.Phase != v1.PodFailed { return fmt.Errorf("expected phase to be failed. got %+v", podData.Status.Phase) } if podData.Status.Reason != "Evicted" { @@ -215,8 +215,8 @@ func verifyPodEviction(podData *api.Pod) error { func nodeHasDiskPressure(cs clientset.Interface) bool { nodeList := framework.GetReadySchedulableNodesOrDie(cs) for _, condition := range nodeList.Items[0].Status.Conditions { - if condition.Type == api.NodeDiskPressure { - return condition.Status == api.ConditionTrue + if condition.Type == v1.NodeDiskPressure { + return condition.Status == v1.ConditionTrue } } return false diff --git a/test/e2e_node/e2e_node_suite_test.go b/test/e2e_node/e2e_node_suite_test.go index bffd6d2295c..2620ea46f6b 100644 --- a/test/e2e_node/e2e_node_suite_test.go +++ b/test/e2e_node/e2e_node_suite_test.go @@ -31,8 +31,8 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" commontest "k8s.io/kubernetes/test/e2e/common" "k8s.io/kubernetes/test/e2e/framework" "k8s.io/kubernetes/test/e2e_node/services" @@ -212,7 +212,7 @@ func waitForNodeReady() { if err != nil { return fmt.Errorf("failed to get node: %v", err) } - if !api.IsNodeReady(node) { + if !v1.IsNodeReady(node) { return fmt.Errorf("node is not ready: %+v", node) } return nil @@ -245,8 +245,8 @@ func updateTestContext() error { } // getNode gets node object from the apiserver. -func getNode(c *clientset.Clientset) (*api.Node, error) { - nodes, err := c.Nodes().List(api.ListOptions{}) +func getNode(c *clientset.Clientset) (*v1.Node, error) { + nodes, err := c.Nodes().List(v1.ListOptions{}) Expect(err).NotTo(HaveOccurred(), "should be able to list nodes.") if nodes == nil { return nil, fmt.Errorf("the node list is nil.") diff --git a/test/e2e_node/garbage_collector_test.go b/test/e2e_node/garbage_collector_test.go index d62385d697f..5287b1956e4 100644 --- a/test/e2e_node/garbage_collector_test.go +++ b/test/e2e_node/garbage_collector_test.go @@ -21,7 +21,7 @@ import ( "strings" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" docker "k8s.io/kubernetes/pkg/kubelet/dockertools" "k8s.io/kubernetes/test/e2e/framework" @@ -230,7 +230,7 @@ func containerGCTest(f *framework.Framework, test testRun) { AfterEach(func() { for _, pod := range test.testPods { By(fmt.Sprintf("Deleting Pod %v", pod.podName)) - f.PodClient().DeleteSync(pod.podName, &api.DeleteOptions{}, defaultRuntimeRequestTimeoutDuration) + f.PodClient().DeleteSync(pod.podName, &v1.DeleteOptions{}, defaultRuntimeRequestTimeoutDuration) } By("Making sure all containers get cleaned up") @@ -279,12 +279,12 @@ func dockerContainerGCTest(f *framework.Framework, test testRun) { containerGCTest(f, test) } -func getPods(specs []*testPodSpec) (pods []*api.Pod) { +func getPods(specs []*testPodSpec) (pods []*v1.Pod) { for _, spec := range specs { By(fmt.Sprintf("Creating %v containers with restartCount: %v", spec.numContainers, spec.restartCount)) - containers := []api.Container{} + containers := []v1.Container{} for i := 0; i < spec.numContainers; i++ { - containers = append(containers, api.Container{ + containers = append(containers, v1.Container{ Image: "gcr.io/google_containers/busybox:1.24", Name: spec.getContainerName(i), Command: []string{ @@ -299,18 +299,18 @@ func getPods(specs []*testPodSpec) (pods []*api.Pod) { while true; do sleep 1; done `, i, spec.restartCount+1), }, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ {MountPath: "/test-empty-dir-mnt", Name: "test-empty-dir"}, }, }) } - pods = append(pods, &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: spec.podName}, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, + pods = append(pods, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: spec.podName}, + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyAlways, Containers: containers, - Volumes: []api.Volume{ - {Name: "test-empty-dir", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, + Volumes: []v1.Volume{ + {Name: "test-empty-dir", VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}}, }, }, }) diff --git a/test/e2e_node/image_id_test.go b/test/e2e_node/image_id_test.go index da831b60794..3636fbed5f4 100644 --- a/test/e2e_node/image_id_test.go +++ b/test/e2e_node/image_id_test.go @@ -17,7 +17,7 @@ limitations under the License. package e2e_node import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/dockertools" "k8s.io/kubernetes/test/e2e/framework" @@ -33,17 +33,17 @@ var _ = framework.KubeDescribe("ImageID", func() { f := framework.NewDefaultFramework("image-id-test") It("should be set to the manifest digest (from RepoDigests) when available", func() { - podDesc := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + podDesc := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-with-repodigest", }, - Spec: api.PodSpec{ - Containers: []api.Container{{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ Name: "test", Image: busyBoxImage, Command: []string{"sh"}, }}, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, }, } diff --git a/test/e2e_node/kubelet_test.go b/test/e2e_node/kubelet_test.go index 734f4d18507..39d0015d6bc 100644 --- a/test/e2e_node/kubelet_test.go +++ b/test/e2e_node/kubelet_test.go @@ -21,8 +21,8 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" apiUnversioned "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -39,14 +39,14 @@ var _ = framework.KubeDescribe("Kubelet", func() { Context("when scheduling a busybox command in a pod", func() { podName := "busybox-scheduling-" + string(uuid.NewUUID()) It("it should print the output to logs [Conformance]", func() { - podClient.CreateSync(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + podClient.CreateSync(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ // Don't restart the Pod since it is expected to exit - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Image: "gcr.io/google_containers/busybox:1.24", Name: podName, @@ -57,7 +57,7 @@ var _ = framework.KubeDescribe("Kubelet", func() { }) Eventually(func() string { sinceTime := apiUnversioned.NewTime(time.Now().Add(time.Duration(-1 * time.Hour))) - rc, err := podClient.GetLogs(podName, &api.PodLogOptions{SinceTime: &sinceTime}).Stream() + rc, err := podClient.GetLogs(podName, &v1.PodLogOptions{SinceTime: &sinceTime}).Stream() if err != nil { return "" } @@ -73,14 +73,14 @@ var _ = framework.KubeDescribe("Kubelet", func() { BeforeEach(func() { podName = "bin-false" + string(uuid.NewUUID()) - podClient.Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + podClient.Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ // Don't restart the Pod since it is expected to exit - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Image: "gcr.io/google_containers/busybox:1.24", Name: podName, @@ -112,7 +112,7 @@ var _ = framework.KubeDescribe("Kubelet", func() { }) It("should be possible to delete", func() { - err := podClient.Delete(podName, &api.DeleteOptions{}) + err := podClient.Delete(podName, &v1.DeleteOptions{}) Expect(err).To(BeNil(), fmt.Sprintf("Error deleting Pod %v", err)) }) }) @@ -120,19 +120,19 @@ var _ = framework.KubeDescribe("Kubelet", func() { podName := "busybox-readonly-fs" + string(uuid.NewUUID()) It("it should not write to root filesystem [Conformance]", func() { isReadOnly := true - podClient.CreateSync(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + podClient.CreateSync(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ // Don't restart the Pod since it is expected to exit - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Image: "gcr.io/google_containers/busybox:1.24", Name: podName, Command: []string{"sh", "-c", "echo test > /file; sleep 240"}, - SecurityContext: &api.SecurityContext{ + SecurityContext: &v1.SecurityContext{ ReadOnlyRootFilesystem: &isReadOnly, }, }, @@ -140,7 +140,7 @@ var _ = framework.KubeDescribe("Kubelet", func() { }, }) Eventually(func() string { - rc, err := podClient.GetLogs(podName, &api.PodLogOptions{}).Stream() + rc, err := podClient.GetLogs(podName, &v1.PodLogOptions{}).Stream() if err != nil { return "" } diff --git a/test/e2e_node/lifecycle_hook_test.go b/test/e2e_node/lifecycle_hook_test.go index a17172fa45a..2417e07ffda 100644 --- a/test/e2e_node/lifecycle_hook_test.go +++ b/test/e2e_node/lifecycle_hook_test.go @@ -20,7 +20,7 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -45,7 +45,7 @@ var _ = framework.KubeDescribe("Container Lifecycle Hook", func() { Context("when it is exec hook", func() { var file string - testPodWithExecHook := func(podWithHook *api.Pod) { + testPodWithExecHook := func(podWithHook *v1.Pod) { podCheckHook := getExecHookTestPod("pod-check-hook", // Wait until the file is created. []string{"sh", "-c", fmt.Sprintf("while [ ! -e %s ]; do sleep 1; done", file)}, @@ -59,7 +59,7 @@ var _ = framework.KubeDescribe("Container Lifecycle Hook", func() { podClient.WaitForSuccess(podCheckHook.Name, postStartWaitTimeout) } By("delete the pod with lifecycle hook") - podClient.DeleteSync(podWithHook.Name, api.NewDeleteOptions(15), podWaitTimeout) + podClient.DeleteSync(podWithHook.Name, v1.NewDeleteOptions(15), podWaitTimeout) if podWithHook.Spec.Containers[0].Lifecycle.PreStop != nil { By("create the hook check pod") podClient.Create(podCheckHook) @@ -84,9 +84,9 @@ var _ = framework.KubeDescribe("Container Lifecycle Hook", func() { // Block forever []string{"tail", "-f", "/dev/null"}, ) - podWithHook.Spec.Containers[0].Lifecycle = &api.Lifecycle{ - PostStart: &api.Handler{ - Exec: &api.ExecAction{Command: []string{"touch", file}}, + podWithHook.Spec.Containers[0].Lifecycle = &v1.Lifecycle{ + PostStart: &v1.Handler{ + Exec: &v1.ExecAction{Command: []string{"touch", file}}, }, } testPodWithExecHook(podWithHook) @@ -97,9 +97,9 @@ var _ = framework.KubeDescribe("Container Lifecycle Hook", func() { // Block forever []string{"tail", "-f", "/dev/null"}, ) - podWithHook.Spec.Containers[0].Lifecycle = &api.Lifecycle{ - PreStop: &api.Handler{ - Exec: &api.ExecAction{Command: []string{"touch", file}}, + podWithHook.Spec.Containers[0].Lifecycle = &v1.Lifecycle{ + PreStop: &v1.Handler{ + Exec: &v1.ExecAction{Command: []string{"touch", file}}, }, } testPodWithExecHook(podWithHook) @@ -108,19 +108,19 @@ var _ = framework.KubeDescribe("Container Lifecycle Hook", func() { Context("when it is http hook", func() { var targetIP string - podHandleHookRequest := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + podHandleHookRequest := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-handle-http-request", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "pod-handle-http-request", Image: "gcr.io/google_containers/netexec:1.7", - Ports: []api.ContainerPort{ + Ports: []v1.ContainerPort{ { ContainerPort: 8080, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, }, }, @@ -132,7 +132,7 @@ var _ = framework.KubeDescribe("Container Lifecycle Hook", func() { newPod := podClient.CreateSync(podHandleHookRequest) targetIP = newPod.Status.PodIP }) - testPodWithHttpHook := func(podWithHook *api.Pod) { + testPodWithHttpHook := func(podWithHook *v1.Pod) { By("create the pod with lifecycle hook") podClient.CreateSync(podWithHook) if podWithHook.Spec.Containers[0].Lifecycle.PostStart != nil { @@ -143,7 +143,7 @@ var _ = framework.KubeDescribe("Container Lifecycle Hook", func() { }, postStartWaitTimeout, podCheckInterval).Should(BeNil()) } By("delete the pod with lifecycle hook") - podClient.DeleteSync(podWithHook.Name, api.NewDeleteOptions(15), podWaitTimeout) + podClient.DeleteSync(podWithHook.Name, v1.NewDeleteOptions(15), podWaitTimeout) if podWithHook.Spec.Containers[0].Lifecycle.PreStop != nil { By("check prestop hook") Eventually(func() error { @@ -153,18 +153,18 @@ var _ = framework.KubeDescribe("Container Lifecycle Hook", func() { } } It("should execute poststart http hook properly [Conformance]", func() { - podWithHook := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + podWithHook := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-with-poststart-http-hook", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "pod-with-poststart-http-hook", Image: framework.GetPauseImageNameForHostArch(), - Lifecycle: &api.Lifecycle{ - PostStart: &api.Handler{ - HTTPGet: &api.HTTPGetAction{ + Lifecycle: &v1.Lifecycle{ + PostStart: &v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Path: "/echo?msg=poststart", Host: targetIP, Port: intstr.FromInt(8080), @@ -178,18 +178,18 @@ var _ = framework.KubeDescribe("Container Lifecycle Hook", func() { testPodWithHttpHook(podWithHook) }) It("should execute prestop http hook properly [Conformance]", func() { - podWithHook := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + podWithHook := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod-with-prestop-http-hook", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "pod-with-prestop-http-hook", Image: framework.GetPauseImageNameForHostArch(), - Lifecycle: &api.Lifecycle{ - PreStop: &api.Handler{ - HTTPGet: &api.HTTPGetAction{ + Lifecycle: &v1.Lifecycle{ + PreStop: &v1.Handler{ + HTTPGet: &v1.HTTPGetAction{ Path: "/echo?msg=prestop", Host: targetIP, Port: intstr.FromInt(8080), @@ -206,17 +206,17 @@ var _ = framework.KubeDescribe("Container Lifecycle Hook", func() { }) }) -func getExecHookTestPod(name string, cmd []string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func getExecHookTestPod(name string, cmd []string) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: name, Image: "gcr.io/google_containers/busybox:1.24", - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "tmpfs", MountPath: "/tmp", @@ -225,11 +225,11 @@ func getExecHookTestPod(name string, cmd []string) *api.Pod { Command: cmd, }, }, - RestartPolicy: api.RestartPolicyNever, - Volumes: []api.Volume{ + RestartPolicy: v1.RestartPolicyNever, + Volumes: []v1.Volume{ { Name: "tmpfs", - VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/tmp"}}, + VolumeSource: v1.VolumeSource{HostPath: &v1.HostPathVolumeSource{Path: "/tmp"}}, }, }, }, diff --git a/test/e2e_node/log_path_test.go b/test/e2e_node/log_path_test.go index bf2b5be1740..620192cd375 100644 --- a/test/e2e_node/log_path_test.go +++ b/test/e2e_node/log_path_test.go @@ -17,7 +17,7 @@ limitations under the License. package e2e_node import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/util/uuid" @@ -44,14 +44,14 @@ var _ = framework.KubeDescribe("ContainerLogPath", func() { checkPodName := "checker" + string(uuid.NewUUID()) checkContName := "checker-c-" + string(uuid.NewUUID()) - logPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + logPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: logPodName, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ // this pod is expected to exit successfully - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Image: "gcr.io/google_containers/busybox:1.24", Name: logContName, @@ -72,21 +72,21 @@ var _ = framework.KubeDescribe("ContainerLogPath", func() { expectedlogFile := logDir + "/" + logPodName + "_" + ns + "_" + logContName + "-" + logConID.ID + ".log" - checkPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + checkPod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: checkPodName, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ // this pod is expected to exit successfully - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Image: "gcr.io/google_containers/busybox:1.24", Name: checkContName, // If we find expected log file and contains right content, exit 0 // else, keep checking until test timeout Command: []string{"sh", "-c", "while true; do if [ -e " + expectedlogFile + " ] && grep -q " + logString + " " + expectedlogFile + "; then exit 0; fi; sleep 1; done"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: logDirVolumeName, // mount ContainerLogsDir to the same path in container @@ -96,11 +96,11 @@ var _ = framework.KubeDescribe("ContainerLogPath", func() { }, }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: logDirVolumeName, - VolumeSource: api.VolumeSource{ - HostPath: &api.HostPathVolumeSource{ + VolumeSource: v1.VolumeSource{ + HostPath: &v1.HostPathVolumeSource{ Path: expectedlogFile, }, }, diff --git a/test/e2e_node/memory_eviction_test.go b/test/e2e_node/memory_eviction_test.go index 05d9f7c349f..727b6b951d1 100644 --- a/test/e2e_node/memory_eviction_test.go +++ b/test/e2e_node/memory_eviction_test.go @@ -22,8 +22,8 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" @@ -50,7 +50,7 @@ var _ = framework.KubeDescribe("MemoryEviction [Slow] [Serial] [Disruptive]", fu // Wait for the memory pressure condition to disappear from the node status before continuing. By("waiting for the memory pressure condition on the node to disappear before ending the test.") Eventually(func() error { - nodeList, err := f.ClientSet.Core().Nodes().List(api.ListOptions{}) + nodeList, err := f.ClientSet.Core().Nodes().List(v1.ListOptions{}) if err != nil { return fmt.Errorf("tried to get node list but got error: %v", err) } @@ -59,8 +59,8 @@ var _ = framework.KubeDescribe("MemoryEviction [Slow] [Serial] [Disruptive]", fu return fmt.Errorf("expected 1 node, but see %d. List: %v", len(nodeList.Items), nodeList.Items) } node := nodeList.Items[0] - _, pressure := api.GetNodeCondition(&node.Status, api.NodeMemoryPressure) - if pressure != nil && pressure.Status == api.ConditionTrue { + _, pressure := v1.GetNodeCondition(&node.Status, v1.NodeMemoryPressure) + if pressure != nil && pressure.Status == v1.ConditionTrue { return fmt.Errorf("node is still reporting memory pressure condition: %s", pressure) } return nil @@ -104,13 +104,13 @@ var _ = framework.KubeDescribe("MemoryEviction [Slow] [Serial] [Disruptive]", fu // Finally, try starting a new pod and wait for it to be scheduled and running. // This is the final check to try to prevent interference with subsequent tests. podName := "admit-best-effort-pod" - f.PodClient().CreateSync(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + f.PodClient().CreateSync(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Image: framework.GetPauseImageNameForHostArch(), Name: podName, @@ -124,25 +124,25 @@ var _ = framework.KubeDescribe("MemoryEviction [Slow] [Serial] [Disruptive]", fu By("creating a guaranteed pod, a burstable pod, and a besteffort pod.") // A pod is guaranteed only when requests and limits are specified for all the containers and they are equal. - guaranteed := createMemhogPod(f, "guaranteed-", "guaranteed", api.ResourceRequirements{ - Requests: api.ResourceList{ + guaranteed := createMemhogPod(f, "guaranteed-", "guaranteed", v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("100m"), "memory": resource.MustParse("100Mi"), }, - Limits: api.ResourceList{ + Limits: v1.ResourceList{ "cpu": resource.MustParse("100m"), "memory": resource.MustParse("100Mi"), }}) // A pod is burstable if limits and requests do not match across all containers. - burstable := createMemhogPod(f, "burstable-", "burstable", api.ResourceRequirements{ - Requests: api.ResourceList{ + burstable := createMemhogPod(f, "burstable-", "burstable", v1.ResourceRequirements{ + Requests: v1.ResourceList{ "cpu": resource.MustParse("100m"), "memory": resource.MustParse("100Mi"), }}) // A pod is besteffort if none of its containers have specified any requests or limits. - besteffort := createMemhogPod(f, "besteffort-", "besteffort", api.ResourceRequirements{}) + besteffort := createMemhogPod(f, "besteffort-", "besteffort", v1.ResourceRequirements{}) // We poll until timeout or all pods are killed. // Inside the func, we check that all pods are in a valid phase with @@ -174,7 +174,7 @@ var _ = framework.KubeDescribe("MemoryEviction [Slow] [Serial] [Disruptive]", fu // see the eviction manager reporting a pressure condition for a while without the besteffort failing, // and we see that the manager did in fact evict the besteffort (this should be in the Kubelet log), we // will have more reason to believe the phase is out of date. - nodeList, err := f.ClientSet.Core().Nodes().List(api.ListOptions{}) + nodeList, err := f.ClientSet.Core().Nodes().List(v1.ListOptions{}) if err != nil { glog.Errorf("tried to get node list but got error: %v", err) } @@ -182,7 +182,7 @@ var _ = framework.KubeDescribe("MemoryEviction [Slow] [Serial] [Disruptive]", fu glog.Errorf("expected 1 node, but see %d. List: %v", len(nodeList.Items), nodeList.Items) } node := nodeList.Items[0] - _, pressure := api.GetNodeCondition(&node.Status, api.NodeMemoryPressure) + _, pressure := v1.GetNodeCondition(&node.Status, v1.NodeMemoryPressure) glog.Infof("node pressure condition: %s", pressure) // NOTE/TODO(mtaufen): Also log (at least temporarily) the actual memory consumption on the node. @@ -198,15 +198,15 @@ var _ = framework.KubeDescribe("MemoryEviction [Slow] [Serial] [Disruptive]", fu } - if bestPh == api.PodRunning { - Expect(burstPh).NotTo(Equal(api.PodFailed), "burstable pod failed before best effort pod") - Expect(gteedPh).NotTo(Equal(api.PodFailed), "guaranteed pod failed before best effort pod") - } else if burstPh == api.PodRunning { - Expect(gteedPh).NotTo(Equal(api.PodFailed), "guaranteed pod failed before burstable pod") + if bestPh == v1.PodRunning { + Expect(burstPh).NotTo(Equal(v1.PodFailed), "burstable pod failed before best effort pod") + Expect(gteedPh).NotTo(Equal(v1.PodFailed), "guaranteed pod failed before best effort pod") + } else if burstPh == v1.PodRunning { + Expect(gteedPh).NotTo(Equal(v1.PodFailed), "guaranteed pod failed before burstable pod") } // When both besteffort and burstable have been evicted, the test has completed. - if bestPh == api.PodFailed && burstPh == api.PodFailed { + if bestPh == v1.PodFailed && burstPh == v1.PodFailed { return nil } return fmt.Errorf("besteffort and burstable have not yet both been evicted.") @@ -219,12 +219,12 @@ var _ = framework.KubeDescribe("MemoryEviction [Slow] [Serial] [Disruptive]", fu }) -func createMemhogPod(f *framework.Framework, genName string, ctnName string, res api.ResourceRequirements) *api.Pod { - env := []api.EnvVar{ +func createMemhogPod(f *framework.Framework, genName string, ctnName string, res v1.ResourceRequirements) *v1.Pod { + env := []v1.EnvVar{ { Name: "MEMORY_LIMIT", - ValueFrom: &api.EnvVarSource{ - ResourceFieldRef: &api.ResourceFieldSelector{ + ValueFrom: &v1.EnvVarSource{ + ResourceFieldRef: &v1.ResourceFieldSelector{ Resource: "limits.memory", }, }, @@ -243,13 +243,13 @@ func createMemhogPod(f *framework.Framework, genName string, ctnName string, res memLimit = "$(MEMORY_LIMIT)" } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ GenerateName: genName, }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Name: ctnName, Image: "gcr.io/google-containers/stress:v1", diff --git a/test/e2e_node/mirror_pod_test.go b/test/e2e_node/mirror_pod_test.go index 6cbcebb0126..1b6f4e57f68 100644 --- a/test/e2e_node/mirror_pod_test.go +++ b/test/e2e_node/mirror_pod_test.go @@ -23,9 +23,9 @@ import ( "path/filepath" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -47,7 +47,7 @@ var _ = framework.KubeDescribe("MirrorPod", func() { By("create the static pod") err := createStaticPod(manifestPath, staticPodName, ns, - "gcr.io/google_containers/nginx-slim:0.7", api.RestartPolicyAlways) + "gcr.io/google_containers/nginx-slim:0.7", v1.RestartPolicyAlways) Expect(err).ShouldNot(HaveOccurred()) By("wait for the mirror pod to be running") @@ -63,7 +63,7 @@ var _ = framework.KubeDescribe("MirrorPod", func() { By("update the static pod container image") image := framework.GetPauseImageNameForHostArch() - err = createStaticPod(manifestPath, staticPodName, ns, image, api.RestartPolicyAlways) + err = createStaticPod(manifestPath, staticPodName, ns, image, v1.RestartPolicyAlways) Expect(err).ShouldNot(HaveOccurred()) By("wait for the mirror pod to be updated") @@ -84,7 +84,7 @@ var _ = framework.KubeDescribe("MirrorPod", func() { uid := pod.UID By("delete the mirror pod with grace period 30s") - err = f.ClientSet.Core().Pods(ns).Delete(mirrorPodName, api.NewDeleteOptions(30)) + err = f.ClientSet.Core().Pods(ns).Delete(mirrorPodName, v1.NewDeleteOptions(30)) Expect(err).ShouldNot(HaveOccurred()) By("wait for the mirror pod to be recreated") @@ -99,7 +99,7 @@ var _ = framework.KubeDescribe("MirrorPod", func() { uid := pod.UID By("delete the mirror pod with grace period 0s") - err = f.ClientSet.Core().Pods(ns).Delete(mirrorPodName, api.NewDeleteOptions(0)) + err = f.ClientSet.Core().Pods(ns).Delete(mirrorPodName, v1.NewDeleteOptions(0)) Expect(err).ShouldNot(HaveOccurred()) By("wait for the mirror pod to be recreated") @@ -124,7 +124,7 @@ func staticPodPath(dir, name, namespace string) string { return filepath.Join(dir, namespace+"-"+name+".yaml") } -func createStaticPod(dir, name, namespace, image string, restart api.RestartPolicy) error { +func createStaticPod(dir, name, namespace, image string, restart v1.RestartPolicy) error { template := ` apiVersion: v1 kind: Pod @@ -168,7 +168,7 @@ func checkMirrorPodRunning(cl clientset.Interface, name, namespace string) error if err != nil { return fmt.Errorf("expected the mirror pod %q to appear: %v", name, err) } - if pod.Status.Phase != api.PodRunning { + if pod.Status.Phase != v1.PodRunning { return fmt.Errorf("expected the mirror pod %q to be running, got %q", name, pod.Status.Phase) } return nil @@ -182,7 +182,7 @@ func checkMirrorPodRecreatedAndRunnig(cl clientset.Interface, name, namespace st if pod.UID == oUID { return fmt.Errorf("expected the uid of mirror pod %q to be changed, got %q", name, pod.UID) } - if pod.Status.Phase != api.PodRunning { + if pod.Status.Phase != v1.PodRunning { return fmt.Errorf("expected the mirror pod %q to be running, got %q", name, pod.Status.Phase) } return nil diff --git a/test/e2e_node/resource_collector.go b/test/e2e_node/resource_collector.go index 40d15a19a37..939ebd93da9 100644 --- a/test/e2e_node/resource_collector.go +++ b/test/e2e_node/resource_collector.go @@ -34,7 +34,7 @@ import ( cadvisorclient "github.com/google/cadvisor/client/v2" cadvisorapiv2 "github.com/google/cadvisor/info/v2" "github.com/opencontainers/runc/libcontainer/cgroups" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/procfs" @@ -292,30 +292,29 @@ func formatCPUSummary(summary framework.ContainersCPUSummary) string { } // createCadvisorPod creates a standalone cadvisor pod for fine-grain resource monitoring. -func getCadvisorPod() *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ +func getCadvisorPod() *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: cadvisorPodName, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ // It uses a host port for the tests to collect data. // Currently we can not use port mapping in test-e2e-node. - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, - Containers: []api.Container{ + HostNetwork: true, + SecurityContext: &v1.PodSecurityContext{}, + Containers: []v1.Container{ { Image: cadvisorImageName, Name: cadvisorPodName, - Ports: []api.ContainerPort{ + Ports: []v1.ContainerPort{ { Name: "http", HostPort: cadvisorPort, ContainerPort: cadvisorPort, - Protocol: api.ProtocolTCP, + Protocol: v1.ProtocolTCP, }, }, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "sys", ReadOnly: true, @@ -344,22 +343,22 @@ func getCadvisorPod() *api.Pod { }, }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: "rootfs", - VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/"}}, + VolumeSource: v1.VolumeSource{HostPath: &v1.HostPathVolumeSource{Path: "/"}}, }, { Name: "var-run", - VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/var/run"}}, + VolumeSource: v1.VolumeSource{HostPath: &v1.HostPathVolumeSource{Path: "/var/run"}}, }, { Name: "sys", - VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/sys"}}, + VolumeSource: v1.VolumeSource{HostPath: &v1.HostPathVolumeSource{Path: "/sys"}}, }, { Name: "docker", - VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/var/lib/docker"}}, + VolumeSource: v1.VolumeSource{HostPath: &v1.HostPathVolumeSource{Path: "/var/lib/docker"}}, }, }, }, @@ -367,14 +366,14 @@ func getCadvisorPod() *api.Pod { } // deletePodsSync deletes a list of pods and block until pods disappear. -func deletePodsSync(f *framework.Framework, pods []*api.Pod) { +func deletePodsSync(f *framework.Framework, pods []*v1.Pod) { var wg sync.WaitGroup for _, pod := range pods { wg.Add(1) - go func(pod *api.Pod) { + go func(pod *v1.Pod) { defer wg.Done() - err := f.PodClient().Delete(pod.ObjectMeta.Name, api.NewDeleteOptions(30)) + err := f.PodClient().Delete(pod.ObjectMeta.Name, v1.NewDeleteOptions(30)) Expect(err).NotTo(HaveOccurred()) Expect(framework.WaitForPodToDisappear(f.ClientSet, f.Namespace.Name, pod.ObjectMeta.Name, labels.Everything(), @@ -386,8 +385,8 @@ func deletePodsSync(f *framework.Framework, pods []*api.Pod) { } // newTestPods creates a list of pods (specification) for test. -func newTestPods(numPods int, imageName, podType string) []*api.Pod { - var pods []*api.Pod +func newTestPods(numPods int, imageName, podType string) []*v1.Pod { + var pods []*v1.Pod for i := 0; i < numPods; i++ { podName := "test-" + string(uuid.NewUUID()) labels := map[string]string{ @@ -395,14 +394,14 @@ func newTestPods(numPods int, imageName, podType string) []*api.Pod { "name": podName, } pods = append(pods, - &api.Pod{ - ObjectMeta: api.ObjectMeta{ + &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: labels, }, - Spec: api.PodSpec{ + Spec: v1.PodSpec{ // Restart policy is always (default). - Containers: []api.Container{ + Containers: []v1.Container{ { Image: imageName, Name: podName, diff --git a/test/e2e_node/resource_usage_test.go b/test/e2e_node/resource_usage_test.go index 07b15f6a358..ed4db7d1636 100644 --- a/test/e2e_node/resource_usage_test.go +++ b/test/e2e_node/resource_usage_test.go @@ -23,7 +23,7 @@ import ( "strings" "time" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" "k8s.io/kubernetes/test/e2e/framework" diff --git a/test/e2e_node/restart_test.go b/test/e2e_node/restart_test.go index 30dc41e50b5..13dea0ac5e9 100644 --- a/test/e2e_node/restart_test.go +++ b/test/e2e_node/restart_test.go @@ -19,27 +19,29 @@ limitations under the License. package e2e_node import ( - "k8s.io/kubernetes/test/e2e/framework" "time" + "k8s.io/kubernetes/test/e2e/framework" + "fmt" - . "github.com/onsi/ginkgo" - "k8s.io/kubernetes/pkg/api" - testutils "k8s.io/kubernetes/test/utils" "os/exec" + + . "github.com/onsi/ginkgo" + "k8s.io/kubernetes/pkg/api/v1" + testutils "k8s.io/kubernetes/test/utils" ) // waitForPods waits for timeout duration, for pod_count. // If the timeout is hit, it returns the list of currently running pods. -func waitForPods(f *framework.Framework, pod_count int, timeout time.Duration) (runningPods []*api.Pod) { +func waitForPods(f *framework.Framework, pod_count int, timeout time.Duration) (runningPods []*v1.Pod) { for start := time.Now(); time.Since(start) < timeout; time.Sleep(10 * time.Second) { - podList, err := f.PodClient().List(api.ListOptions{}) + podList, err := f.PodClient().List(v1.ListOptions{}) if err != nil { framework.Logf("Failed to list pods on node: %v", err) continue } - runningPods = []*api.Pod{} + runningPods = []*v1.Pod{} for _, pod := range podList.Items { if r, err := testutils.PodRunningReady(&pod); err != nil || !r { continue diff --git a/test/e2e_node/runtime_conformance_test.go b/test/e2e_node/runtime_conformance_test.go index 00698016695..b9aa852a155 100644 --- a/test/e2e_node/runtime_conformance_test.go +++ b/test/e2e_node/runtime_conformance_test.go @@ -21,7 +21,7 @@ import ( "path" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/images" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -44,34 +44,34 @@ var _ = framework.KubeDescribe("Container Runtime Conformance Test", func() { It("it should run with the expected status [Conformance]", func() { restartCountVolumeName := "restart-count" restartCountVolumePath := "/restart-count" - testContainer := api.Container{ + testContainer := v1.Container{ Image: "gcr.io/google_containers/busybox:1.24", - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { MountPath: restartCountVolumePath, Name: restartCountVolumeName, }, }, } - testVolumes := []api.Volume{ + testVolumes := []v1.Volume{ { Name: restartCountVolumeName, - VolumeSource: api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{Medium: api.StorageMediumMemory}, + VolumeSource: v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{Medium: v1.StorageMediumMemory}, }, }, } testCases := []struct { Name string - RestartPolicy api.RestartPolicy - Phase api.PodPhase + RestartPolicy v1.RestartPolicy + Phase v1.PodPhase State ContainerState RestartCount int32 Ready bool }{ - {"terminate-cmd-rpa", api.RestartPolicyAlways, api.PodRunning, ContainerStateRunning, 2, true}, - {"terminate-cmd-rpof", api.RestartPolicyOnFailure, api.PodSucceeded, ContainerStateTerminated, 1, false}, - {"terminate-cmd-rpn", api.RestartPolicyNever, api.PodFailed, ContainerStateTerminated, 0, false}, + {"terminate-cmd-rpa", v1.RestartPolicyAlways, v1.PodRunning, ContainerStateRunning, 2, true}, + {"terminate-cmd-rpof", v1.RestartPolicyOnFailure, v1.PodSucceeded, ContainerStateTerminated, 1, false}, + {"terminate-cmd-rpn", v1.RestartPolicyNever, v1.PodFailed, ContainerStateTerminated, 0, false}, } for _, testCase := range testCases { @@ -95,8 +95,8 @@ while true; do sleep 1; done Container: testContainer, RestartPolicy: testCase.RestartPolicy, Volumes: testVolumes, - PodSecurityContext: &api.PodSecurityContext{ - SELinuxOptions: &api.SELinuxOptions{ + PodSecurityContext: &v1.PodSecurityContext{ + SELinuxOptions: &v1.SELinuxOptions{ Level: "s0", }, }, @@ -135,17 +135,17 @@ while true; do sleep 1; done priv := true c := ConformanceContainer{ PodClient: f.PodClient(), - Container: api.Container{ + Container: v1.Container{ Image: "gcr.io/google_containers/busybox:1.24", Name: name, Command: []string{"/bin/sh", "-c"}, Args: []string{fmt.Sprintf("/bin/echo -n %s > %s", terminationMessage, terminationMessagePath)}, TerminationMessagePath: terminationMessagePath, - SecurityContext: &api.SecurityContext{ + SecurityContext: &v1.SecurityContext{ Privileged: &priv, }, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, } By("create the container") @@ -153,7 +153,7 @@ while true; do sleep 1; done defer c.Delete() By("wait for the container to succeed") - Eventually(c.GetPhase, retryTimeout, pollInterval).Should(Equal(api.PodSucceeded)) + Eventually(c.GetPhase, retryTimeout, pollInterval).Should(Equal(v1.PodSucceeded)) By("get the container status") status, err := c.GetStatus() @@ -181,55 +181,55 @@ while true; do sleep 1; done } } }` - secret := &api.Secret{ - Data: map[string][]byte{api.DockerConfigJsonKey: []byte(auth)}, - Type: api.SecretTypeDockerConfigJson, + secret := &v1.Secret{ + Data: map[string][]byte{v1.DockerConfigJsonKey: []byte(auth)}, + Type: v1.SecretTypeDockerConfigJson, } // The following images are not added into NodeImageWhiteList, because this test is // testing image pulling, these images don't need to be prepulled. The ImagePullPolicy - // is api.PullAlways, so it won't be blocked by framework image white list check. + // is v1.PullAlways, so it won't be blocked by framework image white list check. for _, testCase := range []struct { description string image string secret bool - phase api.PodPhase + phase v1.PodPhase waiting bool }{ { description: "should not be able to pull image from invalid registry", image: "invalid.com/invalid/alpine:3.1", - phase: api.PodPending, + phase: v1.PodPending, waiting: true, }, { description: "should not be able to pull non-existing image from gcr.io", image: "gcr.io/google_containers/invalid-image:invalid-tag", - phase: api.PodPending, + phase: v1.PodPending, waiting: true, }, { description: "should be able to pull image from gcr.io", image: "gcr.io/google_containers/alpine-with-bash:1.0", - phase: api.PodRunning, + phase: v1.PodRunning, waiting: false, }, { description: "should be able to pull image from docker hub", image: "alpine:3.1", - phase: api.PodRunning, + phase: v1.PodRunning, waiting: false, }, { description: "should not be able to pull from private registry without secret", image: "gcr.io/authenticated-image-pulling/alpine:3.1", - phase: api.PodPending, + phase: v1.PodPending, waiting: true, }, { description: "should be able to pull from private registry with secret", image: "gcr.io/authenticated-image-pulling/alpine:3.1", secret: true, - phase: api.PodRunning, + phase: v1.PodRunning, waiting: false, }, } { @@ -239,14 +239,14 @@ while true; do sleep 1; done command := []string{"/bin/sh", "-c", "while true; do sleep 1; done"} container := ConformanceContainer{ PodClient: f.PodClient(), - Container: api.Container{ + Container: v1.Container{ Name: name, Image: testCase.image, Command: command, // PullAlways makes sure that the image will always be pulled even if it is present before the test. - ImagePullPolicy: api.PullAlways, + ImagePullPolicy: v1.PullAlways, }, - RestartPolicy: api.RestartPolicyNever, + RestartPolicy: v1.RestartPolicyNever, } if testCase.secret { secret.Name = "image-pull-secret-" + string(uuid.NewUUID()) diff --git a/test/e2e_node/services/BUILD b/test/e2e_node/services/BUILD index 43e88d42558..db051cd59dc 100644 --- a/test/e2e_node/services/BUILD +++ b/test/e2e_node/services/BUILD @@ -25,9 +25,9 @@ go_library( deps = [ "//cmd/kube-apiserver/app:go_default_library", "//cmd/kube-apiserver/app/options:go_default_library", - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/typed/dynamic:go_default_library", "//pkg/controller/namespace:go_default_library", diff --git a/test/e2e_node/services/namespace_controller.go b/test/e2e_node/services/namespace_controller.go index b16e67fd7ec..320c4d064be 100644 --- a/test/e2e_node/services/namespace_controller.go +++ b/test/e2e_node/services/namespace_controller.go @@ -19,9 +19,9 @@ package services import ( "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/typed/dynamic" namespacecontroller "k8s.io/kubernetes/pkg/controller/namespace" @@ -57,7 +57,7 @@ func (n *NamespaceController) Start() error { } clientPool := dynamic.NewClientPool(config, registered.RESTMapper(), dynamic.LegacyAPIPathResolverFunc) gvrFn := client.Discovery().ServerPreferredNamespacedResources - nc := namespacecontroller.NewNamespaceController(client, clientPool, gvrFn, ncResyncPeriod, api.FinalizerKubernetes) + nc := namespacecontroller.NewNamespaceController(client, clientPool, gvrFn, ncResyncPeriod, v1.FinalizerKubernetes) go nc.Run(ncConcurrency, n.stopCh) return nil } diff --git a/test/e2e_node/simple_mount.go b/test/e2e_node/simple_mount.go index 5bcbe5e8ab6..2d052099f88 100644 --- a/test/e2e_node/simple_mount.go +++ b/test/e2e_node/simple_mount.go @@ -17,8 +17,8 @@ limitations under the License. package e2e_node import ( - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" @@ -30,20 +30,20 @@ var _ = framework.KubeDescribe("SimpleMount", func() { // This is a very simple test that exercises the Kubelet's mounter code path. // If the mount fails, the pod will not be able to run, and CreateSync will timeout. It("should be able to mount an emptydir on a container", func() { - pod := &api.Pod{ + pod := &v1.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "simple-mount-pod", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "simple-mount-container", Image: framework.GetPauseImageNameForHostArch(), - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "simply-mounted-volume", MountPath: "/opt/", @@ -51,11 +51,11 @@ var _ = framework.KubeDescribe("SimpleMount", func() { }, }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: "simply-mounted-volume", - VolumeSource: api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{ + VolumeSource: v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{ Medium: "Memory", }, }, diff --git a/test/e2e_node/summary_test.go b/test/e2e_node/summary_test.go index 6bde0894ce8..446ab09ad0b 100644 --- a/test/e2e_node/summary_test.go +++ b/test/e2e_node/summary_test.go @@ -20,9 +20,9 @@ import ( "fmt" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" "k8s.io/kubernetes/test/e2e/framework" @@ -211,39 +211,39 @@ var _ = framework.KubeDescribe("Summary API", func() { }) func createSummaryTestPods(f *framework.Framework, names ...string) { - pods := make([]*api.Pod, 0, len(names)) + pods := make([]*v1.Pod, 0, len(names)) for _, name := range names { - pods = append(pods, &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pods = append(pods, &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - Containers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyAlways, + Containers: []v1.Container{ { Name: "busybox-container", Image: "gcr.io/google_containers/busybox:1.24", Command: []string{"sh", "-c", "ping -c 1 google.com; while true; do echo 'hello world' >> /test-empty-dir-mnt/file ; sleep 1; done"}, - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ + Resources: v1.ResourceRequirements{ + Limits: v1.ResourceList{ // Must set memory limit to get MemoryStats.AvailableBytes - api.ResourceMemory: resource.MustParse("10M"), + v1.ResourceMemory: resource.MustParse("10M"), }, }, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ {MountPath: "/test-empty-dir-mnt", Name: "test-empty-dir"}, }, }, }, - SecurityContext: &api.PodSecurityContext{ - SELinuxOptions: &api.SELinuxOptions{ + SecurityContext: &v1.PodSecurityContext{ + SELinuxOptions: &v1.SELinuxOptions{ Level: "s0", }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ // TODO(#28393): Test secret volumes // TODO(#28394): Test hostpath volumes - {Name: "test-empty-dir", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, + {Name: "test-empty-dir", VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}}, }, }, }) diff --git a/test/e2e_node/util.go b/test/e2e_node/util.go index c6b7ef802a7..e7c144be391 100644 --- a/test/e2e_node/util.go +++ b/test/e2e_node/util.go @@ -30,6 +30,7 @@ import ( "k8s.io/kubernetes/pkg/api" k8serr "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/componentconfig" v1alpha1 "k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1" "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" @@ -84,7 +85,7 @@ func getCurrentKubeletConfig() (*componentconfig.KubeletConfiguration, error) { } // Queries the API server for a Kubelet configuration for the node described by framework.TestContext.NodeName -func getCurrentKubeletConfigMap(f *framework.Framework) (*api.ConfigMap, error) { +func getCurrentKubeletConfigMap(f *framework.Framework) (*v1.ConfigMap, error) { return f.ClientSet.Core().ConfigMaps("kube-system").Get(fmt.Sprintf("kubelet-%s", framework.TestContext.NodeName)) } @@ -195,15 +196,15 @@ func decodeConfigz(resp *http.Response) (*componentconfig.KubeletConfiguration, } // Constructs a Kubelet ConfigMap targeting the current node running the node e2e tests -func makeKubeletConfigMap(nodeName string, kubeCfg *componentconfig.KubeletConfiguration) *api.ConfigMap { +func makeKubeletConfigMap(nodeName string, kubeCfg *componentconfig.KubeletConfiguration) *v1.ConfigMap { kubeCfgExt := v1alpha1.KubeletConfiguration{} api.Scheme.Convert(kubeCfg, &kubeCfgExt, nil) bytes, err := json.Marshal(kubeCfgExt) framework.ExpectNoError(err) - cmap := &api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ + cmap := &v1.ConfigMap{ + ObjectMeta: v1.ObjectMeta{ Name: fmt.Sprintf("kubelet-%s", nodeName), }, Data: map[string]string{ @@ -214,7 +215,7 @@ func makeKubeletConfigMap(nodeName string, kubeCfg *componentconfig.KubeletConfi } // Uses KubeletConfiguration to create a `kubelet-` ConfigMap in the "kube-system" namespace. -func createConfigMap(f *framework.Framework, kubeCfg *componentconfig.KubeletConfiguration) (*api.ConfigMap, error) { +func createConfigMap(f *framework.Framework, kubeCfg *componentconfig.KubeletConfiguration) (*v1.ConfigMap, error) { cmap := makeKubeletConfigMap(framework.TestContext.NodeName, kubeCfg) cmap, err := f.ClientSet.Core().ConfigMaps("kube-system").Create(cmap) if err != nil { @@ -224,7 +225,7 @@ func createConfigMap(f *framework.Framework, kubeCfg *componentconfig.KubeletCon } // Similar to createConfigMap, except this updates an existing ConfigMap. -func updateConfigMap(f *framework.Framework, kubeCfg *componentconfig.KubeletConfiguration) (*api.ConfigMap, error) { +func updateConfigMap(f *framework.Framework, kubeCfg *componentconfig.KubeletConfiguration) (*v1.ConfigMap, error) { cmap := makeKubeletConfigMap(framework.TestContext.NodeName, kubeCfg) cmap, err := f.ClientSet.Core().ConfigMaps("kube-system").Update(cmap) if err != nil { diff --git a/test/e2e_node/volume_manager_test.go b/test/e2e_node/volume_manager_test.go index 8e41a9230d0..a3ba69d2757 100644 --- a/test/e2e_node/volume_manager_test.go +++ b/test/e2e_node/volume_manager_test.go @@ -19,7 +19,7 @@ package e2e_node import ( "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/util/uuid" "k8s.io/kubernetes/test/e2e/framework" @@ -35,24 +35,24 @@ var _ = framework.KubeDescribe("Kubelet Volume Manager", func() { Context("On terminatation of pod with memory backed volume", func() { It("should remove the volume from the node", func() { var ( - memoryBackedPod *api.Pod + memoryBackedPod *v1.Pod volumeName string ) By("Creating a pod with a memory backed volume that exits success without restart", func() { volumeName = "memory-volume" - memoryBackedPod = f.PodClient().Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + memoryBackedPod = f.PodClient().Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod" + string(uuid.NewUUID()), Namespace: f.Namespace.Name, }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Image: "gcr.io/google_containers/busybox:1.24", Name: "container" + string(uuid.NewUUID()), Command: []string{"sh", "-c", "echo"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: volumeName, MountPath: "/tmp", @@ -60,11 +60,11 @@ var _ = framework.KubeDescribe("Kubelet Volume Manager", func() { }, }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: volumeName, - VolumeSource: api.VolumeSource{ - EmptyDir: &api.EmptyDirVolumeSource{Medium: api.StorageMediumMemory}, + VolumeSource: v1.VolumeSource{ + EmptyDir: &v1.EmptyDirVolumeSource{Medium: v1.StorageMediumMemory}, }, }, }, @@ -79,19 +79,19 @@ var _ = framework.KubeDescribe("Kubelet Volume Manager", func() { for i := 0; i < 10; i++ { // need to create a new verification pod on each pass since updates //to the HostPath volume aren't propogated to the pod - pod := f.PodClient().Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := f.PodClient().Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "pod" + string(uuid.NewUUID()), Namespace: f.Namespace.Name, }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - Containers: []api.Container{ + Spec: v1.PodSpec{ + RestartPolicy: v1.RestartPolicyNever, + Containers: []v1.Container{ { Image: "gcr.io/google_containers/busybox:1.24", Name: "container" + string(uuid.NewUUID()), Command: []string{"sh", "-c", "if [ -d " + volumePath + " ]; then exit 1; fi;"}, - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "kubelet-pods", MountPath: "/tmp", @@ -99,13 +99,13 @@ var _ = framework.KubeDescribe("Kubelet Volume Manager", func() { }, }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: "kubelet-pods", - VolumeSource: api.VolumeSource{ + VolumeSource: v1.VolumeSource{ // TODO: remove hardcoded kubelet volume directory path // framework.TestContext.KubeVolumeDir is currently not populated for node e2e - HostPath: &api.HostPathVolumeSource{Path: "/var/lib/kubelet/pods"}, + HostPath: &v1.HostPathVolumeSource{Path: "/var/lib/kubelet/pods"}, }, }, }, @@ -113,7 +113,7 @@ var _ = framework.KubeDescribe("Kubelet Volume Manager", func() { }) err = framework.WaitForPodSuccessInNamespace(f.ClientSet, pod.Name, f.Namespace.Name) gp := int64(1) - f.PodClient().Delete(pod.Name, &api.DeleteOptions{GracePeriodSeconds: &gp}) + f.PodClient().Delete(pod.Name, &v1.DeleteOptions{GracePeriodSeconds: &gp}) if err == nil { break } diff --git a/test/integration/BUILD b/test/integration/BUILD index cbc6a40ac40..ca363df3909 100644 --- a/test/integration/BUILD +++ b/test/integration/BUILD @@ -19,7 +19,7 @@ go_library( tags = ["automanaged"], deps = [ "//pkg/api/errors:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/util/wait:go_default_library", "//test/integration/framework:go_default_library", diff --git a/test/integration/client/client_test.go b/test/integration/client/client_test.go index b5513e409a6..87d56a77aa4 100644 --- a/test/integration/client/client_test.go +++ b/test/integration/client/client_test.go @@ -32,7 +32,7 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" @@ -47,7 +47,7 @@ func TestClient(t *testing.T) { _, s := framework.RunAMaster(nil) defer s.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) ns := framework.CreateTestingNamespace("client", s, t) defer framework.DeleteTestingNamespace(ns, s, t) @@ -60,7 +60,7 @@ func TestClient(t *testing.T) { t.Errorf("expected %#v, got %#v", e, a) } - pods, err := client.Core().Pods(ns.Name).List(api.ListOptions{}) + pods, err := client.Core().Pods(ns.Name).List(v1.ListOptions{}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -69,13 +69,13 @@ func TestClient(t *testing.T) { } // get a validation error - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "test", Namespace: ns.Name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "test", }, @@ -99,7 +99,7 @@ func TestClient(t *testing.T) { } // pod is shown, but not scheduled - pods, err = client.Core().Pods(ns.Name).List(api.ListOptions{}) + pods, err = client.Core().Pods(ns.Name).List(v1.ListOptions{}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -119,35 +119,35 @@ func TestAtomicPut(t *testing.T) { _, s := framework.RunAMaster(nil) defer s.Close() - c := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) ns := framework.CreateTestingNamespace("atomic-put", s, t) defer framework.DeleteTestingNamespace(ns, s, t) - rcBody := api.ReplicationController{ + rcBody := v1.ReplicationController{ TypeMeta: unversioned.TypeMeta{ APIVersion: c.Core().RESTClient().APIVersion().String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "atomicrc", Namespace: ns.Name, Labels: map[string]string{ "name": "atomicrc", }, }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, + Spec: v1.ReplicationControllerSpec{ + Replicas: func(i int32) *int32 { return &i }(0), Selector: map[string]string{ "foo": "bar", }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{ "foo": "bar", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Name: "name", Image: "image"}, }, }, @@ -211,24 +211,24 @@ func TestPatch(t *testing.T) { _, s := framework.RunAMaster(nil) defer s.Close() - c := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) ns := framework.CreateTestingNamespace("patch", s, t) defer framework.DeleteTestingNamespace(ns, s, t) name := "patchpod" resource := "pods" - podBody := api.Pod{ + podBody := v1.Pod{ TypeMeta: unversioned.TypeMeta{ APIVersion: c.Core().RESTClient().APIVersion().String(), }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: name, Namespace: ns.Name, Labels: map[string]string{}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Name: "name", Image: "image"}, }, }, @@ -320,20 +320,20 @@ func TestPatchWithCreateOnUpdate(t *testing.T) { _, s := framework.RunAMaster(nil) defer s.Close() - c := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) ns := framework.CreateTestingNamespace("patch-with-create", s, t) defer framework.DeleteTestingNamespace(ns, s, t) - endpointTemplate := &api.Endpoints{ - ObjectMeta: api.ObjectMeta{ + endpointTemplate := &v1.Endpoints{ + ObjectMeta: v1.ObjectMeta{ Name: "patchendpoint", Namespace: ns.Name, }, - Subsets: []api.EndpointSubset{ + Subsets: []v1.EndpointSubset{ { - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 80, Protocol: api.ProtocolTCP}}, + Addresses: []v1.EndpointAddress{{IP: "1.2.3.4"}}, + Ports: []v1.EndpointPort{{Port: 80, Protocol: v1.ProtocolTCP}}, }, }, } @@ -431,7 +431,7 @@ func TestAPIVersions(t *testing.T) { _, s := framework.RunAMaster(nil) defer s.Close() - c := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) clientVersion := c.Core().RESTClient().APIVersion().String() g, err := c.Discovery().ServerGroups() @@ -456,16 +456,16 @@ func TestSingleWatch(t *testing.T) { ns := framework.CreateTestingNamespace("single-watch", s, t) defer framework.DeleteTestingNamespace(ns, s, t) - client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) - mkEvent := func(i int) *api.Event { + mkEvent := func(i int) *v1.Event { name := fmt.Sprintf("event-%v", i) - return &api.Event{ - ObjectMeta: api.ObjectMeta{ + return &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Namespace: ns.Name, Name: name, }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Namespace: ns.Name, Name: name, }, @@ -517,7 +517,7 @@ func TestSingleWatch(t *testing.T) { t.Errorf("Wanted %v, got %v", e, a) } switch o := got.Object.(type) { - case *api.Event: + case *v1.Event: if e, a := "event-9", o.Name; e != a { t.Errorf("Wanted %v, got %v", e, a) } @@ -541,16 +541,16 @@ func TestMultiWatch(t *testing.T) { ns := framework.CreateTestingNamespace("multi-watch", s, t) defer framework.DeleteTestingNamespace(ns, s, t) - client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) - dummyEvent := func(i int) *api.Event { + dummyEvent := func(i int) *v1.Event { name := fmt.Sprintf("unrelated-%v", i) - return &api.Event{ - ObjectMeta: api.ObjectMeta{ + return &v1.Event{ + ObjectMeta: v1.ObjectMeta{ Name: fmt.Sprintf("%v.%x", name, time.Now().UnixNano()), Namespace: ns.Name, }, - InvolvedObject: api.ObjectReference{ + InvolvedObject: v1.ObjectReference{ Name: name, Namespace: ns.Name, }, @@ -570,13 +570,13 @@ func TestMultiWatch(t *testing.T) { for i := 0; i < watcherCount; i++ { watchesStarted.Add(1) name := fmt.Sprintf("multi-watch-%v", i) - got, err := client.Core().Pods(ns.Name).Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + got, err := client.Core().Pods(ns.Name).Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, Labels: labels.Set{"watchlabel": name}, }, - Spec: api.PodSpec{ - Containers: []api.Container{{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ Name: "pause", Image: e2e.GetPauseImageName(client), }}, @@ -587,8 +587,8 @@ func TestMultiWatch(t *testing.T) { t.Fatalf("Couldn't make %v: %v", name, err) } go func(name, rv string) { - options := api.ListOptions{ - LabelSelector: labels.Set{"watchlabel": name}.AsSelector(), + options := v1.ListOptions{ + LabelSelector: labels.Set{"watchlabel": name}.AsSelector().String(), ResourceVersion: rv, } w, err := client.Core().Pods(ns.Name).Watch(options) @@ -677,12 +677,12 @@ func TestMultiWatch(t *testing.T) { return } name := fmt.Sprintf("unrelated-%v", i) - _, err := client.Core().Pods(ns.Name).Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + _, err := client.Core().Pods(ns.Name).Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: name, }, - Spec: api.PodSpec{ - Containers: []api.Container{{ + Spec: v1.PodSpec{ + Containers: []v1.Container{{ Name: "nothing", Image: e2e.GetPauseImageName(client), }}, @@ -741,16 +741,16 @@ func TestMultiWatch(t *testing.T) { } func runSelfLinkTestOnNamespace(t *testing.T, c clientset.Interface, namespace string) { - podBody := api.Pod{ - ObjectMeta: api.ObjectMeta{ + podBody := v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "selflinktest", Namespace: namespace, Labels: map[string]string{ "name": "selflinktest", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ {Name: "name", Image: "image"}, }, }, @@ -763,7 +763,7 @@ func runSelfLinkTestOnNamespace(t *testing.T, c clientset.Interface, namespace s t.Errorf("Failed listing pod with supplied self link '%v': %v", pod.SelfLink, err) } - podList, err := c.Core().Pods(namespace).List(api.ListOptions{}) + podList, err := c.Core().Pods(namespace).List(v1.ListOptions{}) if err != nil { t.Errorf("Failed listing pods: %v", err) } @@ -797,7 +797,7 @@ func TestSelfLinkOnNamespace(t *testing.T) { ns := framework.CreateTestingNamespace("selflink", s, t) defer framework.DeleteTestingNamespace(ns, s, t) - c := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + c := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) runSelfLinkTestOnNamespace(t, c, ns.Name) } diff --git a/test/integration/client/dynamic_client_test.go b/test/integration/client/dynamic_client_test.go index 122ec19a477..5d0a22f9fb2 100644 --- a/test/integration/client/dynamic_client_test.go +++ b/test/integration/client/dynamic_client_test.go @@ -22,12 +22,11 @@ import ( "reflect" "testing" - "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/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/typed/dynamic" "k8s.io/kubernetes/pkg/runtime" @@ -41,7 +40,7 @@ func TestDynamicClient(t *testing.T) { ns := framework.CreateTestingNamespace("dynamic-client", s, t) defer framework.DeleteTestingNamespace(ns, s, t) - gv := ®istered.GroupOrDie(api.GroupName).GroupVersion + gv := ®istered.GroupOrDie(v1.GroupName).GroupVersion config := &restclient.Config{ Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: gv}, @@ -73,12 +72,12 @@ func TestDynamicClient(t *testing.T) { } // Create a Pod with the normal client - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "test", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "test", Image: "test-image", @@ -108,7 +107,7 @@ func TestDynamicClient(t *testing.T) { got, err := unstructuredToPod(unstructuredList.Items[0]) if err != nil { - t.Fatalf("unexpected error converting Unstructured to api.Pod: %v", err) + t.Fatalf("unexpected error converting Unstructured to v1.Pod: %v", err) } if !reflect.DeepEqual(actual, got) { @@ -123,7 +122,7 @@ func TestDynamicClient(t *testing.T) { got, err = unstructuredToPod(unstruct) if err != nil { - t.Fatalf("unexpected error converting Unstructured to api.Pod: %v", err) + t.Fatalf("unexpected error converting Unstructured to v1.Pod: %v", err) } if !reflect.DeepEqual(actual, got) { @@ -136,7 +135,7 @@ func TestDynamicClient(t *testing.T) { t.Fatalf("unexpected error when deleting pod: %v", err) } - list, err := client.Core().Pods(ns.Name).List(api.ListOptions{}) + list, err := client.Core().Pods(ns.Name).List(v1.ListOptions{}) if err != nil { t.Fatalf("unexpected error when listing pods: %v", err) } @@ -146,12 +145,14 @@ func TestDynamicClient(t *testing.T) { } } -func unstructuredToPod(obj *runtime.Unstructured) (*api.Pod, error) { +func unstructuredToPod(obj *runtime.Unstructured) (*v1.Pod, error) { json, err := runtime.Encode(runtime.UnstructuredJSONScheme, obj) if err != nil { return nil, err } - pod := new(api.Pod) + pod := new(v1.Pod) err = runtime.DecodeInto(testapi.Default.Codec(), json, pod) + pod.Kind = "" + pod.APIVersion = "" return pod, err } diff --git a/test/integration/configmap/configmap_test.go b/test/integration/configmap/configmap_test.go index 468eee8f490..e795c130cb9 100644 --- a/test/integration/configmap/configmap_test.go +++ b/test/integration/configmap/configmap_test.go @@ -23,9 +23,9 @@ package configmap import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/test/integration" "k8s.io/kubernetes/test/integration/framework" @@ -36,7 +36,7 @@ func TestConfigMap(t *testing.T) { _, s := framework.RunAMaster(nil) defer s.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) ns := framework.CreateTestingNamespace("config-map", s, t) defer framework.DeleteTestingNamespace(ns, s, t) @@ -44,9 +44,9 @@ func TestConfigMap(t *testing.T) { DoTestConfigMap(t, client, ns) } -func DoTestConfigMap(t *testing.T, client clientset.Interface, ns *api.Namespace) { - cfg := api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ +func DoTestConfigMap(t *testing.T, client clientset.Interface, ns *v1.Namespace) { + cfg := v1.ConfigMap{ + ObjectMeta: v1.ObjectMeta{ Name: "configmap", Namespace: ns.Name, }, @@ -62,22 +62,22 @@ func DoTestConfigMap(t *testing.T, client clientset.Interface, ns *api.Namespace } defer deleteConfigMapOrErrorf(t, client, cfg.Namespace, cfg.Name) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "XXX", Namespace: ns.Name, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "fake-name", Image: "fakeimage", - Env: []api.EnvVar{ + Env: []v1.EnvVar{ { Name: "CONFIG_DATA_1", - ValueFrom: &api.EnvVarSource{ - ConfigMapKeyRef: &api.ConfigMapKeySelector{ - LocalObjectReference: api.LocalObjectReference{ + ValueFrom: &v1.EnvVarSource{ + ConfigMapKeyRef: &v1.ConfigMapKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ Name: "configmap", }, Key: "data-1", @@ -86,9 +86,9 @@ func DoTestConfigMap(t *testing.T, client clientset.Interface, ns *api.Namespace }, { Name: "CONFIG_DATA_2", - ValueFrom: &api.EnvVarSource{ - ConfigMapKeyRef: &api.ConfigMapKeySelector{ - LocalObjectReference: api.LocalObjectReference{ + ValueFrom: &v1.EnvVarSource{ + ConfigMapKeyRef: &v1.ConfigMapKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ Name: "configmap", }, Key: "data-2", @@ -96,9 +96,9 @@ func DoTestConfigMap(t *testing.T, client clientset.Interface, ns *api.Namespace }, }, { Name: "CONFIG_DATA_3", - ValueFrom: &api.EnvVarSource{ - ConfigMapKeyRef: &api.ConfigMapKeySelector{ - LocalObjectReference: api.LocalObjectReference{ + ValueFrom: &v1.EnvVarSource{ + ConfigMapKeyRef: &v1.ConfigMapKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ Name: "configmap", }, Key: "data-3", diff --git a/test/integration/framework/BUILD b/test/integration/framework/BUILD index 085cdbf746d..5c5e4ed2074 100644 --- a/test/integration/framework/BUILD +++ b/test/integration/framework/BUILD @@ -26,20 +26,21 @@ go_library( "//pkg/api/unversioned:go_default_library", "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/apis/apps:go_default_library", - "//pkg/apis/autoscaling:go_default_library", + "//pkg/apis/apps/v1beta1:go_default_library", + "//pkg/apis/autoscaling/v1:go_default_library", "//pkg/apis/batch:go_default_library", - "//pkg/apis/certificates:go_default_library", - "//pkg/apis/extensions:go_default_library", - "//pkg/apis/policy:go_default_library", - "//pkg/apis/rbac:go_default_library", - "//pkg/apis/storage:go_default_library", + "//pkg/apis/certificates/v1alpha1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", + "//pkg/apis/policy/v1alpha1:go_default_library", + "//pkg/apis/rbac/v1alpha1:go_default_library", + "//pkg/apis/storage/v1beta1:go_default_library", "//pkg/apiserver/authenticator:go_default_library", "//pkg/auth/authenticator:go_default_library", "//pkg/auth/authorizer:go_default_library", "//pkg/auth/authorizer/union:go_default_library", "//pkg/auth/user:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/restclient:go_default_library", diff --git a/test/integration/framework/master_utils.go b/test/integration/framework/master_utils.go index ad1f6e3fc8d..8a77a27706c 100644 --- a/test/integration/framework/master_utils.go +++ b/test/integration/framework/master_utils.go @@ -32,20 +32,21 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/apps" - "k8s.io/kubernetes/pkg/apis/autoscaling" + apps "k8s.io/kubernetes/pkg/apis/apps/v1beta1" + autoscaling "k8s.io/kubernetes/pkg/apis/autoscaling/v1" "k8s.io/kubernetes/pkg/apis/batch" - "k8s.io/kubernetes/pkg/apis/certificates" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/apis/policy" - "k8s.io/kubernetes/pkg/apis/rbac" - "k8s.io/kubernetes/pkg/apis/storage" + certificates "k8s.io/kubernetes/pkg/apis/certificates/v1alpha1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + policy "k8s.io/kubernetes/pkg/apis/policy/v1alpha1" + rbac "k8s.io/kubernetes/pkg/apis/rbac/v1alpha1" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" "k8s.io/kubernetes/pkg/apiserver/authenticator" authauthenticator "k8s.io/kubernetes/pkg/auth/authenticator" authauthorizer "k8s.io/kubernetes/pkg/auth/authorizer" authorizerunion "k8s.io/kubernetes/pkg/auth/authorizer/union" "k8s.io/kubernetes/pkg/auth/user" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" coreclient "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/restclient" @@ -116,7 +117,7 @@ func NewMasterComponents(c *Config) *MasterComponents { // TODO: Allow callers to pipe through a different master url and create a client/start components using it. glog.Infof("Master %+v", s.URL) // TODO: caesarxuchao: remove this client when the refactoring of client libraray is done. - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}, QPS: c.QPS, Burst: c.Burst}) + clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}, QPS: c.QPS, Burst: c.Burst}) rcStopCh := make(chan struct{}) controllerManager := replicationcontroller.NewReplicationManagerFromClient(clientset, controller.NoResyncPeriodFunc, c.Burst, 4096) @@ -265,7 +266,7 @@ func startMasterOrDie(masterConfig *master.Config, incomingServer *httptest.Serv if masterConfig.EnableCoreControllers { // TODO Once /healthz is updated for posthooks, we'll wait for good health coreClient := coreclient.NewForConfigOrDie(&cfg) - svcWatch, err := coreClient.Services(api.NamespaceDefault).Watch(v1.ListOptions{}) + svcWatch, err := coreClient.Services(v1.NamespaceDefault).Watch(v1.ListOptions{}) if err != nil { glog.Fatal(err) } @@ -309,7 +310,7 @@ func NewMasterConfig() *master.Config { storageFactory := genericapiserver.NewDefaultStorageFactory(config, runtime.ContentTypeJSON, ns, genericapiserver.NewDefaultResourceEncodingConfig(), master.DefaultAPIResourceConfigSource()) storageFactory.SetSerializer( - unversioned.GroupResource{Group: api.GroupName, Resource: genericapiserver.AllResources}, + unversioned.GroupResource{Group: v1.GroupName, Resource: genericapiserver.AllResources}, "", ns) storageFactory.SetSerializer( @@ -389,29 +390,29 @@ func (m *MasterComponents) Stop(apiServer, rcManager bool) { } } -func CreateTestingNamespace(baseName string, apiserver *httptest.Server, t *testing.T) *api.Namespace { +func CreateTestingNamespace(baseName string, apiserver *httptest.Server, t *testing.T) *v1.Namespace { // TODO: Create a namespace with a given basename. // Currently we neither create the namespace nor delete all its contents at the end. // But as long as tests are not using the same namespaces, this should work fine. - return &api.Namespace{ - ObjectMeta: api.ObjectMeta{ + return &v1.Namespace{ + ObjectMeta: v1.ObjectMeta{ // TODO: Once we start creating namespaces, switch to GenerateName. Name: baseName, }, } } -func DeleteTestingNamespace(ns *api.Namespace, apiserver *httptest.Server, t *testing.T) { +func DeleteTestingNamespace(ns *v1.Namespace, apiserver *httptest.Server, t *testing.T) { // TODO: Remove all resources from a given namespace once we implement CreateTestingNamespace. } // RCFromManifest reads a .json file and returns the rc in it. -func RCFromManifest(fileName string) *api.ReplicationController { +func RCFromManifest(fileName string) *v1.ReplicationController { data, err := ioutil.ReadFile(fileName) if err != nil { glog.Fatalf("Unexpected error reading rc manifest %v", err) } - var controller api.ReplicationController + var controller v1.ReplicationController if err := runtime.DecodeInto(testapi.Default.Codec(), data, &controller); err != nil { glog.Fatalf("Unexpected error reading rc manifest %v", err) } @@ -419,7 +420,7 @@ func RCFromManifest(fileName string) *api.ReplicationController { } // StopRC stops the rc via kubectl's stop library -func StopRC(rc *api.ReplicationController, clientset clientset.Interface) error { +func StopRC(rc *v1.ReplicationController, clientset internalclientset.Interface) error { reaper, err := kubectl.ReaperFor(api.Kind("ReplicationController"), clientset) if err != nil || reaper == nil { return err @@ -432,7 +433,7 @@ func StopRC(rc *api.ReplicationController, clientset clientset.Interface) error } // ScaleRC scales the given rc to the given replicas. -func ScaleRC(name, ns string, replicas int32, clientset clientset.Interface) (*api.ReplicationController, error) { +func ScaleRC(name, ns string, replicas int32, clientset internalclientset.Interface) (*api.ReplicationController, error) { scaler, err := kubectl.ScalerFor(api.Kind("ReplicationController"), clientset) if err != nil { return nil, err diff --git a/test/integration/framework/perf_utils.go b/test/integration/framework/perf_utils.go index e633c212ccb..574b9722b0a 100644 --- a/test/integration/framework/perf_utils.go +++ b/test/integration/framework/perf_utils.go @@ -17,9 +17,9 @@ limitations under the License. package framework import ( - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" e2eframework "k8s.io/kubernetes/test/e2e/framework" testutils "k8s.io/kubernetes/test/utils" @@ -51,23 +51,23 @@ func (p *IntegrationTestNodePreparer) PrepareNodes() error { } glog.Infof("Making %d nodes", numNodes) - baseNode := &api.Node{ - ObjectMeta: api.ObjectMeta{ + baseNode := &v1.Node{ + ObjectMeta: v1.ObjectMeta{ GenerateName: p.nodeNamePrefix, }, - Spec: api.NodeSpec{ + Spec: v1.NodeSpec{ // TODO: investigate why this is needed. ExternalID: "foo", }, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), - api.ResourceCPU: resource.MustParse("4"), - api.ResourceMemory: resource.MustParse("32Gi"), + Status: v1.NodeStatus{ + Capacity: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), + v1.ResourceCPU: resource.MustParse("4"), + v1.ResourceMemory: resource.MustParse("32Gi"), }, - Phase: api.NodeRunning, - Conditions: []api.NodeCondition{ - {Type: api.NodeReady, Status: api.ConditionTrue}, + Phase: v1.NodeRunning, + Conditions: []v1.NodeCondition{ + {Type: v1.NodeReady, Status: v1.ConditionTrue}, }, }, } @@ -95,7 +95,7 @@ func (p *IntegrationTestNodePreparer) PrepareNodes() error { func (p *IntegrationTestNodePreparer) CleanupNodes() error { nodes := e2eframework.GetReadySchedulableNodesOrDie(p.client) for i := range nodes.Items { - if err := p.client.Core().Nodes().Delete(nodes.Items[i].Name, &api.DeleteOptions{}); err != nil { + if err := p.client.Core().Nodes().Delete(nodes.Items[i].Name, &v1.DeleteOptions{}); err != nil { glog.Errorf("Error while deleting Node: %v", err) } } diff --git a/test/integration/metrics/metrics_test.go b/test/integration/metrics/metrics_test.go index eac3a2f5545..0a87bb6ce3d 100644 --- a/test/integration/metrics/metrics_test.go +++ b/test/integration/metrics/metrics_test.go @@ -25,9 +25,9 @@ import ( "net/http/httptest" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/test/integration/framework" @@ -108,8 +108,8 @@ func TestApiserverMetrics(t *testing.T) { // Make a request to the apiserver to ensure there's at least one data point // for the metrics we're expecting -- otherwise, they won't be exported. - client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) - if _, err := client.Core().Pods(api.NamespaceDefault).List(api.ListOptions{}); err != nil { + client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) + if _, err := client.Core().Pods(v1.NamespaceDefault).List(v1.ListOptions{}); err != nil { t.Fatalf("unexpected error getting pods: %v", err) } diff --git a/test/integration/objectmeta/objectmeta_test.go b/test/integration/objectmeta/objectmeta_test.go index 54bc0c4e9b0..06a47411ea4 100644 --- a/test/integration/objectmeta/objectmeta_test.go +++ b/test/integration/objectmeta/objectmeta_test.go @@ -21,10 +21,10 @@ import ( "github.com/stretchr/testify/assert" "golang.org/x/net/context" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/testapi" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/genericapiserver" etcdstorage "k8s.io/kubernetes/pkg/storage/etcd" @@ -38,14 +38,14 @@ func TestIgnoreClusterName(t *testing.T) { _, s := framework.RunAMaster(config) defer s.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) etcdClient := framework.NewEtcdClient() etcdStorage := etcdstorage.NewEtcdStorage(etcdClient, testapi.Default.Codec(), prefix+"/namespaces/", false, etcdtest.DeserializationCacheSize) ctx := context.TODO() - ns := api.Namespace{ - ObjectMeta: api.ObjectMeta{ + ns := v1.Namespace{ + ObjectMeta: v1.ObjectMeta{ Name: "test-namespace", ClusterName: "cluster-name-to-ignore", }, @@ -55,7 +55,7 @@ func TestIgnoreClusterName(t *testing.T) { assert.Equal(t, ns.Name, nsNew.Name) assert.Empty(t, nsNew.ClusterName) - nsEtcd := api.Namespace{} + nsEtcd := v1.Namespace{} err = etcdStorage.Get(ctx, ns.Name, &nsEtcd, false) assert.Nil(t, err) assert.Equal(t, ns.Name, nsEtcd.Name) @@ -66,7 +66,7 @@ func TestIgnoreClusterName(t *testing.T) { assert.Equal(t, ns.Name, nsNew.Name) assert.Empty(t, nsNew.ClusterName) - nsEtcd = api.Namespace{} + nsEtcd = v1.Namespace{} err = etcdStorage.Get(ctx, ns.Name, &nsEtcd, false) assert.Nil(t, err) assert.Equal(t, ns.Name, nsEtcd.Name) diff --git a/test/integration/persistentvolumes/persistent_volumes_test.go b/test/integration/persistentvolumes/persistent_volumes_test.go index e29993c6bdd..cb23803df00 100644 --- a/test/integration/persistentvolumes/persistent_volumes_test.go +++ b/test/integration/persistentvolumes/persistent_volumes_test.go @@ -27,13 +27,13 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/storage" - storageutil "k8s.io/kubernetes/pkg/apis/storage/util" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" + storageutil "k8s.io/kubernetes/pkg/apis/storage/v1beta1/util" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" fake_cloud "k8s.io/kubernetes/pkg/cloudprovider/providers/fake" persistentvolumecontroller "k8s.io/kubernetes/pkg/controller/volume/persistentvolume" @@ -122,15 +122,15 @@ func TestPersistentVolumeRecycler(t *testing.T) { // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (PersistenceVolumes). - defer testClient.Core().PersistentVolumes().DeleteCollection(nil, api.ListOptions{}) + defer testClient.Core().PersistentVolumes().DeleteCollection(nil, v1.ListOptions{}) stopCh := make(chan struct{}) ctrl.Run(stopCh) defer close(stopCh) // This PV will be claimed, released, and recycled. - pv := createPV("fake-pv-recycler", "/tmp/foo", "10G", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, api.PersistentVolumeReclaimRecycle) - pvc := createPVC("fake-pvc-recycler", ns.Name, "5G", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}) + pv := createPV("fake-pv-recycler", "/tmp/foo", "10G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRecycle) + pvc := createPVC("fake-pvc-recycler", ns.Name, "5G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}) _, err := testClient.PersistentVolumes().Create(pv) if err != nil { @@ -145,9 +145,9 @@ func TestPersistentVolumeRecycler(t *testing.T) { glog.V(2).Infof("TestPersistentVolumeRecycler pvc created") // wait until the controller pairs the volume and claim - waitForPersistentVolumePhase(testClient, pv.Name, watchPV, api.VolumeBound) + waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeBound) glog.V(2).Infof("TestPersistentVolumeRecycler pv bound") - waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, api.ClaimBound) + waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound) glog.V(2).Infof("TestPersistentVolumeRecycler pvc bound") // deleting a claim releases the volume, after which it can be recycled @@ -156,9 +156,9 @@ func TestPersistentVolumeRecycler(t *testing.T) { } glog.V(2).Infof("TestPersistentVolumeRecycler pvc deleted") - waitForPersistentVolumePhase(testClient, pv.Name, watchPV, api.VolumeReleased) + waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeReleased) glog.V(2).Infof("TestPersistentVolumeRecycler pv released") - waitForPersistentVolumePhase(testClient, pv.Name, watchPV, api.VolumeAvailable) + waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeAvailable) glog.V(2).Infof("TestPersistentVolumeRecycler pv available") } @@ -176,15 +176,15 @@ func TestPersistentVolumeDeleter(t *testing.T) { // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (PersistenceVolumes). - defer testClient.Core().PersistentVolumes().DeleteCollection(nil, api.ListOptions{}) + defer testClient.Core().PersistentVolumes().DeleteCollection(nil, v1.ListOptions{}) stopCh := make(chan struct{}) ctrl.Run(stopCh) defer close(stopCh) // This PV will be claimed, released, and deleted. - pv := createPV("fake-pv-deleter", "/tmp/foo", "10G", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, api.PersistentVolumeReclaimDelete) - pvc := createPVC("fake-pvc-deleter", ns.Name, "5G", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}) + pv := createPV("fake-pv-deleter", "/tmp/foo", "10G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimDelete) + pvc := createPVC("fake-pvc-deleter", ns.Name, "5G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}) _, err := testClient.PersistentVolumes().Create(pv) if err != nil { @@ -196,9 +196,9 @@ func TestPersistentVolumeDeleter(t *testing.T) { t.Errorf("Failed to create PersistentVolumeClaim: %v", err) } glog.V(2).Infof("TestPersistentVolumeDeleter pvc created") - waitForPersistentVolumePhase(testClient, pv.Name, watchPV, api.VolumeBound) + waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeBound) glog.V(2).Infof("TestPersistentVolumeDeleter pv bound") - waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, api.ClaimBound) + waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound) glog.V(2).Infof("TestPersistentVolumeDeleter pvc bound") // deleting a claim releases the volume, after which it can be recycled @@ -207,7 +207,7 @@ func TestPersistentVolumeDeleter(t *testing.T) { } glog.V(2).Infof("TestPersistentVolumeDeleter pvc deleted") - waitForPersistentVolumePhase(testClient, pv.Name, watchPV, api.VolumeReleased) + waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeReleased) glog.V(2).Infof("TestPersistentVolumeDeleter pv released") for { @@ -235,22 +235,22 @@ func TestPersistentVolumeBindRace(t *testing.T) { // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (PersistenceVolumes). - defer testClient.Core().PersistentVolumes().DeleteCollection(nil, api.ListOptions{}) + defer testClient.Core().PersistentVolumes().DeleteCollection(nil, v1.ListOptions{}) stopCh := make(chan struct{}) ctrl.Run(stopCh) defer close(stopCh) - pv := createPV("fake-pv-race", "/tmp/foo", "10G", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, api.PersistentVolumeReclaimRetain) - pvc := createPVC("fake-pvc-race", ns.Name, "5G", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}) + pv := createPV("fake-pv-race", "/tmp/foo", "10G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRetain) + pvc := createPVC("fake-pvc-race", ns.Name, "5G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}) counter := 0 maxClaims := 100 - claims := []*api.PersistentVolumeClaim{} + claims := []*v1.PersistentVolumeClaim{} for counter <= maxClaims { counter += 1 clone, _ := conversion.NewCloner().DeepCopy(pvc) - newPvc, _ := clone.(*api.PersistentVolumeClaim) - newPvc.ObjectMeta = api.ObjectMeta{Name: fmt.Sprintf("fake-pvc-race-%d", counter)} + newPvc, _ := clone.(*v1.PersistentVolumeClaim) + newPvc.ObjectMeta = v1.ObjectMeta{Name: fmt.Sprintf("fake-pvc-race-%d", counter)} claim, err := testClient.PersistentVolumeClaims(ns.Name).Create(newPvc) if err != nil { t.Fatalf("Error creating newPvc: %v", err) @@ -262,7 +262,7 @@ func TestPersistentVolumeBindRace(t *testing.T) { // putting a bind manually on a pv should only match the claim it is bound to rand.Seed(time.Now().Unix()) claim := claims[rand.Intn(maxClaims-1)] - claimRef, err := api.GetReference(claim) + claimRef, err := v1.GetReference(claim) if err != nil { t.Fatalf("Unexpected error getting claimRef: %v", err) } @@ -275,9 +275,9 @@ func TestPersistentVolumeBindRace(t *testing.T) { } glog.V(2).Infof("TestPersistentVolumeBindRace pv created, pre-bound to %s", claim.Name) - waitForPersistentVolumePhase(testClient, pv.Name, watchPV, api.VolumeBound) + waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeBound) glog.V(2).Infof("TestPersistentVolumeBindRace pv bound") - waitForAnyPersistentVolumeClaimPhase(watchPVC, api.ClaimBound) + waitForAnyPersistentVolumeClaimPhase(watchPVC, v1.ClaimBound) glog.V(2).Infof("TestPersistentVolumeBindRace pvc bound") pv, err = testClient.PersistentVolumes().Get(pv.Name) @@ -306,7 +306,7 @@ func TestPersistentVolumeClaimLabelSelector(t *testing.T) { // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (PersistenceVolumes). - defer testClient.Core().PersistentVolumes().DeleteCollection(nil, api.ListOptions{}) + defer testClient.Core().PersistentVolumes().DeleteCollection(nil, v1.ListOptions{}) stopCh := make(chan struct{}) controller.Run(stopCh) @@ -314,8 +314,8 @@ func TestPersistentVolumeClaimLabelSelector(t *testing.T) { var ( err error - modes = []api.PersistentVolumeAccessMode{api.ReadWriteOnce} - reclaim = api.PersistentVolumeReclaimRetain + modes = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce} + reclaim = v1.PersistentVolumeReclaimRetain pv_true = createPV("pv-true", "/tmp/foo-label", "1G", modes, reclaim) pv_false = createPV("pv-false", "/tmp/foo-label", "1G", modes, reclaim) @@ -347,9 +347,9 @@ func TestPersistentVolumeClaimLabelSelector(t *testing.T) { } t.Log("claim created") - waitForAnyPersistentVolumePhase(watchPV, api.VolumeBound) + waitForAnyPersistentVolumePhase(watchPV, v1.VolumeBound) t.Log("volume bound") - waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, api.ClaimBound) + waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound) t.Log("claim bound") pv, err := testClient.PersistentVolumes().Get("pv-false") @@ -386,7 +386,7 @@ func TestPersistentVolumeClaimLabelSelectorMatchExpressions(t *testing.T) { // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (PersistenceVolumes). - defer testClient.Core().PersistentVolumes().DeleteCollection(nil, api.ListOptions{}) + defer testClient.Core().PersistentVolumes().DeleteCollection(nil, v1.ListOptions{}) stopCh := make(chan struct{}) controller.Run(stopCh) @@ -394,8 +394,8 @@ func TestPersistentVolumeClaimLabelSelectorMatchExpressions(t *testing.T) { var ( err error - modes = []api.PersistentVolumeAccessMode{api.ReadWriteOnce} - reclaim = api.PersistentVolumeReclaimRetain + modes = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce} + reclaim = v1.PersistentVolumeReclaimRetain pv_true = createPV("pv-true", "/tmp/foo-label", "1G", modes, reclaim) pv_false = createPV("pv-false", "/tmp/foo-label", "1G", modes, reclaim) @@ -446,9 +446,9 @@ func TestPersistentVolumeClaimLabelSelectorMatchExpressions(t *testing.T) { } t.Log("claim created") - waitForAnyPersistentVolumePhase(watchPV, api.VolumeBound) + waitForAnyPersistentVolumePhase(watchPV, v1.VolumeBound) t.Log("volume bound") - waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, api.ClaimBound) + waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound) t.Log("claim bound") pv, err := testClient.PersistentVolumes().Get("pv-false") @@ -485,28 +485,28 @@ func TestPersistentVolumeMultiPVs(t *testing.T) { // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (PersistenceVolumes). - defer testClient.Core().PersistentVolumes().DeleteCollection(nil, api.ListOptions{}) + defer testClient.Core().PersistentVolumes().DeleteCollection(nil, v1.ListOptions{}) stopCh := make(chan struct{}) controller.Run(stopCh) defer close(stopCh) maxPVs := getObjectCount() - pvs := make([]*api.PersistentVolume, maxPVs) + pvs := make([]*v1.PersistentVolume, maxPVs) for i := 0; i < maxPVs; i++ { // This PV will be claimed, released, and deleted pvs[i] = createPV("pv-"+strconv.Itoa(i), "/tmp/foo"+strconv.Itoa(i), strconv.Itoa(i)+"G", - []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, api.PersistentVolumeReclaimRetain) + []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRetain) } - pvc := createPVC("pvc-2", ns.Name, strconv.Itoa(maxPVs/2)+"G", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}) + pvc := createPVC("pvc-2", ns.Name, strconv.Itoa(maxPVs/2)+"G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}) for i := 0; i < maxPVs; i++ { _, err := testClient.PersistentVolumes().Create(pvs[i]) if err != nil { t.Errorf("Failed to create PersistentVolume %d: %v", i, err) } - waitForPersistentVolumePhase(testClient, pvs[i].Name, watchPV, api.VolumeAvailable) + waitForPersistentVolumePhase(testClient, pvs[i].Name, watchPV, v1.VolumeAvailable) } t.Log("volumes created") @@ -517,9 +517,9 @@ func TestPersistentVolumeMultiPVs(t *testing.T) { t.Log("claim created") // wait until the binder pairs the claim with a volume - waitForAnyPersistentVolumePhase(watchPV, api.VolumeBound) + waitForAnyPersistentVolumePhase(watchPV, v1.VolumeBound) t.Log("volume bound") - waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, api.ClaimBound) + waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound) t.Log("claim bound") // only one PV is bound @@ -533,14 +533,14 @@ func TestPersistentVolumeMultiPVs(t *testing.T) { continue } // found a bounded PV - p := pv.Spec.Capacity[api.ResourceStorage] + p := pv.Spec.Capacity[v1.ResourceStorage] pvCap := p.Value() expectedCap := resource.MustParse(strconv.Itoa(maxPVs/2) + "G") expectedCapVal := expectedCap.Value() if pv.Spec.ClaimRef.Name != pvc.Name || pvCap != expectedCapVal { t.Fatalf("Bind mismatch! Expected %s capacity %d but got %s capacity %d", pvc.Name, expectedCapVal, pv.Spec.ClaimRef.Name, pvCap) } - t.Logf("claim bounded to %s capacity %v", pv.Name, pv.Spec.Capacity[api.ResourceStorage]) + t.Logf("claim bounded to %s capacity %v", pv.Name, pv.Spec.Capacity[v1.ResourceStorage]) bound += 1 } t.Log("volumes checked") @@ -555,7 +555,7 @@ func TestPersistentVolumeMultiPVs(t *testing.T) { } t.Log("claim deleted") - waitForAnyPersistentVolumePhase(watchPV, api.VolumeReleased) + waitForAnyPersistentVolumePhase(watchPV, v1.VolumeReleased) t.Log("volumes released") } @@ -574,20 +574,20 @@ func TestPersistentVolumeMultiPVsPVCs(t *testing.T) { // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (PersistenceVolumes). - defer testClient.Core().PersistentVolumes().DeleteCollection(nil, api.ListOptions{}) + defer testClient.Core().PersistentVolumes().DeleteCollection(nil, v1.ListOptions{}) controllerStopCh := make(chan struct{}) binder.Run(controllerStopCh) defer close(controllerStopCh) objCount := getObjectCount() - pvs := make([]*api.PersistentVolume, objCount) - pvcs := make([]*api.PersistentVolumeClaim, objCount) + pvs := make([]*v1.PersistentVolume, objCount) + pvcs := make([]*v1.PersistentVolumeClaim, objCount) for i := 0; i < objCount; i++ { // This PV will be claimed, released, and deleted pvs[i] = createPV("pv-"+strconv.Itoa(i), "/tmp/foo"+strconv.Itoa(i), "1G", - []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, api.PersistentVolumeReclaimRetain) - pvcs[i] = createPVC("pvc-"+strconv.Itoa(i), ns.Name, "1G", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}) + []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRetain) + pvcs[i] = createPVC("pvc-"+strconv.Itoa(i), ns.Name, "1G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}) } // Create PVs first @@ -603,7 +603,7 @@ func TestPersistentVolumeMultiPVsPVCs(t *testing.T) { }() // Wait for them to get Available for i := 0; i < objCount; i++ { - waitForAnyPersistentVolumePhase(watchPV, api.VolumeAvailable) + waitForAnyPersistentVolumePhase(watchPV, v1.VolumeAvailable) glog.V(1).Infof("%d volumes available", i+1) } glog.V(2).Infof("TestPersistentVolumeMultiPVsPVCs: volumes are Available") @@ -643,7 +643,7 @@ func TestPersistentVolumeMultiPVsPVCs(t *testing.T) { // Modify PVC i := rand.Intn(objCount) name := "pvc-" + strconv.Itoa(i) - pvc, err := testClient.PersistentVolumeClaims(api.NamespaceDefault).Get(name) + pvc, err := testClient.PersistentVolumeClaims(v1.NamespaceDefault).Get(name) if err != nil { // Silently ignore error, the PVC may have be already // deleted or not exists yet. @@ -655,7 +655,7 @@ func TestPersistentVolumeMultiPVsPVCs(t *testing.T) { } else { pvc.Annotations["TestAnnotation"] = fmt.Sprint(rand.Int()) } - _, err = testClient.PersistentVolumeClaims(api.NamespaceDefault).Update(pvc) + _, err = testClient.PersistentVolumeClaims(v1.NamespaceDefault).Update(pvc) if err != nil { // Silently ignore error, the PVC may have been updated by // the controller. @@ -684,12 +684,12 @@ func TestPersistentVolumeMultiPVsPVCs(t *testing.T) { // wait until the binder pairs all claims for i := 0; i < objCount; i++ { - waitForAnyPersistentVolumeClaimPhase(watchPVC, api.ClaimBound) + waitForAnyPersistentVolumeClaimPhase(watchPVC, v1.ClaimBound) glog.V(1).Infof("%d claims bound", i+1) } // wait until the binder pairs all volumes for i := 0; i < objCount; i++ { - waitForPersistentVolumePhase(testClient, pvs[i].Name, watchPV, api.VolumeBound) + waitForPersistentVolumePhase(testClient, pvs[i].Name, watchPV, v1.VolumeBound) glog.V(1).Infof("%d claims bound", i+1) } @@ -738,13 +738,13 @@ func TestPersistentVolumeControllerStartup(t *testing.T) { defer watchPVC.Stop() // Create *bound* volumes and PVCs - pvs := make([]*api.PersistentVolume, objCount) - pvcs := make([]*api.PersistentVolumeClaim, objCount) + pvs := make([]*v1.PersistentVolume, objCount) + pvcs := make([]*v1.PersistentVolumeClaim, objCount) for i := 0; i < objCount; i++ { pvName := "pv-startup-" + strconv.Itoa(i) pvcName := "pvc-startup-" + strconv.Itoa(i) - pvc := createPVC(pvcName, ns.Name, "1G", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}) + pvc := createPVC(pvcName, ns.Name, "1G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}) pvc.Annotations = map[string]string{"annBindCompleted": ""} pvc.Spec.VolumeName = pvName newPVC, err := testClient.PersistentVolumeClaims(ns.Name).Create(pvc) @@ -752,7 +752,7 @@ func TestPersistentVolumeControllerStartup(t *testing.T) { t.Fatalf("Cannot create claim %q: %v", pvc.Name, err) } // Save Bound status as a separate transaction - newPVC.Status.Phase = api.ClaimBound + newPVC.Status.Phase = v1.ClaimBound newPVC, err = testClient.PersistentVolumeClaims(ns.Name).UpdateStatus(newPVC) if err != nil { t.Fatalf("Cannot update claim status %q: %v", pvc.Name, err) @@ -761,11 +761,11 @@ func TestPersistentVolumeControllerStartup(t *testing.T) { // Drain watchPVC with all events generated by the PVC until it's bound // We don't want to catch "PVC craated with Status.Phase == Pending" // later in this test. - waitForAnyPersistentVolumeClaimPhase(watchPVC, api.ClaimBound) + waitForAnyPersistentVolumeClaimPhase(watchPVC, v1.ClaimBound) pv := createPV(pvName, "/tmp/foo"+strconv.Itoa(i), "1G", - []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, api.PersistentVolumeReclaimRetain) - claimRef, err := api.GetReference(newPVC) + []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRetain) + claimRef, err := v1.GetReference(newPVC) if err != nil { glog.V(3).Infof("unexpected error getting claim reference: %v", err) return @@ -776,7 +776,7 @@ func TestPersistentVolumeControllerStartup(t *testing.T) { t.Fatalf("Cannot create volume %q: %v", pv.Name, err) } // Save Bound status as a separate transaction - newPV.Status.Phase = api.VolumeBound + newPV.Status.Phase = v1.VolumeBound newPV, err = testClient.PersistentVolumes().UpdateStatus(newPV) if err != nil { t.Fatalf("Cannot update volume status %q: %v", pv.Name, err) @@ -785,7 +785,7 @@ func TestPersistentVolumeControllerStartup(t *testing.T) { // Drain watchPV with all events generated by the PV until it's bound // We don't want to catch "PV craated with Status.Phase == Pending" // later in this test. - waitForAnyPersistentVolumePhase(watchPV, api.VolumeBound) + waitForAnyPersistentVolumePhase(watchPV, v1.VolumeBound) } // Start the controller when all PVs and PVCs are already saved in etcd @@ -801,20 +801,20 @@ func TestPersistentVolumeControllerStartup(t *testing.T) { for !finished { select { case volumeEvent := <-watchPV.ResultChan(): - volume, ok := volumeEvent.Object.(*api.PersistentVolume) + volume, ok := volumeEvent.Object.(*v1.PersistentVolume) if !ok { continue } - if volume.Status.Phase != api.VolumeBound { + if volume.Status.Phase != v1.VolumeBound { t.Errorf("volume %s unexpectedly changed state to %s", volume.Name, volume.Status.Phase) } case claimEvent := <-watchPVC.ResultChan(): - claim, ok := claimEvent.Object.(*api.PersistentVolumeClaim) + claim, ok := claimEvent.Object.(*v1.PersistentVolumeClaim) if !ok { continue } - if claim.Status.Phase != api.ClaimBound { + if claim.Status.Phase != v1.ClaimBound { t.Errorf("claim %s unexpectedly changed state to %s", claim.Name, claim.Status.Phase) } @@ -862,14 +862,14 @@ func TestPersistentVolumeProvisionMultiPVCs(t *testing.T) { // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (PersistenceVolumes and StorageClasses). - defer testClient.Core().PersistentVolumes().DeleteCollection(nil, api.ListOptions{}) - defer testClient.Storage().StorageClasses().DeleteCollection(nil, api.ListOptions{}) + defer testClient.Core().PersistentVolumes().DeleteCollection(nil, v1.ListOptions{}) + defer testClient.Storage().StorageClasses().DeleteCollection(nil, v1.ListOptions{}) storageClass := storage.StorageClass{ TypeMeta: unversioned.TypeMeta{ Kind: "StorageClass", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "gold", }, Provisioner: provisionerPluginName, @@ -881,9 +881,9 @@ func TestPersistentVolumeProvisionMultiPVCs(t *testing.T) { defer close(stopCh) objCount := getObjectCount() - pvcs := make([]*api.PersistentVolumeClaim, objCount) + pvcs := make([]*v1.PersistentVolumeClaim, objCount) for i := 0; i < objCount; i++ { - pvc := createPVC("pvc-provision-"+strconv.Itoa(i), ns.Name, "1G", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}) + pvc := createPVC("pvc-provision-"+strconv.Itoa(i), ns.Name, "1G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}) pvc.Annotations = map[string]string{ storageutil.StorageClassAnnotation: "gold", } @@ -901,13 +901,13 @@ func TestPersistentVolumeProvisionMultiPVCs(t *testing.T) { // Wait until the controller provisions and binds all of them for i := 0; i < objCount; i++ { - waitForAnyPersistentVolumeClaimPhase(watchPVC, api.ClaimBound) + waitForAnyPersistentVolumeClaimPhase(watchPVC, v1.ClaimBound) glog.V(1).Infof("%d claims bound", i+1) } glog.V(2).Infof("TestPersistentVolumeProvisionMultiPVCs: claims are bound") // check that we have enough bound PVs - pvList, err := testClient.PersistentVolumes().List(api.ListOptions{}) + pvList, err := testClient.PersistentVolumes().List(v1.ListOptions{}) if err != nil { t.Fatalf("Failed to list volumes: %s", err) } @@ -916,7 +916,7 @@ func TestPersistentVolumeProvisionMultiPVCs(t *testing.T) { } for i := 0; i < objCount; i++ { pv := &pvList.Items[i] - if pv.Status.Phase != api.VolumeBound { + if pv.Status.Phase != v1.VolumeBound { t.Fatalf("Expected volume %s to be bound, is %s instead", pv.Name, pv.Status.Phase) } glog.V(2).Infof("PV %q is bound to PVC %q", pv.Name, pv.Spec.ClaimRef.Name) @@ -930,7 +930,7 @@ func TestPersistentVolumeProvisionMultiPVCs(t *testing.T) { // Wait for the PVs to get deleted by listing remaining volumes // (delete events were unreliable) for { - volumes, err := testClient.PersistentVolumes().List(api.ListOptions{}) + volumes, err := testClient.PersistentVolumes().List(v1.ListOptions{}) if err != nil { t.Fatalf("Failed to list volumes: %v", err) } @@ -959,7 +959,7 @@ func TestPersistentVolumeMultiPVsDiffAccessModes(t *testing.T) { // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (PersistenceVolumes). - defer testClient.Core().PersistentVolumes().DeleteCollection(nil, api.ListOptions{}) + defer testClient.Core().PersistentVolumes().DeleteCollection(nil, v1.ListOptions{}) stopCh := make(chan struct{}) controller.Run(stopCh) @@ -967,11 +967,11 @@ func TestPersistentVolumeMultiPVsDiffAccessModes(t *testing.T) { // This PV will be claimed, released, and deleted pv_rwo := createPV("pv-rwo", "/tmp/foo", "10G", - []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, api.PersistentVolumeReclaimRetain) + []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRetain) pv_rwm := createPV("pv-rwm", "/tmp/bar", "10G", - []api.PersistentVolumeAccessMode{api.ReadWriteMany}, api.PersistentVolumeReclaimRetain) + []v1.PersistentVolumeAccessMode{v1.ReadWriteMany}, v1.PersistentVolumeReclaimRetain) - pvc := createPVC("pvc-rwm", ns.Name, "5G", []api.PersistentVolumeAccessMode{api.ReadWriteMany}) + pvc := createPVC("pvc-rwm", ns.Name, "5G", []v1.PersistentVolumeAccessMode{v1.ReadWriteMany}) _, err := testClient.PersistentVolumes().Create(pv_rwm) if err != nil { @@ -990,9 +990,9 @@ func TestPersistentVolumeMultiPVsDiffAccessModes(t *testing.T) { t.Log("claim created") // wait until the controller pairs the volume and claim - waitForAnyPersistentVolumePhase(watchPV, api.VolumeBound) + waitForAnyPersistentVolumePhase(watchPV, v1.VolumeBound) t.Log("volume bound") - waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, api.ClaimBound) + waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound) t.Log("claim bound") // only RWM PV is bound @@ -1020,11 +1020,11 @@ func TestPersistentVolumeMultiPVsDiffAccessModes(t *testing.T) { } t.Log("claim deleted") - waitForAnyPersistentVolumePhase(watchPV, api.VolumeReleased) + waitForAnyPersistentVolumePhase(watchPV, v1.VolumeReleased) t.Log("volume released") } -func waitForPersistentVolumePhase(client *clientset.Clientset, pvName string, w watch.Interface, phase api.PersistentVolumePhase) { +func waitForPersistentVolumePhase(client *clientset.Clientset, pvName string, w watch.Interface, phase v1.PersistentVolumePhase) { // Check if the volume is already in requested phase volume, err := client.Core().PersistentVolumes().Get(pvName) if err == nil && volume.Status.Phase == phase { @@ -1034,7 +1034,7 @@ func waitForPersistentVolumePhase(client *clientset.Clientset, pvName string, w // Wait for the phase for { event := <-w.ResultChan() - volume, ok := event.Object.(*api.PersistentVolume) + volume, ok := event.Object.(*v1.PersistentVolume) if !ok { continue } @@ -1045,7 +1045,7 @@ func waitForPersistentVolumePhase(client *clientset.Clientset, pvName string, w } } -func waitForPersistentVolumeClaimPhase(client *clientset.Clientset, claimName, namespace string, w watch.Interface, phase api.PersistentVolumeClaimPhase) { +func waitForPersistentVolumeClaimPhase(client *clientset.Clientset, claimName, namespace string, w watch.Interface, phase v1.PersistentVolumeClaimPhase) { // Check if the claim is already in requested phase claim, err := client.Core().PersistentVolumeClaims(namespace).Get(claimName) if err == nil && claim.Status.Phase == phase { @@ -1055,7 +1055,7 @@ func waitForPersistentVolumeClaimPhase(client *clientset.Clientset, claimName, n // Wait for the phase for { event := <-w.ResultChan() - claim, ok := event.Object.(*api.PersistentVolumeClaim) + claim, ok := event.Object.(*v1.PersistentVolumeClaim) if !ok { continue } @@ -1066,10 +1066,10 @@ func waitForPersistentVolumeClaimPhase(client *clientset.Clientset, claimName, n } } -func waitForAnyPersistentVolumePhase(w watch.Interface, phase api.PersistentVolumePhase) { +func waitForAnyPersistentVolumePhase(w watch.Interface, phase v1.PersistentVolumePhase) { for { event := <-w.ResultChan() - volume, ok := event.Object.(*api.PersistentVolume) + volume, ok := event.Object.(*v1.PersistentVolume) if !ok { continue } @@ -1080,10 +1080,10 @@ func waitForAnyPersistentVolumePhase(w watch.Interface, phase api.PersistentVolu } } -func waitForAnyPersistentVolumeClaimPhase(w watch.Interface, phase api.PersistentVolumeClaimPhase) { +func waitForAnyPersistentVolumeClaimPhase(w watch.Interface, phase v1.PersistentVolumeClaimPhase) { for { event := <-w.ResultChan() - claim, ok := event.Object.(*api.PersistentVolumeClaim) + claim, ok := event.Object.(*v1.PersistentVolumeClaim) if !ok { continue } @@ -1094,18 +1094,18 @@ func waitForAnyPersistentVolumeClaimPhase(w watch.Interface, phase api.Persisten } } -func createClients(ns *api.Namespace, t *testing.T, s *httptest.Server, syncPeriod time.Duration) (*clientset.Clientset, *persistentvolumecontroller.PersistentVolumeController, watch.Interface, watch.Interface) { +func createClients(ns *v1.Namespace, t *testing.T, s *httptest.Server, syncPeriod time.Duration) (*clientset.Clientset, *persistentvolumecontroller.PersistentVolumeController, watch.Interface, watch.Interface) { // Use higher QPS and Burst, there is a test for race conditions which // creates many objects and default values were too low. binderClient := clientset.NewForConfigOrDie(&restclient.Config{ Host: s.URL, - ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}, + ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}, QPS: 1000000, Burst: 1000000, }) testClient := clientset.NewForConfigOrDie(&restclient.Config{ Host: s.URL, - ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}, + ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}, QPS: 1000000, Burst: 1000000, }) @@ -1134,11 +1134,11 @@ func createClients(ns *api.Namespace, t *testing.T, s *httptest.Server, syncPeri EnableDynamicProvisioning: true, }) - watchPV, err := testClient.PersistentVolumes().Watch(api.ListOptions{}) + watchPV, err := testClient.PersistentVolumes().Watch(v1.ListOptions{}) if err != nil { t.Fatalf("Failed to watch PersistentVolumes: %v", err) } - watchPVC, err := testClient.PersistentVolumeClaims(ns.Name).Watch(api.ListOptions{}) + watchPVC, err := testClient.PersistentVolumeClaims(ns.Name).Watch(v1.ListOptions{}) if err != nil { t.Fatalf("Failed to watch PersistentVolumeClaimss: %v", err) } @@ -1146,26 +1146,26 @@ func createClients(ns *api.Namespace, t *testing.T, s *httptest.Server, syncPeri return testClient, ctrl, watchPV, watchPVC } -func createPV(name, path, cap string, mode []api.PersistentVolumeAccessMode, reclaim api.PersistentVolumeReclaimPolicy) *api.PersistentVolume { - return &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{Name: name}, - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{HostPath: &api.HostPathVolumeSource{Path: path}}, - Capacity: api.ResourceList{api.ResourceName(api.ResourceStorage): resource.MustParse(cap)}, +func createPV(name, path, cap string, mode []v1.PersistentVolumeAccessMode, reclaim v1.PersistentVolumeReclaimPolicy) *v1.PersistentVolume { + return &v1.PersistentVolume{ + ObjectMeta: v1.ObjectMeta{Name: name}, + Spec: v1.PersistentVolumeSpec{ + PersistentVolumeSource: v1.PersistentVolumeSource{HostPath: &v1.HostPathVolumeSource{Path: path}}, + Capacity: v1.ResourceList{v1.ResourceName(v1.ResourceStorage): resource.MustParse(cap)}, AccessModes: mode, PersistentVolumeReclaimPolicy: reclaim, }, } } -func createPVC(name, namespace, cap string, mode []api.PersistentVolumeAccessMode) *api.PersistentVolumeClaim { - return &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ +func createPVC(name, namespace, cap string, mode []v1.PersistentVolumeAccessMode) *v1.PersistentVolumeClaim { + return &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: name, Namespace: namespace, }, - Spec: api.PersistentVolumeClaimSpec{ - Resources: api.ResourceRequirements{Requests: api.ResourceList{api.ResourceName(api.ResourceStorage): resource.MustParse(cap)}}, + Spec: v1.PersistentVolumeClaimSpec{ + Resources: v1.ResourceRequirements{Requests: v1.ResourceList{v1.ResourceName(v1.ResourceStorage): resource.MustParse(cap)}}, AccessModes: mode, }, } diff --git a/test/integration/pods/pods_test.go b/test/integration/pods/pods_test.go index 5d92bf21aae..bd75065f463 100644 --- a/test/integration/pods/pods_test.go +++ b/test/integration/pods/pods_test.go @@ -22,9 +22,9 @@ import ( "fmt" "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/test/integration" "k8s.io/kubernetes/test/integration/framework" @@ -37,7 +37,7 @@ func TestPodUpdateActiveDeadlineSeconds(t *testing.T) { ns := framework.CreateTestingNamespace("pod-activedeadline-update", s, t) defer framework.DeleteTestingNamespace(ns, s, t) - client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) var ( iZero = int64(0) @@ -46,13 +46,13 @@ func TestPodUpdateActiveDeadlineSeconds(t *testing.T) { iNeg = int64(-1) ) - prototypePod := func() *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ + prototypePod := func() *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "xxx", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "fake-name", Image: "fakeimage", @@ -155,18 +155,18 @@ func TestPodReadOnlyFilesystem(t *testing.T) { ns := framework.CreateTestingNamespace("pod-readonly-root", s, t) defer framework.DeleteTestingNamespace(ns, s, t) - client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "xxx", }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "fake-name", Image: "fakeimage", - SecurityContext: &api.SecurityContext{ + SecurityContext: &v1.SecurityContext{ ReadOnlyRootFilesystem: &isReadOnly, }, }, diff --git a/test/integration/quota/quota_test.go b/test/integration/quota/quota_test.go index 0811c6fe8ab..aaa6ed39ed2 100644 --- a/test/integration/quota/quota_test.go +++ b/test/integration/quota/quota_test.go @@ -28,8 +28,10 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/controller" replicationcontroller "k8s.io/kubernetes/pkg/controller/replication" @@ -63,8 +65,9 @@ func TestQuota(t *testing.T) { defer s.Close() admissionCh := make(chan struct{}) - clientset := clientset.NewForConfigOrDie(&restclient.Config{QPS: -1, Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) - admission, err := resourcequota.NewResourceQuota(clientset, quotainstall.NewRegistry(clientset, nil), 5, admissionCh) + clientset := clientset.NewForConfigOrDie(&restclient.Config{QPS: -1, Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) + internalClientset := internalclientset.NewForConfigOrDie(&restclient.Config{QPS: -1, Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) + admission, err := resourcequota.NewResourceQuota(internalClientset, quotainstall.NewRegistry(nil, nil), 5, admissionCh) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -104,14 +107,14 @@ func TestQuota(t *testing.T) { endTime := time.Now() t.Logf("Took %v to scale up without quota", endTime.Sub(startTime)) - quota := &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ + quota := &v1.ResourceQuota{ + ObjectMeta: v1.ObjectMeta{ Name: "quota", Namespace: ns.Name, }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourcePods: resource.MustParse("1000"), + Spec: v1.ResourceQuotaSpec{ + Hard: v1.ResourceList{ + v1.ResourcePods: resource.MustParse("1000"), }, }, } @@ -123,8 +126,8 @@ func TestQuota(t *testing.T) { t.Logf("Took %v to scale up with quota", endTime.Sub(startTime)) } -func waitForQuota(t *testing.T, quota *api.ResourceQuota, clientset *clientset.Clientset) { - w, err := clientset.Core().ResourceQuotas(quota.Namespace).Watch(api.SingleObject(api.ObjectMeta{Name: quota.Name})) +func waitForQuota(t *testing.T, quota *v1.ResourceQuota, clientset *clientset.Clientset) { + w, err := clientset.Core().ResourceQuotas(quota.Namespace).Watch(v1.SingleObject(v1.ObjectMeta{Name: quota.Name})) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -141,7 +144,7 @@ func waitForQuota(t *testing.T, quota *api.ResourceQuota, clientset *clientset.C } switch cast := event.Object.(type) { - case *api.ResourceQuota: + case *v1.ResourceQuota: if len(cast.Status.Hard) > 0 { return true, nil } @@ -155,23 +158,23 @@ func waitForQuota(t *testing.T, quota *api.ResourceQuota, clientset *clientset.C } func scale(t *testing.T, namespace string, clientset *clientset.Clientset) { - target := 100 - rc := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ + target := int32(100) + rc := &v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{ Name: "foo", Namespace: namespace, }, - Spec: api.ReplicationControllerSpec{ - Replicas: int32(target), + Spec: v1.ReplicationControllerSpec{ + Replicas: &target, Selector: map[string]string{"foo": "bar"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{ "foo": "bar", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "container", Image: "busybox", @@ -182,7 +185,7 @@ func scale(t *testing.T, namespace string, clientset *clientset.Clientset) { }, } - w, err := clientset.Core().ReplicationControllers(namespace).Watch(api.SingleObject(api.ObjectMeta{Name: rc.Name})) + w, err := clientset.Core().ReplicationControllers(namespace).Watch(v1.SingleObject(v1.ObjectMeta{Name: rc.Name})) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -199,9 +202,9 @@ func scale(t *testing.T, namespace string, clientset *clientset.Clientset) { } switch cast := event.Object.(type) { - case *api.ReplicationController: + case *v1.ReplicationController: fmt.Printf("Found %v of %v replicas\n", int(cast.Status.Replicas), target) - if int(cast.Status.Replicas) == target { + if cast.Status.Replicas == target { return true, nil } } @@ -209,7 +212,7 @@ func scale(t *testing.T, namespace string, clientset *clientset.Clientset) { return false, nil }) if err != nil { - pods, _ := clientset.Core().Pods(namespace).List(api.ListOptions{LabelSelector: labels.Everything(), FieldSelector: fields.Everything()}) + pods, _ := clientset.Core().Pods(namespace).List(v1.ListOptions{LabelSelector: labels.Everything().String(), FieldSelector: fields.Everything().String()}) t.Fatalf("unexpected error: %v, ended with %v pods", err, len(pods.Items)) } } diff --git a/test/integration/replicaset/replicaset_test.go b/test/integration/replicaset/replicaset_test.go index d0636ff232f..0cdbd351a0b 100644 --- a/test/integration/replicaset/replicaset_test.go +++ b/test/integration/replicaset/replicaset_test.go @@ -30,7 +30,6 @@ import ( "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/cache" - internalclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/controller/informers" @@ -137,12 +136,12 @@ func rmSetup(t *testing.T, enableGarbageCollector bool) (*httptest.Server, *repl t.Fatalf("Error in create clientset: %v", err) } resyncPeriod := 12 * time.Hour - informers := informers.NewSharedInformerFactory(internalclientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "rs-informers")), resyncPeriod) + informers := informers.NewSharedInformerFactory(clientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "rs-informers")), nil, resyncPeriod) rm := replicaset.NewReplicaSetController( informers.ReplicaSets(), informers.Pods(), - internalclientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "replicaset-controller")), + clientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "replicaset-controller")), replicaset.BurstReplicas, 4096, enableGarbageCollector, diff --git a/test/integration/replicationcontroller/replicationcontroller_test.go b/test/integration/replicationcontroller/replicationcontroller_test.go index 0d725ae87c6..d746e6bb5f9 100644 --- a/test/integration/replicationcontroller/replicationcontroller_test.go +++ b/test/integration/replicationcontroller/replicationcontroller_test.go @@ -29,7 +29,6 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - internalclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/controller/informers" @@ -137,10 +136,10 @@ func rmSetup(t *testing.T, enableGarbageCollector bool) (*httptest.Server, *repl resyncPeriodFunc := func() time.Duration { return resyncPeriod } - podInformer := informers.NewPodInformer(internalclientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "pod-informer")), resyncPeriod) + podInformer := informers.NewPodInformer(clientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "pod-informer")), resyncPeriod) rm := replication.NewReplicationManager( podInformer, - internalclientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "replication-controller")), + clientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "replication-controller")), resyncPeriodFunc, replication.BurstReplicas, 4096, diff --git a/test/integration/scheduler/extender_test.go b/test/integration/scheduler/extender_test.go index bc2b81f0fba..b916b8a1c32 100644 --- a/test/integration/scheduler/extender_test.go +++ b/test/integration/scheduler/extender_test.go @@ -29,12 +29,12 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/util/wait" @@ -51,8 +51,8 @@ const ( prioritize = "prioritize" ) -type fitPredicate func(pod *api.Pod, node *api.Node) (bool, error) -type priorityFunc func(pod *api.Pod, nodes *api.NodeList) (*schedulerapi.HostPriorityList, error) +type fitPredicate func(pod *v1.Pod, node *v1.Node) (bool, error) +type priorityFunc func(pod *v1.Pod, nodes *v1.NodeList) (*schedulerapi.HostPriorityList, error) type priorityConfig struct { function priorityFunc @@ -104,15 +104,15 @@ func (e *Extender) serveHTTP(t *testing.T, w http.ResponseWriter, req *http.Requ } } -func (e *Extender) Filter(pod *api.Pod, nodes *api.NodeList) (*api.NodeList, schedulerapi.FailedNodesMap, error) { - filtered := []api.Node{} +func (e *Extender) Filter(pod *v1.Pod, nodes *v1.NodeList) (*v1.NodeList, schedulerapi.FailedNodesMap, error) { + filtered := []v1.Node{} failedNodesMap := schedulerapi.FailedNodesMap{} for _, node := range nodes.Items { fits := true for _, predicate := range e.predicates { fit, err := predicate(pod, &node) if err != nil { - return &api.NodeList{}, schedulerapi.FailedNodesMap{}, err + return &v1.NodeList{}, schedulerapi.FailedNodesMap{}, err } if !fit { fits = false @@ -125,10 +125,10 @@ func (e *Extender) Filter(pod *api.Pod, nodes *api.NodeList) (*api.NodeList, sch failedNodesMap[node.Name] = fmt.Sprintf("extender failed: %s", e.name) } } - return &api.NodeList{Items: filtered}, failedNodesMap, nil + return &v1.NodeList{Items: filtered}, failedNodesMap, nil } -func (e *Extender) Prioritize(pod *api.Pod, nodes *api.NodeList) (*schedulerapi.HostPriorityList, error) { +func (e *Extender) Prioritize(pod *v1.Pod, nodes *v1.NodeList) (*schedulerapi.HostPriorityList, error) { result := schedulerapi.HostPriorityList{} combinedScores := map[string]int{} for _, prioritizer := range e.prioritizers { @@ -151,21 +151,21 @@ func (e *Extender) Prioritize(pod *api.Pod, nodes *api.NodeList) (*schedulerapi. return &result, nil } -func machine_1_2_3_Predicate(pod *api.Pod, node *api.Node) (bool, error) { +func machine_1_2_3_Predicate(pod *v1.Pod, node *v1.Node) (bool, error) { if node.Name == "machine1" || node.Name == "machine2" || node.Name == "machine3" { return true, nil } return false, nil } -func machine_2_3_5_Predicate(pod *api.Pod, node *api.Node) (bool, error) { +func machine_2_3_5_Predicate(pod *v1.Pod, node *v1.Node) (bool, error) { if node.Name == "machine2" || node.Name == "machine3" || node.Name == "machine5" { return true, nil } return false, nil } -func machine_2_Prioritizer(pod *api.Pod, nodes *api.NodeList) (*schedulerapi.HostPriorityList, error) { +func machine_2_Prioritizer(pod *v1.Pod, nodes *v1.NodeList) (*schedulerapi.HostPriorityList, error) { result := schedulerapi.HostPriorityList{} for _, node := range nodes.Items { score := 1 @@ -177,7 +177,7 @@ func machine_2_Prioritizer(pod *api.Pod, nodes *api.NodeList) (*schedulerapi.Hos return &result, nil } -func machine_3_Prioritizer(pod *api.Pod, nodes *api.NodeList) (*schedulerapi.HostPriorityList, error) { +func machine_3_Prioritizer(pod *v1.Pod, nodes *v1.NodeList) (*schedulerapi.HostPriorityList, error) { result := schedulerapi.HostPriorityList{} for _, node := range nodes.Items { score := 1 @@ -196,7 +196,7 @@ func TestSchedulerExtender(t *testing.T) { ns := framework.CreateTestingNamespace("scheduler-extender", s, t) defer framework.DeleteTestingNamespace(ns, s, t) - clientSet := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientSet := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) extender1 := &Extender{ name: "extender1", @@ -236,16 +236,16 @@ func TestSchedulerExtender(t *testing.T) { }, }, } - policy.APIVersion = registered.GroupOrDie(api.GroupName).GroupVersion.String() + policy.APIVersion = registered.GroupOrDie(v1.GroupName).GroupVersion.String() - schedulerConfigFactory := factory.NewConfigFactory(clientSet, api.DefaultSchedulerName, api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + schedulerConfigFactory := factory.NewConfigFactory(clientSet, v1.DefaultSchedulerName, v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) schedulerConfig, err := schedulerConfigFactory.CreateFromConfig(policy) if err != nil { t.Fatalf("Couldn't create scheduler config: %v", err) } eventBroadcaster := record.NewBroadcaster() - schedulerConfig.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: api.DefaultSchedulerName}) - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: clientSet.Core().Events("")}) + schedulerConfig.Recorder = eventBroadcaster.NewRecorder(v1.EventSource{Component: v1.DefaultSchedulerName}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: clientSet.Core().Events("")}) scheduler.New(schedulerConfig).Run() defer close(schedulerConfig.StopEverything) @@ -253,24 +253,24 @@ func TestSchedulerExtender(t *testing.T) { DoTestPodScheduling(ns, t, clientSet) } -func DoTestPodScheduling(ns *api.Namespace, t *testing.T, cs clientset.Interface) { +func DoTestPodScheduling(ns *v1.Namespace, t *testing.T, cs clientset.Interface) { // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (Nodes). - defer cs.Core().Nodes().DeleteCollection(nil, api.ListOptions{}) + defer cs.Core().Nodes().DeleteCollection(nil, v1.ListOptions{}) - goodCondition := api.NodeCondition{ - Type: api.NodeReady, - Status: api.ConditionTrue, + goodCondition := v1.NodeCondition{ + Type: v1.NodeReady, + Status: v1.ConditionTrue, Reason: fmt.Sprintf("schedulable condition"), LastHeartbeatTime: unversioned.Time{time.Now()}, } - node := &api.Node{ - Spec: api.NodeSpec{Unschedulable: false}, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), + node := &v1.Node{ + Spec: v1.NodeSpec{Unschedulable: false}, + Status: v1.NodeStatus{ + Capacity: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), }, - Conditions: []api.NodeCondition{goodCondition}, + Conditions: []v1.NodeCondition{goodCondition}, }, } @@ -281,10 +281,10 @@ func DoTestPodScheduling(ns *api.Namespace, t *testing.T, cs clientset.Interface } } - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "extender-test-pod"}, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "container", Image: e2e.GetPauseImageName(cs)}}, + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "extender-test-pod"}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Name: "container", Image: e2e.GetPauseImageName(cs)}}, }, } diff --git a/test/integration/scheduler/scheduler_test.go b/test/integration/scheduler/scheduler_test.go index 6cb354c3e75..b041c4140bf 100644 --- a/test/integration/scheduler/scheduler_test.go +++ b/test/integration/scheduler/scheduler_test.go @@ -25,14 +25,14 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/util/wait" @@ -43,7 +43,7 @@ import ( "k8s.io/kubernetes/test/integration/framework" ) -type nodeMutationFunc func(t *testing.T, n *api.Node, nodeStore cache.Store, c clientset.Interface) +type nodeMutationFunc func(t *testing.T, n *v1.Node, nodeStore cache.Store, c clientset.Interface) type nodeStateManager struct { makeSchedulable nodeMutationFunc @@ -57,16 +57,16 @@ func TestUnschedulableNodes(t *testing.T) { ns := framework.CreateTestingNamespace("unschedulable-nodes", s, t) defer framework.DeleteTestingNamespace(ns, s, t) - clientSet := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientSet := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) - schedulerConfigFactory := factory.NewConfigFactory(clientSet, api.DefaultSchedulerName, api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + schedulerConfigFactory := factory.NewConfigFactory(clientSet, v1.DefaultSchedulerName, v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) schedulerConfig, err := schedulerConfigFactory.Create() if err != nil { t.Fatalf("Couldn't create scheduler config: %v", err) } eventBroadcaster := record.NewBroadcaster() - schedulerConfig.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: api.DefaultSchedulerName}) - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: clientSet.Core().Events(ns.Name)}) + schedulerConfig.Recorder = eventBroadcaster.NewRecorder(v1.EventSource{Component: v1.DefaultSchedulerName}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: clientSet.Core().Events(ns.Name)}) scheduler.New(schedulerConfig).Run() defer close(schedulerConfig.StopEverything) @@ -94,7 +94,7 @@ func podScheduled(c clientset.Interface, podNamespace, podName string) wait.Cond // Wait till the passFunc confirms that the object it expects to see is in the store. // Used to observe reflected events. func waitForReflection(t *testing.T, s cache.Store, key string, passFunc func(n interface{}) bool) error { - nodes := []*api.Node{} + nodes := []*v1.Node{} err := wait.Poll(time.Millisecond*100, wait.ForeverTestTimeout, func() (bool, error) { if n, _, err := s.GetByKey(key); err == nil && passFunc(n) { return true, nil @@ -105,7 +105,7 @@ func waitForReflection(t *testing.T, s cache.Store, key string, passFunc func(n if n == nil { nodes = append(nodes, nil) } else { - nodes = append(nodes, n.(*api.Node)) + nodes = append(nodes, n.(*v1.Node)) } } return false, nil @@ -120,33 +120,33 @@ func waitForReflection(t *testing.T, s cache.Store, key string, passFunc func(n return err } -func DoTestUnschedulableNodes(t *testing.T, cs clientset.Interface, ns *api.Namespace, nodeStore cache.Store) { +func DoTestUnschedulableNodes(t *testing.T, cs clientset.Interface, ns *v1.Namespace, nodeStore cache.Store) { // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (Nodes). - defer cs.Core().Nodes().DeleteCollection(nil, api.ListOptions{}) + defer cs.Core().Nodes().DeleteCollection(nil, v1.ListOptions{}) - goodCondition := api.NodeCondition{ - Type: api.NodeReady, - Status: api.ConditionTrue, + goodCondition := v1.NodeCondition{ + Type: v1.NodeReady, + Status: v1.ConditionTrue, Reason: fmt.Sprintf("schedulable condition"), LastHeartbeatTime: unversioned.Time{time.Now()}, } - badCondition := api.NodeCondition{ - Type: api.NodeReady, - Status: api.ConditionUnknown, + badCondition := v1.NodeCondition{ + Type: v1.NodeReady, + Status: v1.ConditionUnknown, Reason: fmt.Sprintf("unschedulable condition"), LastHeartbeatTime: unversioned.Time{time.Now()}, } // Create a new schedulable node, since we're first going to apply // the unschedulable condition and verify that pods aren't scheduled. - node := &api.Node{ - ObjectMeta: api.ObjectMeta{Name: "node-scheduling-test-node"}, - Spec: api.NodeSpec{Unschedulable: false}, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), + node := &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: "node-scheduling-test-node"}, + Spec: v1.NodeSpec{Unschedulable: false}, + Status: v1.NodeStatus{ + Capacity: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), }, - Conditions: []api.NodeCondition{goodCondition}, + Conditions: []v1.NodeCondition{goodCondition}, }, } nodeKey, err := cache.MetaNamespaceKeyFunc(node) @@ -166,7 +166,7 @@ func DoTestUnschedulableNodes(t *testing.T, cs clientset.Interface, ns *api.Name nodeModifications := []nodeStateManager{ // Test node.Spec.Unschedulable=true/false { - makeUnSchedulable: func(t *testing.T, n *api.Node, s cache.Store, c clientset.Interface) { + makeUnSchedulable: func(t *testing.T, n *v1.Node, s cache.Store, c clientset.Interface) { n.Spec.Unschedulable = true if _, err := c.Core().Nodes().Update(n); err != nil { t.Fatalf("Failed to update node with unschedulable=true: %v", err) @@ -176,19 +176,19 @@ func DoTestUnschedulableNodes(t *testing.T, cs clientset.Interface, ns *api.Name // Nodes that are unschedulable or that are not ready or // have their disk full (Node.Spec.Conditions) are exluded // based on NodeConditionPredicate, a separate check - return node != nil && node.(*api.Node).Spec.Unschedulable == true + return node != nil && node.(*v1.Node).Spec.Unschedulable == true }) if err != nil { t.Fatalf("Failed to observe reflected update for setting unschedulable=true: %v", err) } }, - makeSchedulable: func(t *testing.T, n *api.Node, s cache.Store, c clientset.Interface) { + makeSchedulable: func(t *testing.T, n *v1.Node, s cache.Store, c clientset.Interface) { n.Spec.Unschedulable = false if _, err := c.Core().Nodes().Update(n); err != nil { t.Fatalf("Failed to update node with unschedulable=false: %v", err) } err = waitForReflection(t, s, nodeKey, func(node interface{}) bool { - return node != nil && node.(*api.Node).Spec.Unschedulable == false + return node != nil && node.(*v1.Node).Spec.Unschedulable == false }) if err != nil { t.Fatalf("Failed to observe reflected update for setting unschedulable=false: %v", err) @@ -197,35 +197,35 @@ func DoTestUnschedulableNodes(t *testing.T, cs clientset.Interface, ns *api.Name }, // Test node.Status.Conditions=ConditionTrue/Unknown { - makeUnSchedulable: func(t *testing.T, n *api.Node, s cache.Store, c clientset.Interface) { - n.Status = api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), + makeUnSchedulable: func(t *testing.T, n *v1.Node, s cache.Store, c clientset.Interface) { + n.Status = v1.NodeStatus{ + Capacity: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), }, - Conditions: []api.NodeCondition{badCondition}, + Conditions: []v1.NodeCondition{badCondition}, } if _, err = c.Core().Nodes().UpdateStatus(n); err != nil { t.Fatalf("Failed to update node with bad status condition: %v", err) } err = waitForReflection(t, s, nodeKey, func(node interface{}) bool { - return node != nil && node.(*api.Node).Status.Conditions[0].Status == api.ConditionUnknown + return node != nil && node.(*v1.Node).Status.Conditions[0].Status == v1.ConditionUnknown }) if err != nil { t.Fatalf("Failed to observe reflected update for status condition update: %v", err) } }, - makeSchedulable: func(t *testing.T, n *api.Node, s cache.Store, c clientset.Interface) { - n.Status = api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), + makeSchedulable: func(t *testing.T, n *v1.Node, s cache.Store, c clientset.Interface) { + n.Status = v1.NodeStatus{ + Capacity: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), }, - Conditions: []api.NodeCondition{goodCondition}, + Conditions: []v1.NodeCondition{goodCondition}, } if _, err = c.Core().Nodes().UpdateStatus(n); err != nil { t.Fatalf("Failed to update node with healthy status condition: %v", err) } err = waitForReflection(t, s, nodeKey, func(node interface{}) bool { - return node != nil && node.(*api.Node).Status.Conditions[0].Status == api.ConditionTrue + return node != nil && node.(*v1.Node).Status.Conditions[0].Status == v1.ConditionTrue }) if err != nil { t.Fatalf("Failed to observe reflected update for status condition update: %v", err) @@ -245,10 +245,10 @@ func DoTestUnschedulableNodes(t *testing.T, cs clientset.Interface, ns *api.Name // Create the new pod, note that this needs to happen post unschedulable // modification or we have a race in the test. - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "node-scheduling-test-pod"}, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "container", Image: e2e.GetPauseImageName(cs)}}, + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "node-scheduling-test-pod"}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Name: "container", Image: e2e.GetPauseImageName(cs)}}, }, } myPod, err := cs.Core().Pods(ns.Name).Create(pod) @@ -282,7 +282,7 @@ func DoTestUnschedulableNodes(t *testing.T, cs clientset.Interface, ns *api.Name t.Logf("Test %d: Pod got scheduled on a schedulable node", i) } - err = cs.Core().Pods(ns.Name).Delete(myPod.Name, api.NewDeleteOptions(0)) + err = cs.Core().Pods(ns.Name).Delete(myPod.Name, v1.NewDeleteOptions(0)) if err != nil { t.Errorf("Failed to delete pod: %v", err) } @@ -322,30 +322,30 @@ func TestMultiScheduler(t *testing.T) { - testPodNoAnnotation2 and testPodWithAnnotationFitsDefault2 shoule NOT be scheduled */ // 1. create and start default-scheduler - clientSet := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientSet := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (Nodes). - defer clientSet.Core().Nodes().DeleteCollection(nil, api.ListOptions{}) + defer clientSet.Core().Nodes().DeleteCollection(nil, v1.ListOptions{}) - schedulerConfigFactory := factory.NewConfigFactory(clientSet, api.DefaultSchedulerName, api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + schedulerConfigFactory := factory.NewConfigFactory(clientSet, v1.DefaultSchedulerName, v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) schedulerConfig, err := schedulerConfigFactory.Create() if err != nil { t.Fatalf("Couldn't create scheduler config: %v", err) } eventBroadcaster := record.NewBroadcaster() - schedulerConfig.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: api.DefaultSchedulerName}) - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: clientSet.Core().Events(ns.Name)}) + schedulerConfig.Recorder = eventBroadcaster.NewRecorder(v1.EventSource{Component: v1.DefaultSchedulerName}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: clientSet.Core().Events(ns.Name)}) scheduler.New(schedulerConfig).Run() // default-scheduler will be stopped later // 2. create a node - node := &api.Node{ - ObjectMeta: api.ObjectMeta{Name: "node-multi-scheduler-test-node"}, - Spec: api.NodeSpec{Unschedulable: false}, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), + node := &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: "node-multi-scheduler-test-node"}, + Spec: v1.NodeSpec{Unschedulable: false}, + Status: v1.NodeStatus{ + Capacity: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), }, }, } @@ -397,16 +397,16 @@ func TestMultiScheduler(t *testing.T) { } // 5. create and start a scheduler with name "foo-scheduler" - clientSet2 := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientSet2 := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) - schedulerConfigFactory2 := factory.NewConfigFactory(clientSet2, "foo-scheduler", api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + schedulerConfigFactory2 := factory.NewConfigFactory(clientSet2, "foo-scheduler", v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) schedulerConfig2, err := schedulerConfigFactory2.Create() if err != nil { t.Errorf("Couldn't create scheduler config: %v", err) } eventBroadcaster2 := record.NewBroadcaster() - schedulerConfig2.Recorder = eventBroadcaster2.NewRecorder(api.EventSource{Component: "foo-scheduler"}) - eventBroadcaster2.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: clientSet2.Core().Events(ns.Name)}) + schedulerConfig2.Recorder = eventBroadcaster2.NewRecorder(v1.EventSource{Component: "foo-scheduler"}) + eventBroadcaster2.StartRecordingToSink(&v1core.EventSinkImpl{Interface: clientSet2.Core().Events(ns.Name)}) scheduler.New(schedulerConfig2).Run() defer close(schedulerConfig2.StopEverything) @@ -421,11 +421,11 @@ func TestMultiScheduler(t *testing.T) { } // 7. delete the pods that were scheduled by the default scheduler, and stop the default scheduler - err = clientSet.Core().Pods(ns.Name).Delete(testPodNoAnnotation.Name, api.NewDeleteOptions(0)) + err = clientSet.Core().Pods(ns.Name).Delete(testPodNoAnnotation.Name, v1.NewDeleteOptions(0)) if err != nil { t.Errorf("Failed to delete pod: %v", err) } - err = clientSet.Core().Pods(ns.Name).Delete(testPodWithAnnotationFitsDefault.Name, api.NewDeleteOptions(0)) + err = clientSet.Core().Pods(ns.Name).Delete(testPodWithAnnotationFitsDefault.Name, v1.NewDeleteOptions(0)) if err != nil { t.Errorf("Failed to delete pod: %v", err) } @@ -469,11 +469,11 @@ func TestMultiScheduler(t *testing.T) { */ } -func createPod(client clientset.Interface, name string, annotation map[string]string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: name, Annotations: annotation}, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "container", Image: e2e.GetPauseImageName(client)}}, +func createPod(client clientset.Interface, name string, annotation map[string]string) *v1.Pod { + return &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: name, Annotations: annotation}, + Spec: v1.PodSpec{ + Containers: []v1.Container{{Name: "container", Image: e2e.GetPauseImageName(client)}}, }, } } @@ -487,33 +487,33 @@ func TestAllocatable(t *testing.T) { defer framework.DeleteTestingNamespace(ns, s, t) // 1. create and start default-scheduler - clientSet := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + clientSet := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) // NOTE: This test cannot run in parallel, because it is creating and deleting // non-namespaced objects (Nodes). - defer clientSet.Core().Nodes().DeleteCollection(nil, api.ListOptions{}) + defer clientSet.Core().Nodes().DeleteCollection(nil, v1.ListOptions{}) - schedulerConfigFactory := factory.NewConfigFactory(clientSet, api.DefaultSchedulerName, api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + schedulerConfigFactory := factory.NewConfigFactory(clientSet, v1.DefaultSchedulerName, v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) schedulerConfig, err := schedulerConfigFactory.Create() if err != nil { t.Fatalf("Couldn't create scheduler config: %v", err) } eventBroadcaster := record.NewBroadcaster() - schedulerConfig.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: api.DefaultSchedulerName}) - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: clientSet.Core().Events(ns.Name)}) + schedulerConfig.Recorder = eventBroadcaster.NewRecorder(v1.EventSource{Component: v1.DefaultSchedulerName}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: clientSet.Core().Events(ns.Name)}) scheduler.New(schedulerConfig).Run() // default-scheduler will be stopped later defer close(schedulerConfig.StopEverything) // 2. create a node without allocatable awareness - node := &api.Node{ - ObjectMeta: api.ObjectMeta{Name: "node-allocatable-scheduler-test-node"}, - Spec: api.NodeSpec{Unschedulable: false}, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), - api.ResourceCPU: *resource.NewMilliQuantity(30, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(30, resource.BinarySI), + node := &v1.Node{ + ObjectMeta: v1.ObjectMeta{Name: "node-allocatable-scheduler-test-node"}, + Spec: v1.NodeSpec{Unschedulable: false}, + Status: v1.NodeStatus{ + Capacity: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), + v1.ResourceCPU: *resource.NewMilliQuantity(30, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(30, resource.BinarySI), }, }, } @@ -524,17 +524,17 @@ func TestAllocatable(t *testing.T) { } // 3. create resource pod which requires less than Capacity - podResource := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "pod-test-allocatable"}, - Spec: api.PodSpec{ - Containers: []api.Container{ + podResource := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "pod-test-allocatable"}, + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "container", Image: e2e.GetPauseImageName(clientSet), - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(20, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(20, resource.BinarySI), + Resources: v1.ResourceRequirements{ + Requests: v1.ResourceList{ + v1.ResourceCPU: *resource.NewMilliQuantity(20, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(20, resource.BinarySI), }, }, }, @@ -556,16 +556,16 @@ func TestAllocatable(t *testing.T) { } // 5. Change the node status to allocatable aware, note that Allocatable is less than Pod's requirement - allocNode.Status = api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), - api.ResourceCPU: *resource.NewMilliQuantity(30, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(30, resource.BinarySI), + allocNode.Status = v1.NodeStatus{ + Capacity: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), + v1.ResourceCPU: *resource.NewMilliQuantity(30, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(30, resource.BinarySI), }, - Allocatable: api.ResourceList{ - api.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), - api.ResourceCPU: *resource.NewMilliQuantity(10, resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(10, resource.BinarySI), + Allocatable: v1.ResourceList{ + v1.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), + v1.ResourceCPU: *resource.NewMilliQuantity(10, resource.DecimalSI), + v1.ResourceMemory: *resource.NewQuantity(10, resource.BinarySI), }, } @@ -573,7 +573,7 @@ func TestAllocatable(t *testing.T) { t.Fatalf("Failed to update node with Status.Allocatable: %v", err) } - if err := clientSet.Core().Pods(ns.Name).Delete(podResource.Name, &api.DeleteOptions{}); err != nil { + if err := clientSet.Core().Pods(ns.Name).Delete(podResource.Name, &v1.DeleteOptions{}); err != nil { t.Fatalf("Failed to remove first resource pod: %v", err) } diff --git a/test/integration/scheduler_perf/BUILD b/test/integration/scheduler_perf/BUILD index 459d2dfa98d..f4b5ff0452c 100644 --- a/test/integration/scheduler_perf/BUILD +++ b/test/integration/scheduler_perf/BUILD @@ -15,10 +15,10 @@ go_library( srcs = ["util.go"], tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//pkg/apimachinery/registered:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", - "//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", + "//pkg/client/clientset_generated/release_1_5/typed/core/v1:go_default_library", "//pkg/client/record:go_default_library", "//pkg/client/restclient:go_default_library", "//plugin/pkg/scheduler:go_default_library", @@ -38,7 +38,7 @@ go_test( library = "go_default_library", tags = ["automanaged"], deps = [ - "//pkg/api:go_default_library", + "//pkg/api/v1:go_default_library", "//plugin/pkg/scheduler/factory:go_default_library", "//test/integration/framework:go_default_library", "//test/utils:go_default_library", diff --git a/test/integration/scheduler_perf/scheduler_test.go b/test/integration/scheduler_perf/scheduler_test.go index f36a8a65bc5..9db91a423b2 100644 --- a/test/integration/scheduler_perf/scheduler_test.go +++ b/test/integration/scheduler_perf/scheduler_test.go @@ -22,7 +22,7 @@ import ( "testing" "time" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/plugin/pkg/scheduler/factory" "k8s.io/kubernetes/test/integration/framework" testutils "k8s.io/kubernetes/test/utils" @@ -96,10 +96,10 @@ func TestSchedule100Node3KNodeAffinityPods(t *testing.T) { podCreatorConfig := testutils.NewTestPodCreatorConfig() for i := 0; i < numGroups; i++ { podCreatorConfig.AddStrategy("sched-perf-node-affinity", config.numPods/numGroups, - testutils.NewCustomCreatePodStrategy(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + testutils.NewCustomCreatePodStrategy(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "sched-perf-node-affinity-pod-", - Annotations: map[string]string{api.AffinityAnnotationKey: fmt.Sprintf(affinityTemplate, i)}, + Annotations: map[string]string{v1.AffinityAnnotationKey: fmt.Sprintf(affinityTemplate, i)}, }, Spec: testutils.MakePodSpec(), }), diff --git a/test/integration/scheduler_perf/util.go b/test/integration/scheduler_perf/util.go index 2c212d99007..c4aa8ad4b7c 100644 --- a/test/integration/scheduler_perf/util.go +++ b/test/integration/scheduler_perf/util.go @@ -21,10 +21,10 @@ import ( "net/http/httptest" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" + v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/plugin/pkg/scheduler" @@ -52,20 +52,20 @@ func mustSetupScheduler() (schedulerConfigFactory *factory.ConfigFactory, destro clientSet := clientset.NewForConfigOrDie(&restclient.Config{ Host: s.URL, - ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}, + ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}, QPS: 5000.0, Burst: 5000, }) - schedulerConfigFactory = factory.NewConfigFactory(clientSet, api.DefaultSchedulerName, api.DefaultHardPodAffinitySymmetricWeight, api.DefaultFailureDomains) + schedulerConfigFactory = factory.NewConfigFactory(clientSet, v1.DefaultSchedulerName, v1.DefaultHardPodAffinitySymmetricWeight, v1.DefaultFailureDomains) schedulerConfig, err := schedulerConfigFactory.Create() if err != nil { panic("Couldn't create scheduler config") } eventBroadcaster := record.NewBroadcaster() - schedulerConfig.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: "scheduler"}) - eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: clientSet.Core().Events("")}) + schedulerConfig.Recorder = eventBroadcaster.NewRecorder(v1.EventSource{Component: "scheduler"}) + eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: clientSet.Core().Events("")}) scheduler.New(schedulerConfig).Run() destroyFunc = func() { diff --git a/test/integration/secrets/secrets_test.go b/test/integration/secrets/secrets_test.go index e618dcd3d4e..f37abe5c574 100644 --- a/test/integration/secrets/secrets_test.go +++ b/test/integration/secrets/secrets_test.go @@ -23,9 +23,9 @@ package secrets import ( "testing" - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/test/integration" "k8s.io/kubernetes/test/integration/framework" @@ -42,7 +42,7 @@ func TestSecrets(t *testing.T) { _, s := framework.RunAMaster(nil) defer s.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) ns := framework.CreateTestingNamespace("secret", s, t) defer framework.DeleteTestingNamespace(ns, s, t) @@ -51,10 +51,10 @@ func TestSecrets(t *testing.T) { } // DoTestSecrets test secrets for one api version. -func DoTestSecrets(t *testing.T, client clientset.Interface, ns *api.Namespace) { +func DoTestSecrets(t *testing.T, client clientset.Interface, ns *v1.Namespace) { // Make a secret object. - s := api.Secret{ - ObjectMeta: api.ObjectMeta{ + s := v1.Secret{ + ObjectMeta: v1.ObjectMeta{ Name: "secret", Namespace: ns.Name, }, @@ -69,27 +69,27 @@ func DoTestSecrets(t *testing.T, client clientset.Interface, ns *api.Namespace) defer deleteSecretOrErrorf(t, client, s.Namespace, s.Name) // Template for pods that use a secret. - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + pod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: "XXX", Namespace: ns.Name, }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ + Spec: v1.PodSpec{ + Volumes: []v1.Volume{ { Name: "secvol", - VolumeSource: api.VolumeSource{ - Secret: &api.SecretVolumeSource{ + VolumeSource: v1.VolumeSource{ + Secret: &v1.SecretVolumeSource{ SecretName: "secret", }, }, }, }, - Containers: []api.Container{ + Containers: []v1.Container{ { Name: "fake-name", Image: "fakeimage", - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ { Name: "secvol", MountPath: "/fake/path", diff --git a/test/integration/serviceaccount/service_account_test.go b/test/integration/serviceaccount/service_account_test.go index 79d7a95092a..459a1322cf4 100644 --- a/test/integration/serviceaccount/service_account_test.go +++ b/test/integration/serviceaccount/service_account_test.go @@ -33,12 +33,14 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/auth/authenticator" "k8s.io/kubernetes/pkg/auth/authenticator/bearertoken" "k8s.io/kubernetes/pkg/auth/authorizer" "k8s.io/kubernetes/pkg/auth/user" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/informers" @@ -71,7 +73,7 @@ func TestServiceAccountAutoCreate(t *testing.T) { ns := "test-service-account-creation" // Create namespace - _, err := c.Core().Namespaces().Create(&api.Namespace{ObjectMeta: api.ObjectMeta{Name: ns}}) + _, err := c.Core().Namespaces().Create(&v1.Namespace{ObjectMeta: v1.ObjectMeta{Name: ns}}) if err != nil { t.Fatalf("could not create namespace: %v", err) } @@ -106,13 +108,13 @@ func TestServiceAccountTokenAutoCreate(t *testing.T) { name := "my-service-account" // Create namespace - _, err := c.Core().Namespaces().Create(&api.Namespace{ObjectMeta: api.ObjectMeta{Name: ns}}) + _, err := c.Core().Namespaces().Create(&v1.Namespace{ObjectMeta: v1.ObjectMeta{Name: ns}}) if err != nil { t.Fatalf("could not create namespace: %v", err) } // Create service account - serviceAccount, err := c.Core().ServiceAccounts(ns).Create(&api.ServiceAccount{ObjectMeta: api.ObjectMeta{Name: name}}) + serviceAccount, err := c.Core().ServiceAccounts(ns).Create(&v1.ServiceAccount{ObjectMeta: v1.ObjectMeta{Name: name}}) if err != nil { t.Fatalf("Service Account not created: %v", err) } @@ -146,7 +148,7 @@ func TestServiceAccountTokenAutoCreate(t *testing.T) { if err != nil { t.Fatal(err) } - serviceAccount.Secrets = []api.ObjectReference{} + serviceAccount.Secrets = []v1.ObjectReference{} _, err = c.Core().ServiceAccounts(ns).Update(serviceAccount) if err != nil { t.Fatal(err) @@ -174,7 +176,7 @@ func TestServiceAccountTokenAutoCreate(t *testing.T) { tokensToCleanup := sets.NewString(token1Name, token2Name, token3Name) err = wait.Poll(time.Second, 10*time.Second, func() (bool, error) { // Get all secrets in the namespace - secrets, err := c.Core().Secrets(ns).List(api.ListOptions{}) + secrets, err := c.Core().Secrets(ns).List(v1.ListOptions{}) // Retrieval errors should fail if err != nil { return false, err @@ -200,7 +202,7 @@ func TestServiceAccountTokenAutoMount(t *testing.T) { ns := "auto-mount-ns" // Create "my" namespace - _, err := c.Core().Namespaces().Create(&api.Namespace{ObjectMeta: api.ObjectMeta{Name: ns}}) + _, err := c.Core().Namespaces().Create(&v1.Namespace{ObjectMeta: v1.ObjectMeta{Name: ns}}) if err != nil && !errors.IsAlreadyExists(err) { t.Fatalf("could not create namespace: %v", err) } @@ -212,10 +214,10 @@ func TestServiceAccountTokenAutoMount(t *testing.T) { } // Pod to create - protoPod := api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "protopod"}, - Spec: api.PodSpec{ - Containers: []api.Container{ + protoPod := v1.Pod{ + ObjectMeta: v1.ObjectMeta{Name: "protopod"}, + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "container-1", Image: "container-1-image", @@ -223,15 +225,15 @@ func TestServiceAccountTokenAutoMount(t *testing.T) { { Name: "container-2", Image: "container-2-image", - VolumeMounts: []api.VolumeMount{ + VolumeMounts: []v1.VolumeMount{ {Name: "empty-dir", MountPath: serviceaccountadmission.DefaultAPITokenMountPath}, }, }, }, - Volumes: []api.Volume{ + Volumes: []v1.Volume{ { Name: "empty-dir", - VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}, + VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}, }, }, }, @@ -240,16 +242,16 @@ func TestServiceAccountTokenAutoMount(t *testing.T) { // Pod we expect to get created defaultMode := int32(0644) expectedServiceAccount := serviceaccountadmission.DefaultServiceAccountName - expectedVolumes := append(protoPod.Spec.Volumes, api.Volume{ + expectedVolumes := append(protoPod.Spec.Volumes, v1.Volume{ Name: defaultTokenName, - VolumeSource: api.VolumeSource{ - Secret: &api.SecretVolumeSource{ + VolumeSource: v1.VolumeSource{ + Secret: &v1.SecretVolumeSource{ SecretName: defaultTokenName, DefaultMode: &defaultMode, }, }, }) - expectedContainer1VolumeMounts := []api.VolumeMount{ + expectedContainer1VolumeMounts := []v1.VolumeMount{ {Name: defaultTokenName, MountPath: serviceaccountadmission.DefaultAPITokenMountPath, ReadOnly: true}, } expectedContainer2VolumeMounts := protoPod.Spec.Containers[1].VolumeMounts @@ -280,19 +282,19 @@ func TestServiceAccountTokenAuthentication(t *testing.T) { otherns := "other-ns" // Create "my" namespace - _, err := c.Core().Namespaces().Create(&api.Namespace{ObjectMeta: api.ObjectMeta{Name: myns}}) + _, err := c.Core().Namespaces().Create(&v1.Namespace{ObjectMeta: v1.ObjectMeta{Name: myns}}) if err != nil && !errors.IsAlreadyExists(err) { t.Fatalf("could not create namespace: %v", err) } // Create "other" namespace - _, err = c.Core().Namespaces().Create(&api.Namespace{ObjectMeta: api.ObjectMeta{Name: otherns}}) + _, err = c.Core().Namespaces().Create(&v1.Namespace{ObjectMeta: v1.ObjectMeta{Name: otherns}}) if err != nil && !errors.IsAlreadyExists(err) { t.Fatalf("could not create namespace: %v", err) } // Create "ro" user in myns - _, err = c.Core().ServiceAccounts(myns).Create(&api.ServiceAccount{ObjectMeta: api.ObjectMeta{Name: readOnlyServiceAccountName}}) + _, err = c.Core().ServiceAccounts(myns).Create(&v1.ServiceAccount{ObjectMeta: v1.ObjectMeta{Name: readOnlyServiceAccountName}}) if err != nil { t.Fatalf("Service Account not created: %v", err) } @@ -312,7 +314,7 @@ func TestServiceAccountTokenAuthentication(t *testing.T) { doServiceAccountAPIRequests(t, roClient, myns, false, false, false) // Create "rw" user in myns - _, err = c.Core().ServiceAccounts(myns).Create(&api.ServiceAccount{ObjectMeta: api.ObjectMeta{Name: readWriteServiceAccountName}}) + _, err = c.Core().ServiceAccounts(myns).Create(&v1.ServiceAccount{ObjectMeta: v1.ObjectMeta{Name: readWriteServiceAccountName}}) if err != nil { t.Fatalf("Service Account not created: %v", err) } @@ -348,10 +350,11 @@ func startServiceAccountTestServer(t *testing.T) (*clientset.Clientset, restclie })) // Anonymous client config - clientConfig := restclient.Config{Host: apiServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}} + clientConfig := restclient.Config{Host: apiServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}} // Root client // TODO: remove rootClient after we refactor pkg/admission to use the clientset. - rootClientset := clientset.NewForConfigOrDie(&restclient.Config{Host: apiServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}, BearerToken: rootToken}) + rootClientset := clientset.NewForConfigOrDie(&restclient.Config{Host: apiServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}, BearerToken: rootToken}) + internalRootClientset := internalclientset.NewForConfigOrDie(&restclient.Config{Host: apiServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}, BearerToken: rootToken}) // Set up two authenticators: // 1. A token authenticator that maps the rootToken to the "root" user // 2. A ServiceAccountToken authenticator that validates ServiceAccount tokens @@ -405,7 +408,7 @@ func startServiceAccountTestServer(t *testing.T) (*clientset.Clientset, restclie }) // Set up admission plugin to auto-assign serviceaccounts to pods - serviceAccountAdmission := serviceaccountadmission.NewServiceAccount(rootClientset) + serviceAccountAdmission := serviceaccountadmission.NewServiceAccount(internalRootClientset) masterConfig := framework.NewMasterConfig() masterConfig.GenericConfig.EnableIndex = true @@ -419,7 +422,7 @@ func startServiceAccountTestServer(t *testing.T) (*clientset.Clientset, restclie tokenController := serviceaccountcontroller.NewTokensController(rootClientset, serviceaccountcontroller.TokensControllerOptions{TokenGenerator: serviceaccount.JWTTokenGenerator(serviceAccountKey)}) go tokenController.Run(1, stopCh) - informers := informers.NewSharedInformerFactory(rootClientset, controller.NoResyncPeriodFunc()) + informers := informers.NewSharedInformerFactory(rootClientset, nil, controller.NoResyncPeriodFunc()) serviceAccountController := serviceaccountcontroller.NewServiceAccountsController(informers.ServiceAccounts(), informers.Namespaces(), rootClientset, serviceaccountcontroller.DefaultServiceAccountsControllerOptions()) informers.Start(stopCh) go serviceAccountController.Run(5, stopCh) @@ -435,12 +438,12 @@ func startServiceAccountTestServer(t *testing.T) (*clientset.Clientset, restclie return rootClientset, clientConfig, stop } -func getServiceAccount(c *clientset.Clientset, ns string, name string, shouldWait bool) (*api.ServiceAccount, error) { +func getServiceAccount(c *clientset.Clientset, ns string, name string, shouldWait bool) (*v1.ServiceAccount, error) { if !shouldWait { return c.Core().ServiceAccounts(ns).Get(name) } - var user *api.ServiceAccount + var user *v1.ServiceAccount var err error err = wait.Poll(time.Second, 10*time.Second, func() (bool, error) { user, err = c.Core().ServiceAccounts(ns).Get(name) @@ -476,12 +479,12 @@ func getReferencedServiceAccountToken(c *clientset.Clientset, ns string, name st if err != nil { return false, err } - if secret.Type != api.SecretTypeServiceAccountToken { + if secret.Type != v1.SecretTypeServiceAccountToken { continue } - name := secret.Annotations[api.ServiceAccountNameKey] - uid := secret.Annotations[api.ServiceAccountUIDKey] - tokenData := secret.Data[api.ServiceAccountTokenKey] + name := secret.Annotations[v1.ServiceAccountNameKey] + uid := secret.Annotations[v1.ServiceAccountUIDKey] + tokenData := secret.Data[v1.ServiceAccountTokenKey] if name == user.Name && uid == string(user.UID) && len(tokenData) > 0 { tokenName = secret.Name token = string(tokenData) @@ -512,18 +515,18 @@ func getReferencedServiceAccountToken(c *clientset.Clientset, ns string, name st type testOperation func() error func doServiceAccountAPIRequests(t *testing.T, c *clientset.Clientset, ns string, authenticated bool, canRead bool, canWrite bool) { - testSecret := &api.Secret{ - ObjectMeta: api.ObjectMeta{Name: "testSecret"}, + testSecret := &v1.Secret{ + ObjectMeta: v1.ObjectMeta{Name: "testSecret"}, Data: map[string][]byte{"test": []byte("data")}, } readOps := []testOperation{ func() error { - _, err := c.Core().Secrets(ns).List(api.ListOptions{}) + _, err := c.Core().Secrets(ns).List(v1.ListOptions{}) return err }, func() error { - _, err := c.Core().Pods(ns).List(api.ListOptions{}) + _, err := c.Core().Pods(ns).List(v1.ListOptions{}) return err }, } diff --git a/test/integration/storageclasses/storage_classes_test.go b/test/integration/storageclasses/storage_classes_test.go index cd0c9a99184..c006ddbad8e 100644 --- a/test/integration/storageclasses/storage_classes_test.go +++ b/test/integration/storageclasses/storage_classes_test.go @@ -23,13 +23,13 @@ package storageclasses import ( "testing" - "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/storage" - storageutil "k8s.io/kubernetes/pkg/apis/storage/util" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + storage "k8s.io/kubernetes/pkg/apis/storage/v1beta1" + storageutil "k8s.io/kubernetes/pkg/apis/storage/v1beta1/util" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/test/integration/framework" ) @@ -41,7 +41,7 @@ func TestStorageClasses(t *testing.T) { _, s := framework.RunAMaster(nil) defer s.Close() - client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}) + client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(v1.GroupName).GroupVersion}}) ns := framework.CreateTestingNamespace("storageclass", s, t) defer framework.DeleteTestingNamespace(ns, s, t) @@ -50,13 +50,13 @@ func TestStorageClasses(t *testing.T) { } // DoTestStorageClasses tests storage classes for one api version. -func DoTestStorageClasses(t *testing.T, client clientset.Interface, ns *api.Namespace) { +func DoTestStorageClasses(t *testing.T, client clientset.Interface, ns *v1.Namespace) { // Make a storage class object. s := storage.StorageClass{ TypeMeta: unversioned.TypeMeta{ Kind: "StorageClass", }, - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "gold", }, Provisioner: provisionerPluginName, @@ -68,17 +68,17 @@ func DoTestStorageClasses(t *testing.T, client clientset.Interface, ns *api.Name defer deleteStorageClassOrErrorf(t, client, s.Namespace, s.Name) // Template for pvcs that specify a storage class - pvc := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ + pvc := &v1.PersistentVolumeClaim{ + ObjectMeta: v1.ObjectMeta{ Name: "XXX", Namespace: ns.Name, Annotations: map[string]string{ storageutil.StorageClassAnnotation: "gold", }, }, - Spec: api.PersistentVolumeClaimSpec{ - Resources: api.ResourceRequirements{Requests: api.ResourceList{api.ResourceName(api.ResourceStorage): resource.MustParse("1G")}}, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, + Spec: v1.PersistentVolumeClaimSpec{ + Resources: v1.ResourceRequirements{Requests: v1.ResourceList{v1.ResourceName(v1.ResourceStorage): resource.MustParse("1G")}}, + AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, }, } diff --git a/test/integration/thirdparty/thirdparty_test.go b/test/integration/thirdparty/thirdparty_test.go index d55a4005d40..26492178caf 100644 --- a/test/integration/thirdparty/thirdparty_test.go +++ b/test/integration/thirdparty/thirdparty_test.go @@ -29,8 +29,9 @@ import ( "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/util/diff" "k8s.io/kubernetes/pkg/util/wait" @@ -43,7 +44,7 @@ func TestThirdPartyDelete(t *testing.T) { defer s.Close() clientConfig := &restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{NegotiatedSerializer: api.Codecs}} - client := internalclientset.NewForConfigOrDie(clientConfig) + client := clientset.NewForConfigOrDie(clientConfig) DoTestInstallThirdPartyAPIDelete(t, client, clientConfig) } @@ -53,7 +54,7 @@ func TestThirdPartyMultiple(t *testing.T) { defer s.Close() clientConfig := &restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{NegotiatedSerializer: api.Codecs}} - client := internalclientset.NewForConfigOrDie(clientConfig) + client := clientset.NewForConfigOrDie(clientConfig) DoTestInstallMultipleAPIs(t, client, clientConfig) } @@ -63,7 +64,7 @@ var versionsToTest = []string{"v1"} type Foo struct { unversioned.TypeMeta `json:",inline"` - api.ObjectMeta `json:"metadata,omitempty" description:"standard object metadata"` + v1.ObjectMeta `json:"metadata,omitempty" description:"standard object metadata"` SomeField string `json:"someField"` OtherField int `json:"otherField"` @@ -77,7 +78,7 @@ type FooList struct { } // installThirdParty installs a third party resoure and returns a defer func -func installThirdParty(t *testing.T, client internalclientset.Interface, clientConfig *restclient.Config, tpr *extensions.ThirdPartyResource, group, version, resource string) func() { +func installThirdParty(t *testing.T, client clientset.Interface, clientConfig *restclient.Config, tpr *extensions.ThirdPartyResource, group, version, resource string) func() { var err error _, err = client.Extensions().ThirdPartyResources().Create(tpr) if err != nil { @@ -123,13 +124,13 @@ func installThirdParty(t *testing.T, client internalclientset.Interface, clientC } } -func DoTestInstallMultipleAPIs(t *testing.T, client internalclientset.Interface, clientConfig *restclient.Config) { +func DoTestInstallMultipleAPIs(t *testing.T, client clientset.Interface, clientConfig *restclient.Config) { group := "company.com" version := "v1" defer installThirdParty(t, client, clientConfig, &extensions.ThirdPartyResource{ - ObjectMeta: api.ObjectMeta{Name: "foo.company.com"}, + ObjectMeta: v1.ObjectMeta{Name: "foo.company.com"}, Versions: []extensions.APIVersion{{Name: version}}, }, group, version, "foos", )() @@ -137,24 +138,24 @@ func DoTestInstallMultipleAPIs(t *testing.T, client internalclientset.Interface, // TODO make multiple resources in one version work // defer installThirdParty(t, client, clientConfig, // &extensions.ThirdPartyResource{ - // ObjectMeta: api.ObjectMeta{Name: "bar.company.com"}, + // ObjectMeta: v1.ObjectMeta{Name: "bar.company.com"}, // Versions: []extensions.APIVersion{{Name: version}}, // }, group, version, "bars", // )() } -func DoTestInstallThirdPartyAPIDelete(t *testing.T, client internalclientset.Interface, clientConfig *restclient.Config) { +func DoTestInstallThirdPartyAPIDelete(t *testing.T, client clientset.Interface, clientConfig *restclient.Config) { for _, version := range versionsToTest { testInstallThirdPartyAPIDeleteVersion(t, client, clientConfig, version) } } -func testInstallThirdPartyAPIDeleteVersion(t *testing.T, client internalclientset.Interface, clientConfig *restclient.Config, version string) { +func testInstallThirdPartyAPIDeleteVersion(t *testing.T, client clientset.Interface, clientConfig *restclient.Config, version string) { group := "company.com" defer installThirdParty(t, client, clientConfig, &extensions.ThirdPartyResource{ - ObjectMeta: api.ObjectMeta{Name: "foo.company.com"}, + ObjectMeta: v1.ObjectMeta{Name: "foo.company.com"}, Versions: []extensions.APIVersion{{Name: version}}, }, group, version, "foos", )() @@ -168,7 +169,7 @@ func testInstallThirdPartyAPIDeleteVersion(t *testing.T, client internalclientse } expectedObj := Foo{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: "test", Namespace: "default", }, diff --git a/test/integration/utils.go b/test/integration/utils.go index faaa43b675d..a9e384d9755 100644 --- a/test/integration/utils.go +++ b/test/integration/utils.go @@ -26,7 +26,7 @@ import ( "github.com/golang/glog" "golang.org/x/net/context" "k8s.io/kubernetes/pkg/api/errors" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" coreclient "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5/typed/core/v1" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/integration/framework" diff --git a/test/soak/serve_hostnames/BUILD b/test/soak/serve_hostnames/BUILD index 6ce9a9fb8e8..51328dce83d 100644 --- a/test/soak/serve_hostnames/BUILD +++ b/test/soak/serve_hostnames/BUILD @@ -18,7 +18,8 @@ go_binary( "//pkg/api:go_default_library", "//pkg/api/errors:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/client/restclient:go_default_library", "//pkg/client/unversioned/clientcmd:go_default_library", "//pkg/runtime:go_default_library", diff --git a/test/soak/serve_hostnames/serve_hostnames.go b/test/soak/serve_hostnames/serve_hostnames.go index b08007d5d49..068ef36128f 100644 --- a/test/soak/serve_hostnames/serve_hostnames.go +++ b/test/soak/serve_hostnames/serve_hostnames.go @@ -33,7 +33,8 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" "k8s.io/kubernetes/pkg/runtime" @@ -88,9 +89,9 @@ func main() { glog.Fatalf("Failed to make client: %v", err) } - var nodes *api.NodeList + var nodes *v1.NodeList for start := time.Now(); time.Since(start) < nodeListTimeout; time.Sleep(2 * time.Second) { - nodes, err = client.Nodes().List(api.ListOptions{}) + nodes, err = client.Nodes().List(v1.ListOptions{}) if err == nil { break } @@ -112,7 +113,7 @@ func main() { queries := *queriesAverage * len(nodes.Items) * *podsPerNode // Create the namespace - got, err := client.Namespaces().Create(&api.Namespace{ObjectMeta: api.ObjectMeta{GenerateName: "serve-hostnames-"}}) + got, err := client.Namespaces().Create(&v1.Namespace{ObjectMeta: v1.ObjectMeta{GenerateName: "serve-hostnames-"}}) if err != nil { glog.Fatalf("Failed to create namespace: %v", err) } @@ -137,18 +138,18 @@ func main() { // Create a service for these pods. glog.Infof("Creating service %s/serve-hostnames", ns) // Make several attempts to create a service. - var svc *api.Service + var svc *v1.Service for start := time.Now(); time.Since(start) < serviceCreateTimeout; time.Sleep(2 * time.Second) { t := time.Now() - svc, err = client.Services(ns).Create(&api.Service{ - ObjectMeta: api.ObjectMeta{ + svc, err = client.Services(ns).Create(&v1.Service{ + ObjectMeta: v1.ObjectMeta{ Name: "serve-hostnames", Labels: map[string]string{ "name": "serve-hostname", }, }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{{ + Spec: v1.ServiceSpec{ + Ports: []v1.ServicePort{{ Protocol: "TCP", Port: 9376, TargetPort: intstr.FromInt(9376), @@ -190,19 +191,19 @@ func main() { for start := time.Now(); time.Since(start) < podCreateTimeout; time.Sleep(2 * time.Second) { glog.Infof("Creating pod %s/%s on node %s", ns, podName, node.Name) t := time.Now() - _, err = client.Pods(ns).Create(&api.Pod{ - ObjectMeta: api.ObjectMeta{ + _, err = client.Pods(ns).Create(&v1.Pod{ + ObjectMeta: v1.ObjectMeta{ Name: podName, Labels: map[string]string{ "name": "serve-hostname", }, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: "serve-hostname", Image: "gcr.io/google_containers/serve_hostname:v1.4", - Ports: []api.ContainerPort{{ContainerPort: 9376}}, + Ports: []v1.ContainerPort{{ContainerPort: 9376}}, }, }, NodeName: node.Name, @@ -236,18 +237,18 @@ func main() { glog.Info("Waiting for the serve-hostname pods to be ready") for _, podName := range podNames { - var pod *api.Pod + var pod *v1.Pod for start := time.Now(); time.Since(start) < podStartTimeout; time.Sleep(5 * time.Second) { pod, err = client.Pods(ns).Get(podName) if err != nil { glog.Warningf("Get pod %s/%s failed, ignoring for %v: %v", ns, podName, err, podStartTimeout) continue } - if pod.Status.Phase == api.PodRunning { + if pod.Status.Phase == v1.PodRunning { break } } - if pod.Status.Phase != api.PodRunning { + if pod.Status.Phase != v1.PodRunning { glog.Warningf("Gave up waiting on pod %s/%s to be running (saw %v)", ns, podName, pod.Status.Phase) } else { glog.Infof("%s/%s is running", ns, podName) diff --git a/test/utils/BUILD b/test/utils/BUILD index ab02bc4651b..df784dc1027 100644 --- a/test/utils/BUILD +++ b/test/utils/BUILD @@ -25,9 +25,11 @@ go_library( "//pkg/api/errors:go_default_library", "//pkg/api/resource:go_default_library", "//pkg/api/unversioned:go_default_library", - "//pkg/apis/extensions:go_default_library", + "//pkg/api/v1:go_default_library", + "//pkg/apis/extensions/v1beta1:go_default_library", "//pkg/client/cache:go_default_library", "//pkg/client/clientset_generated/internalclientset:go_default_library", + "//pkg/client/clientset_generated/release_1_5:go_default_library", "//pkg/fields:go_default_library", "//pkg/labels:go_default_library", "//pkg/runtime:go_default_library", diff --git a/test/utils/conditions.go b/test/utils/conditions.go index 023e84694ed..fc9bb1e1c98 100644 --- a/test/utils/conditions.go +++ b/test/utils/conditions.go @@ -18,33 +18,34 @@ package utils import ( "fmt" - "k8s.io/kubernetes/pkg/api" + + "k8s.io/kubernetes/pkg/api/v1" ) type ContainerFailures struct { - status *api.ContainerStateTerminated + status *v1.ContainerStateTerminated Restarts int } // PodRunningReady checks whether pod p's phase is running and it has a ready // condition of status true. -func PodRunningReady(p *api.Pod) (bool, error) { +func PodRunningReady(p *v1.Pod) (bool, error) { // Check the phase is running. - if p.Status.Phase != api.PodRunning { + if p.Status.Phase != v1.PodRunning { return false, fmt.Errorf("want pod '%s' on '%s' to be '%v' but was '%v'", - p.ObjectMeta.Name, p.Spec.NodeName, api.PodRunning, p.Status.Phase) + p.ObjectMeta.Name, p.Spec.NodeName, v1.PodRunning, p.Status.Phase) } // Check the ready condition is true. if !PodReady(p) { return false, fmt.Errorf("pod '%s' on '%s' didn't have condition {%v %v}; conditions: %v", - p.ObjectMeta.Name, p.Spec.NodeName, api.PodReady, api.ConditionTrue, p.Status.Conditions) + p.ObjectMeta.Name, p.Spec.NodeName, v1.PodReady, v1.ConditionTrue, p.Status.Conditions) } return true, nil } -func PodRunningReadyOrSucceeded(p *api.Pod) (bool, error) { +func PodRunningReadyOrSucceeded(p *v1.Pod) (bool, error) { // Check if the phase is succeeded. - if p.Status.Phase == api.PodSucceeded { + if p.Status.Phase == v1.PodSucceeded { return true, nil } return PodRunningReady(p) @@ -54,7 +55,7 @@ func PodRunningReadyOrSucceeded(p *api.Pod) (bool, error) { // information for containers that have failed or been restarted. // A map is returned where the key is the containerID and the value is a // struct containing the restart and failure information -func FailedContainers(pod *api.Pod) map[string]ContainerFailures { +func FailedContainers(pod *v1.Pod) map[string]ContainerFailures { var state ContainerFailures states := make(map[string]ContainerFailures) @@ -85,7 +86,7 @@ func FailedContainers(pod *api.Pod) map[string]ContainerFailures { // TerminatedContainers inspects all containers in a pod and returns a map // of "container name: termination reason", for all currently terminated // containers. -func TerminatedContainers(pod *api.Pod) map[string]string { +func TerminatedContainers(pod *v1.Pod) map[string]string { states := make(map[string]string) statuses := pod.Status.ContainerStatuses if len(statuses) == 0 { @@ -100,20 +101,20 @@ func TerminatedContainers(pod *api.Pod) map[string]string { } // PodNotReady checks whether pod p's has a ready condition of status false. -func PodNotReady(p *api.Pod) (bool, error) { +func PodNotReady(p *v1.Pod) (bool, error) { // Check the ready condition is false. if PodReady(p) { return false, fmt.Errorf("pod '%s' on '%s' didn't have condition {%v %v}; conditions: %v", - p.ObjectMeta.Name, p.Spec.NodeName, api.PodReady, api.ConditionFalse, p.Status.Conditions) + p.ObjectMeta.Name, p.Spec.NodeName, v1.PodReady, v1.ConditionFalse, p.Status.Conditions) } return true, nil } // podReady returns whether pod has a condition of Ready with a status of true. -// TODO: should be replaced with api.IsPodReady -func PodReady(pod *api.Pod) bool { +// TODO: should be replaced with v1.IsPodReady +func PodReady(pod *v1.Pod) bool { for _, cond := range pod.Status.Conditions { - if cond.Type == api.PodReady && cond.Status == api.ConditionTrue { + if cond.Type == v1.PodReady && cond.Status == v1.ConditionTrue { return true } } diff --git a/test/utils/density_utils.go b/test/utils/density_utils.go index 148eb3ab05d..234fee897e5 100644 --- a/test/utils/density_utils.go +++ b/test/utils/density_utils.go @@ -23,7 +23,8 @@ import ( "k8s.io/kubernetes/pkg/api" apierrs "k8s.io/kubernetes/pkg/api/errors" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/api/v1" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "github.com/golang/glog" ) @@ -57,7 +58,7 @@ func AddLabelsToNode(c clientset.Interface, nodeName string, labels map[string]s // RemoveLabelOffNode is for cleaning up labels temporarily added to node, // won't fail if target label doesn't exist or has been removed. func RemoveLabelOffNode(c clientset.Interface, nodeName string, labelKeys []string) error { - var node *api.Node + var node *v1.Node var err error for attempt := 0; attempt < retries; attempt++ { node, err = c.Core().Nodes().Get(nodeName) diff --git a/test/utils/pod_store.go b/test/utils/pod_store.go index d7700ffdc01..712943c38f6 100644 --- a/test/utils/pod_store.go +++ b/test/utils/pod_store.go @@ -17,16 +17,16 @@ limitations under the License. package utils import ( - "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/watch" ) -// Convenient wrapper around cache.Store that returns list of api.Pod instead of interface{}. +// Convenient wrapper around cache.Store that returns list of v1.Pod instead of interface{}. type PodStore struct { cache.Store stopCh chan struct{} @@ -35,30 +35,30 @@ type PodStore struct { func NewPodStore(c clientset.Interface, namespace string, label labels.Selector, field fields.Selector) *PodStore { lw := &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - options.LabelSelector = label - options.FieldSelector = field + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + options.LabelSelector = label.String() + options.FieldSelector = field.String() obj, err := c.Core().Pods(namespace).List(options) return runtime.Object(obj), err }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - options.LabelSelector = label - options.FieldSelector = field + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + options.LabelSelector = label.String() + options.FieldSelector = field.String() return c.Core().Pods(namespace).Watch(options) }, } store := cache.NewStore(cache.MetaNamespaceKeyFunc) stopCh := make(chan struct{}) - reflector := cache.NewReflector(lw, &api.Pod{}, store, 0) + reflector := cache.NewReflector(lw, &v1.Pod{}, store, 0) reflector.RunUntil(stopCh) return &PodStore{Store: store, stopCh: stopCh, Reflector: reflector} } -func (s *PodStore) List() []*api.Pod { +func (s *PodStore) List() []*v1.Pod { objects := s.Store.List() - pods := make([]*api.Pod, 0) + pods := make([]*v1.Pod, 0) for _, o := range objects { - pods = append(pods, o.(*api.Pod)) + pods = append(pods, o.(*v1.Pod)) } return pods } diff --git a/test/utils/runners.go b/test/utils/runners.go index 8a1a1e98a46..8547b1a9c87 100644 --- a/test/utils/runners.go +++ b/test/utils/runners.go @@ -27,8 +27,10 @@ import ( apierrs "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" "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/api/v1" + extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" + "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/sets" @@ -45,6 +47,7 @@ const ( type RCConfig struct { Client clientset.Interface + InternalClient internalclientset.Interface Image string Command []string Name string @@ -57,8 +60,8 @@ type RCConfig struct { CpuLimit int64 // millicores MemRequest int64 // bytes MemLimit int64 // bytes - ReadinessProbe *api.Probe - DNSPolicy *api.DNSPolicy + ReadinessProbe *v1.Probe + DNSPolicy *v1.DNSPolicy // Env vars, set the same for every pod. Env map[string]string @@ -74,12 +77,12 @@ type RCConfig struct { // Ports to declare in the container as host and container ports. HostPorts map[string]int - Volumes []api.Volume - VolumeMounts []api.VolumeMount + Volumes []v1.Volume + VolumeMounts []v1.VolumeMount // Pointer to a list of pods; if non-nil, will be set to a list of pods // created by this RC by RunRC. - CreatedPods *[]*api.Pod + CreatedPods *[]*v1.Pod // Maximum allowable container failures. If exceeded, RunRC returns an error. // Defaults to replicas*0.1 if unspecified. @@ -159,7 +162,7 @@ func (p PodDiff) String(ignorePhases sets.String) string { } // Diff computes a PodDiff given 2 lists of pods. -func Diff(oldPods []*api.Pod, curPods []*api.Pod) PodDiff { +func Diff(oldPods []*v1.Pod, curPods []*v1.Pod) PodDiff { podInfoMap := PodDiff{} // New pods will show up in the curPods list but not in oldPods. They have oldhostname/phase == nonexist. @@ -192,27 +195,27 @@ func RunDeployment(config DeploymentConfig) error { func (config *DeploymentConfig) create() error { deployment := &extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.Name, }, Spec: extensions.DeploymentSpec{ - Replicas: int32(config.Replicas), + Replicas: func(i int) *int32 { x := int32(i); return &x }(config.Replicas), Selector: &unversioned.LabelSelector{ MatchLabels: map[string]string{ "name": config.Name, }, }, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"name": config.Name}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: config.Name, Image: config.Image, Command: config.Command, - Ports: []api.ContainerPort{{ContainerPort: 80}}, + Ports: []v1.ContainerPort{{ContainerPort: 80}}, }, }, }, @@ -244,27 +247,27 @@ func RunReplicaSet(config ReplicaSetConfig) error { func (config *ReplicaSetConfig) create() error { rs := &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ + ObjectMeta: v1.ObjectMeta{ Name: config.Name, }, Spec: extensions.ReplicaSetSpec{ - Replicas: int32(config.Replicas), + Replicas: func(i int) *int32 { x := int32(i); return &x }(config.Replicas), Selector: &unversioned.LabelSelector{ MatchLabels: map[string]string{ "name": config.Name, }, }, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"name": config.Name}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: config.Name, Image: config.Image, Command: config.Command, - Ports: []api.ContainerPort{{ContainerPort: 80}}, + Ports: []v1.ContainerPort{{ContainerPort: 80}}, }, }, }, @@ -295,30 +298,30 @@ func RunRC(config RCConfig) error { } func (config *RCConfig) create() error { - dnsDefault := api.DNSDefault + dnsDefault := v1.DNSDefault if config.DNSPolicy == nil { config.DNSPolicy = &dnsDefault } - rc := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ + rc := &v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{ Name: config.Name, }, - Spec: api.ReplicationControllerSpec{ - Replicas: int32(config.Replicas), + Spec: v1.ReplicationControllerSpec{ + Replicas: func(i int) *int32 { x := int32(i); return &x }(config.Replicas), Selector: map[string]string{ "name": config.Name, }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"name": config.Name}, }, - Spec: api.PodSpec{ - Containers: []api.Container{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ { Name: config.Name, Image: config.Image, Command: config.Command, - Ports: []api.ContainerPort{{ContainerPort: 80}}, + Ports: []v1.ContainerPort{{ContainerPort: 80}}, ReadinessProbe: config.ReadinessProbe, }, }, @@ -339,11 +342,11 @@ func (config *RCConfig) create() error { return nil } -func (config *RCConfig) applyTo(template *api.PodTemplateSpec) { +func (config *RCConfig) applyTo(template *v1.PodTemplateSpec) { if config.Env != nil { for k, v := range config.Env { c := &template.Spec.Containers[0] - c.Env = append(c.Env, api.EnvVar{Name: k, Value: v}) + c.Env = append(c.Env, v1.EnvVar{Name: k, Value: v}) } } if config.Labels != nil { @@ -360,32 +363,32 @@ func (config *RCConfig) applyTo(template *api.PodTemplateSpec) { if config.Ports != nil { for k, v := range config.Ports { c := &template.Spec.Containers[0] - c.Ports = append(c.Ports, api.ContainerPort{Name: k, ContainerPort: int32(v)}) + c.Ports = append(c.Ports, v1.ContainerPort{Name: k, ContainerPort: int32(v)}) } } if config.HostPorts != nil { for k, v := range config.HostPorts { c := &template.Spec.Containers[0] - c.Ports = append(c.Ports, api.ContainerPort{Name: k, ContainerPort: int32(v), HostPort: int32(v)}) + c.Ports = append(c.Ports, v1.ContainerPort{Name: k, ContainerPort: int32(v), HostPort: int32(v)}) } } if config.CpuLimit > 0 || config.MemLimit > 0 { - template.Spec.Containers[0].Resources.Limits = api.ResourceList{} + template.Spec.Containers[0].Resources.Limits = v1.ResourceList{} } if config.CpuLimit > 0 { - template.Spec.Containers[0].Resources.Limits[api.ResourceCPU] = *resource.NewMilliQuantity(config.CpuLimit, resource.DecimalSI) + template.Spec.Containers[0].Resources.Limits[v1.ResourceCPU] = *resource.NewMilliQuantity(config.CpuLimit, resource.DecimalSI) } if config.MemLimit > 0 { - template.Spec.Containers[0].Resources.Limits[api.ResourceMemory] = *resource.NewQuantity(config.MemLimit, resource.DecimalSI) + template.Spec.Containers[0].Resources.Limits[v1.ResourceMemory] = *resource.NewQuantity(config.MemLimit, resource.DecimalSI) } if config.CpuRequest > 0 || config.MemRequest > 0 { - template.Spec.Containers[0].Resources.Requests = api.ResourceList{} + template.Spec.Containers[0].Resources.Requests = v1.ResourceList{} } if config.CpuRequest > 0 { - template.Spec.Containers[0].Resources.Requests[api.ResourceCPU] = *resource.NewMilliQuantity(config.CpuRequest, resource.DecimalSI) + template.Spec.Containers[0].Resources.Requests[v1.ResourceCPU] = *resource.NewMilliQuantity(config.CpuRequest, resource.DecimalSI) } if config.MemRequest > 0 { - template.Spec.Containers[0].Resources.Requests[api.ResourceMemory] = *resource.NewQuantity(config.MemRequest, resource.DecimalSI) + template.Spec.Containers[0].Resources.Requests[v1.ResourceMemory] = *resource.NewQuantity(config.MemRequest, resource.DecimalSI) } if len(config.Volumes) > 0 { template.Spec.Volumes = config.Volumes @@ -405,7 +408,7 @@ type RCStartupStatus struct { Unknown int Inactive int FailedContainers int - Created []*api.Pod + Created []*v1.Pod ContainerRestartNodes sets.String } @@ -414,10 +417,10 @@ func (s *RCStartupStatus) String(name string) string { name, len(s.Created), s.Expected, s.Running, s.Pending, s.Waiting, s.Inactive, s.Terminating, s.Unknown, s.RunningButNotReady) } -func ComputeRCStartupStatus(pods []*api.Pod, expected int) RCStartupStatus { +func ComputeRCStartupStatus(pods []*v1.Pod, expected int) RCStartupStatus { startupStatus := RCStartupStatus{ Expected: expected, - Created: make([]*api.Pod, 0, expected), + Created: make([]*v1.Pod, 0, expected), ContainerRestartNodes: sets.NewString(), } for _, p := range pods { @@ -426,10 +429,10 @@ func ComputeRCStartupStatus(pods []*api.Pod, expected int) RCStartupStatus { continue } startupStatus.Created = append(startupStatus.Created, p) - if p.Status.Phase == api.PodRunning { + if p.Status.Phase == v1.PodRunning { ready := false for _, c := range p.Status.Conditions { - if c.Type == api.PodReady && c.Status == api.ConditionTrue { + if c.Type == v1.PodReady && c.Status == v1.ConditionTrue { ready = true break } @@ -444,15 +447,15 @@ func ComputeRCStartupStatus(pods []*api.Pod, expected int) RCStartupStatus { startupStatus.FailedContainers = startupStatus.FailedContainers + v.Restarts startupStatus.ContainerRestartNodes.Insert(p.Spec.NodeName) } - } else if p.Status.Phase == api.PodPending { + } else if p.Status.Phase == v1.PodPending { if p.Spec.NodeName == "" { startupStatus.Waiting++ } else { startupStatus.Pending++ } - } else if p.Status.Phase == api.PodSucceeded || p.Status.Phase == api.PodFailed { + } else if p.Status.Phase == v1.PodSucceeded || p.Status.Phase == v1.PodFailed { startupStatus.Inactive++ - } else if p.Status.Phase == api.PodUnknown { + } else if p.Status.Phase == v1.PodUnknown { startupStatus.Unknown++ } } @@ -481,7 +484,7 @@ func (config *RCConfig) start() error { if timeout <= 0 { timeout = 5 * time.Minute } - oldPods := make([]*api.Pod, 0) + oldPods := make([]*v1.Pod, 0) oldRunning := 0 lastChange := time.Now() for oldRunning != config.Replicas { @@ -537,8 +540,8 @@ func (config *RCConfig) start() error { if oldRunning != config.Replicas { // List only pods from a given replication controller. - options := api.ListOptions{LabelSelector: label} - if pods, err := config.Client.Core().Pods(api.NamespaceAll).List(options); err == nil { + options := v1.ListOptions{LabelSelector: label.String()} + if pods, err := config.Client.Core().Pods(v1.NamespaceAll).List(options); err == nil { for _, pod := range pods.Items { config.RCConfigLog("Pod %s\t%s\t%s\t%s", pod.Name, pod.Spec.NodeName, pod.Status.Phase, pod.DeletionTimestamp) @@ -555,7 +558,7 @@ func (config *RCConfig) start() error { // Optionally waits for pods to start running (if waitForRunning == true). // The number of replicas must be non-zero. func StartPods(c clientset.Interface, replicas int, namespace string, podNamePrefix string, - pod api.Pod, waitForRunning bool, logFunc func(fmt string, args ...interface{})) error { + pod v1.Pod, waitForRunning bool, logFunc func(fmt string, args ...interface{})) error { // no pod to start if replicas < 1 { panic("StartPods: number of replicas must be non-zero") @@ -596,7 +599,7 @@ waitLoop: continue waitLoop } for _, p := range pods { - if p.Status.Phase != api.PodRunning { + if p.Status.Phase != v1.PodRunning { continue waitLoop } } @@ -620,17 +623,17 @@ type TestNodePreparer interface { } type PrepareNodeStrategy interface { - PreparePatch(node *api.Node) []byte - CleanupNode(node *api.Node) *api.Node + PreparePatch(node *v1.Node) []byte + CleanupNode(node *v1.Node) *v1.Node } type TrivialNodePrepareStrategy struct{} -func (*TrivialNodePrepareStrategy) PreparePatch(*api.Node) []byte { +func (*TrivialNodePrepareStrategy) PreparePatch(*v1.Node) []byte { return []byte{} } -func (*TrivialNodePrepareStrategy) CleanupNode(node *api.Node) *api.Node { +func (*TrivialNodePrepareStrategy) CleanupNode(node *v1.Node) *v1.Node { nodeCopy := *node return &nodeCopy } @@ -647,20 +650,20 @@ func NewLabelNodePrepareStrategy(labelKey string, labelValue string) *LabelNodeP } } -func (s *LabelNodePrepareStrategy) PreparePatch(*api.Node) []byte { +func (s *LabelNodePrepareStrategy) PreparePatch(*v1.Node) []byte { labelString := fmt.Sprintf("{\"%v\":\"%v\"}", s.labelKey, s.labelValue) patch := fmt.Sprintf(`{"metadata":{"labels":%v}}`, labelString) return []byte(patch) } -func (s *LabelNodePrepareStrategy) CleanupNode(node *api.Node) *api.Node { +func (s *LabelNodePrepareStrategy) CleanupNode(node *v1.Node) *v1.Node { objCopy, err := api.Scheme.DeepCopy(*node) if err != nil { - return &api.Node{} + return &v1.Node{} } - nodeCopy, ok := (objCopy).(*api.Node) + nodeCopy, ok := (objCopy).(*v1.Node) if !ok { - return &api.Node{} + return &v1.Node{} } if node.Labels != nil && len(node.Labels[s.labelKey]) != 0 { delete(nodeCopy.Labels, s.labelKey) @@ -668,7 +671,7 @@ func (s *LabelNodePrepareStrategy) CleanupNode(node *api.Node) *api.Node { return nodeCopy } -func DoPrepareNode(client clientset.Interface, node *api.Node, strategy PrepareNodeStrategy) error { +func DoPrepareNode(client clientset.Interface, node *v1.Node, strategy PrepareNodeStrategy) error { var err error patch := strategy.PreparePatch(node) if len(patch) == 0 { @@ -750,27 +753,27 @@ func (c *TestPodCreator) CreatePods() error { return nil } -func MakePodSpec() api.PodSpec { - return api.PodSpec{ - Containers: []api.Container{{ +func MakePodSpec() v1.PodSpec { + return v1.PodSpec{ + Containers: []v1.Container{{ Name: "pause", Image: "kubernetes/pause", - Ports: []api.ContainerPort{{ContainerPort: 80}}, - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100m"), - api.ResourceMemory: resource.MustParse("500Mi"), + Ports: []v1.ContainerPort{{ContainerPort: 80}}, + Resources: v1.ResourceRequirements{ + Limits: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("100m"), + v1.ResourceMemory: resource.MustParse("500Mi"), }, - Requests: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100m"), - api.ResourceMemory: resource.MustParse("500Mi"), + Requests: v1.ResourceList{ + v1.ResourceCPU: resource.MustParse("100m"), + v1.ResourceMemory: resource.MustParse("500Mi"), }, }, }}, } } -func makeCreatePod(client clientset.Interface, namespace string, podTemplate *api.Pod) error { +func makeCreatePod(client clientset.Interface, namespace string, podTemplate *v1.Pod) error { var err error for attempt := 0; attempt < retries; attempt++ { if _, err := client.Core().Pods(namespace).Create(podTemplate); err == nil { @@ -781,7 +784,7 @@ func makeCreatePod(client clientset.Interface, namespace string, podTemplate *ap return fmt.Errorf("Terminal error while creating pod, won't retry: %v", err) } -func createPod(client clientset.Interface, namespace string, podCount int, podTemplate *api.Pod) error { +func createPod(client clientset.Interface, namespace string, podCount int, podTemplate *v1.Pod) error { var createError error lock := sync.Mutex{} createPodFunc := func(i int) { @@ -800,16 +803,16 @@ func createPod(client clientset.Interface, namespace string, podCount int, podTe return createError } -func createController(client clientset.Interface, controllerName, namespace string, podCount int, podTemplate *api.Pod) error { - rc := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ +func createController(client clientset.Interface, controllerName, namespace string, podCount int, podTemplate *v1.Pod) error { + rc := &v1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{ Name: controllerName, }, - Spec: api.ReplicationControllerSpec{ - Replicas: int32(podCount), + Spec: v1.ReplicationControllerSpec{ + Replicas: func(i int) *int32 { x := int32(i); return &x }(podCount), Selector: map[string]string{"name": controllerName}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ + Template: &v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ Labels: map[string]string{"name": controllerName}, }, Spec: podTemplate.Spec, @@ -826,15 +829,15 @@ func createController(client clientset.Interface, controllerName, namespace stri return fmt.Errorf("Terminal error while creating rc, won't retry: %v", err) } -func NewCustomCreatePodStrategy(podTemplate *api.Pod) TestPodCreateStrategy { +func NewCustomCreatePodStrategy(podTemplate *v1.Pod) TestPodCreateStrategy { return func(client clientset.Interface, namespace string, podCount int) error { return createPod(client, namespace, podCount, podTemplate) } } func NewSimpleCreatePodStrategy() TestPodCreateStrategy { - basePod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + basePod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ GenerateName: "simple-pod-", }, Spec: MakePodSpec(), @@ -844,8 +847,8 @@ func NewSimpleCreatePodStrategy() TestPodCreateStrategy { func NewSimpleWithControllerCreatePodStrategy(controllerName string) TestPodCreateStrategy { return func(client clientset.Interface, namespace string, podCount int) error { - basePod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ + basePod := &v1.Pod{ + ObjectMeta: v1.ObjectMeta{ GenerateName: controllerName + "-pod-", Labels: map[string]string{"name": controllerName}, },