Commit 254e71bf authored by deads2k's avatar deads2k

bulk delete of tpr packages

parent c10cc3de
......@@ -238,8 +238,6 @@ pkg/registry/core/service/ipallocator/controller
pkg/registry/core/service/ipallocator/storage
pkg/registry/core/serviceaccount
pkg/registry/extensions/podsecuritypolicy/storage
pkg/registry/extensions/thirdpartyresource
pkg/registry/extensions/thirdpartyresource/storage
pkg/registry/rbac/clusterrole/storage
pkg/registry/rbac/clusterrolebinding/storage
pkg/registry/rbac/role/storage
......
......@@ -43,7 +43,6 @@ go_library(
"//pkg/client/clientset_generated/clientset/typed/core/v1:go_default_library",
"//pkg/client/clientset_generated/internalclientset/typed/core/internalversion:go_default_library",
"//pkg/kubelet/client:go_default_library",
"//pkg/master/thirdparty:go_default_library",
"//pkg/master/tunneler:go_default_library",
"//pkg/registry/admissionregistration/rest:go_default_library",
"//pkg/registry/apps/rest:go_default_library",
......
......@@ -54,7 +54,6 @@ import (
corev1client "k8s.io/kubernetes/pkg/client/clientset_generated/clientset/typed/core/v1"
coreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion"
kubeletclient "k8s.io/kubernetes/pkg/kubelet/client"
"k8s.io/kubernetes/pkg/master/thirdparty"
"k8s.io/kubernetes/pkg/master/tunneler"
"k8s.io/kubernetes/pkg/routes"
nodeutil "k8s.io/kubernetes/pkg/util/node"
......@@ -259,7 +258,7 @@ func (c completedConfig) New(delegationTarget genericapiserver.DelegationTarget,
batchrest.RESTStorageProvider{},
certificatesrest.RESTStorageProvider{},
// TODO(enisoc): Remove crdRESTOptionsGetter input argument when TPR code is removed.
extensionsrest.RESTStorageProvider{ResourceInterface: thirdparty.NewThirdPartyResourceServer(s, s.DiscoveryGroupManager, c.StorageFactory, crdRESTOptionsGetter)},
extensionsrest.RESTStorageProvider{},
networkingrest.RESTStorageProvider{},
policyrest.RESTStorageProvider{},
rbacrest.RESTStorageProvider{Authorizer: c.GenericConfig.Authorizer},
......
......@@ -10,44 +10,19 @@ load(
go_library(
name = "go_default_library",
srcs = [
"thirdparty.go",
"tprregistration_controller.go",
],
srcs = ["tprregistration_controller.go"],
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/apis/extensions:go_default_library",
"//pkg/controller:go_default_library",
"//pkg/registry/extensions/rest:go_default_library",
"//pkg/registry/extensions/thirdpartyresourcedata:go_default_library",
"//pkg/registry/extensions/thirdpartyresourcedata/storage:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions:go_default_library",
"//vendor/k8s.io/apiextensions-apiserver/pkg/apiserver:go_default_library",
"//vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/internalclientset/typed/apiextensions/internalversion:go_default_library",
"//vendor/k8s.io/apiextensions-apiserver/pkg/client/informers/internalversion/apiextensions/internalversion:go_default_library",
"//vendor/k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/internalversion:go_default_library",
"//vendor/k8s.io/apiextensions-apiserver/pkg/registry/customresource:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/labels:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/errors:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/json:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/discovery:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/request:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/generic:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/rest:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server/storage:go_default_library",
"//vendor/k8s.io/apiserver/pkg/storage/storagebackend:go_default_library",
"//vendor/k8s.io/client-go/discovery:go_default_library",
"//vendor/k8s.io/client-go/tools/cache:go_default_library",
"//vendor/k8s.io/client-go/util/workqueue:go_default_library",
"//vendor/k8s.io/kube-aggregator/pkg/apis/apiregistration:go_default_library",
......
......@@ -71,8 +71,6 @@ filegroup(
"//pkg/registry/extensions/podsecuritypolicy:all-srcs",
"//pkg/registry/extensions/replicaset:all-srcs",
"//pkg/registry/extensions/rest:all-srcs",
"//pkg/registry/extensions/thirdpartyresource:all-srcs",
"//pkg/registry/extensions/thirdpartyresourcedata:all-srcs",
"//pkg/registry/networking/networkpolicy:all-srcs",
"//pkg/registry/networking/rest:all-srcs",
"//pkg/registry/policy/poddisruptionbudget:all-srcs",
......
......@@ -5,33 +5,15 @@ licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["thirdparty_controller_test.go"],
library = ":go_default_library",
tags = ["automanaged"],
deps = [
"//pkg/apis/extensions:go_default_library",
"//pkg/registry/extensions/thirdpartyresourcedata:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"storage_extensions.go",
"thirdparty_controller.go",
],
srcs = ["storage_extensions.go"],
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/apis/extensions:go_default_library",
"//pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion:go_default_library",
"//pkg/registry/extensions/controller/storage:go_default_library",
"//pkg/registry/extensions/daemonset/storage:go_default_library",
"//pkg/registry/extensions/deployment/storage:go_default_library",
......@@ -39,11 +21,7 @@ go_library(
"//pkg/registry/extensions/networkpolicy/storage:go_default_library",
"//pkg/registry/extensions/podsecuritypolicy/storage:go_default_library",
"//pkg/registry/extensions/replicaset/storage:go_default_library",
"//pkg/registry/extensions/thirdpartyresourcedata:go_default_library",
"//vendor/k8s.io/api/extensions/v1beta1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/generic:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/rest:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server:go_default_library",
......
......@@ -34,7 +34,6 @@ import (
)
type RESTStorageProvider struct {
ResourceInterface ResourceInterface
}
func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) {
......
/*
Copyright 2016 The 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 rest
import (
"fmt"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/kubernetes/pkg/apis/extensions"
extensionsclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion"
"k8s.io/kubernetes/pkg/registry/extensions/thirdpartyresourcedata"
)
// ResourceInterface is the interface for the parts of the master that know how to add/remove
// third party resources. Extracted into an interface for injection for testing.
type ResourceInterface interface {
// Remove a third party resource based on the RESTful path for that resource, the path is <api-group-path>/<resource-plural-name>
RemoveThirdPartyResource(path string) error
// Install a third party resource described by 'rsrc'
InstallThirdPartyResource(rsrc *extensions.ThirdPartyResource) error
// Is a particular third party resource currently installed?
HasThirdPartyResource(rsrc *extensions.ThirdPartyResource) (bool, error)
// List all currently installed third party resources, the returned
// names are of the form <api-group-path>/<resource-plural-name>
ListThirdPartyResources() []string
}
const thirdpartyprefix = "/apis"
// ThirdPartyController is a control loop that knows how to synchronize ThirdPartyResource objects with
// RESTful resources which are present in the API server.
type ThirdPartyController struct {
master ResourceInterface
client extensionsclient.ThirdPartyResourcesGetter
}
// SyncOneResource synchronizes a single resource with RESTful resources on the master
func (t *ThirdPartyController) SyncOneResource(rsrc *extensions.ThirdPartyResource) error {
// TODO: we also need to test if the existing installed resource matches the resource we are sync-ing.
// Currently, if there is an older, incompatible resource installed, we won't remove it. We should detect
// older, incompatible resources and remove them before testing if the resource exists.
hasResource, err := t.master.HasThirdPartyResource(rsrc)
if err != nil {
return err
}
if !hasResource {
return t.master.InstallThirdPartyResource(rsrc)
}
return nil
}
// Synchronize all resources with RESTful resources on the master
func (t *ThirdPartyController) SyncResources() error {
list, err := t.client.ThirdPartyResources().List(metav1.ListOptions{})
if err != nil {
return err
}
return t.syncResourceList(list)
}
func (t *ThirdPartyController) syncResourceList(list runtime.Object) error {
existing := sets.String{}
switch list := list.(type) {
case *extensions.ThirdPartyResourceList:
// Loop across all schema objects for third party resources
for ix := range list.Items {
item := &list.Items[ix]
// extract the api group and resource kind from the schema
_, group, err := thirdpartyresourcedata.ExtractApiGroupAndKind(item)
if err != nil {
return err
}
// place it in the set of resources that we expect, so that we don't delete it in the delete pass
existing.Insert(MakeThirdPartyPath(group))
// ensure a RESTful resource for this schema exists on the master
if err := t.SyncOneResource(item); err != nil {
return err
}
}
default:
return fmt.Errorf("expected a *ThirdPartyResourceList, got %#v", list)
}
// deletion phase, get all installed RESTful resources
installed := t.master.ListThirdPartyResources()
for _, installedAPI := range installed {
found := false
// search across the expected restful resources to see if this resource belongs to one of the expected ones
for _, apiPath := range existing.List() {
if installedAPI == apiPath || strings.HasPrefix(installedAPI, apiPath+"/") {
found = true
break
}
}
// not expected, delete the resource
if !found {
if err := t.master.RemoveThirdPartyResource(installedAPI); err != nil {
return err
}
}
}
return nil
}
func MakeThirdPartyPath(group string) string {
if len(group) == 0 {
return thirdpartyprefix
}
return thirdpartyprefix + "/" + group
}
func GetThirdPartyGroupName(path string) string {
return strings.TrimPrefix(strings.TrimPrefix(path, thirdpartyprefix), "/")
}
/*
Copyright 2014 The 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 rest
import (
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
expapi "k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/registry/extensions/thirdpartyresourcedata"
)
type FakeAPIInterface struct {
removed []string
installed []*expapi.ThirdPartyResource
apis []string
t *testing.T
}
func (f *FakeAPIInterface) RemoveThirdPartyResource(path string) error {
f.removed = append(f.removed, path)
return nil
}
func (f *FakeAPIInterface) InstallThirdPartyResource(rsrc *expapi.ThirdPartyResource) error {
f.installed = append(f.installed, rsrc)
_, group, _ := thirdpartyresourcedata.ExtractApiGroupAndKind(rsrc)
f.apis = append(f.apis, MakeThirdPartyPath(group))
return nil
}
func (f *FakeAPIInterface) HasThirdPartyResource(rsrc *expapi.ThirdPartyResource) (bool, error) {
if f.apis == nil {
return false, nil
}
_, group, _ := thirdpartyresourcedata.ExtractApiGroupAndKind(rsrc)
path := MakeThirdPartyPath(group)
for _, api := range f.apis {
if api == path {
return true, nil
}
}
return false, nil
}
func (f *FakeAPIInterface) ListThirdPartyResources() []string {
return f.apis
}
func TestSyncAPIs(t *testing.T) {
resourcesNamed := func(names ...string) []expapi.ThirdPartyResource {
result := []expapi.ThirdPartyResource{}
for _, name := range names {
result = append(result, expapi.ThirdPartyResource{ObjectMeta: metav1.ObjectMeta{Name: name}})
}
return result
}
tests := []struct {
list *expapi.ThirdPartyResourceList
apis []string
expectedInstalled []string
expectedRemoved []string
name string
}{
{
list: &expapi.ThirdPartyResourceList{
Items: resourcesNamed("foo.example.com"),
},
expectedInstalled: []string{"foo.example.com"},
name: "simple add",
},
{
list: &expapi.ThirdPartyResourceList{
Items: resourcesNamed("foo.example.com"),
},
apis: []string{
"/apis/example.com",
"/apis/example.com/v1",
},
name: "does nothing",
},
{
list: &expapi.ThirdPartyResourceList{
Items: resourcesNamed("foo.example.com"),
},
apis: []string{
"/apis/example.com",
"/apis/example.com/v1",
"/apis/example.co",
"/apis/example.co/v1",
},
name: "deletes substring API",
expectedRemoved: []string{
"/apis/example.co",
"/apis/example.co/v1",
},
},
{
list: &expapi.ThirdPartyResourceList{
Items: resourcesNamed("foo.example.com", "foo.company.com"),
},
apis: []string{
"/apis/company.com",
"/apis/company.com/v1",
},
expectedInstalled: []string{"foo.example.com"},
name: "adds with existing",
},
{
list: &expapi.ThirdPartyResourceList{
Items: resourcesNamed("foo.example.com"),
},
apis: []string{
"/apis/company.com",
"/apis/company.com/v1",
},
expectedInstalled: []string{"foo.example.com"},
expectedRemoved: []string{"/apis/company.com", "/apis/company.com/v1"},
name: "removes with existing",
},
}
for _, test := range tests {
fake := FakeAPIInterface{
apis: test.apis,
t: t,
}
cntrl := ThirdPartyController{master: &fake}
if err := cntrl.syncResourceList(test.list); err != nil {
t.Errorf("[%s] unexpected error: %v", test.name, err)
}
if len(test.expectedInstalled) != len(fake.installed) {
t.Errorf("[%s] unexpected installed APIs: %d, expected %d (%#v)", test.name, len(fake.installed), len(test.expectedInstalled), fake.installed[0])
continue
} else {
names := sets.String{}
for ix := range fake.installed {
names.Insert(fake.installed[ix].Name)
}
for _, name := range test.expectedInstalled {
if !names.Has(name) {
t.Errorf("[%s] missing installed API: %s", test.name, name)
}
}
}
if len(test.expectedRemoved) != len(fake.removed) {
t.Errorf("[%s] unexpected installed APIs: %d, expected %d", test.name, len(fake.removed), len(test.expectedRemoved))
continue
} else {
names := sets.String{}
names.Insert(fake.removed...)
for _, name := range test.expectedRemoved {
if !names.Has(name) {
t.Errorf("[%s] missing removed API: %s (%s)", test.name, name, names)
}
}
}
}
}
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"doc.go",
"strategy.go",
],
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/apis/extensions:go_default_library",
"//pkg/apis/extensions/validation:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/fields:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/labels:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/request:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/rest:go_default_library",
"//vendor/k8s.io/apiserver/pkg/storage:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = ["strategy_test.go"],
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/apis/extensions:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//pkg/registry/extensions/thirdpartyresource/storage:all-srcs",
],
tags = ["automanaged"],
)
/*
Copyright 2015 The 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 thirdpartyresource provides Registry interface and its REST
// implementation for storing ThirdPartyResource api objects.
package thirdpartyresource // import "k8s.io/kubernetes/pkg/registry/extensions/thirdpartyresource"
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["storage_test.go"],
library = ":go_default_library",
tags = ["automanaged"],
deps = [
"//pkg/apis/extensions:go_default_library",
"//pkg/registry/registrytest:go_default_library",
"//vendor/k8s.io/api/extensions/v1beta1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/fields:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/labels:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/generic:go_default_library",
"//vendor/k8s.io/apiserver/pkg/storage/etcd/testing:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["storage.go"],
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/apis/extensions:go_default_library",
"//pkg/registry/cachesize:go_default_library",
"//pkg/registry/extensions/thirdpartyresource:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/generic:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/generic/registry:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
/*
Copyright 2015 The 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 storage
import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/registry/generic"
genericregistry "k8s.io/apiserver/pkg/registry/generic/registry"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/registry/cachesize"
"k8s.io/kubernetes/pkg/registry/extensions/thirdpartyresource"
)
// REST implements a RESTStorage for ThirdPartyResources
type REST struct {
*genericregistry.Store
}
// NewREST returns a registry which will store ThirdPartyResource in the given helper
func NewREST(optsGetter generic.RESTOptionsGetter) *REST {
resource := extensions.Resource("thirdpartyresources")
opts, err := optsGetter.GetRESTOptions(resource)
if err != nil {
panic(err) // TODO: Propagate error up
}
// We explicitly do NOT do any decoration here yet. // TODO determine why we do not want to cache here
opts.Decorator = generic.UndecoratedStorage
store := &genericregistry.Store{
Copier: api.Scheme,
NewFunc: func() runtime.Object { return &extensions.ThirdPartyResource{} },
NewListFunc: func() runtime.Object { return &extensions.ThirdPartyResourceList{} },
PredicateFunc: thirdpartyresource.Matcher,
QualifiedResource: resource,
WatchCacheSize: cachesize.GetWatchCacheSizeByResource(resource.Resource),
CreateStrategy: thirdpartyresource.Strategy,
UpdateStrategy: thirdpartyresource.Strategy,
DeleteStrategy: thirdpartyresource.Strategy,
}
options := &generic.StoreOptions{RESTOptions: opts, AttrFunc: thirdpartyresource.GetAttrs} // Pass in opts to use UndecoratedStorage
if err := store.CompleteWithOptions(options); err != nil {
panic(err) // TODO: Propagate error up
}
return &REST{store}
}
/*
Copyright 2015 The 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 storage
import (
"fmt"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/apis/extensions"
// Ensure that extensions/v1beta1 package is initialized.
_ "k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/registry/generic"
etcdtesting "k8s.io/apiserver/pkg/storage/etcd/testing"
"k8s.io/kubernetes/pkg/registry/registrytest"
)
func newStorage(t *testing.T) (*REST, *etcdtesting.EtcdTestServer) {
etcdStorage, server := registrytest.NewEtcdStorage(t, extensions.GroupName)
restOptions := generic.RESTOptions{
StorageConfig: etcdStorage,
Decorator: generic.UndecoratedStorage,
DeleteCollectionWorkers: 1,
ResourcePrefix: "thirdpartyresources",
}
return NewREST(restOptions), server
}
func validNewThirdPartyResource(name string) *extensions.ThirdPartyResource {
return &extensions.ThirdPartyResource{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Versions: []extensions.APIVersion{
{
Name: "v1",
},
},
}
}
func namer(i int) string {
return fmt.Sprintf("kind%d.example.com", i)
}
func TestCreate(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store).ClusterScope().Namer(namer).GeneratesName()
rsrc := validNewThirdPartyResource("kind.domain.tld")
test.TestCreate(
// valid
rsrc,
// invalid
&extensions.ThirdPartyResource{},
&extensions.ThirdPartyResource{ObjectMeta: metav1.ObjectMeta{Name: "kind"}, Versions: []extensions.APIVersion{{Name: "v1"}}},
&extensions.ThirdPartyResource{ObjectMeta: metav1.ObjectMeta{Name: "kind.tld"}, Versions: []extensions.APIVersion{{Name: "v1"}}},
&extensions.ThirdPartyResource{ObjectMeta: metav1.ObjectMeta{Name: "kind.domain.tld"}, Versions: []extensions.APIVersion{{Name: "v.1"}}},
&extensions.ThirdPartyResource{ObjectMeta: metav1.ObjectMeta{Name: "kind.domain.tld"}, Versions: []extensions.APIVersion{{Name: "stable/v1"}}},
)
}
func TestUpdate(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store).ClusterScope().Namer(namer)
test.TestUpdate(
// valid
validNewThirdPartyResource("kind.domain.tld"),
// updateFunc
func(obj runtime.Object) runtime.Object {
object := obj.(*extensions.ThirdPartyResource)
object.Description = "new description"
return object
},
)
}
func TestDelete(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store).ClusterScope().Namer(namer)
test.TestDelete(validNewThirdPartyResource("kind.domain.tld"))
}
func TestGet(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store).ClusterScope().Namer(namer)
test.TestGet(validNewThirdPartyResource("kind.domain.tld"))
}
func TestList(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store).ClusterScope().Namer(namer)
test.TestList(validNewThirdPartyResource("kind.domain.tld"))
}
func TestWatch(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store).ClusterScope().Namer(namer)
test.TestWatch(
validNewThirdPartyResource("kind.domain.tld"),
// matching labels
[]labels.Set{},
// not matching labels
[]labels.Set{
{"foo": "bar"},
},
// matching fields
[]fields.Set{},
// not matching fields
[]fields.Set{
{"metadata.name": "bar"},
{"name": "foo"},
},
)
}
/*
Copyright 2015 The 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 thirdpartyresource
import (
"fmt"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/apiserver/pkg/storage"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/apis/extensions/validation"
)
// strategy implements behavior for ThirdPartyResource objects
type strategy struct {
runtime.ObjectTyper
}
// Strategy is the default logic that applies when creating and updating ThirdPartyResource
// objects via the REST API.
var Strategy = strategy{api.Scheme}
var _ = rest.RESTCreateStrategy(Strategy)
var _ = rest.RESTUpdateStrategy(Strategy)
func (strategy) NamespaceScoped() bool {
return false
}
func (strategy) GenerateName(base string) string {
return ""
}
func (strategy) PrepareForCreate(ctx genericapirequest.Context, obj runtime.Object) {
}
func (strategy) Validate(ctx genericapirequest.Context, obj runtime.Object) field.ErrorList {
return validation.ValidateThirdPartyResource(obj.(*extensions.ThirdPartyResource))
}
// Canonicalize normalizes the object after validation.
func (strategy) Canonicalize(obj runtime.Object) {
}
func (strategy) AllowCreateOnUpdate() bool {
return false
}
func (strategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) {
}
func (strategy) ValidateUpdate(ctx genericapirequest.Context, obj, old runtime.Object) field.ErrorList {
return validation.ValidateThirdPartyResourceUpdate(obj.(*extensions.ThirdPartyResource), old.(*extensions.ThirdPartyResource))
}
func (strategy) AllowUnconditionalUpdate() bool {
return true
}
// GetAttrs returns labels and fields of a given object for filtering purposes.
func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, bool, error) {
tpr, ok := obj.(*extensions.ThirdPartyResource)
if !ok {
return nil, nil, false, fmt.Errorf("not a ThirdPartyResource")
}
return labels.Set(tpr.Labels), SelectableFields(tpr), tpr.Initializers != nil, nil
}
// Matcher returns a generic matcher for a given label and field selector.
func Matcher(label labels.Selector, field fields.Selector) storage.SelectionPredicate {
return storage.SelectionPredicate{
Label: label,
Field: field,
GetAttrs: GetAttrs,
}
}
// SelectableFields returns a field set that can be used for filter selection
func SelectableFields(obj *extensions.ThirdPartyResource) fields.Set {
return nil
}
/*
Copyright 2015 The 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 thirdpartyresource
import (
"testing"
_ "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/testapi"
apitesting "k8s.io/kubernetes/pkg/api/testing"
"k8s.io/kubernetes/pkg/apis/extensions"
)
func TestSelectableFieldLabelConversions(t *testing.T) {
apitesting.TestSelectableFieldLabelConversionsOfKind(t,
testapi.Extensions.GroupVersion().String(),
"ThirdPartyResource",
SelectableFields(&extensions.ThirdPartyResource{}),
nil,
)
}
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"codec.go",
"doc.go",
"registry.go",
"strategy.go",
"util.go",
],
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/api/util:go_default_library",
"//pkg/apis/extensions:go_default_library",
"//pkg/apis/extensions/validation:go_default_library",
"//vendor/k8s.io/api/core/v1:go_default_library",
"//vendor/k8s.io/api/extensions/v1beta1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/fields:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/labels:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/json:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/yaml:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/watch:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/request:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/rest:go_default_library",
"//vendor/k8s.io/apiserver/pkg/storage:go_default_library",
"//vendor/k8s.io/apiserver/pkg/storage/names:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = [
"codec_test.go",
"strategy_test.go",
"util_test.go",
],
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/apis/extensions:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//pkg/registry/extensions/thirdpartyresourcedata/storage:all-srcs",
],
tags = ["automanaged"],
)
/*
Copyright 2015 The 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 thirdpartyresourcedata
import (
"bytes"
"encoding/json"
"reflect"
"strings"
"testing"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/testapi"
"k8s.io/kubernetes/pkg/apis/extensions"
)
type Foo struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty" description:"standard object metadata"`
SomeField string `json:"someField"`
OtherField int `json:"otherField"`
}
func (*Foo) GetObjectKind() schema.ObjectKind {
return schema.EmptyObjectKind
}
type FooList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty" description:"standard list metadata; see https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata"`
Items []Foo `json:"items"`
}
func TestCodec(t *testing.T) {
tests := []struct {
into runtime.Object
obj *Foo
expectErr bool
name string
}{
{
into: &runtime.VersionedObjects{},
obj: &Foo{
ObjectMeta: metav1.ObjectMeta{Name: "bar"},
TypeMeta: metav1.TypeMeta{APIVersion: "company.com/v1", Kind: "Foo"},
},
expectErr: false,
name: "versioned objects list",
},
{
obj: &Foo{ObjectMeta: metav1.ObjectMeta{Name: "bar"}},
expectErr: true,
name: "missing kind",
},
{
obj: &Foo{
ObjectMeta: metav1.ObjectMeta{Name: "bar"},
TypeMeta: metav1.TypeMeta{APIVersion: "company.com/v1", Kind: "Foo"},
},
name: "basic",
},
{
into: &extensions.ThirdPartyResourceData{},
obj: &Foo{
ObjectMeta: metav1.ObjectMeta{Name: "bar"},
TypeMeta: metav1.TypeMeta{Kind: "ThirdPartyResourceData"},
},
expectErr: true,
name: "broken kind",
},
{
obj: &Foo{
ObjectMeta: metav1.ObjectMeta{Name: "bar", ResourceVersion: "baz"},
TypeMeta: metav1.TypeMeta{APIVersion: "company.com/v1", Kind: "Foo"},
},
name: "resource version",
},
{
obj: &Foo{
ObjectMeta: metav1.ObjectMeta{
Name: "bar",
CreationTimestamp: metav1.Time{Time: time.Unix(100, 0)},
},
TypeMeta: metav1.TypeMeta{
APIVersion: "company.com/v1",
Kind: "Foo",
},
},
name: "creation time",
},
{
obj: &Foo{
ObjectMeta: metav1.ObjectMeta{
Name: "bar",
ResourceVersion: "baz",
Labels: map[string]string{"foo": "bar", "baz": "blah"},
},
TypeMeta: metav1.TypeMeta{APIVersion: "company.com/v1", Kind: "Foo"},
},
name: "labels",
},
}
api.Registry.AddThirdPartyAPIGroupVersions(schema.GroupVersion{Group: "company.com", Version: "v1"})
for _, test := range tests {
d := &thirdPartyResourceDataDecoder{kind: "Foo", delegate: testapi.Extensions.Codec()}
e := &thirdPartyResourceDataEncoder{gvk: schema.GroupVersionKind{
Group: "company.com",
Version: "v1",
Kind: "Foo",
}, delegate: testapi.Extensions.Codec()}
data, err := json.Marshal(test.obj)
if err != nil {
t.Errorf("[%s] unexpected error: %v", test.name, err)
continue
}
var obj runtime.Object
if test.into != nil {
err = runtime.DecodeInto(d, data, test.into)
obj = test.into
} else {
obj, err = runtime.Decode(d, data)
}
if err != nil && !test.expectErr {
t.Errorf("[%s] unexpected error: %v", test.name, err)
continue
}
if test.expectErr {
if err == nil {
t.Errorf("[%s] unexpected non-error", test.name)
}
continue
}
var rsrcObj *extensions.ThirdPartyResourceData
switch o := obj.(type) {
case *extensions.ThirdPartyResourceData:
rsrcObj = o
case *runtime.VersionedObjects:
rsrcObj = o.First().(*extensions.ThirdPartyResourceData)
default:
t.Errorf("[%s] unexpected object: %v", test.name, obj)
continue
}
if !reflect.DeepEqual(rsrcObj.ObjectMeta, test.obj.ObjectMeta) {
t.Errorf("[%s]\nexpected\n%v\nsaw\n%v\n", test.name, rsrcObj.ObjectMeta, test.obj.ObjectMeta)
}
var output Foo
if err := json.Unmarshal(rsrcObj.Data, &output); err != nil {
t.Errorf("[%s] unexpected error: %v", test.name, err)
continue
}
if !reflect.DeepEqual(&output, test.obj) {
t.Errorf("[%s]\nexpected\n%v\nsaw\n%v\n", test.name, test.obj, &output)
}
data, err = runtime.Encode(e, rsrcObj)
if err != nil {
t.Errorf("[%s] unexpected error: %v", test.name, err)
}
var output2 Foo
if err := json.Unmarshal(data, &output2); err != nil {
t.Errorf("[%s] unexpected error: %v", test.name, err)
continue
}
if !reflect.DeepEqual(&output2, test.obj) {
t.Errorf("[%s]\nexpected\n%v\nsaw\n%v\n", test.name, test.obj, &output2)
}
}
}
func TestCreater(t *testing.T) {
creater := NewObjectCreator("creater group", "creater version", api.Scheme)
tests := []struct {
name string
kind schema.GroupVersionKind
expectedObj runtime.Object
expectErr bool
}{
{
name: "valid ThirdPartyResourceData creation",
kind: schema.GroupVersionKind{Group: "creater group", Version: "creater version", Kind: "ThirdPartyResourceData"},
expectedObj: &extensions.ThirdPartyResourceData{},
expectErr: false,
},
{
name: "invalid ThirdPartyResourceData creation",
kind: schema.GroupVersionKind{Version: "invalid version", Kind: "ThirdPartyResourceData"},
expectedObj: nil,
expectErr: true,
},
{
name: "valid ListOptions creation",
kind: schema.GroupVersionKind{Version: "v1", Kind: "ListOptions"},
expectedObj: &metav1.ListOptions{},
expectErr: false,
},
}
for _, test := range tests {
out, err := creater.New(test.kind)
if err != nil && !test.expectErr {
t.Errorf("[%s] unexpected error: %v", test.name, err)
}
if err == nil && test.expectErr {
t.Errorf("[%s] unexpected non-error", test.name)
}
if !reflect.DeepEqual(test.expectedObj, out) {
t.Errorf("[%s] unexpected error: expect: %v, got: %v", test.name, test.expectedObj, out)
}
}
}
func TestEncodeToStreamForInternalEvent(t *testing.T) {
e := &thirdPartyResourceDataEncoder{gvk: schema.GroupVersionKind{
Group: "company.com",
Version: "v1",
Kind: "Foo",
}, delegate: testapi.Extensions.Codec()}
buf := bytes.NewBuffer([]byte{})
expected := &metav1.WatchEvent{
Type: "Added",
}
err := e.Encode(&metav1.InternalEvent{
Type: "Added",
}, buf)
jBytes, _ := json.Marshal(expected)
if string(jBytes) == buf.String() {
t.Errorf("unexpected encoding expected %s got %s", string(jBytes), buf.String())
}
if err != nil {
t.Errorf("unexpected error encoding: %v", err)
}
}
func TestThirdPartyResourceDataListEncoding(t *testing.T) {
gv := schema.GroupVersion{Group: "stable.foo.faz", Version: "v1"}
gvk := gv.WithKind("Bar")
e := &thirdPartyResourceDataEncoder{delegate: testapi.Extensions.Codec(), gvk: gvk}
subject := &extensions.ThirdPartyResourceDataList{}
buf := bytes.NewBuffer([]byte{})
err := e.Encode(subject, buf)
if err != nil {
t.Errorf("encoding unexpected error: %v", err)
}
targetOutput := struct {
Kind string `json:"kind,omitempty"`
Items []json.RawMessage `json:"items"`
Metadata metav1.ListMeta `json:"metadata,omitempty"`
APIVersion string `json:"apiVersion,omitempty"`
}{}
err = json.Unmarshal(buf.Bytes(), &targetOutput)
if err != nil {
t.Errorf("unmarshal unexpected error: %v", err)
}
if expectedKind := gvk.Kind + "List"; expectedKind != targetOutput.Kind {
t.Errorf("unexpected kind on list got %s expected %s", targetOutput.Kind, expectedKind)
}
if targetOutput.Metadata != subject.ListMeta {
t.Errorf("metadata mismatch %v != %v", targetOutput.Metadata, subject.ListMeta)
}
if targetOutput.APIVersion != gv.String() {
t.Errorf("apiversion mismatch %v != %v", targetOutput.APIVersion, gv.String())
}
}
func TestDecodeNumbers(t *testing.T) {
gv := schema.GroupVersion{Group: "stable.foo.faz", Version: "v1"}
gvk := gv.WithKind("Foo")
e := &thirdPartyResourceDataEncoder{delegate: testapi.Extensions.Codec(), gvk: gvk}
d := &thirdPartyResourceDataDecoder{kind: "Foo", delegate: testapi.Extensions.Codec()}
// Use highest int64 number and 1000000.
subject := &extensions.ThirdPartyResourceDataList{
Items: []extensions.ThirdPartyResourceData{
{
Data: []byte(`{"num1": 9223372036854775807, "num2": 1000000}`),
},
},
}
// Encode to get original JSON.
originalJSON := bytes.NewBuffer([]byte{})
err := e.Encode(subject, originalJSON)
if err != nil {
t.Errorf("encoding unexpected error: %v", err)
}
// Decode original JSON.
var into runtime.Object
into, _, err = d.Decode(originalJSON.Bytes(), &gvk, into)
if err != nil {
t.Errorf("decoding unexpected error: %v", err)
}
// Check if int is preserved.
decodedJSON := into.(*extensions.ThirdPartyResourceDataList).Items[0].Data
if !strings.Contains(string(decodedJSON), `"num1":9223372036854775807,"num2":1000000`) {
t.Errorf("Expected %s, got %s", `"num1":9223372036854775807,"num2":1000000`, string(decodedJSON))
}
}
/*
Copyright 2015 The 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 thirdpartyresourcedata provides Registry interface and its REST
// implementation for storing ThirdPartyResourceData api objects.
package thirdpartyresourcedata // import "k8s.io/kubernetes/pkg/registry/extensions/thirdpartyresourcedata"
/*
Copyright 2015 The 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 thirdpartyresourcedata
import (
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/apis/extensions"
)
// Registry is an interface implemented by things that know how to store ThirdPartyResourceData objects.
type Registry interface {
ListThirdPartyResourceData(ctx genericapirequest.Context, options *metainternalversion.ListOptions) (*extensions.ThirdPartyResourceDataList, error)
WatchThirdPartyResourceData(ctx genericapirequest.Context, options *metainternalversion.ListOptions) (watch.Interface, error)
GetThirdPartyResourceData(ctx genericapirequest.Context, name string, options *metav1.GetOptions) (*extensions.ThirdPartyResourceData, error)
CreateThirdPartyResourceData(ctx genericapirequest.Context, resource *extensions.ThirdPartyResourceData) (*extensions.ThirdPartyResourceData, error)
UpdateThirdPartyResourceData(ctx genericapirequest.Context, resource *extensions.ThirdPartyResourceData) (*extensions.ThirdPartyResourceData, error)
DeleteThirdPartyResourceData(ctx genericapirequest.Context, name string) error
}
// storage puts strong typing around storage calls
type storage struct {
rest.StandardStorage
}
// NewRegistry returns a new Registry interface for the given Storage. Any mismatched
// types will panic.
func NewRegistry(s rest.StandardStorage) Registry {
return &storage{s}
}
func (s *storage) ListThirdPartyResourceData(ctx genericapirequest.Context, options *metainternalversion.ListOptions) (*extensions.ThirdPartyResourceDataList, error) {
obj, err := s.List(ctx, options)
if err != nil {
return nil, err
}
return obj.(*extensions.ThirdPartyResourceDataList), nil
}
func (s *storage) WatchThirdPartyResourceData(ctx genericapirequest.Context, options *metainternalversion.ListOptions) (watch.Interface, error) {
return s.Watch(ctx, options)
}
func (s *storage) GetThirdPartyResourceData(ctx genericapirequest.Context, name string, options *metav1.GetOptions) (*extensions.ThirdPartyResourceData, error) {
obj, err := s.Get(ctx, name, options)
if err != nil {
return nil, err
}
return obj.(*extensions.ThirdPartyResourceData), nil
}
func (s *storage) CreateThirdPartyResourceData(ctx genericapirequest.Context, ThirdPartyResourceData *extensions.ThirdPartyResourceData) (*extensions.ThirdPartyResourceData, error) {
obj, err := s.Create(ctx, ThirdPartyResourceData, false)
return obj.(*extensions.ThirdPartyResourceData), err
}
func (s *storage) UpdateThirdPartyResourceData(ctx genericapirequest.Context, ThirdPartyResourceData *extensions.ThirdPartyResourceData) (*extensions.ThirdPartyResourceData, error) {
obj, _, err := s.Update(ctx, ThirdPartyResourceData.Name, rest.DefaultUpdatedObjectInfo(ThirdPartyResourceData, api.Scheme))
return obj.(*extensions.ThirdPartyResourceData), err
}
func (s *storage) DeleteThirdPartyResourceData(ctx genericapirequest.Context, name string) error {
_, _, err := s.Delete(ctx, name, nil)
return err
}
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["storage_test.go"],
library = ":go_default_library",
tags = ["automanaged"],
deps = [
"//pkg/apis/extensions:go_default_library",
"//pkg/registry/registrytest:go_default_library",
"//vendor/k8s.io/api/extensions/v1beta1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/fields:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/labels:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/generic:go_default_library",
"//vendor/k8s.io/apiserver/pkg/storage/etcd/testing:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["storage.go"],
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/apis/extensions:go_default_library",
"//pkg/registry/cachesize:go_default_library",
"//pkg/registry/extensions/thirdpartyresourcedata:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/errors:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/request:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/generic:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/generic/registry:go_default_library",
"//vendor/k8s.io/apiserver/pkg/registry/rest:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
/*
Copyright 2015 The 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 storage
import (
"strings"
"sync/atomic"
"k8s.io/apimachinery/pkg/api/errors"
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/generic"
genericregistry "k8s.io/apiserver/pkg/registry/generic/registry"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/registry/cachesize"
"k8s.io/kubernetes/pkg/registry/extensions/thirdpartyresourcedata"
)
// errFrozen is a transient error to indicate that clients should retry with backoff.
var errFrozen = errors.NewServiceUnavailable("TPR data is temporarily frozen")
// REST implements a RESTStorage for ThirdPartyResourceData.
type REST struct {
*genericregistry.Store
kind string
frozen atomic.Value
}
// Freeze causes all future calls to Create/Update/Delete/DeleteCollection to return a transient error.
// This is irreversible and meant for use when the TPR data is being deleted or migrated/abandoned.
func (r *REST) Freeze() {
r.frozen.Store(true)
}
func (r *REST) isFrozen() bool {
return r.frozen.Load() != nil
}
// Create is a wrapper to support Freeze.
func (r *REST) Create(ctx genericapirequest.Context, obj runtime.Object, includeUninitialized bool) (runtime.Object, error) {
if r.isFrozen() {
return nil, errFrozen
}
return r.Store.Create(ctx, obj, includeUninitialized)
}
// Update is a wrapper to support Freeze.
func (r *REST) Update(ctx genericapirequest.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) {
if r.isFrozen() {
return nil, false, errFrozen
}
return r.Store.Update(ctx, name, objInfo)
}
// Delete is a wrapper to support Freeze.
func (r *REST) Delete(ctx genericapirequest.Context, name string, options *metav1.DeleteOptions) (runtime.Object, bool, error) {
if r.isFrozen() {
return nil, false, errFrozen
}
return r.Store.Delete(ctx, name, options)
}
// DeleteCollection is a wrapper to support Freeze.
func (r *REST) DeleteCollection(ctx genericapirequest.Context, options *metav1.DeleteOptions, listOptions *metainternalversion.ListOptions) (runtime.Object, error) {
if r.isFrozen() {
return nil, errFrozen
}
return r.Store.DeleteCollection(ctx, options, listOptions)
}
// NewREST returns a registry which will store ThirdPartyResourceData in the given helper
func NewREST(optsGetter generic.RESTOptionsGetter, group, kind string) *REST {
resource := extensions.Resource("thirdpartyresourcedatas")
opts, err := optsGetter.GetRESTOptions(resource)
if err != nil {
panic(err) // TODO: Propagate error up
}
// We explicitly do NOT do any decoration here yet.
opts.Decorator = generic.UndecoratedStorage // TODO use watchCacheSize=-1 to signal UndecoratedStorage
opts.ResourcePrefix = "/ThirdPartyResourceData/" + group + "/" + strings.ToLower(kind) + "s"
store := &genericregistry.Store{
Copier: api.Scheme,
NewFunc: func() runtime.Object { return &extensions.ThirdPartyResourceData{} },
NewListFunc: func() runtime.Object { return &extensions.ThirdPartyResourceDataList{} },
PredicateFunc: thirdpartyresourcedata.Matcher,
QualifiedResource: resource,
WatchCacheSize: cachesize.GetWatchCacheSizeByResource(resource.Resource),
CreateStrategy: thirdpartyresourcedata.Strategy,
UpdateStrategy: thirdpartyresourcedata.Strategy,
DeleteStrategy: thirdpartyresourcedata.Strategy,
}
options := &generic.StoreOptions{RESTOptions: opts, AttrFunc: thirdpartyresourcedata.GetAttrs} // Pass in opts to use UndecoratedStorage and custom ResourcePrefix
if err := store.CompleteWithOptions(options); err != nil {
panic(err) // TODO: Propagate error up
}
return &REST{
Store: store,
kind: kind,
}
}
// Implements the rest.KindProvider interface
func (r *REST) Kind() string {
return r.kind
}
/*
Copyright 2015 The 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 storage
import (
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/apis/extensions"
// Ensure that extensions/v1beta1 package is initialized.
_ "k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/registry/generic"
etcdtesting "k8s.io/apiserver/pkg/storage/etcd/testing"
"k8s.io/kubernetes/pkg/registry/registrytest"
)
func newStorage(t *testing.T) (*REST, *etcdtesting.EtcdTestServer) {
etcdStorage, server := registrytest.NewEtcdStorage(t, extensions.GroupName)
restOptions := generic.RESTOptions{StorageConfig: etcdStorage, Decorator: generic.UndecoratedStorage, DeleteCollectionWorkers: 1}
return NewREST(restOptions, "foo", "bar"), server
}
func validNewThirdPartyResourceData(name string) *extensions.ThirdPartyResourceData {
return &extensions.ThirdPartyResourceData{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: metav1.NamespaceDefault,
},
Data: []byte("foobarbaz"),
}
}
func TestCreate(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store)
rsrc := validNewThirdPartyResourceData("foo")
rsrc.ObjectMeta = metav1.ObjectMeta{}
test.TestCreate(
// valid
rsrc,
// invalid
&extensions.ThirdPartyResourceData{},
)
}
func TestUpdate(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store)
test.TestUpdate(
// valid
validNewThirdPartyResourceData("foo"),
// updateFunc
func(obj runtime.Object) runtime.Object {
object := obj.(*extensions.ThirdPartyResourceData)
object.Data = []byte("new description")
return object
},
)
}
func TestDelete(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store)
test.TestDelete(validNewThirdPartyResourceData("foo"))
}
func TestGet(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store)
test.TestGet(validNewThirdPartyResourceData("foo"))
}
func TestList(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store)
test.TestList(validNewThirdPartyResourceData("foo"))
}
func TestWatch(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
defer storage.Store.DestroyFunc()
test := registrytest.New(t, storage.Store)
test.TestWatch(
validNewThirdPartyResourceData("foo"),
// matching labels
[]labels.Set{},
// not matching labels
[]labels.Set{
{"foo": "bar"},
},
// matching fields
[]fields.Set{},
// not matching fields
[]fields.Set{
{"metadata.name": "bar"},
{"name": "foo"},
},
)
}
/*
Copyright 2015 The 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 thirdpartyresourcedata
import (
"fmt"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
apistorage "k8s.io/apiserver/pkg/storage"
"k8s.io/apiserver/pkg/storage/names"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/apis/extensions/validation"
)
// strategy implements behavior for ThirdPartyResource objects
type strategy struct {
runtime.ObjectTyper
names.NameGenerator
}
// Strategy is the default logic that applies when creating and updating ThirdPartyResource
// objects via the REST API.
var Strategy = strategy{api.Scheme, names.SimpleNameGenerator}
var _ = rest.RESTCreateStrategy(Strategy)
var _ = rest.RESTUpdateStrategy(Strategy)
func (strategy) NamespaceScoped() bool {
return true
}
func (strategy) PrepareForCreate(ctx genericapirequest.Context, obj runtime.Object) {
}
func (strategy) Validate(ctx genericapirequest.Context, obj runtime.Object) field.ErrorList {
return validation.ValidateThirdPartyResourceData(obj.(*extensions.ThirdPartyResourceData))
}
// Canonicalize normalizes the object after validation.
func (strategy) Canonicalize(obj runtime.Object) {
}
func (strategy) AllowCreateOnUpdate() bool {
return false
}
func (strategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) {
}
func (strategy) ValidateUpdate(ctx genericapirequest.Context, obj, old runtime.Object) field.ErrorList {
return validation.ValidateThirdPartyResourceDataUpdate(obj.(*extensions.ThirdPartyResourceData), old.(*extensions.ThirdPartyResourceData))
}
func (strategy) AllowUnconditionalUpdate() bool {
return true
}
// GetAttrs returns labels and fields of a given object for filtering purposes.
func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, bool, error) {
tprd, ok := obj.(*extensions.ThirdPartyResourceData)
if !ok {
return nil, nil, false, fmt.Errorf("not a ThirdPartyResourceData")
}
return labels.Set(tprd.Labels), SelectableFields(tprd), tprd.Initializers != nil, nil
}
// Matcher returns a generic matcher for a given label and field selector.
func Matcher(label labels.Selector, field fields.Selector) apistorage.SelectionPredicate {
return apistorage.SelectionPredicate{
Label: label,
Field: field,
GetAttrs: GetAttrs,
}
}
// SelectableFields returns a field set that can be used for filter selection
func SelectableFields(obj *extensions.ThirdPartyResourceData) fields.Set {
return nil
}
/*
Copyright 2015 The 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 thirdpartyresourcedata
import (
"testing"
_ "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/testapi"
apitesting "k8s.io/kubernetes/pkg/api/testing"
"k8s.io/kubernetes/pkg/apis/extensions"
)
func TestSelectableFieldLabelConversions(t *testing.T) {
apitesting.TestSelectableFieldLabelConversionsOfKind(t,
testapi.Extensions.GroupVersion().String(),
"ThirdPartyResourceData",
SelectableFields(&extensions.ThirdPartyResourceData{}),
nil,
)
}
/*
Copyright 2015 The 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 thirdpartyresourcedata
import (
"fmt"
"strings"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/kubernetes/pkg/apis/extensions"
)
func ExtractGroupVersionKind(list *extensions.ThirdPartyResourceList) ([]schema.GroupVersion, []schema.GroupVersionKind, error) {
gvs := []schema.GroupVersion{}
gvks := []schema.GroupVersionKind{}
for ix := range list.Items {
rsrc := &list.Items[ix]
kind, group, err := ExtractApiGroupAndKind(rsrc)
if err != nil {
return nil, nil, err
}
for _, version := range rsrc.Versions {
gv := schema.GroupVersion{Group: group, Version: version.Name}
gvs = append(gvs, gv)
gvks = append(gvks, schema.GroupVersionKind{Group: group, Version: version.Name, Kind: kind})
}
}
return gvs, gvks, nil
}
func convertToCamelCase(input string) string {
result := ""
toUpper := true
for ix := range input {
char := input[ix]
if toUpper {
result = result + string([]byte{(char - 32)})
toUpper = false
} else if char == '-' {
toUpper = true
} else {
result = result + string([]byte{char})
}
}
return result
}
func ExtractApiGroupAndKind(rsrc *extensions.ThirdPartyResource) (kind string, group string, err error) {
parts := strings.Split(rsrc.Name, ".")
if len(parts) < 3 {
return "", "", fmt.Errorf("unexpectedly short resource name: %s, expected at least <kind>.<domain>.<tld>", rsrc.Name)
}
return convertToCamelCase(parts[0]), strings.Join(parts[1:], "."), nil
}
/*
Copyright 2015 The 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 thirdpartyresourcedata
import (
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/apis/extensions"
)
func TestExtractAPIGroupAndKind(t *testing.T) {
tests := []struct {
input string
expectedKind string
expectedGroup string
expectErr bool
}{
{
input: "foo.company.com",
expectedKind: "Foo",
expectedGroup: "company.com",
},
{
input: "cron-tab.company.com",
expectedKind: "CronTab",
expectedGroup: "company.com",
},
{
input: "foo",
expectErr: true,
},
}
for _, test := range tests {
kind, group, err := ExtractApiGroupAndKind(&extensions.ThirdPartyResource{ObjectMeta: metav1.ObjectMeta{Name: test.input}})
if err != nil && !test.expectErr {
t.Errorf("unexpected error: %v", err)
continue
}
if err == nil && test.expectErr {
t.Errorf("unexpected non-error")
continue
}
if kind != test.expectedKind {
t.Errorf("expected: %s, saw: %s", test.expectedKind, kind)
}
if group != test.expectedGroup {
t.Errorf("expected: %s, saw: %s", test.expectedGroup, group)
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment