Switch to github.com/golang/dep for vendoring

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
This commit is contained in:
Mrunal Patel 2017-01-31 16:45:59 -08:00
parent d6ab91be27
commit 8e5b17cf13
15431 changed files with 3971413 additions and 8881 deletions

11
vendor/k8s.io/kubernetes/pkg/client/testing/OWNERS generated vendored Executable file
View file

@ -0,0 +1,11 @@
reviewers:
- smarterclayton
- wojtek-t
- caesarxuchao
- mikedanese
- pmorie
- saad-ali
- krousey
- '249043822'
- lixiaobing10051267
- goltermann

View file

@ -0,0 +1,48 @@
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 = ["fake_controller_source.go"],
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/api/v1:go_default_library",
"//vendor:k8s.io/apimachinery/pkg/api/meta",
"//vendor:k8s.io/apimachinery/pkg/runtime",
"//vendor:k8s.io/apimachinery/pkg/types",
"//vendor:k8s.io/apimachinery/pkg/watch",
],
)
go_test(
name = "go_default_test",
srcs = ["fake_controller_source_test.go"],
library = ":go_default_library",
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/api/v1:go_default_library",
"//vendor:k8s.io/apimachinery/pkg/watch",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View file

@ -0,0 +1,263 @@
/*
Copyright 2015 The 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 framework
import (
"errors"
"math/rand"
"strconv"
"sync"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/v1"
)
func NewFakeControllerSource() *FakeControllerSource {
return &FakeControllerSource{
Items: map[nnu]runtime.Object{},
Broadcaster: watch.NewBroadcaster(100, watch.WaitIfChannelFull),
}
}
func NewFakePVControllerSource() *FakePVControllerSource {
return &FakePVControllerSource{
FakeControllerSource{
Items: map[nnu]runtime.Object{},
Broadcaster: watch.NewBroadcaster(100, watch.WaitIfChannelFull),
}}
}
func NewFakePVCControllerSource() *FakePVCControllerSource {
return &FakePVCControllerSource{
FakeControllerSource{
Items: map[nnu]runtime.Object{},
Broadcaster: watch.NewBroadcaster(100, watch.WaitIfChannelFull),
}}
}
// FakeControllerSource implements listing/watching for testing.
type FakeControllerSource struct {
lock sync.RWMutex
Items map[nnu]runtime.Object
changes []watch.Event // one change per resourceVersion
Broadcaster *watch.Broadcaster
}
type FakePVControllerSource struct {
FakeControllerSource
}
type FakePVCControllerSource struct {
FakeControllerSource
}
// namespace, name, uid to be used as a key.
type nnu struct {
namespace, name string
uid types.UID
}
// Add adds an object to the set and sends an add event to watchers.
// obj's ResourceVersion is set.
func (f *FakeControllerSource) Add(obj runtime.Object) {
f.Change(watch.Event{Type: watch.Added, Object: obj}, 1)
}
// Modify updates an object in the set and sends a modified event to watchers.
// obj's ResourceVersion is set.
func (f *FakeControllerSource) Modify(obj runtime.Object) {
f.Change(watch.Event{Type: watch.Modified, Object: obj}, 1)
}
// Delete deletes an object from the set and sends a delete event to watchers.
// obj's ResourceVersion is set.
func (f *FakeControllerSource) Delete(lastValue runtime.Object) {
f.Change(watch.Event{Type: watch.Deleted, Object: lastValue}, 1)
}
// AddDropWatch adds an object to the set but forgets to send an add event to
// watchers.
// obj's ResourceVersion is set.
func (f *FakeControllerSource) AddDropWatch(obj runtime.Object) {
f.Change(watch.Event{Type: watch.Added, Object: obj}, 0)
}
// ModifyDropWatch updates an object in the set but forgets to send a modify
// event to watchers.
// obj's ResourceVersion is set.
func (f *FakeControllerSource) ModifyDropWatch(obj runtime.Object) {
f.Change(watch.Event{Type: watch.Modified, Object: obj}, 0)
}
// DeleteDropWatch deletes an object from the set but forgets to send a delete
// event to watchers.
// obj's ResourceVersion is set.
func (f *FakeControllerSource) DeleteDropWatch(lastValue runtime.Object) {
f.Change(watch.Event{Type: watch.Deleted, Object: lastValue}, 0)
}
func (f *FakeControllerSource) key(accessor meta.Object) nnu {
return nnu{accessor.GetNamespace(), accessor.GetName(), accessor.GetUID()}
}
// Change records the given event (setting the object's resource version) and
// sends a watch event with the specified probability.
func (f *FakeControllerSource) Change(e watch.Event, watchProbability float64) {
f.lock.Lock()
defer f.lock.Unlock()
accessor, err := meta.Accessor(e.Object)
if err != nil {
panic(err) // this is test code only
}
resourceVersion := len(f.changes) + 1
accessor.SetResourceVersion(strconv.Itoa(resourceVersion))
f.changes = append(f.changes, e)
key := f.key(accessor)
switch e.Type {
case watch.Added, watch.Modified:
f.Items[key] = e.Object
case watch.Deleted:
delete(f.Items, key)
}
if rand.Float64() < watchProbability {
f.Broadcaster.Action(e.Type, e.Object)
}
}
func (f *FakeControllerSource) getListItemsLocked() ([]runtime.Object, error) {
list := make([]runtime.Object, 0, len(f.Items))
for _, obj := range f.Items {
// Must make a copy to allow clients to modify the object.
// Otherwise, if they make a change and write it back, they
// will inadvertently change our canonical copy (in
// addition to racing with other clients).
objCopy, err := api.Scheme.DeepCopy(obj)
if err != nil {
return nil, err
}
list = append(list, objCopy.(runtime.Object))
}
return list, nil
}
// List returns a list object, with its resource version set.
func (f *FakeControllerSource) List(options v1.ListOptions) (runtime.Object, error) {
f.lock.RLock()
defer f.lock.RUnlock()
list, err := f.getListItemsLocked()
if err != nil {
return nil, err
}
listObj := &api.List{}
if err := meta.SetList(listObj, list); err != nil {
return nil, err
}
objMeta, err := api.ListMetaFor(listObj)
if err != nil {
return nil, err
}
resourceVersion := len(f.changes)
objMeta.ResourceVersion = strconv.Itoa(resourceVersion)
return listObj, nil
}
// List returns a list object, with its resource version set.
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 := &v1.PersistentVolumeList{}
if err := meta.SetList(listObj, list); err != nil {
return nil, err
}
objMeta, err := api.ListMetaFor(listObj)
if err != nil {
return nil, err
}
resourceVersion := len(f.changes)
objMeta.ResourceVersion = strconv.Itoa(resourceVersion)
return listObj, nil
}
// List returns a list object, with its resource version set.
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 := &v1.PersistentVolumeClaimList{}
if err := meta.SetList(listObj, list); err != nil {
return nil, err
}
objMeta, err := api.ListMetaFor(listObj)
if err != nil {
return nil, err
}
resourceVersion := len(f.changes)
objMeta.ResourceVersion = strconv.Itoa(resourceVersion)
return listObj, nil
}
// Watch returns a watch, which will be pre-populated with all changes
// after resourceVersion.
func (f *FakeControllerSource) Watch(options v1.ListOptions) (watch.Interface, error) {
f.lock.RLock()
defer f.lock.RUnlock()
rc, err := strconv.Atoi(options.ResourceVersion)
if err != nil {
return nil, err
}
if rc < len(f.changes) {
changes := []watch.Event{}
for _, c := range f.changes[rc:] {
// Must make a copy to allow clients to modify the
// object. Otherwise, if they make a change and write
// it back, they will inadvertently change the our
// canonical copy (in addition to racing with other
// clients).
objCopy, err := api.Scheme.DeepCopy(c.Object)
if err != nil {
return nil, err
}
changes = append(changes, watch.Event{Type: c.Type, Object: objCopy.(runtime.Object)})
}
return f.Broadcaster.WatchWithPrefix(changes), nil
} else if rc > len(f.changes) {
return nil, errors.New("resource version in the future not supported by this fake")
}
return f.Broadcaster.Watch(), nil
}
// Shutdown closes the underlying broadcaster, waiting for events to be
// delivered. It's an error to call any method after calling shutdown. This is
// enforced by Shutdown() leaving f locked.
func (f *FakeControllerSource) Shutdown() {
f.lock.Lock() // Purposely no unlock.
f.Broadcaster.Shutdown()
}

View file

@ -0,0 +1,95 @@
/*
Copyright 2015 The 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 framework
import (
"sync"
"testing"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/v1"
)
// ensure the watch delivers the requested and only the requested items.
func consume(t *testing.T, w watch.Interface, rvs []string, done *sync.WaitGroup) {
defer done.Done()
for _, rv := range rvs {
got, ok := <-w.ResultChan()
if !ok {
t.Errorf("%#v: unexpected channel close, wanted %v", rvs, rv)
return
}
gotRV := got.Object.(*v1.Pod).ObjectMeta.ResourceVersion
if e, a := rv, gotRV; e != a {
t.Errorf("wanted %v, got %v", e, a)
} else {
t.Logf("Got %v as expected", gotRV)
}
}
// We should not get anything else.
got, open := <-w.ResultChan()
if open {
t.Errorf("%#v: unwanted object %#v", rvs, got)
}
}
func TestRCNumber(t *testing.T) {
pod := func(name string) *v1.Pod {
return &v1.Pod{
ObjectMeta: v1.ObjectMeta{
Name: name,
},
}
}
wg := &sync.WaitGroup{}
wg.Add(3)
source := NewFakeControllerSource()
source.Add(pod("foo"))
source.Modify(pod("foo"))
source.Modify(pod("foo"))
w, err := source.Watch(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(v1.ListOptions{})
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if e, a := "3", list.(*api.List).ResourceVersion; e != a {
t.Errorf("wanted %v, got %v", e, a)
}
w2, err := source.Watch(v1.ListOptions{ResourceVersion: "2"})
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
go consume(t, w2, []string{"3"}, wg)
w3, err := source.Watch(v1.ListOptions{ResourceVersion: "3"})
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
go consume(t, w3, []string{}, wg)
source.Shutdown()
wg.Wait()
}

57
vendor/k8s.io/kubernetes/pkg/client/testing/core/BUILD generated vendored Normal file
View file

@ -0,0 +1,57 @@
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 = [
"actions.go",
"fake.go",
"fixture.go",
],
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/api/v1:go_default_library",
"//pkg/client/restclient:go_default_library",
"//pkg/fields:go_default_library",
"//pkg/version:go_default_library",
"//vendor:k8s.io/apimachinery/pkg/api/errors",
"//vendor:k8s.io/apimachinery/pkg/api/meta",
"//vendor:k8s.io/apimachinery/pkg/apis/meta/v1",
"//vendor:k8s.io/apimachinery/pkg/labels",
"//vendor:k8s.io/apimachinery/pkg/runtime",
"//vendor:k8s.io/apimachinery/pkg/runtime/schema",
"//vendor:k8s.io/apimachinery/pkg/watch",
],
)
go_test(
name = "go_default_xtest",
srcs = ["fake_test.go"],
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/client/clientset_generated/internalclientset/fake:go_default_library",
"//vendor:k8s.io/apimachinery/pkg/apis/meta/v1",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View file

@ -0,0 +1,476 @@
/*
Copyright 2015 The 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 core
import (
"fmt"
"path"
"strings"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/v1"
"k8s.io/kubernetes/pkg/fields"
)
func NewRootGetAction(resource schema.GroupVersionResource, name string) GetActionImpl {
action := GetActionImpl{}
action.Verb = "get"
action.Resource = resource
action.Name = name
return action
}
func NewGetAction(resource schema.GroupVersionResource, namespace, name string) GetActionImpl {
action := GetActionImpl{}
action.Verb = "get"
action.Resource = resource
action.Namespace = namespace
action.Name = name
return action
}
func NewRootListAction(resource schema.GroupVersionResource, opts interface{}) ListActionImpl {
action := ListActionImpl{}
action.Verb = "list"
action.Resource = resource
labelSelector, fieldSelector, _ := ExtractFromListOptions(opts)
action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector}
return action
}
func NewListAction(resource schema.GroupVersionResource, namespace string, opts interface{}) ListActionImpl {
action := ListActionImpl{}
action.Verb = "list"
action.Resource = resource
action.Namespace = namespace
labelSelector, fieldSelector, _ := ExtractFromListOptions(opts)
action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector}
return action
}
func NewRootCreateAction(resource schema.GroupVersionResource, object runtime.Object) CreateActionImpl {
action := CreateActionImpl{}
action.Verb = "create"
action.Resource = resource
action.Object = object
return action
}
func NewCreateAction(resource schema.GroupVersionResource, namespace string, object runtime.Object) CreateActionImpl {
action := CreateActionImpl{}
action.Verb = "create"
action.Resource = resource
action.Namespace = namespace
action.Object = object
return action
}
func NewRootUpdateAction(resource schema.GroupVersionResource, object runtime.Object) UpdateActionImpl {
action := UpdateActionImpl{}
action.Verb = "update"
action.Resource = resource
action.Object = object
return action
}
func NewUpdateAction(resource schema.GroupVersionResource, namespace string, object runtime.Object) UpdateActionImpl {
action := UpdateActionImpl{}
action.Verb = "update"
action.Resource = resource
action.Namespace = namespace
action.Object = object
return action
}
func NewRootPatchAction(resource schema.GroupVersionResource, name string, patch []byte) PatchActionImpl {
action := PatchActionImpl{}
action.Verb = "patch"
action.Resource = resource
action.Name = name
action.Patch = patch
return action
}
func NewPatchAction(resource schema.GroupVersionResource, namespace string, name string, patch []byte) PatchActionImpl {
action := PatchActionImpl{}
action.Verb = "patch"
action.Resource = resource
action.Namespace = namespace
action.Name = name
action.Patch = patch
return action
}
func NewRootPatchSubresourceAction(resource schema.GroupVersionResource, name string, patch []byte, subresources ...string) PatchActionImpl {
action := PatchActionImpl{}
action.Verb = "patch"
action.Resource = resource
action.Subresource = path.Join(subresources...)
action.Name = name
action.Patch = patch
return action
}
func NewPatchSubresourceAction(resource schema.GroupVersionResource, namespace, name string, patch []byte, subresources ...string) PatchActionImpl {
action := PatchActionImpl{}
action.Verb = "patch"
action.Resource = resource
action.Subresource = path.Join(subresources...)
action.Namespace = namespace
action.Name = name
action.Patch = patch
return action
}
func NewRootUpdateSubresourceAction(resource schema.GroupVersionResource, subresource string, object runtime.Object) UpdateActionImpl {
action := UpdateActionImpl{}
action.Verb = "update"
action.Resource = resource
action.Subresource = subresource
action.Object = object
return action
}
func NewUpdateSubresourceAction(resource schema.GroupVersionResource, subresource string, namespace string, object runtime.Object) UpdateActionImpl {
action := UpdateActionImpl{}
action.Verb = "update"
action.Resource = resource
action.Subresource = subresource
action.Namespace = namespace
action.Object = object
return action
}
func NewRootDeleteAction(resource schema.GroupVersionResource, name string) DeleteActionImpl {
action := DeleteActionImpl{}
action.Verb = "delete"
action.Resource = resource
action.Name = name
return action
}
func NewDeleteAction(resource schema.GroupVersionResource, namespace, name string) DeleteActionImpl {
action := DeleteActionImpl{}
action.Verb = "delete"
action.Resource = resource
action.Namespace = namespace
action.Name = name
return action
}
func NewRootDeleteCollectionAction(resource schema.GroupVersionResource, opts interface{}) DeleteCollectionActionImpl {
action := DeleteCollectionActionImpl{}
action.Verb = "delete-collection"
action.Resource = resource
labelSelector, fieldSelector, _ := ExtractFromListOptions(opts)
action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector}
return action
}
func NewDeleteCollectionAction(resource schema.GroupVersionResource, namespace string, opts interface{}) DeleteCollectionActionImpl {
action := DeleteCollectionActionImpl{}
action.Verb = "delete-collection"
action.Resource = resource
action.Namespace = namespace
labelSelector, fieldSelector, _ := ExtractFromListOptions(opts)
action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector}
return action
}
func NewRootWatchAction(resource schema.GroupVersionResource, opts interface{}) WatchActionImpl {
action := WatchActionImpl{}
action.Verb = "watch"
action.Resource = resource
labelSelector, fieldSelector, resourceVersion := ExtractFromListOptions(opts)
action.WatchRestrictions = WatchRestrictions{labelSelector, fieldSelector, resourceVersion}
return action
}
func ExtractFromListOptions(opts interface{}) (labelSelector labels.Selector, fieldSelector fields.Selector, resourceVersion string) {
var err error
switch t := opts.(type) {
case api.ListOptions:
labelSelector = t.LabelSelector
fieldSelector = t.FieldSelector
resourceVersion = t.ResourceVersion
case v1.ListOptions:
labelSelector, err = labels.Parse(t.LabelSelector)
if err != nil {
panic(err)
}
fieldSelector, err = fields.ParseSelector(t.FieldSelector)
if err != nil {
panic(err)
}
resourceVersion = t.ResourceVersion
default:
panic(fmt.Errorf("expect a ListOptions"))
}
if labelSelector == nil {
labelSelector = labels.Everything()
}
if fieldSelector == nil {
fieldSelector = fields.Everything()
}
return labelSelector, fieldSelector, resourceVersion
}
func NewWatchAction(resource schema.GroupVersionResource, namespace string, opts interface{}) WatchActionImpl {
action := WatchActionImpl{}
action.Verb = "watch"
action.Resource = resource
action.Namespace = namespace
labelSelector, fieldSelector, resourceVersion := ExtractFromListOptions(opts)
action.WatchRestrictions = WatchRestrictions{labelSelector, fieldSelector, resourceVersion}
return action
}
func NewProxyGetAction(resource schema.GroupVersionResource, namespace, scheme, name, port, path string, params map[string]string) ProxyGetActionImpl {
action := ProxyGetActionImpl{}
action.Verb = "get"
action.Resource = resource
action.Namespace = namespace
action.Scheme = scheme
action.Name = name
action.Port = port
action.Path = path
action.Params = params
return action
}
type ListRestrictions struct {
Labels labels.Selector
Fields fields.Selector
}
type WatchRestrictions struct {
Labels labels.Selector
Fields fields.Selector
ResourceVersion string
}
type Action interface {
GetNamespace() string
GetVerb() string
GetResource() schema.GroupVersionResource
GetSubresource() string
Matches(verb, resource string) bool
}
type GenericAction interface {
Action
GetValue() interface{}
}
type GetAction interface {
Action
GetName() string
}
type ListAction interface {
Action
GetListRestrictions() ListRestrictions
}
type CreateAction interface {
Action
GetObject() runtime.Object
}
type UpdateAction interface {
Action
GetObject() runtime.Object
}
type DeleteAction interface {
Action
GetName() string
}
type WatchAction interface {
Action
GetWatchRestrictions() WatchRestrictions
}
type ProxyGetAction interface {
Action
GetScheme() string
GetName() string
GetPort() string
GetPath() string
GetParams() map[string]string
}
type ActionImpl struct {
Namespace string
Verb string
Resource schema.GroupVersionResource
Subresource string
}
func (a ActionImpl) GetNamespace() string {
return a.Namespace
}
func (a ActionImpl) GetVerb() string {
return a.Verb
}
func (a ActionImpl) GetResource() schema.GroupVersionResource {
return a.Resource
}
func (a ActionImpl) GetSubresource() string {
return a.Subresource
}
func (a ActionImpl) Matches(verb, resource string) bool {
return strings.ToLower(verb) == strings.ToLower(a.Verb) &&
strings.ToLower(resource) == strings.ToLower(a.Resource.Resource)
}
type GenericActionImpl struct {
ActionImpl
Value interface{}
}
func (a GenericActionImpl) GetValue() interface{} {
return a.Value
}
type GetActionImpl struct {
ActionImpl
Name string
}
func (a GetActionImpl) GetName() string {
return a.Name
}
type ListActionImpl struct {
ActionImpl
ListRestrictions ListRestrictions
}
func (a ListActionImpl) GetListRestrictions() ListRestrictions {
return a.ListRestrictions
}
type CreateActionImpl struct {
ActionImpl
Object runtime.Object
}
func (a CreateActionImpl) GetObject() runtime.Object {
return a.Object
}
type UpdateActionImpl struct {
ActionImpl
Object runtime.Object
}
func (a UpdateActionImpl) GetObject() runtime.Object {
return a.Object
}
type PatchActionImpl struct {
ActionImpl
Name string
Patch []byte
}
func (a PatchActionImpl) GetName() string {
return a.Name
}
func (a PatchActionImpl) GetPatch() []byte {
return a.Patch
}
type DeleteActionImpl struct {
ActionImpl
Name string
}
func (a DeleteActionImpl) GetName() string {
return a.Name
}
type DeleteCollectionActionImpl struct {
ActionImpl
ListRestrictions ListRestrictions
}
func (a DeleteCollectionActionImpl) GetListRestrictions() ListRestrictions {
return a.ListRestrictions
}
type WatchActionImpl struct {
ActionImpl
WatchRestrictions WatchRestrictions
}
func (a WatchActionImpl) GetWatchRestrictions() WatchRestrictions {
return a.WatchRestrictions
}
type ProxyGetActionImpl struct {
ActionImpl
Scheme string
Name string
Port string
Path string
Params map[string]string
}
func (a ProxyGetActionImpl) GetScheme() string {
return a.Scheme
}
func (a ProxyGetActionImpl) GetName() string {
return a.Name
}
func (a ProxyGetActionImpl) GetPort() string {
return a.Port
}
func (a ProxyGetActionImpl) GetPath() string {
return a.Path
}
func (a ProxyGetActionImpl) GetParams() map[string]string {
return a.Params
}

View file

@ -0,0 +1,258 @@
/*
Copyright 2016 The 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 core
import (
"fmt"
"sync"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/kubernetes/pkg/client/restclient"
"k8s.io/kubernetes/pkg/version"
)
// Fake implements client.Interface. Meant to be embedded into a struct to get
// a default implementation. This makes faking out just the method you want to
// test easier.
type Fake struct {
sync.RWMutex
actions []Action // these may be castable to other types, but "Action" is the minimum
// ReactionChain is the list of reactors that will be attempted for every
// request in the order they are tried.
ReactionChain []Reactor
// WatchReactionChain is the list of watch reactors that will be attempted
// for every request in the order they are tried.
WatchReactionChain []WatchReactor
// ProxyReactionChain is the list of proxy reactors that will be attempted
// for every request in the order they are tried.
ProxyReactionChain []ProxyReactor
Resources []*metav1.APIResourceList
}
// Reactor is an interface to allow the composition of reaction functions.
type Reactor interface {
// Handles indicates whether or not this Reactor deals with a given
// action.
Handles(action Action) bool
// React handles the action and returns results. It may choose to
// delegate by indicated handled=false.
React(action Action) (handled bool, ret runtime.Object, err error)
}
// WatchReactor is an interface to allow the composition of watch functions.
type WatchReactor interface {
// Handles indicates whether or not this Reactor deals with a given
// action.
Handles(action Action) bool
// React handles a watch action and returns results. It may choose to
// delegate by indicating handled=false.
React(action Action) (handled bool, ret watch.Interface, err error)
}
// ProxyReactor is an interface to allow the composition of proxy get
// functions.
type ProxyReactor interface {
// Handles indicates whether or not this Reactor deals with a given
// action.
Handles(action Action) bool
// React handles a watch action and returns results. It may choose to
// delegate by indicating handled=false.
React(action Action) (handled bool, ret restclient.ResponseWrapper, err error)
}
// ReactionFunc is a function that returns an object or error for a given
// Action. If "handled" is false, then the test client will ignore the
// results and continue to the next ReactionFunc. A ReactionFunc can describe
// reactions on subresources by testing the result of the action's
// GetSubresource() method.
type ReactionFunc func(action Action) (handled bool, ret runtime.Object, err error)
// WatchReactionFunc is a function that returns a watch interface. If
// "handled" is false, then the test client will ignore the results and
// continue to the next ReactionFunc.
type WatchReactionFunc func(action Action) (handled bool, ret watch.Interface, err error)
// ProxyReactionFunc is a function that returns a ResponseWrapper interface
// for a given Action. If "handled" is false, then the test client will
// ignore the results and continue to the next ProxyReactionFunc.
type ProxyReactionFunc func(action Action) (handled bool, ret restclient.ResponseWrapper, err error)
// AddReactor appends a reactor to the end of the chain.
func (c *Fake) AddReactor(verb, resource string, reaction ReactionFunc) {
c.ReactionChain = append(c.ReactionChain, &SimpleReactor{verb, resource, reaction})
}
// PrependReactor adds a reactor to the beginning of the chain.
func (c *Fake) PrependReactor(verb, resource string, reaction ReactionFunc) {
c.ReactionChain = append([]Reactor{&SimpleReactor{verb, resource, reaction}}, c.ReactionChain...)
}
// AddWatchReactor appends a reactor to the end of the chain.
func (c *Fake) AddWatchReactor(resource string, reaction WatchReactionFunc) {
c.WatchReactionChain = append(c.WatchReactionChain, &SimpleWatchReactor{resource, reaction})
}
// PrependWatchReactor adds a reactor to the beginning of the chain.
func (c *Fake) PrependWatchReactor(resource string, reaction WatchReactionFunc) {
c.WatchReactionChain = append([]WatchReactor{&SimpleWatchReactor{resource, reaction}}, c.WatchReactionChain...)
}
// AddProxyReactor appends a reactor to the end of the chain.
func (c *Fake) AddProxyReactor(resource string, reaction ProxyReactionFunc) {
c.ProxyReactionChain = append(c.ProxyReactionChain, &SimpleProxyReactor{resource, reaction})
}
// PrependProxyReactor adds a reactor to the beginning of the chain.
func (c *Fake) PrependProxyReactor(resource string, reaction ProxyReactionFunc) {
c.ProxyReactionChain = append([]ProxyReactor{&SimpleProxyReactor{resource, reaction}}, c.ProxyReactionChain...)
}
// Invokes records the provided Action and then invokes the ReactionFunc that
// handles the action if one exists. defaultReturnObj is expected to be of the
// same type a normal call would return.
func (c *Fake) Invokes(action Action, defaultReturnObj runtime.Object) (runtime.Object, error) {
c.Lock()
defer c.Unlock()
c.actions = append(c.actions, action)
for _, reactor := range c.ReactionChain {
if !reactor.Handles(action) {
continue
}
handled, ret, err := reactor.React(action)
if !handled {
continue
}
return ret, err
}
return defaultReturnObj, nil
}
// InvokesWatch records the provided Action and then invokes the ReactionFunc
// that handles the action if one exists.
func (c *Fake) InvokesWatch(action Action) (watch.Interface, error) {
c.Lock()
defer c.Unlock()
c.actions = append(c.actions, action)
for _, reactor := range c.WatchReactionChain {
if !reactor.Handles(action) {
continue
}
handled, ret, err := reactor.React(action)
if !handled {
continue
}
return ret, err
}
return nil, fmt.Errorf("unhandled watch: %#v", action)
}
// InvokesProxy records the provided Action and then invokes the ReactionFunc
// that handles the action if one exists.
func (c *Fake) InvokesProxy(action Action) restclient.ResponseWrapper {
c.Lock()
defer c.Unlock()
c.actions = append(c.actions, action)
for _, reactor := range c.ProxyReactionChain {
if !reactor.Handles(action) {
continue
}
handled, ret, err := reactor.React(action)
if !handled || err != nil {
continue
}
return ret
}
return nil
}
// ClearActions clears the history of actions called on the fake client.
func (c *Fake) ClearActions() {
c.Lock()
defer c.Unlock()
c.actions = make([]Action, 0)
}
// Actions returns a chronologically ordered slice fake actions called on the
// fake client.
func (c *Fake) Actions() []Action {
c.RLock()
defer c.RUnlock()
fa := make([]Action, len(c.actions))
copy(fa, c.actions)
return fa
}
// TODO: this probably should be moved to somewhere else.
type FakeDiscovery struct {
*Fake
}
func (c *FakeDiscovery) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) {
action := ActionImpl{
Verb: "get",
Resource: schema.GroupVersionResource{Resource: "resource"},
}
c.Invokes(action, nil)
for _, rl := range c.Resources {
if rl.GroupVersion == groupVersion {
return rl, nil
}
}
return nil, fmt.Errorf("GroupVersion %q not found", groupVersion)
}
func (c *FakeDiscovery) ServerResources() ([]*metav1.APIResourceList, error) {
action := ActionImpl{
Verb: "get",
Resource: schema.GroupVersionResource{Resource: "resource"},
}
c.Invokes(action, nil)
return c.Resources, nil
}
func (c *FakeDiscovery) ServerGroups() (*metav1.APIGroupList, error) {
return nil, nil
}
func (c *FakeDiscovery) ServerVersion() (*version.Info, error) {
action := ActionImpl{}
action.Verb = "get"
action.Resource = schema.GroupVersionResource{Resource: "version"}
c.Invokes(action, nil)
versionInfo := version.Get()
return &versionInfo, nil
}

View file

@ -0,0 +1,180 @@
/*
Copyright 2016 The 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 core_test
import (
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/api"
clientsetfake "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake"
)
func TestFakeClientSetFiltering(t *testing.T) {
tc := clientsetfake.NewSimpleClientset(
testPod("nsA", "pod-1"),
testPod("nsB", "pod-2"),
testSA("nsA", "sa-1"),
testSA("nsA", "sa-2"),
testSA("nsB", "sa-1"),
testSA("nsB", "sa-2"),
testSA("nsB", "sa-3"),
)
saList1, err := tc.Core().ServiceAccounts("nsA").List(api.ListOptions{})
if err != nil {
t.Fatalf("ServiceAccounts.List: %s", err)
}
if actual, expected := len(saList1.Items), 2; expected != actual {
t.Fatalf("Expected %d records to match, got %d", expected, actual)
}
for _, sa := range saList1.Items {
if sa.Namespace != "nsA" {
t.Fatalf("Expected namespace %q; got %q", "nsA", sa.Namespace)
}
}
saList2, err := tc.Core().ServiceAccounts("nsB").List(api.ListOptions{})
if err != nil {
t.Fatalf("ServiceAccounts.List: %s", err)
}
if actual, expected := len(saList2.Items), 3; expected != actual {
t.Fatalf("Expected %d records to match, got %d", expected, actual)
}
for _, sa := range saList2.Items {
if sa.Namespace != "nsB" {
t.Fatalf("Expected namespace %q; got %q", "nsA", sa.Namespace)
}
}
pod1, err := tc.Core().Pods("nsA").Get("pod-1", metav1.GetOptions{})
if err != nil {
t.Fatalf("Pods.Get: %s", err)
}
if pod1 == nil {
t.Fatalf("Expected to find pod nsA/pod-1 but it wasn't found")
}
if pod1.Namespace != "nsA" || pod1.Name != "pod-1" {
t.Fatalf("Expected to find pod nsA/pod-1t, got %s/%s", pod1.Namespace, pod1.Name)
}
wrongPod, err := tc.Core().Pods("nsB").Get("pod-1", metav1.GetOptions{})
if err == nil {
t.Fatalf("Pods.Get: expected nsB/pod-1 not to match, but it matched %s/%s", wrongPod.Namespace, wrongPod.Name)
}
allPods, err := tc.Core().Pods(api.NamespaceAll).List(api.ListOptions{})
if err != nil {
t.Fatalf("Pods.List: %s", err)
}
if actual, expected := len(allPods.Items), 2; expected != actual {
t.Fatalf("Expected %d pods to match, got %d", expected, actual)
}
allSAs, err := tc.Core().ServiceAccounts(api.NamespaceAll).List(api.ListOptions{})
if err != nil {
t.Fatalf("ServiceAccounts.List: %s", err)
}
if actual, expected := len(allSAs.Items), 5; expected != actual {
t.Fatalf("Expected %d service accounts to match, got %d", expected, actual)
}
}
func TestFakeClientsetInheritsNamespace(t *testing.T) {
tc := clientsetfake.NewSimpleClientset(
testNamespace("nsA"),
testPod("nsA", "pod-1"),
)
_, err := tc.Core().Namespaces().Create(testNamespace("nsB"))
if err != nil {
t.Fatalf("Namespaces.Create: %s", err)
}
allNS, err := tc.Core().Namespaces().List(api.ListOptions{})
if err != nil {
t.Fatalf("Namespaces.List: %s", err)
}
if actual, expected := len(allNS.Items), 2; expected != actual {
t.Fatalf("Expected %d namespaces to match, got %d", expected, actual)
}
_, err = tc.Core().Pods("nsB").Create(testPod("", "pod-1"))
if err != nil {
t.Fatalf("Pods.Create nsB/pod-1: %s", err)
}
podB1, err := tc.Core().Pods("nsB").Get("pod-1", metav1.GetOptions{})
if err != nil {
t.Fatalf("Pods.Get nsB/pod-1: %s", err)
}
if podB1 == nil {
t.Fatalf("Expected to find pod nsB/pod-1 but it wasn't found")
}
if podB1.Namespace != "nsB" || podB1.Name != "pod-1" {
t.Fatalf("Expected to find pod nsB/pod-1t, got %s/%s", podB1.Namespace, podB1.Name)
}
_, err = tc.Core().Pods("nsA").Create(testPod("", "pod-1"))
if err == nil {
t.Fatalf("Expected Pods.Create to fail with already exists error")
}
_, err = tc.Core().Pods("nsA").Update(testPod("", "pod-1"))
if err != nil {
t.Fatalf("Pods.Update nsA/pod-1: %s", err)
}
_, err = tc.Core().Pods("nsA").Create(testPod("nsB", "pod-2"))
if err == nil {
t.Fatalf("Expected Pods.Create to fail with bad request from namespace mismtach")
}
if err.Error() != `request namespace does not match object namespace, request: "nsA" object: "nsB"` {
t.Fatalf("Expected Pods.Create error to provide object and request namespaces, got %q", err)
}
_, err = tc.Core().Pods("nsA").Update(testPod("", "pod-3"))
if err == nil {
t.Fatalf("Expected Pods.Update nsA/pod-3 to fail with not found error")
}
}
func testSA(ns, name string) *api.ServiceAccount {
return &api.ServiceAccount{
ObjectMeta: api.ObjectMeta{
Namespace: ns,
Name: name,
},
}
}
func testPod(ns, name string) *api.Pod {
return &api.Pod{
ObjectMeta: api.ObjectMeta{
Namespace: ns,
Name: name,
},
}
}
func testNamespace(ns string) *api.Namespace {
return &api.Namespace{
ObjectMeta: api.ObjectMeta{
Name: ns,
},
}
}

View file

@ -0,0 +1,516 @@
/*
Copyright 2015 The 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 core
import (
"fmt"
"sync"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/client/restclient"
)
// ObjectTracker keeps track of objects. It is intended to be used to
// fake calls to a server by returning objects based on their kind,
// namespace and name.
type ObjectTracker interface {
// Add adds an object to the tracker. If object being added
// is a list, its items are added separately.
Add(obj runtime.Object) error
// Get retrieves the object by its kind, namespace and name.
Get(gvk schema.GroupVersionKind, ns, name string) (runtime.Object, error)
// Create adds an object to the tracker in the specified namespace.
Create(obj runtime.Object, ns string) error
// Update updates an existing object in the tracker in the specified namespace.
Update(obj runtime.Object, ns string) error
// List retrieves all objects of a given kind in the given
// namespace. Only non-List kinds are accepted.
List(gvk schema.GroupVersionKind, ns string) (runtime.Object, error)
// Delete deletes an existing object from the tracker. If object
// didn't exist in the tracker prior to deletion, Delete returns
// no error.
Delete(gvk schema.GroupVersionKind, ns, name string) error
}
// ObjectScheme abstracts the implementation of common operations on objects.
type ObjectScheme interface {
runtime.ObjectCreater
runtime.ObjectCopier
runtime.ObjectTyper
}
// ObjectReaction returns a ReactionFunc that applies core.Action to
// the given tracker.
func ObjectReaction(tracker ObjectTracker, mapper meta.RESTMapper) ReactionFunc {
return func(action Action) (bool, runtime.Object, error) {
ns := action.GetNamespace()
gvr := action.GetResource()
gvk, err := mapper.KindFor(gvr)
if err != nil {
return false, nil, fmt.Errorf("error getting kind for resource %q: %s", gvr, err)
}
// This is a temporary fix. Because there is no internal resource, so
// the caller has no way to express that it expects to get an internal
// kind back. A more proper fix will be directly specify the Kind when
// build the action.
gvk.Version = gvr.Version
if len(gvk.Version) == 0 {
gvk.Version = runtime.APIVersionInternal
}
// Here and below we need to switch on implementation types,
// not on interfaces, as some interfaces are identical
// (e.g. UpdateAction and CreateAction), so if we use them,
// updates and creates end up matching the same case branch.
switch action := action.(type) {
case ListActionImpl:
obj, err := tracker.List(gvk, ns)
return true, obj, err
case GetActionImpl:
obj, err := tracker.Get(gvk, ns, action.GetName())
return true, obj, err
case CreateActionImpl:
objMeta, err := meta.Accessor(action.GetObject())
if err != nil {
return true, nil, err
}
if action.GetSubresource() == "" {
err = tracker.Create(action.GetObject(), ns)
} else {
// TODO: Currently we're handling subresource creation as an update
// on the enclosing resource. This works for some subresources but
// might not be generic enough.
err = tracker.Update(action.GetObject(), ns)
}
if err != nil {
return true, nil, err
}
obj, err := tracker.Get(gvk, ns, objMeta.GetName())
return true, obj, err
case UpdateActionImpl:
objMeta, err := meta.Accessor(action.GetObject())
if err != nil {
return true, nil, err
}
err = tracker.Update(action.GetObject(), ns)
if err != nil {
return true, nil, err
}
obj, err := tracker.Get(gvk, ns, objMeta.GetName())
return true, obj, err
case DeleteActionImpl:
err := tracker.Delete(gvk, ns, action.GetName())
if err != nil {
return true, nil, err
}
return true, nil, nil
default:
return false, nil, fmt.Errorf("no reaction implemented for %s", action)
}
}
}
type tracker struct {
scheme ObjectScheme
decoder runtime.Decoder
lock sync.RWMutex
objects map[schema.GroupVersionKind][]runtime.Object
}
var _ ObjectTracker = &tracker{}
// NewObjectTracker returns an ObjectTracker that can be used to keep track
// of objects for the fake clientset. Mostly useful for unit tests.
func NewObjectTracker(scheme ObjectScheme, decoder runtime.Decoder) ObjectTracker {
return &tracker{
scheme: scheme,
decoder: decoder,
objects: make(map[schema.GroupVersionKind][]runtime.Object),
}
}
func (t *tracker) List(gvk schema.GroupVersionKind, ns string) (runtime.Object, error) {
// Heuristic for list kind: original kind + List suffix. Might
// not always be true but this tracker has a pretty limited
// understanding of the actual API model.
listGVK := gvk
listGVK.Kind = listGVK.Kind + "List"
list, err := t.scheme.New(listGVK)
if err != nil {
return nil, err
}
if !meta.IsListType(list) {
return nil, fmt.Errorf("%q is not a list type", listGVK.Kind)
}
t.lock.RLock()
defer t.lock.RUnlock()
objs, ok := t.objects[gvk]
if !ok {
return list, nil
}
matchingObjs, err := filterByNamespaceAndName(objs, ns, "")
if err != nil {
return nil, err
}
if err := meta.SetList(list, matchingObjs); err != nil {
return nil, err
}
if list, err = t.scheme.Copy(list); err != nil {
return nil, err
}
return list, nil
}
func (t *tracker) Get(gvk schema.GroupVersionKind, ns, name string) (runtime.Object, error) {
if err := checkNamespace(gvk, ns); err != nil {
return nil, err
}
errNotFound := errors.NewNotFound(schema.GroupResource{Group: gvk.Group, Resource: gvk.Kind}, name)
t.lock.RLock()
defer t.lock.RUnlock()
objs, ok := t.objects[gvk]
if !ok {
return nil, errNotFound
}
matchingObjs, err := filterByNamespaceAndName(objs, ns, name)
if err != nil {
return nil, err
}
if len(matchingObjs) == 0 {
return nil, errNotFound
}
if len(matchingObjs) > 1 {
return nil, fmt.Errorf("more than one object matched gvk %s, ns: %q name: %q", gvk, ns, name)
}
// Only one object should match in the tracker if it works
// correctly, as Add/Update methods enforce kind/namespace/name
// uniqueness.
obj, err := t.scheme.Copy(matchingObjs[0])
if err != nil {
return nil, err
}
if status, ok := obj.(*metav1.Status); ok {
if status.Details != nil {
status.Details.Kind = gvk.Kind
}
if status.Status != metav1.StatusSuccess {
return nil, &errors.StatusError{ErrStatus: *status}
}
}
return obj, nil
}
func (t *tracker) Add(obj runtime.Object) error {
if meta.IsListType(obj) {
return t.addList(obj, false)
}
objMeta, err := meta.Accessor(obj)
if err != nil {
return err
}
return t.add(obj, objMeta.GetNamespace(), false)
}
func (t *tracker) Create(obj runtime.Object, ns string) error {
return t.add(obj, ns, false)
}
func (t *tracker) Update(obj runtime.Object, ns string) error {
return t.add(obj, ns, true)
}
func (t *tracker) add(obj runtime.Object, ns string, replaceExisting bool) error {
gvks, _, err := t.scheme.ObjectKinds(obj)
if err != nil {
return err
}
if len(gvks) == 0 {
return fmt.Errorf("no registered kinds for %v", obj)
}
t.lock.Lock()
defer t.lock.Unlock()
for _, gvk := range gvks {
gr := schema.GroupResource{Group: gvk.Group, Resource: gvk.Kind}
// To avoid the object from being accidentally modified by caller
// after it's been added to the tracker, we always store the deep
// copy.
obj, err = t.scheme.Copy(obj)
if err != nil {
return err
}
if status, ok := obj.(*metav1.Status); ok && status.Details != nil {
gvk.Kind = status.Details.Kind
}
newMeta, err := meta.Accessor(obj)
if err != nil {
return err
}
// Propagate namespace to the new object if hasn't already been set.
if len(newMeta.GetNamespace()) == 0 {
newMeta.SetNamespace(ns)
}
if ns != newMeta.GetNamespace() {
msg := fmt.Sprintf("request namespace does not match object namespace, request: %q object: %q", ns, newMeta.GetNamespace())
return errors.NewBadRequest(msg)
}
if err := checkNamespace(gvk, newMeta.GetNamespace()); err != nil {
return err
}
for i, existingObj := range t.objects[gvk] {
oldMeta, err := meta.Accessor(existingObj)
if err != nil {
return err
}
if oldMeta.GetNamespace() == newMeta.GetNamespace() && oldMeta.GetName() == newMeta.GetName() {
if replaceExisting {
t.objects[gvk][i] = obj
return nil
}
return errors.NewAlreadyExists(gr, newMeta.GetName())
}
}
if replaceExisting {
// Tried to update but no matching object was found.
return errors.NewNotFound(gr, newMeta.GetName())
}
t.objects[gvk] = append(t.objects[gvk], obj)
}
return nil
}
func (t *tracker) addList(obj runtime.Object, replaceExisting bool) error {
list, err := meta.ExtractList(obj)
if err != nil {
return err
}
errs := runtime.DecodeList(list, t.decoder)
if len(errs) > 0 {
return errs[0]
}
for _, obj := range list {
objMeta, err := meta.Accessor(obj)
if err != nil {
return err
}
err = t.add(obj, objMeta.GetNamespace(), replaceExisting)
if err != nil {
return err
}
}
return nil
}
func (t *tracker) Delete(gvk schema.GroupVersionKind, ns, name string) error {
if err := checkNamespace(gvk, ns); err != nil {
return err
}
t.lock.Lock()
defer t.lock.Unlock()
found := false
for i, existingObj := range t.objects[gvk] {
objMeta, err := meta.Accessor(existingObj)
if err != nil {
return err
}
if objMeta.GetNamespace() == ns && objMeta.GetName() == name {
t.objects[gvk] = append(t.objects[gvk][:i], t.objects[gvk][i+1:]...)
found = true
break
}
}
if found {
return nil
}
return errors.NewNotFound(schema.GroupResource{Group: gvk.Group, Resource: gvk.Kind}, name)
}
// filterByNamespaceAndName returns all objects in the collection that
// match provided namespace and name. Empty namespace matches
// non-namespaced objects.
func filterByNamespaceAndName(objs []runtime.Object, ns, name string) ([]runtime.Object, error) {
var res []runtime.Object
for _, obj := range objs {
acc, err := meta.Accessor(obj)
if err != nil {
return nil, err
}
if ns != "" && acc.GetNamespace() != ns {
continue
}
if name != "" && acc.GetName() != name {
continue
}
res = append(res, obj)
}
return res, nil
}
// checkNamespace makes sure that the scope of gvk matches ns. It
// returns an error if namespace is empty but gvk is a namespaced
// kind, or if ns is non-empty and gvk is a namespaced kind.
func checkNamespace(gvk schema.GroupVersionKind, ns string) error {
group, err := api.Registry.Group(gvk.Group)
if err != nil {
return err
}
mapping, err := group.RESTMapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return err
}
switch mapping.Scope.Name() {
case meta.RESTScopeNameRoot:
if ns != "" {
return fmt.Errorf("namespace specified for a non-namespaced kind %s", gvk)
}
case meta.RESTScopeNameNamespace:
if ns == "" {
// Skipping this check for Events, since
// controllers emit events that have no namespace,
// even though Event is a namespaced resource.
if gvk.Kind != "Event" {
return fmt.Errorf("no namespace specified for a namespaced kind %s", gvk)
}
}
}
return nil
}
func DefaultWatchReactor(watchInterface watch.Interface, err error) WatchReactionFunc {
return func(action Action) (bool, watch.Interface, error) {
return true, watchInterface, err
}
}
// SimpleReactor is a Reactor. Each reaction function is attached to a given verb,resource tuple. "*" in either field matches everything for that value.
// For instance, *,pods matches all verbs on pods. This allows for easier composition of reaction functions
type SimpleReactor struct {
Verb string
Resource string
Reaction ReactionFunc
}
func (r *SimpleReactor) Handles(action Action) bool {
verbCovers := r.Verb == "*" || r.Verb == action.GetVerb()
if !verbCovers {
return false
}
resourceCovers := r.Resource == "*" || r.Resource == action.GetResource().Resource
if !resourceCovers {
return false
}
return true
}
func (r *SimpleReactor) React(action Action) (bool, runtime.Object, error) {
return r.Reaction(action)
}
// SimpleWatchReactor is a WatchReactor. Each reaction function is attached to a given resource. "*" matches everything for that value.
// For instance, *,pods matches all verbs on pods. This allows for easier composition of reaction functions
type SimpleWatchReactor struct {
Resource string
Reaction WatchReactionFunc
}
func (r *SimpleWatchReactor) Handles(action Action) bool {
resourceCovers := r.Resource == "*" || r.Resource == action.GetResource().Resource
if !resourceCovers {
return false
}
return true
}
func (r *SimpleWatchReactor) React(action Action) (bool, watch.Interface, error) {
return r.Reaction(action)
}
// SimpleProxyReactor is a ProxyReactor. Each reaction function is attached to a given resource. "*" matches everything for that value.
// For instance, *,pods matches all verbs on pods. This allows for easier composition of reaction functions.
type SimpleProxyReactor struct {
Resource string
Reaction ProxyReactionFunc
}
func (r *SimpleProxyReactor) Handles(action Action) bool {
resourceCovers := r.Resource == "*" || r.Resource == action.GetResource().Resource
if !resourceCovers {
return false
}
return true
}
func (r *SimpleProxyReactor) React(action Action) (bool, restclient.ResponseWrapper, error) {
return r.Reaction(action)
}