summaryrefslogtreecommitdiff
path: root/vendor/k8s.io/apimachinery/pkg
diff options
context:
space:
mode:
authorDaniel J Walsh <dwalsh@redhat.com>2018-03-30 05:49:37 -0400
committerAtomic Bot <atomic-devel@projectatomic.io>2018-04-03 14:48:52 +0000
commit838df4eec4496868e772d5708e00f38bad478718 (patch)
tree89e72bb0b9668ff4005156d590465602589ec4c3 /vendor/k8s.io/apimachinery/pkg
parentf41dc0b2580ae83129264edbe45b92231bd119a2 (diff)
downloadpodman-838df4eec4496868e772d5708e00f38bad478718.tar.gz
podman-838df4eec4496868e772d5708e00f38bad478718.tar.bz2
podman-838df4eec4496868e772d5708e00f38bad478718.zip
Vendor in latest containers/image
Some more features. docker-archive generates docker legacy compatible images Do not create $DiffID subdirectories for layers with no configs Ensure the layer IDs in legacy docker/tarfile metadata are unique docker-archive: repeated layers are symlinked in the tar file sysregistries: remove all trailing slashes Improve docker/* error messages Fix failure to make auth directory Create a new slice in Schema1.UpdateLayerInfos Drop unused storageImageDestination.{image,systemContext} Load a *storage.Image only once in storageImageSource Support gzip for docker-archive files Remove .tar extension from blob and config file names ostree, src: support copy of compressed layers ostree: re-pull layer if it misses uncompressed_digest|uncompressed_size image: fix docker schema v1 -> OCI conversion Add /etc/containers/certs.d as default certs directory Signed-off-by: Daniel J Walsh <dwalsh@redhat.com> Closes: #569 Approved by: mheon
Diffstat (limited to 'vendor/k8s.io/apimachinery/pkg')
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/equality/semantic.go49
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/meta/doc.go19
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/meta/errors.go121
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/meta/firsthit_restmapper.go97
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/meta/help.go205
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/meta/interfaces.go149
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/meta/lazy.go121
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/meta/meta.go653
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go210
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/meta/priority.go222
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/meta/restmapper.go548
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/meta/unstructured.go47
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/validation/doc.go18
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/validation/generic.go85
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go343
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apimachinery/announced/announced.go99
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apimachinery/announced/group_factory.go255
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apimachinery/doc.go20
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apimachinery/registered/registered.go336
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apimachinery/types.go87
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/conversion.go77
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/doc.go20
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register.go105
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go70
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.conversion.go118
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.deepcopy.go108
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go475
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go379
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go189
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/zz_generated.deepcopy.go57
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go92
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/conversion.go27
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/deepcopy.go61
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/doc.go22
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.pb.go633
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto58
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/register.go57
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types.go161
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types_swagger_doc_generated.go104
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/zz_generated.deepcopy.go194
-rw-r--r--vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/zz_generated.defaults.go32
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/cache/cache.go83
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go102
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/diff/diff.go273
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/mergepatch/errors.go102
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go133
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/strategicpatch/errors.go49
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go194
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go2151
-rw-r--r--vendor/k8s.io/apimachinery/pkg/util/strategicpatch/types.go193
50 files changed, 0 insertions, 10003 deletions
diff --git a/vendor/k8s.io/apimachinery/pkg/api/equality/semantic.go b/vendor/k8s.io/apimachinery/pkg/api/equality/semantic.go
deleted file mode 100644
index f02fa8e43..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/equality/semantic.go
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
-Copyright 2014 The 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 equality
-
-import (
- "k8s.io/apimachinery/pkg/api/resource"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/conversion"
- "k8s.io/apimachinery/pkg/fields"
- "k8s.io/apimachinery/pkg/labels"
-)
-
-// Semantic can do semantic deep equality checks for api objects.
-// Example: apiequality.Semantic.DeepEqual(aPod, aPodWithNonNilButEmptyMaps) == true
-var Semantic = conversion.EqualitiesOrDie(
- func(a, b resource.Quantity) bool {
- // Ignore formatting, only care that numeric value stayed the same.
- // TODO: if we decide it's important, it should be safe to start comparing the format.
- //
- // Uninitialized quantities are equivalent to 0 quantities.
- return a.Cmp(b) == 0
- },
- func(a, b metav1.MicroTime) bool {
- return a.UTC() == b.UTC()
- },
- func(a, b metav1.Time) bool {
- return a.UTC() == b.UTC()
- },
- func(a, b labels.Selector) bool {
- return a.String() == b.String()
- },
- func(a, b fields.Selector) bool {
- return a.String() == b.String()
- },
-)
diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/doc.go b/vendor/k8s.io/apimachinery/pkg/api/meta/doc.go
deleted file mode 100644
index b6d42acf8..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/meta/doc.go
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
-Copyright 2014 The 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 meta provides functions for retrieving API metadata from objects
-// belonging to the Kubernetes API
-package meta // import "k8s.io/apimachinery/pkg/api/meta"
diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/errors.go b/vendor/k8s.io/apimachinery/pkg/api/meta/errors.go
deleted file mode 100644
index cbf5d0263..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/meta/errors.go
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
-Copyright 2014 The 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 meta
-
-import (
- "fmt"
-
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/util/sets"
-)
-
-// AmbiguousResourceError is returned if the RESTMapper finds multiple matches for a resource
-type AmbiguousResourceError struct {
- PartialResource schema.GroupVersionResource
-
- MatchingResources []schema.GroupVersionResource
- MatchingKinds []schema.GroupVersionKind
-}
-
-func (e *AmbiguousResourceError) Error() string {
- switch {
- case len(e.MatchingKinds) > 0 && len(e.MatchingResources) > 0:
- return fmt.Sprintf("%v matches multiple resources %v and kinds %v", e.PartialResource, e.MatchingResources, e.MatchingKinds)
- case len(e.MatchingKinds) > 0:
- return fmt.Sprintf("%v matches multiple kinds %v", e.PartialResource, e.MatchingKinds)
- case len(e.MatchingResources) > 0:
- return fmt.Sprintf("%v matches multiple resources %v", e.PartialResource, e.MatchingResources)
- }
- return fmt.Sprintf("%v matches multiple resources or kinds", e.PartialResource)
-}
-
-// AmbiguousKindError is returned if the RESTMapper finds multiple matches for a kind
-type AmbiguousKindError struct {
- PartialKind schema.GroupVersionKind
-
- MatchingResources []schema.GroupVersionResource
- MatchingKinds []schema.GroupVersionKind
-}
-
-func (e *AmbiguousKindError) Error() string {
- switch {
- case len(e.MatchingKinds) > 0 && len(e.MatchingResources) > 0:
- return fmt.Sprintf("%v matches multiple resources %v and kinds %v", e.PartialKind, e.MatchingResources, e.MatchingKinds)
- case len(e.MatchingKinds) > 0:
- return fmt.Sprintf("%v matches multiple kinds %v", e.PartialKind, e.MatchingKinds)
- case len(e.MatchingResources) > 0:
- return fmt.Sprintf("%v matches multiple resources %v", e.PartialKind, e.MatchingResources)
- }
- return fmt.Sprintf("%v matches multiple resources or kinds", e.PartialKind)
-}
-
-func IsAmbiguousError(err error) bool {
- if err == nil {
- return false
- }
- switch err.(type) {
- case *AmbiguousResourceError, *AmbiguousKindError:
- return true
- default:
- return false
- }
-}
-
-// NoResourceMatchError is returned if the RESTMapper can't find any match for a resource
-type NoResourceMatchError struct {
- PartialResource schema.GroupVersionResource
-}
-
-func (e *NoResourceMatchError) Error() string {
- return fmt.Sprintf("no matches for %v", e.PartialResource)
-}
-
-// NoKindMatchError is returned if the RESTMapper can't find any match for a kind
-type NoKindMatchError struct {
- // GroupKind is the API group and kind that was searched
- GroupKind schema.GroupKind
- // SearchedVersions is the optional list of versions the search was restricted to
- SearchedVersions []string
-}
-
-func (e *NoKindMatchError) Error() string {
- searchedVersions := sets.NewString()
- for _, v := range e.SearchedVersions {
- searchedVersions.Insert(schema.GroupVersion{Group: e.GroupKind.Group, Version: v}.String())
- }
-
- switch len(searchedVersions) {
- case 0:
- return fmt.Sprintf("no matches for kind %q in group %q", e.GroupKind.Kind, e.GroupKind.Group)
- case 1:
- return fmt.Sprintf("no matches for kind %q in version %q", e.GroupKind.Kind, searchedVersions.List()[0])
- default:
- return fmt.Sprintf("no matches for kind %q in versions %q", e.GroupKind.Kind, searchedVersions.List())
- }
-}
-
-func IsNoMatchError(err error) bool {
- if err == nil {
- return false
- }
- switch err.(type) {
- case *NoResourceMatchError, *NoKindMatchError:
- return true
- default:
- return false
- }
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/firsthit_restmapper.go b/vendor/k8s.io/apimachinery/pkg/api/meta/firsthit_restmapper.go
deleted file mode 100644
index fd2210022..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/meta/firsthit_restmapper.go
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
-Copyright 2014 The 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 meta
-
-import (
- "fmt"
-
- "k8s.io/apimachinery/pkg/runtime/schema"
- utilerrors "k8s.io/apimachinery/pkg/util/errors"
-)
-
-// FirstHitRESTMapper is a wrapper for multiple RESTMappers which returns the
-// first successful result for the singular requests
-type FirstHitRESTMapper struct {
- MultiRESTMapper
-}
-
-func (m FirstHitRESTMapper) String() string {
- return fmt.Sprintf("FirstHitRESTMapper{\n\t%v\n}", m.MultiRESTMapper)
-}
-
-func (m FirstHitRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {
- errors := []error{}
- for _, t := range m.MultiRESTMapper {
- ret, err := t.ResourceFor(resource)
- if err == nil {
- return ret, nil
- }
- errors = append(errors, err)
- }
-
- return schema.GroupVersionResource{}, collapseAggregateErrors(errors)
-}
-
-func (m FirstHitRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
- errors := []error{}
- for _, t := range m.MultiRESTMapper {
- ret, err := t.KindFor(resource)
- if err == nil {
- return ret, nil
- }
- errors = append(errors, err)
- }
-
- return schema.GroupVersionKind{}, collapseAggregateErrors(errors)
-}
-
-// RESTMapping provides the REST mapping for the resource based on the
-// kind and version. This implementation supports multiple REST schemas and
-// return the first match.
-func (m FirstHitRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {
- errors := []error{}
- for _, t := range m.MultiRESTMapper {
- ret, err := t.RESTMapping(gk, versions...)
- if err == nil {
- return ret, nil
- }
- errors = append(errors, err)
- }
-
- return nil, collapseAggregateErrors(errors)
-}
-
-// collapseAggregateErrors returns the minimal errors. it handles empty as nil, handles one item in a list
-// by returning the item, and collapses all NoMatchErrors to a single one (since they should all be the same)
-func collapseAggregateErrors(errors []error) error {
- if len(errors) == 0 {
- return nil
- }
- if len(errors) == 1 {
- return errors[0]
- }
-
- allNoMatchErrors := true
- for _, err := range errors {
- allNoMatchErrors = allNoMatchErrors && IsNoMatchError(err)
- }
- if allNoMatchErrors {
- return errors[0]
- }
-
- return utilerrors.NewAggregate(errors)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/help.go b/vendor/k8s.io/apimachinery/pkg/api/meta/help.go
deleted file mode 100644
index c70b3d2b6..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/meta/help.go
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
-Copyright 2015 The 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 meta
-
-import (
- "fmt"
- "reflect"
-
- "k8s.io/apimachinery/pkg/conversion"
- "k8s.io/apimachinery/pkg/runtime"
-)
-
-// IsListType returns true if the provided Object has a slice called Items
-func IsListType(obj runtime.Object) bool {
- // if we're a runtime.Unstructured, check whether this is a list.
- // TODO: refactor GetItemsPtr to use an interface that returns []runtime.Object
- if unstructured, ok := obj.(runtime.Unstructured); ok {
- return unstructured.IsList()
- }
-
- _, err := GetItemsPtr(obj)
- return err == nil
-}
-
-// GetItemsPtr returns a pointer to the list object's Items member.
-// If 'list' doesn't have an Items member, it's not really a list type
-// and an error will be returned.
-// This function will either return a pointer to a slice, or an error, but not both.
-func GetItemsPtr(list runtime.Object) (interface{}, error) {
- v, err := conversion.EnforcePtr(list)
- if err != nil {
- return nil, err
- }
-
- items := v.FieldByName("Items")
- if !items.IsValid() {
- return nil, fmt.Errorf("no Items field in %#v", list)
- }
- switch items.Kind() {
- case reflect.Interface, reflect.Ptr:
- target := reflect.TypeOf(items.Interface()).Elem()
- if target.Kind() != reflect.Slice {
- return nil, fmt.Errorf("items: Expected slice, got %s", target.Kind())
- }
- return items.Interface(), nil
- case reflect.Slice:
- return items.Addr().Interface(), nil
- default:
- return nil, fmt.Errorf("items: Expected slice, got %s", items.Kind())
- }
-}
-
-// EachListItem invokes fn on each runtime.Object in the list. Any error immediately terminates
-// the loop.
-func EachListItem(obj runtime.Object, fn func(runtime.Object) error) error {
- if unstructured, ok := obj.(runtime.Unstructured); ok {
- return unstructured.EachListItem(fn)
- }
- // TODO: Change to an interface call?
- itemsPtr, err := GetItemsPtr(obj)
- if err != nil {
- return err
- }
- items, err := conversion.EnforcePtr(itemsPtr)
- if err != nil {
- return err
- }
- len := items.Len()
- if len == 0 {
- return nil
- }
- takeAddr := false
- if elemType := items.Type().Elem(); elemType.Kind() != reflect.Ptr && elemType.Kind() != reflect.Interface {
- if !items.Index(0).CanAddr() {
- return fmt.Errorf("unable to take address of items in %T for EachListItem", obj)
- }
- takeAddr = true
- }
-
- for i := 0; i < len; i++ {
- raw := items.Index(i)
- if takeAddr {
- raw = raw.Addr()
- }
- switch item := raw.Interface().(type) {
- case *runtime.RawExtension:
- if err := fn(item.Object); err != nil {
- return err
- }
- case runtime.Object:
- if err := fn(item); err != nil {
- return err
- }
- default:
- obj, ok := item.(runtime.Object)
- if !ok {
- return fmt.Errorf("%v: item[%v]: Expected object, got %#v(%s)", obj, i, raw.Interface(), raw.Kind())
- }
- if err := fn(obj); err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-// ExtractList returns obj's Items element as an array of runtime.Objects.
-// Returns an error if obj is not a List type (does not have an Items member).
-func ExtractList(obj runtime.Object) ([]runtime.Object, error) {
- itemsPtr, err := GetItemsPtr(obj)
- if err != nil {
- return nil, err
- }
- items, err := conversion.EnforcePtr(itemsPtr)
- if err != nil {
- return nil, err
- }
- list := make([]runtime.Object, items.Len())
- for i := range list {
- raw := items.Index(i)
- switch item := raw.Interface().(type) {
- case runtime.RawExtension:
- switch {
- case item.Object != nil:
- list[i] = item.Object
- case item.Raw != nil:
- // TODO: Set ContentEncoding and ContentType correctly.
- list[i] = &runtime.Unknown{Raw: item.Raw}
- default:
- list[i] = nil
- }
- case runtime.Object:
- list[i] = item
- default:
- var found bool
- if list[i], found = raw.Addr().Interface().(runtime.Object); !found {
- return nil, fmt.Errorf("%v: item[%v]: Expected object, got %#v(%s)", obj, i, raw.Interface(), raw.Kind())
- }
- }
- }
- return list, nil
-}
-
-// objectSliceType is the type of a slice of Objects
-var objectSliceType = reflect.TypeOf([]runtime.Object{})
-
-// SetList sets the given list object's Items member have the elements given in
-// objects.
-// Returns an error if list is not a List type (does not have an Items member),
-// or if any of the objects are not of the right type.
-func SetList(list runtime.Object, objects []runtime.Object) error {
- itemsPtr, err := GetItemsPtr(list)
- if err != nil {
- return err
- }
- items, err := conversion.EnforcePtr(itemsPtr)
- if err != nil {
- return err
- }
- if items.Type() == objectSliceType {
- items.Set(reflect.ValueOf(objects))
- return nil
- }
- slice := reflect.MakeSlice(items.Type(), len(objects), len(objects))
- for i := range objects {
- dest := slice.Index(i)
- if dest.Type() == reflect.TypeOf(runtime.RawExtension{}) {
- dest = dest.FieldByName("Object")
- }
-
- // check to see if you're directly assignable
- if reflect.TypeOf(objects[i]).AssignableTo(dest.Type()) {
- dest.Set(reflect.ValueOf(objects[i]))
- continue
- }
-
- src, err := conversion.EnforcePtr(objects[i])
- if err != nil {
- return err
- }
- if src.Type().AssignableTo(dest.Type()) {
- dest.Set(src)
- } else if src.Type().ConvertibleTo(dest.Type()) {
- dest.Set(src.Convert(dest.Type()))
- } else {
- return fmt.Errorf("item[%d]: can't assign or convert %v into %v", i, src.Type(), dest.Type())
- }
- }
- items.Set(slice)
- return nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/interfaces.go b/vendor/k8s.io/apimachinery/pkg/api/meta/interfaces.go
deleted file mode 100644
index 5dc9d89e6..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/meta/interfaces.go
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
-Copyright 2014 The 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 meta
-
-import (
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/types"
-)
-
-// VersionInterfaces contains the interfaces one should use for dealing with types of a particular version.
-type VersionInterfaces struct {
- runtime.ObjectConvertor
- MetadataAccessor
-}
-
-type ListMetaAccessor interface {
- GetListMeta() List
-}
-
-// List lets you work with list metadata from any of the versioned or
-// internal API objects. Attempting to set or retrieve a field on an object that does
-// not support that field will be a no-op and return a default value.
-type List metav1.ListInterface
-
-// Type exposes the type and APIVersion of versioned or internal API objects.
-type Type metav1.Type
-
-// MetadataAccessor lets you work with object and list metadata from any of the versioned or
-// internal API objects. Attempting to set or retrieve a field on an object that does
-// not support that field (Name, UID, Namespace on lists) will be a no-op and return
-// a default value.
-//
-// MetadataAccessor exposes Interface in a way that can be used with multiple objects.
-type MetadataAccessor interface {
- APIVersion(obj runtime.Object) (string, error)
- SetAPIVersion(obj runtime.Object, version string) error
-
- Kind(obj runtime.Object) (string, error)
- SetKind(obj runtime.Object, kind string) error
-
- Namespace(obj runtime.Object) (string, error)
- SetNamespace(obj runtime.Object, namespace string) error
-
- Name(obj runtime.Object) (string, error)
- SetName(obj runtime.Object, name string) error
-
- GenerateName(obj runtime.Object) (string, error)
- SetGenerateName(obj runtime.Object, name string) error
-
- UID(obj runtime.Object) (types.UID, error)
- SetUID(obj runtime.Object, uid types.UID) error
-
- SelfLink(obj runtime.Object) (string, error)
- SetSelfLink(obj runtime.Object, selfLink string) error
-
- Labels(obj runtime.Object) (map[string]string, error)
- SetLabels(obj runtime.Object, labels map[string]string) error
-
- Annotations(obj runtime.Object) (map[string]string, error)
- SetAnnotations(obj runtime.Object, annotations map[string]string) error
-
- Continue(obj runtime.Object) (string, error)
- SetContinue(obj runtime.Object, c string) error
-
- runtime.ResourceVersioner
-}
-
-type RESTScopeName string
-
-const (
- RESTScopeNameNamespace RESTScopeName = "namespace"
- RESTScopeNameRoot RESTScopeName = "root"
-)
-
-// RESTScope contains the information needed to deal with REST resources that are in a resource hierarchy
-type RESTScope interface {
- // Name of the scope
- Name() RESTScopeName
- // ParamName is the optional name of the parameter that should be inserted in the resource url
- // If empty, no param will be inserted
- ParamName() string
- // ArgumentName is the optional name that should be used for the variable holding the value.
- ArgumentName() string
- // ParamDescription is the optional description to use to document the parameter in api documentation
- ParamDescription() string
-}
-
-// RESTMapping contains the information needed to deal with objects of a specific
-// resource and kind in a RESTful manner.
-type RESTMapping struct {
- // Resource is a string representing the name of this resource as a REST client would see it
- Resource string
-
- GroupVersionKind schema.GroupVersionKind
-
- // Scope contains the information needed to deal with REST Resources that are in a resource hierarchy
- Scope RESTScope
-
- runtime.ObjectConvertor
- MetadataAccessor
-}
-
-// RESTMapper allows clients to map resources to kind, and map kind and version
-// to interfaces for manipulating those objects. It is primarily intended for
-// consumers of Kubernetes compatible REST APIs as defined in docs/devel/api-conventions.md.
-//
-// The Kubernetes API provides versioned resources and object kinds which are scoped
-// to API groups. In other words, kinds and resources should not be assumed to be
-// unique across groups.
-//
-// TODO: split into sub-interfaces
-type RESTMapper interface {
- // KindFor takes a partial resource and returns the single match. Returns an error if there are multiple matches
- KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error)
-
- // KindsFor takes a partial resource and returns the list of potential kinds in priority order
- KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error)
-
- // ResourceFor takes a partial resource and returns the single match. Returns an error if there are multiple matches
- ResourceFor(input schema.GroupVersionResource) (schema.GroupVersionResource, error)
-
- // ResourcesFor takes a partial resource and returns the list of potential resource in priority order
- ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error)
-
- // RESTMapping identifies a preferred resource mapping for the provided group kind.
- RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error)
- // RESTMappings returns all resource mappings for the provided group kind if no
- // version search is provided. Otherwise identifies a preferred resource mapping for
- // the provided version(s).
- RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error)
-
- ResourceSingularizer(resource string) (singular string, err error)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/lazy.go b/vendor/k8s.io/apimachinery/pkg/api/meta/lazy.go
deleted file mode 100644
index 7f92f39a4..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/meta/lazy.go
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
-Copyright 2017 The 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 meta
-
-import (
- "sync"
-
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// lazyObject defers loading the mapper and typer until necessary.
-type lazyObject struct {
- loader func() (RESTMapper, runtime.ObjectTyper, error)
-
- lock sync.Mutex
- loaded bool
- err error
- mapper RESTMapper
- typer runtime.ObjectTyper
-}
-
-// NewLazyObjectLoader handles unrecoverable errors when creating a RESTMapper / ObjectTyper by
-// returning those initialization errors when the interface methods are invoked. This defers the
-// initialization and any server calls until a client actually needs to perform the action.
-func NewLazyObjectLoader(fn func() (RESTMapper, runtime.ObjectTyper, error)) (RESTMapper, runtime.ObjectTyper) {
- obj := &lazyObject{loader: fn}
- return obj, obj
-}
-
-// init lazily loads the mapper and typer, returning an error if initialization has failed.
-func (o *lazyObject) init() error {
- o.lock.Lock()
- defer o.lock.Unlock()
- if o.loaded {
- return o.err
- }
- o.mapper, o.typer, o.err = o.loader()
- o.loaded = true
- return o.err
-}
-
-var _ RESTMapper = &lazyObject{}
-var _ runtime.ObjectTyper = &lazyObject{}
-
-func (o *lazyObject) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
- if err := o.init(); err != nil {
- return schema.GroupVersionKind{}, err
- }
- return o.mapper.KindFor(resource)
-}
-
-func (o *lazyObject) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) {
- if err := o.init(); err != nil {
- return []schema.GroupVersionKind{}, err
- }
- return o.mapper.KindsFor(resource)
-}
-
-func (o *lazyObject) ResourceFor(input schema.GroupVersionResource) (schema.GroupVersionResource, error) {
- if err := o.init(); err != nil {
- return schema.GroupVersionResource{}, err
- }
- return o.mapper.ResourceFor(input)
-}
-
-func (o *lazyObject) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
- if err := o.init(); err != nil {
- return []schema.GroupVersionResource{}, err
- }
- return o.mapper.ResourcesFor(input)
-}
-
-func (o *lazyObject) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {
- if err := o.init(); err != nil {
- return nil, err
- }
- return o.mapper.RESTMapping(gk, versions...)
-}
-
-func (o *lazyObject) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {
- if err := o.init(); err != nil {
- return nil, err
- }
- return o.mapper.RESTMappings(gk, versions...)
-}
-
-func (o *lazyObject) ResourceSingularizer(resource string) (singular string, err error) {
- if err := o.init(); err != nil {
- return "", err
- }
- return o.mapper.ResourceSingularizer(resource)
-}
-
-func (o *lazyObject) ObjectKinds(obj runtime.Object) ([]schema.GroupVersionKind, bool, error) {
- if err := o.init(); err != nil {
- return nil, false, err
- }
- return o.typer.ObjectKinds(obj)
-}
-
-func (o *lazyObject) Recognizes(gvk schema.GroupVersionKind) bool {
- if err := o.init(); err != nil {
- return false
- }
- return o.typer.Recognizes(gvk)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/meta.go b/vendor/k8s.io/apimachinery/pkg/api/meta/meta.go
deleted file mode 100644
index b9670071c..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/meta/meta.go
+++ /dev/null
@@ -1,653 +0,0 @@
-/*
-Copyright 2014 The 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 meta
-
-import (
- "fmt"
- "reflect"
-
- "github.com/golang/glog"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
- "k8s.io/apimachinery/pkg/conversion"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/types"
-)
-
-// errNotList is returned when an object implements the Object style interfaces but not the List style
-// interfaces.
-var errNotList = fmt.Errorf("object does not implement the List interfaces")
-
-var errNotCommon = fmt.Errorf("object does not implement the common interface for accessing the SelfLink")
-
-// CommonAccessor returns a Common interface for the provided object or an error if the object does
-// not provide List.
-// TODO: return bool instead of error
-func CommonAccessor(obj interface{}) (metav1.Common, error) {
- switch t := obj.(type) {
- case List:
- return t, nil
- case metav1.ListInterface:
- return t, nil
- case ListMetaAccessor:
- if m := t.GetListMeta(); m != nil {
- return m, nil
- }
- return nil, errNotCommon
- case metav1.ListMetaAccessor:
- if m := t.GetListMeta(); m != nil {
- return m, nil
- }
- return nil, errNotCommon
- case metav1.Object:
- return t, nil
- case metav1.ObjectMetaAccessor:
- if m := t.GetObjectMeta(); m != nil {
- return m, nil
- }
- return nil, errNotCommon
- default:
- return nil, errNotCommon
- }
-}
-
-// ListAccessor returns a List interface for the provided object or an error if the object does
-// not provide List.
-// IMPORTANT: Objects are NOT a superset of lists. Do not use this check to determine whether an
-// object *is* a List.
-// TODO: return bool instead of error
-func ListAccessor(obj interface{}) (List, error) {
- switch t := obj.(type) {
- case List:
- return t, nil
- case metav1.ListInterface:
- return t, nil
- case ListMetaAccessor:
- if m := t.GetListMeta(); m != nil {
- return m, nil
- }
- return nil, errNotList
- case metav1.ListMetaAccessor:
- if m := t.GetListMeta(); m != nil {
- return m, nil
- }
- return nil, errNotList
- default:
- return nil, errNotList
- }
-}
-
-// errNotObject is returned when an object implements the List style interfaces but not the Object style
-// interfaces.
-var errNotObject = fmt.Errorf("object does not implement the Object interfaces")
-
-// Accessor takes an arbitrary object pointer and returns meta.Interface.
-// obj must be a pointer to an API type. An error is returned if the minimum
-// required fields are missing. Fields that are not required return the default
-// value and are a no-op if set.
-// TODO: return bool instead of error
-func Accessor(obj interface{}) (metav1.Object, error) {
- switch t := obj.(type) {
- case metav1.Object:
- return t, nil
- case metav1.ObjectMetaAccessor:
- if m := t.GetObjectMeta(); m != nil {
- return m, nil
- }
- return nil, errNotObject
- default:
- return nil, errNotObject
- }
-}
-
-// AsPartialObjectMetadata takes the metav1 interface and returns a partial object.
-// TODO: consider making this solely a conversion action.
-func AsPartialObjectMetadata(m metav1.Object) *metav1beta1.PartialObjectMetadata {
- switch t := m.(type) {
- case *metav1.ObjectMeta:
- return &metav1beta1.PartialObjectMetadata{ObjectMeta: *t}
- default:
- return &metav1beta1.PartialObjectMetadata{
- ObjectMeta: metav1.ObjectMeta{
- Name: m.GetName(),
- GenerateName: m.GetGenerateName(),
- Namespace: m.GetNamespace(),
- SelfLink: m.GetSelfLink(),
- UID: m.GetUID(),
- ResourceVersion: m.GetResourceVersion(),
- Generation: m.GetGeneration(),
- CreationTimestamp: m.GetCreationTimestamp(),
- DeletionTimestamp: m.GetDeletionTimestamp(),
- DeletionGracePeriodSeconds: m.GetDeletionGracePeriodSeconds(),
- Labels: m.GetLabels(),
- Annotations: m.GetAnnotations(),
- OwnerReferences: m.GetOwnerReferences(),
- Finalizers: m.GetFinalizers(),
- ClusterName: m.GetClusterName(),
- Initializers: m.GetInitializers(),
- },
- }
- }
-}
-
-// TypeAccessor returns an interface that allows retrieving and modifying the APIVersion
-// and Kind of an in-memory internal object.
-// TODO: this interface is used to test code that does not have ObjectMeta or ListMeta
-// in round tripping (objects which can use apiVersion/kind, but do not fit the Kube
-// api conventions).
-func TypeAccessor(obj interface{}) (Type, error) {
- if typed, ok := obj.(runtime.Object); ok {
- return objectAccessor{typed}, nil
- }
- v, err := conversion.EnforcePtr(obj)
- if err != nil {
- return nil, err
- }
- t := v.Type()
- if v.Kind() != reflect.Struct {
- return nil, fmt.Errorf("expected struct, but got %v: %v (%#v)", v.Kind(), t, v.Interface())
- }
-
- typeMeta := v.FieldByName("TypeMeta")
- if !typeMeta.IsValid() {
- return nil, fmt.Errorf("struct %v lacks embedded TypeMeta type", t)
- }
- a := &genericAccessor{}
- if err := extractFromTypeMeta(typeMeta, a); err != nil {
- return nil, fmt.Errorf("unable to find type fields on %#v: %v", typeMeta, err)
- }
- return a, nil
-}
-
-type objectAccessor struct {
- runtime.Object
-}
-
-func (obj objectAccessor) GetKind() string {
- return obj.GetObjectKind().GroupVersionKind().Kind
-}
-
-func (obj objectAccessor) SetKind(kind string) {
- gvk := obj.GetObjectKind().GroupVersionKind()
- gvk.Kind = kind
- obj.GetObjectKind().SetGroupVersionKind(gvk)
-}
-
-func (obj objectAccessor) GetAPIVersion() string {
- return obj.GetObjectKind().GroupVersionKind().GroupVersion().String()
-}
-
-func (obj objectAccessor) SetAPIVersion(version string) {
- gvk := obj.GetObjectKind().GroupVersionKind()
- gv, err := schema.ParseGroupVersion(version)
- if err != nil {
- gv = schema.GroupVersion{Version: version}
- }
- gvk.Group, gvk.Version = gv.Group, gv.Version
- obj.GetObjectKind().SetGroupVersionKind(gvk)
-}
-
-// NewAccessor returns a MetadataAccessor that can retrieve
-// or manipulate resource version on objects derived from core API
-// metadata concepts.
-func NewAccessor() MetadataAccessor {
- return resourceAccessor{}
-}
-
-// resourceAccessor implements ResourceVersioner and SelfLinker.
-type resourceAccessor struct{}
-
-func (resourceAccessor) Kind(obj runtime.Object) (string, error) {
- return objectAccessor{obj}.GetKind(), nil
-}
-
-func (resourceAccessor) SetKind(obj runtime.Object, kind string) error {
- objectAccessor{obj}.SetKind(kind)
- return nil
-}
-
-func (resourceAccessor) APIVersion(obj runtime.Object) (string, error) {
- return objectAccessor{obj}.GetAPIVersion(), nil
-}
-
-func (resourceAccessor) SetAPIVersion(obj runtime.Object, version string) error {
- objectAccessor{obj}.SetAPIVersion(version)
- return nil
-}
-
-func (resourceAccessor) Namespace(obj runtime.Object) (string, error) {
- accessor, err := Accessor(obj)
- if err != nil {
- return "", err
- }
- return accessor.GetNamespace(), nil
-}
-
-func (resourceAccessor) SetNamespace(obj runtime.Object, namespace string) error {
- accessor, err := Accessor(obj)
- if err != nil {
- return err
- }
- accessor.SetNamespace(namespace)
- return nil
-}
-
-func (resourceAccessor) Name(obj runtime.Object) (string, error) {
- accessor, err := Accessor(obj)
- if err != nil {
- return "", err
- }
- return accessor.GetName(), nil
-}
-
-func (resourceAccessor) SetName(obj runtime.Object, name string) error {
- accessor, err := Accessor(obj)
- if err != nil {
- return err
- }
- accessor.SetName(name)
- return nil
-}
-
-func (resourceAccessor) GenerateName(obj runtime.Object) (string, error) {
- accessor, err := Accessor(obj)
- if err != nil {
- return "", err
- }
- return accessor.GetGenerateName(), nil
-}
-
-func (resourceAccessor) SetGenerateName(obj runtime.Object, name string) error {
- accessor, err := Accessor(obj)
- if err != nil {
- return err
- }
- accessor.SetGenerateName(name)
- return nil
-}
-
-func (resourceAccessor) UID(obj runtime.Object) (types.UID, error) {
- accessor, err := Accessor(obj)
- if err != nil {
- return "", err
- }
- return accessor.GetUID(), nil
-}
-
-func (resourceAccessor) SetUID(obj runtime.Object, uid types.UID) error {
- accessor, err := Accessor(obj)
- if err != nil {
- return err
- }
- accessor.SetUID(uid)
- return nil
-}
-
-func (resourceAccessor) SelfLink(obj runtime.Object) (string, error) {
- accessor, err := CommonAccessor(obj)
- if err != nil {
- return "", err
- }
- return accessor.GetSelfLink(), nil
-}
-
-func (resourceAccessor) SetSelfLink(obj runtime.Object, selfLink string) error {
- accessor, err := CommonAccessor(obj)
- if err != nil {
- return err
- }
- accessor.SetSelfLink(selfLink)
- return nil
-}
-
-func (resourceAccessor) Labels(obj runtime.Object) (map[string]string, error) {
- accessor, err := Accessor(obj)
- if err != nil {
- return nil, err
- }
- return accessor.GetLabels(), nil
-}
-
-func (resourceAccessor) SetLabels(obj runtime.Object, labels map[string]string) error {
- accessor, err := Accessor(obj)
- if err != nil {
- return err
- }
- accessor.SetLabels(labels)
- return nil
-}
-
-func (resourceAccessor) Annotations(obj runtime.Object) (map[string]string, error) {
- accessor, err := Accessor(obj)
- if err != nil {
- return nil, err
- }
- return accessor.GetAnnotations(), nil
-}
-
-func (resourceAccessor) SetAnnotations(obj runtime.Object, annotations map[string]string) error {
- accessor, err := Accessor(obj)
- if err != nil {
- return err
- }
- accessor.SetAnnotations(annotations)
- return nil
-}
-
-func (resourceAccessor) ResourceVersion(obj runtime.Object) (string, error) {
- accessor, err := CommonAccessor(obj)
- if err != nil {
- return "", err
- }
- return accessor.GetResourceVersion(), nil
-}
-
-func (resourceAccessor) SetResourceVersion(obj runtime.Object, version string) error {
- accessor, err := CommonAccessor(obj)
- if err != nil {
- return err
- }
- accessor.SetResourceVersion(version)
- return nil
-}
-
-func (resourceAccessor) Continue(obj runtime.Object) (string, error) {
- accessor, err := ListAccessor(obj)
- if err != nil {
- return "", err
- }
- return accessor.GetContinue(), nil
-}
-
-func (resourceAccessor) SetContinue(obj runtime.Object, version string) error {
- accessor, err := ListAccessor(obj)
- if err != nil {
- return err
- }
- accessor.SetContinue(version)
- return nil
-}
-
-// extractFromOwnerReference extracts v to o. v is the OwnerReferences field of an object.
-func extractFromOwnerReference(v reflect.Value, o *metav1.OwnerReference) error {
- if err := runtime.Field(v, "APIVersion", &o.APIVersion); err != nil {
- return err
- }
- if err := runtime.Field(v, "Kind", &o.Kind); err != nil {
- return err
- }
- if err := runtime.Field(v, "Name", &o.Name); err != nil {
- return err
- }
- if err := runtime.Field(v, "UID", &o.UID); err != nil {
- return err
- }
- var controllerPtr *bool
- if err := runtime.Field(v, "Controller", &controllerPtr); err != nil {
- return err
- }
- if controllerPtr != nil {
- controller := *controllerPtr
- o.Controller = &controller
- }
- var blockOwnerDeletionPtr *bool
- if err := runtime.Field(v, "BlockOwnerDeletion", &blockOwnerDeletionPtr); err != nil {
- return err
- }
- if blockOwnerDeletionPtr != nil {
- block := *blockOwnerDeletionPtr
- o.BlockOwnerDeletion = &block
- }
- return nil
-}
-
-// setOwnerReference sets v to o. v is the OwnerReferences field of an object.
-func setOwnerReference(v reflect.Value, o *metav1.OwnerReference) error {
- if err := runtime.SetField(o.APIVersion, v, "APIVersion"); err != nil {
- return err
- }
- if err := runtime.SetField(o.Kind, v, "Kind"); err != nil {
- return err
- }
- if err := runtime.SetField(o.Name, v, "Name"); err != nil {
- return err
- }
- if err := runtime.SetField(o.UID, v, "UID"); err != nil {
- return err
- }
- if o.Controller != nil {
- controller := *(o.Controller)
- if err := runtime.SetField(&controller, v, "Controller"); err != nil {
- return err
- }
- }
- if o.BlockOwnerDeletion != nil {
- block := *(o.BlockOwnerDeletion)
- if err := runtime.SetField(&block, v, "BlockOwnerDeletion"); err != nil {
- return err
- }
- }
- return nil
-}
-
-// genericAccessor contains pointers to strings that can modify an arbitrary
-// struct and implements the Accessor interface.
-type genericAccessor struct {
- namespace *string
- name *string
- generateName *string
- uid *types.UID
- apiVersion *string
- kind *string
- resourceVersion *string
- selfLink *string
- creationTimestamp *metav1.Time
- deletionTimestamp **metav1.Time
- labels *map[string]string
- annotations *map[string]string
- ownerReferences reflect.Value
- finalizers *[]string
-}
-
-func (a genericAccessor) GetNamespace() string {
- if a.namespace == nil {
- return ""
- }
- return *a.namespace
-}
-
-func (a genericAccessor) SetNamespace(namespace string) {
- if a.namespace == nil {
- return
- }
- *a.namespace = namespace
-}
-
-func (a genericAccessor) GetName() string {
- if a.name == nil {
- return ""
- }
- return *a.name
-}
-
-func (a genericAccessor) SetName(name string) {
- if a.name == nil {
- return
- }
- *a.name = name
-}
-
-func (a genericAccessor) GetGenerateName() string {
- if a.generateName == nil {
- return ""
- }
- return *a.generateName
-}
-
-func (a genericAccessor) SetGenerateName(generateName string) {
- if a.generateName == nil {
- return
- }
- *a.generateName = generateName
-}
-
-func (a genericAccessor) GetUID() types.UID {
- if a.uid == nil {
- return ""
- }
- return *a.uid
-}
-
-func (a genericAccessor) SetUID(uid types.UID) {
- if a.uid == nil {
- return
- }
- *a.uid = uid
-}
-
-func (a genericAccessor) GetAPIVersion() string {
- return *a.apiVersion
-}
-
-func (a genericAccessor) SetAPIVersion(version string) {
- *a.apiVersion = version
-}
-
-func (a genericAccessor) GetKind() string {
- return *a.kind
-}
-
-func (a genericAccessor) SetKind(kind string) {
- *a.kind = kind
-}
-
-func (a genericAccessor) GetResourceVersion() string {
- return *a.resourceVersion
-}
-
-func (a genericAccessor) SetResourceVersion(version string) {
- *a.resourceVersion = version
-}
-
-func (a genericAccessor) GetSelfLink() string {
- return *a.selfLink
-}
-
-func (a genericAccessor) SetSelfLink(selfLink string) {
- *a.selfLink = selfLink
-}
-
-func (a genericAccessor) GetCreationTimestamp() metav1.Time {
- return *a.creationTimestamp
-}
-
-func (a genericAccessor) SetCreationTimestamp(timestamp metav1.Time) {
- *a.creationTimestamp = timestamp
-}
-
-func (a genericAccessor) GetDeletionTimestamp() *metav1.Time {
- return *a.deletionTimestamp
-}
-
-func (a genericAccessor) SetDeletionTimestamp(timestamp *metav1.Time) {
- *a.deletionTimestamp = timestamp
-}
-
-func (a genericAccessor) GetLabels() map[string]string {
- if a.labels == nil {
- return nil
- }
- return *a.labels
-}
-
-func (a genericAccessor) SetLabels(labels map[string]string) {
- *a.labels = labels
-}
-
-func (a genericAccessor) GetAnnotations() map[string]string {
- if a.annotations == nil {
- return nil
- }
- return *a.annotations
-}
-
-func (a genericAccessor) SetAnnotations(annotations map[string]string) {
- if a.annotations == nil {
- emptyAnnotations := make(map[string]string)
- a.annotations = &emptyAnnotations
- }
- *a.annotations = annotations
-}
-
-func (a genericAccessor) GetFinalizers() []string {
- if a.finalizers == nil {
- return nil
- }
- return *a.finalizers
-}
-
-func (a genericAccessor) SetFinalizers(finalizers []string) {
- *a.finalizers = finalizers
-}
-
-func (a genericAccessor) GetOwnerReferences() []metav1.OwnerReference {
- var ret []metav1.OwnerReference
- s := a.ownerReferences
- if s.Kind() != reflect.Ptr || s.Elem().Kind() != reflect.Slice {
- glog.Errorf("expect %v to be a pointer to slice", s)
- return ret
- }
- s = s.Elem()
- // Set the capacity to one element greater to avoid copy if the caller later append an element.
- ret = make([]metav1.OwnerReference, s.Len(), s.Len()+1)
- for i := 0; i < s.Len(); i++ {
- if err := extractFromOwnerReference(s.Index(i), &ret[i]); err != nil {
- glog.Errorf("extractFromOwnerReference failed: %v", err)
- return ret
- }
- }
- return ret
-}
-
-func (a genericAccessor) SetOwnerReferences(references []metav1.OwnerReference) {
- s := a.ownerReferences
- if s.Kind() != reflect.Ptr || s.Elem().Kind() != reflect.Slice {
- glog.Errorf("expect %v to be a pointer to slice", s)
- }
- s = s.Elem()
- newReferences := reflect.MakeSlice(s.Type(), len(references), len(references))
- for i := 0; i < len(references); i++ {
- if err := setOwnerReference(newReferences.Index(i), &references[i]); err != nil {
- glog.Errorf("setOwnerReference failed: %v", err)
- return
- }
- }
- s.Set(newReferences)
-}
-
-// extractFromTypeMeta extracts pointers to version and kind fields from an object
-func extractFromTypeMeta(v reflect.Value, a *genericAccessor) error {
- if err := runtime.FieldPtr(v, "APIVersion", &a.apiVersion); err != nil {
- return err
- }
- if err := runtime.FieldPtr(v, "Kind", &a.kind); err != nil {
- return err
- }
- return nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go b/vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go
deleted file mode 100644
index 6b01bf197..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
-Copyright 2014 The 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 meta
-
-import (
- "fmt"
- "strings"
-
- "k8s.io/apimachinery/pkg/runtime/schema"
- utilerrors "k8s.io/apimachinery/pkg/util/errors"
-)
-
-// MultiRESTMapper is a wrapper for multiple RESTMappers.
-type MultiRESTMapper []RESTMapper
-
-func (m MultiRESTMapper) String() string {
- nested := []string{}
- for _, t := range m {
- currString := fmt.Sprintf("%v", t)
- splitStrings := strings.Split(currString, "\n")
- nested = append(nested, strings.Join(splitStrings, "\n\t"))
- }
-
- return fmt.Sprintf("MultiRESTMapper{\n\t%s\n}", strings.Join(nested, "\n\t"))
-}
-
-// ResourceSingularizer converts a REST resource name from plural to singular (e.g., from pods to pod)
-// This implementation supports multiple REST schemas and return the first match.
-func (m MultiRESTMapper) ResourceSingularizer(resource string) (singular string, err error) {
- for _, t := range m {
- singular, err = t.ResourceSingularizer(resource)
- if err == nil {
- return
- }
- }
- return
-}
-
-func (m MultiRESTMapper) ResourcesFor(resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
- allGVRs := []schema.GroupVersionResource{}
- for _, t := range m {
- gvrs, err := t.ResourcesFor(resource)
- // ignore "no match" errors, but any other error percolates back up
- if IsNoMatchError(err) {
- continue
- }
- if err != nil {
- return nil, err
- }
-
- // walk the existing values to de-dup
- for _, curr := range gvrs {
- found := false
- for _, existing := range allGVRs {
- if curr == existing {
- found = true
- break
- }
- }
-
- if !found {
- allGVRs = append(allGVRs, curr)
- }
- }
- }
-
- if len(allGVRs) == 0 {
- return nil, &NoResourceMatchError{PartialResource: resource}
- }
-
- return allGVRs, nil
-}
-
-func (m MultiRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) {
- allGVKs := []schema.GroupVersionKind{}
- for _, t := range m {
- gvks, err := t.KindsFor(resource)
- // ignore "no match" errors, but any other error percolates back up
- if IsNoMatchError(err) {
- continue
- }
- if err != nil {
- return nil, err
- }
-
- // walk the existing values to de-dup
- for _, curr := range gvks {
- found := false
- for _, existing := range allGVKs {
- if curr == existing {
- found = true
- break
- }
- }
-
- if !found {
- allGVKs = append(allGVKs, curr)
- }
- }
- }
-
- if len(allGVKs) == 0 {
- return nil, &NoResourceMatchError{PartialResource: resource}
- }
-
- return allGVKs, nil
-}
-
-func (m MultiRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {
- resources, err := m.ResourcesFor(resource)
- if err != nil {
- return schema.GroupVersionResource{}, err
- }
- if len(resources) == 1 {
- return resources[0], nil
- }
-
- return schema.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: resource, MatchingResources: resources}
-}
-
-func (m MultiRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
- kinds, err := m.KindsFor(resource)
- if err != nil {
- return schema.GroupVersionKind{}, err
- }
- if len(kinds) == 1 {
- return kinds[0], nil
- }
-
- return schema.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds}
-}
-
-// RESTMapping provides the REST mapping for the resource based on the
-// kind and version. This implementation supports multiple REST schemas and
-// return the first match.
-func (m MultiRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {
- allMappings := []*RESTMapping{}
- errors := []error{}
-
- for _, t := range m {
- currMapping, err := t.RESTMapping(gk, versions...)
- // ignore "no match" errors, but any other error percolates back up
- if IsNoMatchError(err) {
- continue
- }
- if err != nil {
- errors = append(errors, err)
- continue
- }
-
- allMappings = append(allMappings, currMapping)
- }
-
- // if we got exactly one mapping, then use it even if other requested failed
- if len(allMappings) == 1 {
- return allMappings[0], nil
- }
- if len(allMappings) > 1 {
- var kinds []schema.GroupVersionKind
- for _, m := range allMappings {
- kinds = append(kinds, m.GroupVersionKind)
- }
- return nil, &AmbiguousKindError{PartialKind: gk.WithVersion(""), MatchingKinds: kinds}
- }
- if len(errors) > 0 {
- return nil, utilerrors.NewAggregate(errors)
- }
- return nil, &NoKindMatchError{GroupKind: gk, SearchedVersions: versions}
-}
-
-// RESTMappings returns all possible RESTMappings for the provided group kind, or an error
-// if the type is not recognized.
-func (m MultiRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {
- var allMappings []*RESTMapping
- var errors []error
-
- for _, t := range m {
- currMappings, err := t.RESTMappings(gk, versions...)
- // ignore "no match" errors, but any other error percolates back up
- if IsNoMatchError(err) {
- continue
- }
- if err != nil {
- errors = append(errors, err)
- continue
- }
- allMappings = append(allMappings, currMappings...)
- }
- if len(errors) > 0 {
- return nil, utilerrors.NewAggregate(errors)
- }
- if len(allMappings) == 0 {
- return nil, &NoKindMatchError{GroupKind: gk, SearchedVersions: versions}
- }
- return allMappings, nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/priority.go b/vendor/k8s.io/apimachinery/pkg/api/meta/priority.go
deleted file mode 100644
index df28e64ff..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/meta/priority.go
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
-Copyright 2016 The 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 meta
-
-import (
- "fmt"
-
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-const (
- AnyGroup = "*"
- AnyVersion = "*"
- AnyResource = "*"
- AnyKind = "*"
-)
-
-// PriorityRESTMapper is a wrapper for automatically choosing a particular Resource or Kind
-// when multiple matches are possible
-type PriorityRESTMapper struct {
- // Delegate is the RESTMapper to use to locate all the Kind and Resource matches
- Delegate RESTMapper
-
- // ResourcePriority is a list of priority patterns to apply to matching resources.
- // The list of all matching resources is narrowed based on the patterns until only one remains.
- // A pattern with no matches is skipped. A pattern with more than one match uses its
- // matches as the list to continue matching against.
- ResourcePriority []schema.GroupVersionResource
-
- // KindPriority is a list of priority patterns to apply to matching kinds.
- // The list of all matching kinds is narrowed based on the patterns until only one remains.
- // A pattern with no matches is skipped. A pattern with more than one match uses its
- // matches as the list to continue matching against.
- KindPriority []schema.GroupVersionKind
-}
-
-func (m PriorityRESTMapper) String() string {
- return fmt.Sprintf("PriorityRESTMapper{\n\t%v\n\t%v\n\t%v\n}", m.ResourcePriority, m.KindPriority, m.Delegate)
-}
-
-// ResourceFor finds all resources, then passes them through the ResourcePriority patterns to find a single matching hit.
-func (m PriorityRESTMapper) ResourceFor(partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionResource, error) {
- originalGVRs, err := m.Delegate.ResourcesFor(partiallySpecifiedResource)
- if err != nil {
- return schema.GroupVersionResource{}, err
- }
- if len(originalGVRs) == 1 {
- return originalGVRs[0], nil
- }
-
- remainingGVRs := append([]schema.GroupVersionResource{}, originalGVRs...)
- for _, pattern := range m.ResourcePriority {
- matchedGVRs := []schema.GroupVersionResource{}
- for _, gvr := range remainingGVRs {
- if resourceMatches(pattern, gvr) {
- matchedGVRs = append(matchedGVRs, gvr)
- }
- }
-
- switch len(matchedGVRs) {
- case 0:
- // if you have no matches, then nothing matched this pattern just move to the next
- continue
- case 1:
- // one match, return
- return matchedGVRs[0], nil
- default:
- // more than one match, use the matched hits as the list moving to the next pattern.
- // this way you can have a series of selection criteria
- remainingGVRs = matchedGVRs
- }
- }
-
- return schema.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: partiallySpecifiedResource, MatchingResources: originalGVRs}
-}
-
-// KindFor finds all kinds, then passes them through the KindPriority patterns to find a single matching hit.
-func (m PriorityRESTMapper) KindFor(partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
- originalGVKs, err := m.Delegate.KindsFor(partiallySpecifiedResource)
- if err != nil {
- return schema.GroupVersionKind{}, err
- }
- if len(originalGVKs) == 1 {
- return originalGVKs[0], nil
- }
-
- remainingGVKs := append([]schema.GroupVersionKind{}, originalGVKs...)
- for _, pattern := range m.KindPriority {
- matchedGVKs := []schema.GroupVersionKind{}
- for _, gvr := range remainingGVKs {
- if kindMatches(pattern, gvr) {
- matchedGVKs = append(matchedGVKs, gvr)
- }
- }
-
- switch len(matchedGVKs) {
- case 0:
- // if you have no matches, then nothing matched this pattern just move to the next
- continue
- case 1:
- // one match, return
- return matchedGVKs[0], nil
- default:
- // more than one match, use the matched hits as the list moving to the next pattern.
- // this way you can have a series of selection criteria
- remainingGVKs = matchedGVKs
- }
- }
-
- return schema.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: partiallySpecifiedResource, MatchingKinds: originalGVKs}
-}
-
-func resourceMatches(pattern schema.GroupVersionResource, resource schema.GroupVersionResource) bool {
- if pattern.Group != AnyGroup && pattern.Group != resource.Group {
- return false
- }
- if pattern.Version != AnyVersion && pattern.Version != resource.Version {
- return false
- }
- if pattern.Resource != AnyResource && pattern.Resource != resource.Resource {
- return false
- }
-
- return true
-}
-
-func kindMatches(pattern schema.GroupVersionKind, kind schema.GroupVersionKind) bool {
- if pattern.Group != AnyGroup && pattern.Group != kind.Group {
- return false
- }
- if pattern.Version != AnyVersion && pattern.Version != kind.Version {
- return false
- }
- if pattern.Kind != AnyKind && pattern.Kind != kind.Kind {
- return false
- }
-
- return true
-}
-
-func (m PriorityRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (mapping *RESTMapping, err error) {
- mappings, err := m.Delegate.RESTMappings(gk, versions...)
- if err != nil {
- return nil, err
- }
-
- // any versions the user provides take priority
- priorities := m.KindPriority
- if len(versions) > 0 {
- priorities = make([]schema.GroupVersionKind, 0, len(m.KindPriority)+len(versions))
- for _, version := range versions {
- gv := schema.GroupVersion{
- Version: version,
- Group: gk.Group,
- }
- priorities = append(priorities, gv.WithKind(AnyKind))
- }
- priorities = append(priorities, m.KindPriority...)
- }
-
- remaining := append([]*RESTMapping{}, mappings...)
- for _, pattern := range priorities {
- var matching []*RESTMapping
- for _, m := range remaining {
- if kindMatches(pattern, m.GroupVersionKind) {
- matching = append(matching, m)
- }
- }
-
- switch len(matching) {
- case 0:
- // if you have no matches, then nothing matched this pattern just move to the next
- continue
- case 1:
- // one match, return
- return matching[0], nil
- default:
- // more than one match, use the matched hits as the list moving to the next pattern.
- // this way you can have a series of selection criteria
- remaining = matching
- }
- }
- if len(remaining) == 1 {
- return remaining[0], nil
- }
-
- var kinds []schema.GroupVersionKind
- for _, m := range mappings {
- kinds = append(kinds, m.GroupVersionKind)
- }
- return nil, &AmbiguousKindError{PartialKind: gk.WithVersion(""), MatchingKinds: kinds}
-}
-
-func (m PriorityRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {
- return m.Delegate.RESTMappings(gk, versions...)
-}
-
-func (m PriorityRESTMapper) ResourceSingularizer(resource string) (singular string, err error) {
- return m.Delegate.ResourceSingularizer(resource)
-}
-
-func (m PriorityRESTMapper) ResourcesFor(partiallySpecifiedResource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
- return m.Delegate.ResourcesFor(partiallySpecifiedResource)
-}
-
-func (m PriorityRESTMapper) KindsFor(partiallySpecifiedResource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) {
- return m.Delegate.KindsFor(partiallySpecifiedResource)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/restmapper.go b/vendor/k8s.io/apimachinery/pkg/api/meta/restmapper.go
deleted file mode 100644
index ff945acd1..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/meta/restmapper.go
+++ /dev/null
@@ -1,548 +0,0 @@
-/*
-Copyright 2014 The 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.
-*/
-
-// TODO: move everything in this file to pkg/api/rest
-package meta
-
-import (
- "fmt"
- "sort"
- "strings"
-
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// Implements RESTScope interface
-type restScope struct {
- name RESTScopeName
- paramName string
- argumentName string
- paramDescription string
-}
-
-func (r *restScope) Name() RESTScopeName {
- return r.name
-}
-func (r *restScope) ParamName() string {
- return r.paramName
-}
-func (r *restScope) ArgumentName() string {
- return r.argumentName
-}
-func (r *restScope) ParamDescription() string {
- return r.paramDescription
-}
-
-var RESTScopeNamespace = &restScope{
- name: RESTScopeNameNamespace,
- paramName: "namespaces",
- argumentName: "namespace",
- paramDescription: "object name and auth scope, such as for teams and projects",
-}
-
-var RESTScopeRoot = &restScope{
- name: RESTScopeNameRoot,
-}
-
-// DefaultRESTMapper exposes mappings between the types defined in a
-// runtime.Scheme. It assumes that all types defined the provided scheme
-// can be mapped with the provided MetadataAccessor and Codec interfaces.
-//
-// The resource name of a Kind is defined as the lowercase,
-// English-plural version of the Kind string.
-// When converting from resource to Kind, the singular version of the
-// resource name is also accepted for convenience.
-//
-// TODO: Only accept plural for some operations for increased control?
-// (`get pod bar` vs `get pods bar`)
-type DefaultRESTMapper struct {
- defaultGroupVersions []schema.GroupVersion
-
- resourceToKind map[schema.GroupVersionResource]schema.GroupVersionKind
- kindToPluralResource map[schema.GroupVersionKind]schema.GroupVersionResource
- kindToScope map[schema.GroupVersionKind]RESTScope
- singularToPlural map[schema.GroupVersionResource]schema.GroupVersionResource
- pluralToSingular map[schema.GroupVersionResource]schema.GroupVersionResource
-
- interfacesFunc VersionInterfacesFunc
-}
-
-func (m *DefaultRESTMapper) String() string {
- return fmt.Sprintf("DefaultRESTMapper{kindToPluralResource=%v}", m.kindToPluralResource)
-}
-
-var _ RESTMapper = &DefaultRESTMapper{}
-
-// VersionInterfacesFunc returns the appropriate typer, and metadata accessor for a
-// given api version, or an error if no such api version exists.
-type VersionInterfacesFunc func(version schema.GroupVersion) (*VersionInterfaces, error)
-
-// NewDefaultRESTMapper initializes a mapping between Kind and APIVersion
-// to a resource name and back based on the objects in a runtime.Scheme
-// and the Kubernetes API conventions. Takes a group name, a priority list of the versions
-// to search when an object has no default version (set empty to return an error),
-// and a function that retrieves the correct metadata for a given version.
-func NewDefaultRESTMapper(defaultGroupVersions []schema.GroupVersion, f VersionInterfacesFunc) *DefaultRESTMapper {
- resourceToKind := make(map[schema.GroupVersionResource]schema.GroupVersionKind)
- kindToPluralResource := make(map[schema.GroupVersionKind]schema.GroupVersionResource)
- kindToScope := make(map[schema.GroupVersionKind]RESTScope)
- singularToPlural := make(map[schema.GroupVersionResource]schema.GroupVersionResource)
- pluralToSingular := make(map[schema.GroupVersionResource]schema.GroupVersionResource)
- // TODO: verify name mappings work correctly when versions differ
-
- return &DefaultRESTMapper{
- resourceToKind: resourceToKind,
- kindToPluralResource: kindToPluralResource,
- kindToScope: kindToScope,
- defaultGroupVersions: defaultGroupVersions,
- singularToPlural: singularToPlural,
- pluralToSingular: pluralToSingular,
- interfacesFunc: f,
- }
-}
-
-func (m *DefaultRESTMapper) Add(kind schema.GroupVersionKind, scope RESTScope) {
- plural, singular := UnsafeGuessKindToResource(kind)
- m.AddSpecific(kind, plural, singular, scope)
-}
-
-func (m *DefaultRESTMapper) AddSpecific(kind schema.GroupVersionKind, plural, singular schema.GroupVersionResource, scope RESTScope) {
- m.singularToPlural[singular] = plural
- m.pluralToSingular[plural] = singular
-
- m.resourceToKind[singular] = kind
- m.resourceToKind[plural] = kind
-
- m.kindToPluralResource[kind] = plural
- m.kindToScope[kind] = scope
-}
-
-// unpluralizedSuffixes is a list of resource suffixes that are the same plural and singular
-// This is only is only necessary because some bits of code are lazy and don't actually use the RESTMapper like they should.
-// TODO eliminate this so that different callers can correctly map to resources. This probably means updating all
-// callers to use the RESTMapper they mean.
-var unpluralizedSuffixes = []string{
- "endpoints",
-}
-
-// UnsafeGuessKindToResource converts Kind to a resource name.
-// Broken. This method only "sort of" works when used outside of this package. It assumes that Kinds and Resources match
-// and they aren't guaranteed to do so.
-func UnsafeGuessKindToResource(kind schema.GroupVersionKind) ( /*plural*/ schema.GroupVersionResource /*singular*/, schema.GroupVersionResource) {
- kindName := kind.Kind
- if len(kindName) == 0 {
- return schema.GroupVersionResource{}, schema.GroupVersionResource{}
- }
- singularName := strings.ToLower(kindName)
- singular := kind.GroupVersion().WithResource(singularName)
-
- for _, skip := range unpluralizedSuffixes {
- if strings.HasSuffix(singularName, skip) {
- return singular, singular
- }
- }
-
- switch string(singularName[len(singularName)-1]) {
- case "s":
- return kind.GroupVersion().WithResource(singularName + "es"), singular
- case "y":
- return kind.GroupVersion().WithResource(strings.TrimSuffix(singularName, "y") + "ies"), singular
- }
-
- return kind.GroupVersion().WithResource(singularName + "s"), singular
-}
-
-// ResourceSingularizer implements RESTMapper
-// It converts a resource name from plural to singular (e.g., from pods to pod)
-func (m *DefaultRESTMapper) ResourceSingularizer(resourceType string) (string, error) {
- partialResource := schema.GroupVersionResource{Resource: resourceType}
- resources, err := m.ResourcesFor(partialResource)
- if err != nil {
- return resourceType, err
- }
-
- singular := schema.GroupVersionResource{}
- for _, curr := range resources {
- currSingular, ok := m.pluralToSingular[curr]
- if !ok {
- continue
- }
- if singular.Empty() {
- singular = currSingular
- continue
- }
-
- if currSingular.Resource != singular.Resource {
- return resourceType, fmt.Errorf("multiple possible singular resources (%v) found for %v", resources, resourceType)
- }
- }
-
- if singular.Empty() {
- return resourceType, fmt.Errorf("no singular of resource %v has been defined", resourceType)
- }
-
- return singular.Resource, nil
-}
-
-// coerceResourceForMatching makes the resource lower case and converts internal versions to unspecified (legacy behavior)
-func coerceResourceForMatching(resource schema.GroupVersionResource) schema.GroupVersionResource {
- resource.Resource = strings.ToLower(resource.Resource)
- if resource.Version == runtime.APIVersionInternal {
- resource.Version = ""
- }
-
- return resource
-}
-
-func (m *DefaultRESTMapper) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
- resource := coerceResourceForMatching(input)
-
- hasResource := len(resource.Resource) > 0
- hasGroup := len(resource.Group) > 0
- hasVersion := len(resource.Version) > 0
-
- if !hasResource {
- return nil, fmt.Errorf("a resource must be present, got: %v", resource)
- }
-
- ret := []schema.GroupVersionResource{}
- switch {
- case hasGroup && hasVersion:
- // fully qualified. Find the exact match
- for plural, singular := range m.pluralToSingular {
- if singular == resource {
- ret = append(ret, plural)
- break
- }
- if plural == resource {
- ret = append(ret, plural)
- break
- }
- }
-
- case hasGroup:
- // given a group, prefer an exact match. If you don't find one, resort to a prefix match on group
- foundExactMatch := false
- requestedGroupResource := resource.GroupResource()
- for plural, singular := range m.pluralToSingular {
- if singular.GroupResource() == requestedGroupResource {
- foundExactMatch = true
- ret = append(ret, plural)
- }
- if plural.GroupResource() == requestedGroupResource {
- foundExactMatch = true
- ret = append(ret, plural)
- }
- }
-
- // if you didn't find an exact match, match on group prefixing. This allows storageclass.storage to match
- // storageclass.storage.k8s.io
- if !foundExactMatch {
- for plural, singular := range m.pluralToSingular {
- if !strings.HasPrefix(plural.Group, requestedGroupResource.Group) {
- continue
- }
- if singular.Resource == requestedGroupResource.Resource {
- ret = append(ret, plural)
- }
- if plural.Resource == requestedGroupResource.Resource {
- ret = append(ret, plural)
- }
- }
-
- }
-
- case hasVersion:
- for plural, singular := range m.pluralToSingular {
- if singular.Version == resource.Version && singular.Resource == resource.Resource {
- ret = append(ret, plural)
- }
- if plural.Version == resource.Version && plural.Resource == resource.Resource {
- ret = append(ret, plural)
- }
- }
-
- default:
- for plural, singular := range m.pluralToSingular {
- if singular.Resource == resource.Resource {
- ret = append(ret, plural)
- }
- if plural.Resource == resource.Resource {
- ret = append(ret, plural)
- }
- }
- }
-
- if len(ret) == 0 {
- return nil, &NoResourceMatchError{PartialResource: resource}
- }
-
- sort.Sort(resourceByPreferredGroupVersion{ret, m.defaultGroupVersions})
- return ret, nil
-}
-
-func (m *DefaultRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {
- resources, err := m.ResourcesFor(resource)
- if err != nil {
- return schema.GroupVersionResource{}, err
- }
- if len(resources) == 1 {
- return resources[0], nil
- }
-
- return schema.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: resource, MatchingResources: resources}
-}
-
-func (m *DefaultRESTMapper) KindsFor(input schema.GroupVersionResource) ([]schema.GroupVersionKind, error) {
- resource := coerceResourceForMatching(input)
-
- hasResource := len(resource.Resource) > 0
- hasGroup := len(resource.Group) > 0
- hasVersion := len(resource.Version) > 0
-
- if !hasResource {
- return nil, fmt.Errorf("a resource must be present, got: %v", resource)
- }
-
- ret := []schema.GroupVersionKind{}
- switch {
- // fully qualified. Find the exact match
- case hasGroup && hasVersion:
- kind, exists := m.resourceToKind[resource]
- if exists {
- ret = append(ret, kind)
- }
-
- case hasGroup:
- foundExactMatch := false
- requestedGroupResource := resource.GroupResource()
- for currResource, currKind := range m.resourceToKind {
- if currResource.GroupResource() == requestedGroupResource {
- foundExactMatch = true
- ret = append(ret, currKind)
- }
- }
-
- // if you didn't find an exact match, match on group prefixing. This allows storageclass.storage to match
- // storageclass.storage.k8s.io
- if !foundExactMatch {
- for currResource, currKind := range m.resourceToKind {
- if !strings.HasPrefix(currResource.Group, requestedGroupResource.Group) {
- continue
- }
- if currResource.Resource == requestedGroupResource.Resource {
- ret = append(ret, currKind)
- }
- }
-
- }
-
- case hasVersion:
- for currResource, currKind := range m.resourceToKind {
- if currResource.Version == resource.Version && currResource.Resource == resource.Resource {
- ret = append(ret, currKind)
- }
- }
-
- default:
- for currResource, currKind := range m.resourceToKind {
- if currResource.Resource == resource.Resource {
- ret = append(ret, currKind)
- }
- }
- }
-
- if len(ret) == 0 {
- return nil, &NoResourceMatchError{PartialResource: input}
- }
-
- sort.Sort(kindByPreferredGroupVersion{ret, m.defaultGroupVersions})
- return ret, nil
-}
-
-func (m *DefaultRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
- kinds, err := m.KindsFor(resource)
- if err != nil {
- return schema.GroupVersionKind{}, err
- }
- if len(kinds) == 1 {
- return kinds[0], nil
- }
-
- return schema.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds}
-}
-
-type kindByPreferredGroupVersion struct {
- list []schema.GroupVersionKind
- sortOrder []schema.GroupVersion
-}
-
-func (o kindByPreferredGroupVersion) Len() int { return len(o.list) }
-func (o kindByPreferredGroupVersion) Swap(i, j int) { o.list[i], o.list[j] = o.list[j], o.list[i] }
-func (o kindByPreferredGroupVersion) Less(i, j int) bool {
- lhs := o.list[i]
- rhs := o.list[j]
- if lhs == rhs {
- return false
- }
-
- if lhs.GroupVersion() == rhs.GroupVersion() {
- return lhs.Kind < rhs.Kind
- }
-
- // otherwise, the difference is in the GroupVersion, so we need to sort with respect to the preferred order
- lhsIndex := -1
- rhsIndex := -1
-
- for i := range o.sortOrder {
- if o.sortOrder[i] == lhs.GroupVersion() {
- lhsIndex = i
- }
- if o.sortOrder[i] == rhs.GroupVersion() {
- rhsIndex = i
- }
- }
-
- if rhsIndex == -1 {
- return true
- }
-
- return lhsIndex < rhsIndex
-}
-
-type resourceByPreferredGroupVersion struct {
- list []schema.GroupVersionResource
- sortOrder []schema.GroupVersion
-}
-
-func (o resourceByPreferredGroupVersion) Len() int { return len(o.list) }
-func (o resourceByPreferredGroupVersion) Swap(i, j int) { o.list[i], o.list[j] = o.list[j], o.list[i] }
-func (o resourceByPreferredGroupVersion) Less(i, j int) bool {
- lhs := o.list[i]
- rhs := o.list[j]
- if lhs == rhs {
- return false
- }
-
- if lhs.GroupVersion() == rhs.GroupVersion() {
- return lhs.Resource < rhs.Resource
- }
-
- // otherwise, the difference is in the GroupVersion, so we need to sort with respect to the preferred order
- lhsIndex := -1
- rhsIndex := -1
-
- for i := range o.sortOrder {
- if o.sortOrder[i] == lhs.GroupVersion() {
- lhsIndex = i
- }
- if o.sortOrder[i] == rhs.GroupVersion() {
- rhsIndex = i
- }
- }
-
- if rhsIndex == -1 {
- return true
- }
-
- return lhsIndex < rhsIndex
-}
-
-// RESTMapping returns a struct representing the resource path and conversion interfaces a
-// RESTClient should use to operate on the provided group/kind in order of versions. If a version search
-// order is not provided, the search order provided to DefaultRESTMapper will be used to resolve which
-// version should be used to access the named group/kind.
-func (m *DefaultRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {
- mappings, err := m.RESTMappings(gk, versions...)
- if err != nil {
- return nil, err
- }
- if len(mappings) == 0 {
- return nil, &NoKindMatchError{GroupKind: gk, SearchedVersions: versions}
- }
- // since we rely on RESTMappings method
- // take the first match and return to the caller
- // as this was the existing behavior.
- return mappings[0], nil
-}
-
-// RESTMappings returns the RESTMappings for the provided group kind. If a version search order
-// is not provided, the search order provided to DefaultRESTMapper will be used.
-func (m *DefaultRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {
- mappings := make([]*RESTMapping, 0)
- potentialGVK := make([]schema.GroupVersionKind, 0)
- hadVersion := false
-
- // Pick an appropriate version
- for _, version := range versions {
- if len(version) == 0 || version == runtime.APIVersionInternal {
- continue
- }
- currGVK := gk.WithVersion(version)
- hadVersion = true
- if _, ok := m.kindToPluralResource[currGVK]; ok {
- potentialGVK = append(potentialGVK, currGVK)
- break
- }
- }
- // Use the default preferred versions
- if !hadVersion && len(potentialGVK) == 0 {
- for _, gv := range m.defaultGroupVersions {
- if gv.Group != gk.Group {
- continue
- }
- potentialGVK = append(potentialGVK, gk.WithVersion(gv.Version))
- }
- }
-
- if len(potentialGVK) == 0 {
- return nil, &NoKindMatchError{GroupKind: gk, SearchedVersions: versions}
- }
-
- for _, gvk := range potentialGVK {
- //Ensure we have a REST mapping
- res, ok := m.kindToPluralResource[gvk]
- if !ok {
- continue
- }
-
- // Ensure we have a REST scope
- scope, ok := m.kindToScope[gvk]
- if !ok {
- return nil, fmt.Errorf("the provided version %q and kind %q cannot be mapped to a supported scope", gvk.GroupVersion(), gvk.Kind)
- }
-
- interfaces, err := m.interfacesFunc(gvk.GroupVersion())
- if err != nil {
- return nil, fmt.Errorf("the provided version %q has no relevant versions: %v", gvk.GroupVersion().String(), err)
- }
-
- mappings = append(mappings, &RESTMapping{
- Resource: res.Resource,
- GroupVersionKind: gvk,
- Scope: scope,
-
- ObjectConvertor: interfaces.ObjectConvertor,
- MetadataAccessor: interfaces.MetadataAccessor,
- })
- }
-
- if len(mappings) == 0 {
- return nil, &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Group: gk.Group, Resource: gk.Kind}}
- }
- return mappings, nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/unstructured.go b/vendor/k8s.io/apimachinery/pkg/api/meta/unstructured.go
deleted file mode 100644
index 4e13efea3..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/meta/unstructured.go
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
-Copyright 2016 The 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 meta
-
-import (
- "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// InterfacesForUnstructuredConversion returns VersionInterfaces suitable for
-// dealing with unstructured.Unstructured objects and supports conversion
-// from typed objects (provided by parent) to untyped objects.
-func InterfacesForUnstructuredConversion(parent VersionInterfacesFunc) VersionInterfacesFunc {
- return func(version schema.GroupVersion) (*VersionInterfaces, error) {
- if i, err := parent(version); err == nil {
- return &VersionInterfaces{
- ObjectConvertor: i.ObjectConvertor,
- MetadataAccessor: NewAccessor(),
- }, nil
- }
- return InterfacesForUnstructured(version)
- }
-}
-
-// InterfacesForUnstructured returns VersionInterfaces suitable for
-// dealing with unstructured.Unstructured objects. It will return errors for
-// other conversions.
-func InterfacesForUnstructured(schema.GroupVersion) (*VersionInterfaces, error) {
- return &VersionInterfaces{
- ObjectConvertor: &unstructured.UnstructuredObjectConverter{},
- MetadataAccessor: NewAccessor(),
- }, nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/api/validation/doc.go b/vendor/k8s.io/apimachinery/pkg/api/validation/doc.go
deleted file mode 100644
index 9f20152e4..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/validation/doc.go
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
-Copyright 2017 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package validation contains generic api type validation functions.
-package validation // import "k8s.io/apimachinery/pkg/api/validation"
diff --git a/vendor/k8s.io/apimachinery/pkg/api/validation/generic.go b/vendor/k8s.io/apimachinery/pkg/api/validation/generic.go
deleted file mode 100644
index 348cdc087..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/validation/generic.go
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package validation
-
-import (
- "strings"
-
- "k8s.io/apimachinery/pkg/util/validation"
- "k8s.io/apimachinery/pkg/util/validation/field"
-)
-
-const IsNegativeErrorMsg string = `must be greater than or equal to 0`
-
-// ValidateNameFunc validates that the provided name is valid for a given resource type.
-// Not all resources have the same validation rules for names. Prefix is true
-// if the name will have a value appended to it. If the name is not valid,
-// this returns a list of descriptions of individual characteristics of the
-// value that were not valid. Otherwise this returns an empty list or nil.
-type ValidateNameFunc func(name string, prefix bool) []string
-
-// NameIsDNSSubdomain is a ValidateNameFunc for names that must be a DNS subdomain.
-func NameIsDNSSubdomain(name string, prefix bool) []string {
- if prefix {
- name = maskTrailingDash(name)
- }
- return validation.IsDNS1123Subdomain(name)
-}
-
-// NameIsDNSLabel is a ValidateNameFunc for names that must be a DNS 1123 label.
-func NameIsDNSLabel(name string, prefix bool) []string {
- if prefix {
- name = maskTrailingDash(name)
- }
- return validation.IsDNS1123Label(name)
-}
-
-// NameIsDNS1035Label is a ValidateNameFunc for names that must be a DNS 952 label.
-func NameIsDNS1035Label(name string, prefix bool) []string {
- if prefix {
- name = maskTrailingDash(name)
- }
- return validation.IsDNS1035Label(name)
-}
-
-// ValidateNamespaceName can be used to check whether the given namespace name is valid.
-// Prefix indicates this name will be used as part of generation, in which case
-// trailing dashes are allowed.
-var ValidateNamespaceName = NameIsDNSLabel
-
-// ValidateServiceAccountName can be used to check whether the given service account name is valid.
-// Prefix indicates this name will be used as part of generation, in which case
-// trailing dashes are allowed.
-var ValidateServiceAccountName = NameIsDNSSubdomain
-
-// maskTrailingDash replaces the final character of a string with a subdomain safe
-// value if is a dash.
-func maskTrailingDash(name string) string {
- if strings.HasSuffix(name, "-") {
- return name[:len(name)-2] + "a"
- }
- return name
-}
-
-// Validates that given value is not negative.
-func ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- if value < 0 {
- allErrs = append(allErrs, field.Invalid(fldPath, value, IsNegativeErrorMsg))
- }
- return allErrs
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go b/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go
deleted file mode 100644
index 3c32a937a..000000000
--- a/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go
+++ /dev/null
@@ -1,343 +0,0 @@
-/*
-Copyright 2014 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package validation
-
-import (
- "fmt"
- "strings"
-
- apiequality "k8s.io/apimachinery/pkg/api/equality"
- "k8s.io/apimachinery/pkg/api/meta"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- v1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/util/sets"
- "k8s.io/apimachinery/pkg/util/validation"
- "k8s.io/apimachinery/pkg/util/validation/field"
-)
-
-// TODO: delete this global variable when we enable the validation of common
-// fields by default.
-var RepairMalformedUpdates bool = true
-
-const FieldImmutableErrorMsg string = `field is immutable`
-
-const totalAnnotationSizeLimitB int = 256 * (1 << 10) // 256 kB
-
-// BannedOwners is a black list of object that are not allowed to be owners.
-var BannedOwners = map[schema.GroupVersionKind]struct{}{
- {Group: "", Version: "v1", Kind: "Event"}: {},
-}
-
-// ValidateClusterName can be used to check whether the given cluster name is valid.
-var ValidateClusterName = NameIsDNS1035Label
-
-// ValidateAnnotations validates that a set of annotations are correctly defined.
-func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- var totalSize int64
- for k, v := range annotations {
- for _, msg := range validation.IsQualifiedName(strings.ToLower(k)) {
- allErrs = append(allErrs, field.Invalid(fldPath, k, msg))
- }
- totalSize += (int64)(len(k)) + (int64)(len(v))
- }
- if totalSize > (int64)(totalAnnotationSizeLimitB) {
- allErrs = append(allErrs, field.TooLong(fldPath, "", totalAnnotationSizeLimitB))
- }
- return allErrs
-}
-
-func validateOwnerReference(ownerReference metav1.OwnerReference, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- gvk := schema.FromAPIVersionAndKind(ownerReference.APIVersion, ownerReference.Kind)
- // gvk.Group is empty for the legacy group.
- if len(gvk.Version) == 0 {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("apiVersion"), ownerReference.APIVersion, "version must not be empty"))
- }
- if len(gvk.Kind) == 0 {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("kind"), ownerReference.Kind, "kind must not be empty"))
- }
- if len(ownerReference.Name) == 0 {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), ownerReference.Name, "name must not be empty"))
- }
- if len(ownerReference.UID) == 0 {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("uid"), ownerReference.UID, "uid must not be empty"))
- }
- if _, ok := BannedOwners[gvk]; ok {
- allErrs = append(allErrs, field.Invalid(fldPath, ownerReference, fmt.Sprintf("%s is disallowed from being an owner", gvk)))
- }
- return allErrs
-}
-
-func ValidateOwnerReferences(ownerReferences []metav1.OwnerReference, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- controllerName := ""
- for _, ref := range ownerReferences {
- allErrs = append(allErrs, validateOwnerReference(ref, fldPath)...)
- if ref.Controller != nil && *ref.Controller {
- if controllerName != "" {
- allErrs = append(allErrs, field.Invalid(fldPath, ownerReferences,
- fmt.Sprintf("Only one reference can have Controller set to true. Found \"true\" in references for %v and %v", controllerName, ref.Name)))
- } else {
- controllerName = ref.Name
- }
- }
- }
- return allErrs
-}
-
-// Validate finalizer names
-func ValidateFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- for _, msg := range validation.IsQualifiedName(stringValue) {
- allErrs = append(allErrs, field.Invalid(fldPath, stringValue, msg))
- }
-
- return allErrs
-}
-
-func ValidateNoNewFinalizers(newFinalizers []string, oldFinalizers []string, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- extra := sets.NewString(newFinalizers...).Difference(sets.NewString(oldFinalizers...))
- if len(extra) != 0 {
- allErrs = append(allErrs, field.Forbidden(fldPath, fmt.Sprintf("no new finalizers can be added if the object is being deleted, found new finalizers %#v", extra.List())))
- }
- return allErrs
-}
-
-func ValidateImmutableField(newVal, oldVal interface{}, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- if !apiequality.Semantic.DeepEqual(oldVal, newVal) {
- allErrs = append(allErrs, field.Invalid(fldPath, newVal, FieldImmutableErrorMsg))
- }
- return allErrs
-}
-
-// ValidateObjectMeta validates an object's metadata on creation. It expects that name generation has already
-// been performed.
-// It doesn't return an error for rootscoped resources with namespace, because namespace should already be cleared before.
-func ValidateObjectMeta(objMeta *metav1.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList {
- metadata, err := meta.Accessor(objMeta)
- if err != nil {
- allErrs := field.ErrorList{}
- allErrs = append(allErrs, field.Invalid(fldPath, objMeta, err.Error()))
- return allErrs
- }
- return ValidateObjectMetaAccessor(metadata, requiresNamespace, nameFn, fldPath)
-}
-
-// ValidateObjectMeta validates an object's metadata on creation. It expects that name generation has already
-// been performed.
-// It doesn't return an error for rootscoped resources with namespace, because namespace should already be cleared before.
-func ValidateObjectMetaAccessor(meta metav1.Object, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
-
- if len(meta.GetGenerateName()) != 0 {
- for _, msg := range nameFn(meta.GetGenerateName(), true) {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("generateName"), meta.GetGenerateName(), msg))
- }
- }
- // If the generated name validates, but the calculated value does not, it's a problem with generation, and we
- // report it here. This may confuse users, but indicates a programming bug and still must be validated.
- // If there are multiple fields out of which one is required then add an or as a separator
- if len(meta.GetName()) == 0 {
- allErrs = append(allErrs, field.Required(fldPath.Child("name"), "name or generateName is required"))
- } else {
- for _, msg := range nameFn(meta.GetName(), false) {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), meta.GetName(), msg))
- }
- }
- if requiresNamespace {
- if len(meta.GetNamespace()) == 0 {
- allErrs = append(allErrs, field.Required(fldPath.Child("namespace"), ""))
- } else {
- for _, msg := range ValidateNamespaceName(meta.GetNamespace(), false) {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("namespace"), meta.GetNamespace(), msg))
- }
- }
- } else {
- if len(meta.GetNamespace()) != 0 {
- allErrs = append(allErrs, field.Forbidden(fldPath.Child("namespace"), "not allowed on this type"))
- }
- }
- if len(meta.GetClusterName()) != 0 {
- for _, msg := range ValidateClusterName(meta.GetClusterName(), false) {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("clusterName"), meta.GetClusterName(), msg))
- }
- }
- allErrs = append(allErrs, ValidateNonnegativeField(meta.GetGeneration(), fldPath.Child("generation"))...)
- allErrs = append(allErrs, v1validation.ValidateLabels(meta.GetLabels(), fldPath.Child("labels"))...)
- allErrs = append(allErrs, ValidateAnnotations(meta.GetAnnotations(), fldPath.Child("annotations"))...)
- allErrs = append(allErrs, ValidateOwnerReferences(meta.GetOwnerReferences(), fldPath.Child("ownerReferences"))...)
- allErrs = append(allErrs, ValidateInitializers(meta.GetInitializers(), fldPath.Child("initializers"))...)
- allErrs = append(allErrs, ValidateFinalizers(meta.GetFinalizers(), fldPath.Child("finalizers"))...)
- return allErrs
-}
-
-func ValidateInitializers(initializers *metav1.Initializers, fldPath *field.Path) field.ErrorList {
- var allErrs field.ErrorList
- if initializers == nil {
- return allErrs
- }
- for i, initializer := range initializers.Pending {
- allErrs = append(allErrs, validation.IsFullyQualifiedName(fldPath.Child("pending").Index(i).Child("name"), initializer.Name)...)
- }
- allErrs = append(allErrs, validateInitializersResult(initializers.Result, fldPath.Child("result"))...)
- return allErrs
-}
-
-func validateInitializersResult(result *metav1.Status, fldPath *field.Path) field.ErrorList {
- var allErrs field.ErrorList
- if result == nil {
- return allErrs
- }
- switch result.Status {
- case metav1.StatusFailure:
- default:
- allErrs = append(allErrs, field.Invalid(fldPath.Child("status"), result.Status, "must be 'Failure'"))
- }
- return allErrs
-}
-
-// ValidateFinalizers tests if the finalizers name are valid, and if there are conflicting finalizers.
-func ValidateFinalizers(finalizers []string, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- hasFinalizerOrphanDependents := false
- hasFinalizerDeleteDependents := false
- for _, finalizer := range finalizers {
- allErrs = append(allErrs, ValidateFinalizerName(finalizer, fldPath)...)
- if finalizer == metav1.FinalizerOrphanDependents {
- hasFinalizerOrphanDependents = true
- }
- if finalizer == metav1.FinalizerDeleteDependents {
- hasFinalizerDeleteDependents = true
- }
- }
- if hasFinalizerDeleteDependents && hasFinalizerOrphanDependents {
- allErrs = append(allErrs, field.Invalid(fldPath, finalizers, fmt.Sprintf("finalizer %s and %s cannot be both set", metav1.FinalizerOrphanDependents, metav1.FinalizerDeleteDependents)))
- }
- return allErrs
-}
-
-// ValidateObjectMetaUpdate validates an object's metadata when updated
-func ValidateObjectMetaUpdate(newMeta, oldMeta *metav1.ObjectMeta, fldPath *field.Path) field.ErrorList {
- newMetadata, err := meta.Accessor(newMeta)
- if err != nil {
- allErrs := field.ErrorList{}
- allErrs = append(allErrs, field.Invalid(fldPath, newMeta, err.Error()))
- return allErrs
- }
- oldMetadata, err := meta.Accessor(oldMeta)
- if err != nil {
- allErrs := field.ErrorList{}
- allErrs = append(allErrs, field.Invalid(fldPath, oldMeta, err.Error()))
- return allErrs
- }
- return ValidateObjectMetaAccessorUpdate(newMetadata, oldMetadata, fldPath)
-}
-
-func ValidateObjectMetaAccessorUpdate(newMeta, oldMeta metav1.Object, fldPath *field.Path) field.ErrorList {
- var allErrs field.ErrorList
-
- if !RepairMalformedUpdates && newMeta.GetUID() != oldMeta.GetUID() {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("uid"), newMeta.GetUID(), "field is immutable"))
- }
- // in the event it is left empty, set it, to allow clients more flexibility
- // TODO: remove the following code that repairs the update request when we retire the clients that modify the immutable fields.
- // Please do not copy this pattern elsewhere; validation functions should not be modifying the objects they are passed!
- if RepairMalformedUpdates {
- if len(newMeta.GetUID()) == 0 {
- newMeta.SetUID(oldMeta.GetUID())
- }
- // ignore changes to timestamp
- if oldCreationTime := oldMeta.GetCreationTimestamp(); oldCreationTime.IsZero() {
- oldMeta.SetCreationTimestamp(newMeta.GetCreationTimestamp())
- } else {
- newMeta.SetCreationTimestamp(oldMeta.GetCreationTimestamp())
- }
- // an object can never remove a deletion timestamp or clear/change grace period seconds
- if !oldMeta.GetDeletionTimestamp().IsZero() {
- newMeta.SetDeletionTimestamp(oldMeta.GetDeletionTimestamp())
- }
- if oldMeta.GetDeletionGracePeriodSeconds() != nil && newMeta.GetDeletionGracePeriodSeconds() == nil {
- newMeta.SetDeletionGracePeriodSeconds(oldMeta.GetDeletionGracePeriodSeconds())
- }
- }
-
- // TODO: needs to check if newMeta==nil && oldMeta !=nil after the repair logic is removed.
- if newMeta.GetDeletionGracePeriodSeconds() != nil && (oldMeta.GetDeletionGracePeriodSeconds() == nil || *newMeta.GetDeletionGracePeriodSeconds() != *oldMeta.GetDeletionGracePeriodSeconds()) {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("deletionGracePeriodSeconds"), newMeta.GetDeletionGracePeriodSeconds(), "field is immutable; may only be changed via deletion"))
- }
- if newMeta.GetDeletionTimestamp() != nil && (oldMeta.GetDeletionTimestamp() == nil || !newMeta.GetDeletionTimestamp().Equal(oldMeta.GetDeletionTimestamp())) {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("deletionTimestamp"), newMeta.GetDeletionTimestamp(), "field is immutable; may only be changed via deletion"))
- }
-
- // Finalizers cannot be added if the object is already being deleted.
- if oldMeta.GetDeletionTimestamp() != nil {
- allErrs = append(allErrs, ValidateNoNewFinalizers(newMeta.GetFinalizers(), oldMeta.GetFinalizers(), fldPath.Child("finalizers"))...)
- }
-
- // Reject updates that don't specify a resource version
- if len(newMeta.GetResourceVersion()) == 0 {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("resourceVersion"), newMeta.GetResourceVersion(), "must be specified for an update"))
- }
-
- // Generation shouldn't be decremented
- if newMeta.GetGeneration() < oldMeta.GetGeneration() {
- allErrs = append(allErrs, field.Invalid(fldPath.Child("generation"), newMeta.GetGeneration(), "must not be decremented"))
- }
-
- allErrs = append(allErrs, ValidateInitializersUpdate(newMeta.GetInitializers(), oldMeta.GetInitializers(), fldPath.Child("initializers"))...)
-
- allErrs = append(allErrs, ValidateImmutableField(newMeta.GetName(), oldMeta.GetName(), fldPath.Child("name"))...)
- allErrs = append(allErrs, ValidateImmutableField(newMeta.GetNamespace(), oldMeta.GetNamespace(), fldPath.Child("namespace"))...)
- allErrs = append(allErrs, ValidateImmutableField(newMeta.GetUID(), oldMeta.GetUID(), fldPath.Child("uid"))...)
- allErrs = append(allErrs, ValidateImmutableField(newMeta.GetCreationTimestamp(), oldMeta.GetCreationTimestamp(), fldPath.Child("creationTimestamp"))...)
- allErrs = append(allErrs, ValidateImmutableField(newMeta.GetClusterName(), oldMeta.GetClusterName(), fldPath.Child("clusterName"))...)
-
- allErrs = append(allErrs, v1validation.ValidateLabels(newMeta.GetLabels(), fldPath.Child("labels"))...)
- allErrs = append(allErrs, ValidateAnnotations(newMeta.GetAnnotations(), fldPath.Child("annotations"))...)
- allErrs = append(allErrs, ValidateOwnerReferences(newMeta.GetOwnerReferences(), fldPath.Child("ownerReferences"))...)
-
- return allErrs
-}
-
-// ValidateInitializersUpdate checks the update of the metadata initializers field
-func ValidateInitializersUpdate(newInit, oldInit *metav1.Initializers, fldPath *field.Path) field.ErrorList {
- var allErrs field.ErrorList
- switch {
- case oldInit == nil && newInit != nil:
- // Initializers may not be set on new objects
- allErrs = append(allErrs, field.Invalid(fldPath, nil, "field is immutable once initialization has completed"))
- case oldInit != nil && newInit == nil:
- // this is a valid transition and means initialization was successful
- case oldInit != nil && newInit != nil:
- // validate changes to initializers
- switch {
- case oldInit.Result == nil && newInit.Result != nil:
- // setting a result is allowed
- allErrs = append(allErrs, validateInitializersResult(newInit.Result, fldPath.Child("result"))...)
- case oldInit.Result != nil:
- // setting Result implies permanent failure, and all future updates will be prevented
- allErrs = append(allErrs, ValidateImmutableField(newInit.Result, oldInit.Result, fldPath.Child("result"))...)
- default:
- // leaving the result nil is allowed
- }
- }
- return allErrs
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/announced.go b/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/announced.go
deleted file mode 100644
index 4e38cc8c5..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/announced.go
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
-Copyright 2016 The 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 announced contains tools for announcing API group factories. This is
-// distinct from registration (in the 'registered' package) in that it's safe
-// to announce every possible group linked in, but only groups requested at
-// runtime should be registered. This package contains both a registry, and
-// factory code (which was formerly copy-pasta in every install package).
-package announced
-
-import (
- "fmt"
-
- "k8s.io/apimachinery/pkg/apimachinery/registered"
- "k8s.io/apimachinery/pkg/runtime"
-)
-
-// APIGroupFactoryRegistry allows for groups and versions to announce themselves,
-// which simply makes them available and doesn't take other actions. Later,
-// users of the registry can select which groups and versions they'd actually
-// like to register with an APIRegistrationManager.
-//
-// (Right now APIRegistrationManager has separate 'registration' and 'enabled'
-// concepts-- APIGroupFactory is going to take over the former function;
-// they will overlap until the refactoring is finished.)
-//
-// The key is the group name. After initialization, this should be treated as
-// read-only. It is implemented as a map from group name to group factory, and
-// it is safe to use this knowledge to manually pick out groups to register
-// (e.g., for testing).
-type APIGroupFactoryRegistry map[string]*GroupMetaFactory
-
-func (gar APIGroupFactoryRegistry) group(groupName string) *GroupMetaFactory {
- gmf, ok := gar[groupName]
- if !ok {
- gmf = &GroupMetaFactory{VersionArgs: map[string]*GroupVersionFactoryArgs{}}
- gar[groupName] = gmf
- }
- return gmf
-}
-
-// AnnounceGroupVersion adds the particular arguments for this group version to the group factory.
-func (gar APIGroupFactoryRegistry) AnnounceGroupVersion(gvf *GroupVersionFactoryArgs) error {
- gmf := gar.group(gvf.GroupName)
- if _, ok := gmf.VersionArgs[gvf.VersionName]; ok {
- return fmt.Errorf("version %q in group %q has already been announced", gvf.VersionName, gvf.GroupName)
- }
- gmf.VersionArgs[gvf.VersionName] = gvf
- return nil
-}
-
-// AnnounceGroup adds the group-wide arguments to the group factory.
-func (gar APIGroupFactoryRegistry) AnnounceGroup(args *GroupMetaFactoryArgs) error {
- gmf := gar.group(args.GroupName)
- if gmf.GroupArgs != nil {
- return fmt.Errorf("group %q has already been announced", args.GroupName)
- }
- gmf.GroupArgs = args
- return nil
-}
-
-// RegisterAndEnableAll throws every factory at the specified API registration
-// manager, and lets it decide which to register. (If you want to do this a la
-// cart, you may look through gar itself-- it's just a map.)
-func (gar APIGroupFactoryRegistry) RegisterAndEnableAll(m *registered.APIRegistrationManager, scheme *runtime.Scheme) error {
- for groupName, gmf := range gar {
- if err := gmf.Register(m); err != nil {
- return fmt.Errorf("error registering %v: %v", groupName, err)
- }
- if err := gmf.Enable(m, scheme); err != nil {
- return fmt.Errorf("error enabling %v: %v", groupName, err)
- }
- }
- return nil
-}
-
-// AnnouncePreconstructedFactory announces a factory which you've manually assembled.
-// You may call this instead of calling AnnounceGroup and AnnounceGroupVersion.
-func (gar APIGroupFactoryRegistry) AnnouncePreconstructedFactory(gmf *GroupMetaFactory) error {
- name := gmf.GroupArgs.GroupName
- if _, exists := gar[name]; exists {
- return fmt.Errorf("the group %q has already been announced.", name)
- }
- gar[name] = gmf
- return nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/group_factory.go b/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/group_factory.go
deleted file mode 100644
index 154ed08f5..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/group_factory.go
+++ /dev/null
@@ -1,255 +0,0 @@
-/*
-Copyright 2016 The 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 announced
-
-import (
- "fmt"
-
- "github.com/golang/glog"
-
- "k8s.io/apimachinery/pkg/api/meta"
- "k8s.io/apimachinery/pkg/apimachinery"
- "k8s.io/apimachinery/pkg/apimachinery/registered"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/util/sets"
-)
-
-type SchemeFunc func(*runtime.Scheme) error
-type VersionToSchemeFunc map[string]SchemeFunc
-
-// GroupVersionFactoryArgs contains all the per-version parts of a GroupMetaFactory.
-type GroupVersionFactoryArgs struct {
- GroupName string
- VersionName string
-
- AddToScheme SchemeFunc
-}
-
-// GroupMetaFactoryArgs contains the group-level args of a GroupMetaFactory.
-type GroupMetaFactoryArgs struct {
- // GroupName is the name of the API-Group
- //
- // example: 'servicecatalog.k8s.io'
- GroupName string
- VersionPreferenceOrder []string
- // RootScopedKinds are resources that are not namespaced.
- RootScopedKinds sets.String // nil is allowed
- IgnoredKinds sets.String // nil is allowed
-
- // May be nil if there are no internal objects.
- AddInternalObjectsToScheme SchemeFunc
-}
-
-// NewGroupMetaFactory builds the args for you. This is for if you're
-// constructing a factory all at once and not using the registry.
-func NewGroupMetaFactory(groupArgs *GroupMetaFactoryArgs, versions VersionToSchemeFunc) *GroupMetaFactory {
- gmf := &GroupMetaFactory{
- GroupArgs: groupArgs,
- VersionArgs: map[string]*GroupVersionFactoryArgs{},
- }
- for v, f := range versions {
- gmf.VersionArgs[v] = &GroupVersionFactoryArgs{
- GroupName: groupArgs.GroupName,
- VersionName: v,
- AddToScheme: f,
- }
- }
- return gmf
-}
-
-// Announce adds this Group factory to the global factory registry. It should
-// only be called if you constructed the GroupMetaFactory yourself via
-// NewGroupMetaFactory.
-// Note that this will panic on an error, since it's expected that you'll be
-// calling this at initialization time and any error is a result of a
-// programmer importing the wrong set of packages. If this assumption doesn't
-// work for you, just call DefaultGroupFactoryRegistry.AnnouncePreconstructedFactory
-// yourself.
-func (gmf *GroupMetaFactory) Announce(groupFactoryRegistry APIGroupFactoryRegistry) *GroupMetaFactory {
- if err := groupFactoryRegistry.AnnouncePreconstructedFactory(gmf); err != nil {
- panic(err)
- }
- return gmf
-}
-
-// GroupMetaFactory has the logic for actually assembling and registering a group.
-//
-// There are two ways of obtaining one of these.
-// 1. You can announce your group and versions separately, and then let the
-// GroupFactoryRegistry assemble this object for you. (This allows group and
-// versions to be imported separately, without referencing each other, to
-// keep import trees small.)
-// 2. You can call NewGroupMetaFactory(), which is mostly a drop-in replacement
-// for the old, bad way of doing things. You can then call .Announce() to
-// announce your constructed factory to any code that would like to do
-// things the new, better way.
-//
-// Note that GroupMetaFactory actually does construct GroupMeta objects, but
-// currently it does so in a way that's very entangled with an
-// APIRegistrationManager. It's a TODO item to cleanly separate that interface.
-type GroupMetaFactory struct {
- GroupArgs *GroupMetaFactoryArgs
- // map of version name to version factory
- VersionArgs map[string]*GroupVersionFactoryArgs
-
- // assembled by Register()
- prioritizedVersionList []schema.GroupVersion
-}
-
-// Register constructs the finalized prioritized version list and sanity checks
-// the announced group & versions. Then it calls register.
-func (gmf *GroupMetaFactory) Register(m *registered.APIRegistrationManager) error {
- if gmf.GroupArgs == nil {
- return fmt.Errorf("partially announced groups are not allowed, only got versions: %#v", gmf.VersionArgs)
- }
- if len(gmf.VersionArgs) == 0 {
- return fmt.Errorf("group %v announced but no versions announced", gmf.GroupArgs.GroupName)
- }
-
- pvSet := sets.NewString(gmf.GroupArgs.VersionPreferenceOrder...)
- if pvSet.Len() != len(gmf.GroupArgs.VersionPreferenceOrder) {
- return fmt.Errorf("preference order for group %v has duplicates: %v", gmf.GroupArgs.GroupName, gmf.GroupArgs.VersionPreferenceOrder)
- }
- prioritizedVersions := []schema.GroupVersion{}
- for _, v := range gmf.GroupArgs.VersionPreferenceOrder {
- prioritizedVersions = append(
- prioritizedVersions,
- schema.GroupVersion{
- Group: gmf.GroupArgs.GroupName,
- Version: v,
- },
- )
- }
-
- // Go through versions that weren't explicitly prioritized.
- unprioritizedVersions := []schema.GroupVersion{}
- for _, v := range gmf.VersionArgs {
- if v.GroupName != gmf.GroupArgs.GroupName {
- return fmt.Errorf("found %v/%v in group %v?", v.GroupName, v.VersionName, gmf.GroupArgs.GroupName)
- }
- if pvSet.Has(v.VersionName) {
- pvSet.Delete(v.VersionName)
- continue
- }
- unprioritizedVersions = append(unprioritizedVersions, schema.GroupVersion{Group: v.GroupName, Version: v.VersionName})
- }
- if len(unprioritizedVersions) > 1 {
- glog.Warningf("group %v has multiple unprioritized versions: %#v. They will have an arbitrary preference order!", gmf.GroupArgs.GroupName, unprioritizedVersions)
- }
- if pvSet.Len() != 0 {
- return fmt.Errorf("group %v has versions in the priority list that were never announced: %s", gmf.GroupArgs.GroupName, pvSet)
- }
- prioritizedVersions = append(prioritizedVersions, unprioritizedVersions...)
- m.RegisterVersions(prioritizedVersions)
- gmf.prioritizedVersionList = prioritizedVersions
- return nil
-}
-
-func (gmf *GroupMetaFactory) newRESTMapper(scheme *runtime.Scheme, externalVersions []schema.GroupVersion, groupMeta *apimachinery.GroupMeta) meta.RESTMapper {
- // the list of kinds that are scoped at the root of the api hierarchy
- // if a kind is not enumerated here, it is assumed to have a namespace scope
- rootScoped := sets.NewString()
- if gmf.GroupArgs.RootScopedKinds != nil {
- rootScoped = gmf.GroupArgs.RootScopedKinds
- }
- ignoredKinds := sets.NewString()
- if gmf.GroupArgs.IgnoredKinds != nil {
- ignoredKinds = gmf.GroupArgs.IgnoredKinds
- }
-
- mapper := meta.NewDefaultRESTMapper(externalVersions, groupMeta.InterfacesFor)
- for _, gv := range externalVersions {
- for kind := range scheme.KnownTypes(gv) {
- if ignoredKinds.Has(kind) {
- continue
- }
- scope := meta.RESTScopeNamespace
- if rootScoped.Has(kind) {
- scope = meta.RESTScopeRoot
- }
- mapper.Add(gv.WithKind(kind), scope)
- }
- }
-
- return mapper
-}
-
-// Enable enables group versions that are allowed, adds methods to the scheme, etc.
-func (gmf *GroupMetaFactory) Enable(m *registered.APIRegistrationManager, scheme *runtime.Scheme) error {
- externalVersions := []schema.GroupVersion{}
- for _, v := range gmf.prioritizedVersionList {
- if !m.IsAllowedVersion(v) {
- continue
- }
- externalVersions = append(externalVersions, v)
- if err := m.EnableVersions(v); err != nil {
- return err
- }
- gmf.VersionArgs[v.Version].AddToScheme(scheme)
- }
- if len(externalVersions) == 0 {
- glog.V(4).Infof("No version is registered for group %v", gmf.GroupArgs.GroupName)
- return nil
- }
-
- if gmf.GroupArgs.AddInternalObjectsToScheme != nil {
- gmf.GroupArgs.AddInternalObjectsToScheme(scheme)
- }
-
- preferredExternalVersion := externalVersions[0]
- accessor := meta.NewAccessor()
-
- groupMeta := &apimachinery.GroupMeta{
- GroupVersion: preferredExternalVersion,
- GroupVersions: externalVersions,
- SelfLinker: runtime.SelfLinker(accessor),
- }
- for _, v := range externalVersions {
- gvf := gmf.VersionArgs[v.Version]
- if err := groupMeta.AddVersionInterfaces(
- schema.GroupVersion{Group: gvf.GroupName, Version: gvf.VersionName},
- &meta.VersionInterfaces{
- ObjectConvertor: scheme,
- MetadataAccessor: accessor,
- },
- ); err != nil {
- return err
- }
- }
- groupMeta.InterfacesFor = groupMeta.DefaultInterfacesFor
- groupMeta.RESTMapper = gmf.newRESTMapper(scheme, externalVersions, groupMeta)
-
- if err := m.RegisterGroup(*groupMeta); err != nil {
- return err
- }
- return nil
-}
-
-// RegisterAndEnable is provided only to allow this code to get added in multiple steps.
-// It's really bad that this is called in init() methods, but supporting this
-// temporarily lets us do the change incrementally.
-func (gmf *GroupMetaFactory) RegisterAndEnable(registry *registered.APIRegistrationManager, scheme *runtime.Scheme) error {
- if err := gmf.Register(registry); err != nil {
- return err
- }
- if err := gmf.Enable(registry, scheme); err != nil {
- return err
- }
-
- return nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apimachinery/doc.go b/vendor/k8s.io/apimachinery/pkg/apimachinery/doc.go
deleted file mode 100644
index b238454b2..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apimachinery/doc.go
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
-Copyright 2014 The 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 apimachinery contains the generic API machinery code that
-// is common to both server and clients.
-// This package should never import specific API objects.
-package apimachinery // import "k8s.io/apimachinery/pkg/apimachinery"
diff --git a/vendor/k8s.io/apimachinery/pkg/apimachinery/registered/registered.go b/vendor/k8s.io/apimachinery/pkg/apimachinery/registered/registered.go
deleted file mode 100644
index 0da94f50f..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apimachinery/registered/registered.go
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
-Copyright 2015 The 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 to keep track of API Versions that can be registered and are enabled in a Scheme.
-package registered
-
-import (
- "fmt"
- "sort"
- "strings"
-
- "github.com/golang/glog"
-
- "k8s.io/apimachinery/pkg/api/meta"
- "k8s.io/apimachinery/pkg/apimachinery"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/util/sets"
-)
-
-// APIRegistrationManager provides the concept of what API groups are enabled.
-//
-// TODO: currently, it also provides a "registered" concept. But it's wrong to
-// have both concepts in the same object. Therefore the "announced" package is
-// going to take over the registered concept. After all the install packages
-// are switched to using the announce package instead of this package, then we
-// can combine the registered/enabled concepts in this object. Simplifying this
-// isn't easy right now because there are so many callers of this package.
-type APIRegistrationManager struct {
- // registeredGroupVersions stores all API group versions for which RegisterGroup is called.
- registeredVersions map[schema.GroupVersion]struct{}
-
- // enabledVersions represents all enabled API versions. It should be a
- // subset of registeredVersions. Please call EnableVersions() to add
- // enabled versions.
- enabledVersions map[schema.GroupVersion]struct{}
-
- // map of group meta for all groups.
- groupMetaMap map[string]*apimachinery.GroupMeta
-
- // envRequestedVersions represents the versions requested via the
- // KUBE_API_VERSIONS environment variable. The install package of each group
- // checks this list before add their versions to the latest package and
- // Scheme. This list is small and order matters, so represent as a slice
- envRequestedVersions []schema.GroupVersion
-}
-
-// NewAPIRegistrationManager constructs a new manager. The argument ought to be
-// the value of the KUBE_API_VERSIONS env var, or a value of this which you
-// wish to test.
-func NewAPIRegistrationManager(kubeAPIVersions string) (*APIRegistrationManager, error) {
- m := &APIRegistrationManager{
- registeredVersions: map[schema.GroupVersion]struct{}{},
- enabledVersions: map[schema.GroupVersion]struct{}{},
- groupMetaMap: map[string]*apimachinery.GroupMeta{},
- envRequestedVersions: []schema.GroupVersion{},
- }
-
- if len(kubeAPIVersions) != 0 {
- for _, version := range strings.Split(kubeAPIVersions, ",") {
- gv, err := schema.ParseGroupVersion(version)
- if err != nil {
- return nil, fmt.Errorf("invalid api version: %s in KUBE_API_VERSIONS: %s.",
- version, kubeAPIVersions)
- }
- m.envRequestedVersions = append(m.envRequestedVersions, gv)
- }
- }
- return m, nil
-}
-
-func NewOrDie(kubeAPIVersions string) *APIRegistrationManager {
- m, err := NewAPIRegistrationManager(kubeAPIVersions)
- if err != nil {
- glog.Fatalf("Could not construct version manager: %v (KUBE_API_VERSIONS=%q)", err, kubeAPIVersions)
- }
- return m
-}
-
-// RegisterVersions adds the given group versions to the list of registered group versions.
-func (m *APIRegistrationManager) RegisterVersions(availableVersions []schema.GroupVersion) {
- for _, v := range availableVersions {
- m.registeredVersions[v] = struct{}{}
- }
-}
-
-// RegisterGroup adds the given group to the list of registered groups.
-func (m *APIRegistrationManager) RegisterGroup(groupMeta apimachinery.GroupMeta) error {
- groupName := groupMeta.GroupVersion.Group
- if _, found := m.groupMetaMap[groupName]; found {
- return fmt.Errorf("group %q is already registered in groupsMap: %v", groupName, m.groupMetaMap)
- }
- m.groupMetaMap[groupName] = &groupMeta
- return nil
-}
-
-// EnableVersions adds the versions for the given group to the list of enabled versions.
-// Note that the caller should call RegisterGroup before calling this method.
-// The caller of this function is responsible to add the versions to scheme and RESTMapper.
-func (m *APIRegistrationManager) EnableVersions(versions ...schema.GroupVersion) error {
- var unregisteredVersions []schema.GroupVersion
- for _, v := range versions {
- if _, found := m.registeredVersions[v]; !found {
- unregisteredVersions = append(unregisteredVersions, v)
- }
- m.enabledVersions[v] = struct{}{}
- }
- if len(unregisteredVersions) != 0 {
- return fmt.Errorf("Please register versions before enabling them: %v", unregisteredVersions)
- }
- return nil
-}
-
-// IsAllowedVersion returns if the version is allowed by the KUBE_API_VERSIONS
-// environment variable. If the environment variable is empty, then it always
-// returns true.
-func (m *APIRegistrationManager) IsAllowedVersion(v schema.GroupVersion) bool {
- if len(m.envRequestedVersions) == 0 {
- return true
- }
- for _, envGV := range m.envRequestedVersions {
- if v == envGV {
- return true
- }
- }
- return false
-}
-
-// IsEnabledVersion returns if a version is enabled.
-func (m *APIRegistrationManager) IsEnabledVersion(v schema.GroupVersion) bool {
- _, found := m.enabledVersions[v]
- return found
-}
-
-// EnabledVersions returns all enabled versions. Groups are randomly ordered, but versions within groups
-// are priority order from best to worst
-func (m *APIRegistrationManager) EnabledVersions() []schema.GroupVersion {
- ret := []schema.GroupVersion{}
- for _, groupMeta := range m.groupMetaMap {
- for _, version := range groupMeta.GroupVersions {
- if m.IsEnabledVersion(version) {
- ret = append(ret, version)
- }
- }
- }
- return ret
-}
-
-// EnabledVersionsForGroup returns all enabled versions for a group in order of best to worst
-func (m *APIRegistrationManager) EnabledVersionsForGroup(group string) []schema.GroupVersion {
- groupMeta, ok := m.groupMetaMap[group]
- if !ok {
- return []schema.GroupVersion{}
- }
-
- ret := []schema.GroupVersion{}
- for _, version := range groupMeta.GroupVersions {
- if m.IsEnabledVersion(version) {
- ret = append(ret, version)
- }
- }
- return ret
-}
-
-// Group returns the metadata of a group if the group is registered, otherwise
-// an error is returned.
-func (m *APIRegistrationManager) Group(group string) (*apimachinery.GroupMeta, error) {
- groupMeta, found := m.groupMetaMap[group]
- if !found {
- return nil, fmt.Errorf("group %v has not been registered", group)
- }
- groupMetaCopy := *groupMeta
- return &groupMetaCopy, nil
-}
-
-// IsRegistered takes a string and determines if it's one of the registered groups
-func (m *APIRegistrationManager) IsRegistered(group string) bool {
- _, found := m.groupMetaMap[group]
- return found
-}
-
-// IsRegisteredVersion returns if a version is registered.
-func (m *APIRegistrationManager) IsRegisteredVersion(v schema.GroupVersion) bool {
- _, found := m.registeredVersions[v]
- return found
-}
-
-// RegisteredGroupVersions returns all registered group versions.
-func (m *APIRegistrationManager) RegisteredGroupVersions() []schema.GroupVersion {
- ret := []schema.GroupVersion{}
- for groupVersion := range m.registeredVersions {
- ret = append(ret, groupVersion)
- }
- return ret
-}
-
-// InterfacesFor is a union meta.VersionInterfacesFunc func for all registered types
-func (m *APIRegistrationManager) InterfacesFor(version schema.GroupVersion) (*meta.VersionInterfaces, error) {
- groupMeta, err := m.Group(version.Group)
- if err != nil {
- return nil, err
- }
- return groupMeta.InterfacesFor(version)
-}
-
-// TODO: This is an expedient function, because we don't check if a Group is
-// supported throughout the code base. We will abandon this function and
-// checking the error returned by the Group() function.
-func (m *APIRegistrationManager) GroupOrDie(group string) *apimachinery.GroupMeta {
- groupMeta, found := m.groupMetaMap[group]
- if !found {
- if group == "" {
- panic("The legacy v1 API is not registered.")
- } else {
- panic(fmt.Sprintf("Group %s is not registered.", group))
- }
- }
- groupMetaCopy := *groupMeta
- return &groupMetaCopy
-}
-
-// RESTMapper returns a union RESTMapper of all known types with priorities chosen in the following order:
-// 1. if KUBE_API_VERSIONS is specified, then KUBE_API_VERSIONS in order, OR
-// 1. legacy kube group preferred version, extensions preferred version, metrics perferred version, legacy
-// kube any version, extensions any version, metrics any version, all other groups alphabetical preferred version,
-// all other groups alphabetical.
-func (m *APIRegistrationManager) RESTMapper(versionPatterns ...schema.GroupVersion) meta.RESTMapper {
- unionMapper := meta.MultiRESTMapper{}
- unionedGroups := sets.NewString()
- for enabledVersion := range m.enabledVersions {
- if !unionedGroups.Has(enabledVersion.Group) {
- unionedGroups.Insert(enabledVersion.Group)
- groupMeta := m.groupMetaMap[enabledVersion.Group]
- unionMapper = append(unionMapper, groupMeta.RESTMapper)
- }
- }
-
- if len(versionPatterns) != 0 {
- resourcePriority := []schema.GroupVersionResource{}
- kindPriority := []schema.GroupVersionKind{}
- for _, versionPriority := range versionPatterns {
- resourcePriority = append(resourcePriority, versionPriority.WithResource(meta.AnyResource))
- kindPriority = append(kindPriority, versionPriority.WithKind(meta.AnyKind))
- }
-
- return meta.PriorityRESTMapper{Delegate: unionMapper, ResourcePriority: resourcePriority, KindPriority: kindPriority}
- }
-
- if len(m.envRequestedVersions) != 0 {
- resourcePriority := []schema.GroupVersionResource{}
- kindPriority := []schema.GroupVersionKind{}
-
- for _, versionPriority := range m.envRequestedVersions {
- resourcePriority = append(resourcePriority, versionPriority.WithResource(meta.AnyResource))
- kindPriority = append(kindPriority, versionPriority.WithKind(meta.AnyKind))
- }
-
- return meta.PriorityRESTMapper{Delegate: unionMapper, ResourcePriority: resourcePriority, KindPriority: kindPriority}
- }
-
- prioritizedGroups := []string{"", "extensions", "metrics"}
- resourcePriority, kindPriority := m.prioritiesForGroups(prioritizedGroups...)
-
- prioritizedGroupsSet := sets.NewString(prioritizedGroups...)
- remainingGroups := sets.String{}
- for enabledVersion := range m.enabledVersions {
- if !prioritizedGroupsSet.Has(enabledVersion.Group) {
- remainingGroups.Insert(enabledVersion.Group)
- }
- }
-
- remainingResourcePriority, remainingKindPriority := m.prioritiesForGroups(remainingGroups.List()...)
- resourcePriority = append(resourcePriority, remainingResourcePriority...)
- kindPriority = append(kindPriority, remainingKindPriority...)
-
- return meta.PriorityRESTMapper{Delegate: unionMapper, ResourcePriority: resourcePriority, KindPriority: kindPriority}
-}
-
-// prioritiesForGroups returns the resource and kind priorities for a PriorityRESTMapper, preferring the preferred version of each group first,
-// then any non-preferred version of the group second.
-func (m *APIRegistrationManager) prioritiesForGroups(groups ...string) ([]schema.GroupVersionResource, []schema.GroupVersionKind) {
- resourcePriority := []schema.GroupVersionResource{}
- kindPriority := []schema.GroupVersionKind{}
-
- for _, group := range groups {
- availableVersions := m.EnabledVersionsForGroup(group)
- if len(availableVersions) > 0 {
- resourcePriority = append(resourcePriority, availableVersions[0].WithResource(meta.AnyResource))
- kindPriority = append(kindPriority, availableVersions[0].WithKind(meta.AnyKind))
- }
- }
- for _, group := range groups {
- resourcePriority = append(resourcePriority, schema.GroupVersionResource{Group: group, Version: meta.AnyVersion, Resource: meta.AnyResource})
- kindPriority = append(kindPriority, schema.GroupVersionKind{Group: group, Version: meta.AnyVersion, Kind: meta.AnyKind})
- }
-
- return resourcePriority, kindPriority
-}
-
-// AllPreferredGroupVersions returns the preferred versions of all registered
-// groups in the form of "group1/version1,group2/version2,..."
-func (m *APIRegistrationManager) AllPreferredGroupVersions() string {
- if len(m.groupMetaMap) == 0 {
- return ""
- }
- var defaults []string
- for _, groupMeta := range m.groupMetaMap {
- defaults = append(defaults, groupMeta.GroupVersion.String())
- }
- sort.Strings(defaults)
- return strings.Join(defaults, ",")
-}
-
-// ValidateEnvRequestedVersions returns a list of versions that are requested in
-// the KUBE_API_VERSIONS environment variable, but not enabled.
-func (m *APIRegistrationManager) ValidateEnvRequestedVersions() []schema.GroupVersion {
- var missingVersions []schema.GroupVersion
- for _, v := range m.envRequestedVersions {
- if _, found := m.enabledVersions[v]; !found {
- missingVersions = append(missingVersions, v)
- }
- }
- return missingVersions
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apimachinery/types.go b/vendor/k8s.io/apimachinery/pkg/apimachinery/types.go
deleted file mode 100644
index baca784fa..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apimachinery/types.go
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
-Copyright 2016 The 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 apimachinery
-
-import (
- "fmt"
-
- "k8s.io/apimachinery/pkg/api/meta"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// GroupMeta stores the metadata of a group.
-type GroupMeta struct {
- // GroupVersion represents the preferred version of the group.
- GroupVersion schema.GroupVersion
-
- // GroupVersions is Group + all versions in that group.
- GroupVersions []schema.GroupVersion
-
- // SelfLinker can set or get the SelfLink field of all API types.
- // TODO: when versioning changes, make this part of each API definition.
- // TODO(lavalamp): Combine SelfLinker & ResourceVersioner interfaces, force all uses
- // to go through the InterfacesFor method below.
- SelfLinker runtime.SelfLinker
-
- // RESTMapper provides the default mapping between REST paths and the objects declared in a Scheme and all known
- // versions.
- RESTMapper meta.RESTMapper
-
- // InterfacesFor returns the default Codec and ResourceVersioner for a given version
- // string, or an error if the version is not known.
- // TODO: make this stop being a func pointer and always use the default
- // function provided below once every place that populates this field has been changed.
- InterfacesFor func(version schema.GroupVersion) (*meta.VersionInterfaces, error)
-
- // InterfacesByVersion stores the per-version interfaces.
- InterfacesByVersion map[schema.GroupVersion]*meta.VersionInterfaces
-}
-
-// DefaultInterfacesFor returns the default Codec and ResourceVersioner for a given version
-// string, or an error if the version is not known.
-// TODO: Remove the "Default" prefix.
-func (gm *GroupMeta) DefaultInterfacesFor(version schema.GroupVersion) (*meta.VersionInterfaces, error) {
- if v, ok := gm.InterfacesByVersion[version]; ok {
- return v, nil
- }
- return nil, fmt.Errorf("unsupported storage version: %s (valid: %v)", version, gm.GroupVersions)
-}
-
-// AddVersionInterfaces adds the given version to the group. Only call during
-// init, after that GroupMeta objects should be immutable. Not thread safe.
-// (If you use this, be sure to set .InterfacesFor = .DefaultInterfacesFor)
-// TODO: remove the "Interfaces" suffix and make this also maintain the
-// .GroupVersions member.
-func (gm *GroupMeta) AddVersionInterfaces(version schema.GroupVersion, interfaces *meta.VersionInterfaces) error {
- if e, a := gm.GroupVersion.Group, version.Group; a != e {
- return fmt.Errorf("got a version in group %v, but am in group %v", a, e)
- }
- if gm.InterfacesByVersion == nil {
- gm.InterfacesByVersion = make(map[schema.GroupVersion]*meta.VersionInterfaces)
- }
- gm.InterfacesByVersion[version] = interfaces
-
- // TODO: refactor to make the below error not possible, this function
- // should *set* GroupVersions rather than depend on it.
- for _, v := range gm.GroupVersions {
- if v == version {
- return nil
- }
- }
- return fmt.Errorf("added a version interface without the corresponding version %v being in the list %#v", version, gm.GroupVersions)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/conversion.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/conversion.go
deleted file mode 100644
index 1ea8c137b..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/conversion.go
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
-Copyright 2017 The 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 internalversion
-
-import (
- "fmt"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/conversion"
- "k8s.io/apimachinery/pkg/util/validation/field"
-)
-
-func Convert_internalversion_ListOptions_To_v1_ListOptions(in *ListOptions, out *metav1.ListOptions, s conversion.Scope) error {
- if err := metav1.Convert_fields_Selector_To_string(&in.FieldSelector, &out.FieldSelector, s); err != nil {
- return err
- }
- if err := metav1.Convert_labels_Selector_To_string(&in.LabelSelector, &out.LabelSelector, s); err != nil {
- return err
- }
- out.IncludeUninitialized = in.IncludeUninitialized
- out.ResourceVersion = in.ResourceVersion
- out.TimeoutSeconds = in.TimeoutSeconds
- out.Watch = in.Watch
- out.Limit = in.Limit
- out.Continue = in.Continue
- return nil
-}
-
-func Convert_v1_ListOptions_To_internalversion_ListOptions(in *metav1.ListOptions, out *ListOptions, s conversion.Scope) error {
- if err := metav1.Convert_string_To_fields_Selector(&in.FieldSelector, &out.FieldSelector, s); err != nil {
- return err
- }
- if err := metav1.Convert_string_To_labels_Selector(&in.LabelSelector, &out.LabelSelector, s); err != nil {
- return err
- }
- out.IncludeUninitialized = in.IncludeUninitialized
- out.ResourceVersion = in.ResourceVersion
- out.TimeoutSeconds = in.TimeoutSeconds
- out.Watch = in.Watch
- out.Limit = in.Limit
- out.Continue = in.Continue
- return nil
-}
-
-func Convert_map_to_v1_LabelSelector(in *map[string]string, out *metav1.LabelSelector, s conversion.Scope) error {
- if in == nil {
- return nil
- }
- out = new(metav1.LabelSelector)
- for labelKey, labelValue := range *in {
- metav1.AddLabelToSelector(out, labelKey, labelValue)
- }
- return nil
-}
-
-func Convert_v1_LabelSelector_to_map(in *metav1.LabelSelector, out *map[string]string, s conversion.Scope) error {
- var err error
- *out, err = metav1.LabelSelectorAsMap(in)
- if err != nil {
- err = field.Invalid(field.NewPath("labelSelector"), *in, fmt.Sprintf("cannot convert to old selector: %v", err))
- }
- return err
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/doc.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/doc.go
deleted file mode 100644
index 1e85c5c43..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/doc.go
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
-Copyright 2016 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// +k8s:deepcopy-gen=package
-// +k8s:conversion-gen=k8s.io/apimachinery/pkg/apis/meta/v1
-
-package internalversion
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register.go
deleted file mode 100644
index 4bde90b3f..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register.go
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
-Copyright 2017 The 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 internalversion
-
-import (
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/runtime/serializer"
-)
-
-// GroupName is the group name for this API.
-const GroupName = "meta.k8s.io"
-
-// Scheme is the registry for any type that adheres to the meta API spec.
-var scheme = runtime.NewScheme()
-
-var (
- // TODO: move SchemeBuilder with zz_generated.deepcopy.go to k8s.io/api.
- // localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes.
- SchemeBuilder runtime.SchemeBuilder
- localSchemeBuilder = &SchemeBuilder
- AddToScheme = localSchemeBuilder.AddToScheme
-)
-
-// Codecs provides access to encoding and decoding for the scheme.
-var Codecs = serializer.NewCodecFactory(scheme)
-
-// SchemeGroupVersion is group version used to register these objects
-var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: runtime.APIVersionInternal}
-
-// ParameterCodec handles versioning of objects that are converted to query parameters.
-var ParameterCodec = runtime.NewParameterCodec(scheme)
-
-// Kind takes an unqualified kind and returns a Group qualified GroupKind
-func Kind(kind string) schema.GroupKind {
- return SchemeGroupVersion.WithKind(kind).GroupKind()
-}
-
-// addToGroupVersion registers common meta types into schemas.
-func addToGroupVersion(scheme *runtime.Scheme, groupVersion schema.GroupVersion) error {
- if err := scheme.AddIgnoredConversionType(&metav1.TypeMeta{}, &metav1.TypeMeta{}); err != nil {
- return err
- }
- scheme.AddConversionFuncs(
- metav1.Convert_string_To_labels_Selector,
- metav1.Convert_labels_Selector_To_string,
-
- metav1.Convert_string_To_fields_Selector,
- metav1.Convert_fields_Selector_To_string,
-
- Convert_map_to_v1_LabelSelector,
- Convert_v1_LabelSelector_to_map,
-
- Convert_internalversion_ListOptions_To_v1_ListOptions,
- Convert_v1_ListOptions_To_internalversion_ListOptions,
- )
- // ListOptions is the only options struct which needs conversion (it exposes labels and fields
- // as selectors for convenience). The other types have only a single representation today.
- scheme.AddKnownTypes(SchemeGroupVersion,
- &ListOptions{},
- &metav1.GetOptions{},
- &metav1.ExportOptions{},
- &metav1.DeleteOptions{},
- )
- scheme.AddKnownTypes(SchemeGroupVersion,
- &metav1beta1.Table{},
- &metav1beta1.TableOptions{},
- &metav1beta1.PartialObjectMetadata{},
- &metav1beta1.PartialObjectMetadataList{},
- )
- scheme.AddKnownTypes(metav1beta1.SchemeGroupVersion,
- &metav1beta1.Table{},
- &metav1beta1.TableOptions{},
- &metav1beta1.PartialObjectMetadata{},
- &metav1beta1.PartialObjectMetadataList{},
- )
- // Allow delete options to be decoded across all version in this scheme (we may want to be more clever than this)
- scheme.AddUnversionedTypes(SchemeGroupVersion, &metav1.DeleteOptions{})
- metav1.AddToGroupVersion(scheme, metav1.SchemeGroupVersion)
- return nil
-}
-
-// Unlike other API groups, meta internal knows about all meta external versions, but keeps
-// the logic for conversion private.
-func init() {
- if err := addToGroupVersion(scheme, SchemeGroupVersion); err != nil {
- panic(err)
- }
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go
deleted file mode 100644
index 2f6740d36..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
-Copyright 2017 The 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 internalversion
-
-import (
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/fields"
- "k8s.io/apimachinery/pkg/labels"
- "k8s.io/apimachinery/pkg/runtime"
-)
-
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-
-// ListOptions is the query options to a standard REST list call.
-type ListOptions struct {
- metav1.TypeMeta
-
- // A selector based on labels
- LabelSelector labels.Selector
- // A selector based on fields
- FieldSelector fields.Selector
- // If true, partially initialized resources are included in the response.
- // +optional
- IncludeUninitialized bool
- // If true, watch for changes to this list
- Watch bool
- // When specified with a watch call, shows changes that occur after that particular version of a resource.
- // Defaults to changes from the beginning of history.
- // When specified for list:
- // - if unset, then the result is returned from remote storage based on quorum-read flag;
- // - if it's 0, then we simply return what we currently have in cache, no guarantee;
- // - if set to non zero, then the result is at least as fresh as given rv.
- ResourceVersion string
- // Timeout for the list/watch call.
- TimeoutSeconds *int64
- // Limit specifies the maximum number of results to return from the server. The server may
- // not support this field on all resource types, but if it does and more results remain it
- // will set the continue field on the returned list object.
- Limit int64
- // Continue is a token returned by the server that lets a client retrieve chunks of results
- // from the server by specifying limit. The server may reject requests for continuation tokens
- // it does not recognize and will return a 410 error if the token can no longer be used because
- // it has expired.
- Continue string
-}
-
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-
-// List holds a list of objects, which may not be known by the server.
-type List struct {
- metav1.TypeMeta
- // +optional
- metav1.ListMeta
-
- Items []runtime.Object
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.conversion.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.conversion.go
deleted file mode 100644
index 247577b0c..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.conversion.go
+++ /dev/null
@@ -1,118 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// This file was autogenerated by conversion-gen. Do not edit it manually!
-
-package internalversion
-
-import (
- unsafe "unsafe"
-
- v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- conversion "k8s.io/apimachinery/pkg/conversion"
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-func init() {
- localSchemeBuilder.Register(RegisterConversions)
-}
-
-// RegisterConversions adds conversion functions to the given scheme.
-// Public to allow building arbitrary schemes.
-func RegisterConversions(scheme *runtime.Scheme) error {
- return scheme.AddGeneratedConversionFuncs(
- Convert_internalversion_List_To_v1_List,
- Convert_v1_List_To_internalversion_List,
- Convert_internalversion_ListOptions_To_v1_ListOptions,
- Convert_v1_ListOptions_To_internalversion_ListOptions,
- )
-}
-
-func autoConvert_internalversion_List_To_v1_List(in *List, out *v1.List, s conversion.Scope) error {
- out.ListMeta = in.ListMeta
- if in.Items != nil {
- in, out := &in.Items, &out.Items
- *out = make([]runtime.RawExtension, len(*in))
- for i := range *in {
- if err := runtime.Convert_runtime_Object_To_runtime_RawExtension(&(*in)[i], &(*out)[i], s); err != nil {
- return err
- }
- }
- } else {
- out.Items = nil
- }
- return nil
-}
-
-// Convert_internalversion_List_To_v1_List is an autogenerated conversion function.
-func Convert_internalversion_List_To_v1_List(in *List, out *v1.List, s conversion.Scope) error {
- return autoConvert_internalversion_List_To_v1_List(in, out, s)
-}
-
-func autoConvert_v1_List_To_internalversion_List(in *v1.List, out *List, s conversion.Scope) error {
- out.ListMeta = in.ListMeta
- if in.Items != nil {
- in, out := &in.Items, &out.Items
- *out = make([]runtime.Object, len(*in))
- for i := range *in {
- if err := runtime.Convert_runtime_RawExtension_To_runtime_Object(&(*in)[i], &(*out)[i], s); err != nil {
- return err
- }
- }
- } else {
- out.Items = nil
- }
- return nil
-}
-
-// Convert_v1_List_To_internalversion_List is an autogenerated conversion function.
-func Convert_v1_List_To_internalversion_List(in *v1.List, out *List, s conversion.Scope) error {
- return autoConvert_v1_List_To_internalversion_List(in, out, s)
-}
-
-func autoConvert_internalversion_ListOptions_To_v1_ListOptions(in *ListOptions, out *v1.ListOptions, s conversion.Scope) error {
- if err := v1.Convert_labels_Selector_To_string(&in.LabelSelector, &out.LabelSelector, s); err != nil {
- return err
- }
- if err := v1.Convert_fields_Selector_To_string(&in.FieldSelector, &out.FieldSelector, s); err != nil {
- return err
- }
- out.IncludeUninitialized = in.IncludeUninitialized
- out.Watch = in.Watch
- out.ResourceVersion = in.ResourceVersion
- out.TimeoutSeconds = (*int64)(unsafe.Pointer(in.TimeoutSeconds))
- out.Limit = in.Limit
- out.Continue = in.Continue
- return nil
-}
-
-func autoConvert_v1_ListOptions_To_internalversion_ListOptions(in *v1.ListOptions, out *ListOptions, s conversion.Scope) error {
- if err := v1.Convert_string_To_labels_Selector(&in.LabelSelector, &out.LabelSelector, s); err != nil {
- return err
- }
- if err := v1.Convert_string_To_fields_Selector(&in.FieldSelector, &out.FieldSelector, s); err != nil {
- return err
- }
- out.IncludeUninitialized = in.IncludeUninitialized
- out.Watch = in.Watch
- out.ResourceVersion = in.ResourceVersion
- out.TimeoutSeconds = (*int64)(unsafe.Pointer(in.TimeoutSeconds))
- out.Limit = in.Limit
- out.Continue = in.Continue
- return nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.deepcopy.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.deepcopy.go
deleted file mode 100644
index 2bc1c3f96..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.deepcopy.go
+++ /dev/null
@@ -1,108 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// This file was autogenerated by deepcopy-gen. Do not edit it manually!
-
-package internalversion
-
-import (
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *List) DeepCopyInto(out *List) {
- *out = *in
- out.TypeMeta = in.TypeMeta
- out.ListMeta = in.ListMeta
- if in.Items != nil {
- in, out := &in.Items, &out.Items
- *out = make([]runtime.Object, len(*in))
- for i := range *in {
- if (*in)[i] == nil {
- (*out)[i] = nil
- } else {
- (*out)[i] = (*in)[i].DeepCopyObject()
- }
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new List.
-func (in *List) DeepCopy() *List {
- if in == nil {
- return nil
- }
- out := new(List)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *List) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- } else {
- return nil
- }
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *ListOptions) DeepCopyInto(out *ListOptions) {
- *out = *in
- out.TypeMeta = in.TypeMeta
- if in.LabelSelector == nil {
- out.LabelSelector = nil
- } else {
- out.LabelSelector = in.LabelSelector.DeepCopySelector()
- }
- if in.FieldSelector == nil {
- out.FieldSelector = nil
- } else {
- out.FieldSelector = in.FieldSelector.DeepCopySelector()
- }
- if in.TimeoutSeconds != nil {
- in, out := &in.TimeoutSeconds, &out.TimeoutSeconds
- if *in == nil {
- *out = nil
- } else {
- *out = new(int64)
- **out = **in
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ListOptions.
-func (in *ListOptions) DeepCopy() *ListOptions {
- if in == nil {
- return nil
- }
- out := new(ListOptions)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *ListOptions) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- } else {
- return nil
- }
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go
deleted file mode 100644
index 08705ac84..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go
+++ /dev/null
@@ -1,475 +0,0 @@
-/*
-Copyright 2015 The 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 unstructured
-
-import (
- gojson "encoding/json"
- "errors"
- "fmt"
- "io"
- "strings"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/types"
- "k8s.io/apimachinery/pkg/util/json"
-)
-
-// NestedFieldCopy returns a deep copy of the value of a nested field.
-// Returns false if the value is missing.
-// No error is returned for a nil field.
-func NestedFieldCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error) {
- val, found, err := nestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- return runtime.DeepCopyJSONValue(val), true, nil
-}
-
-func nestedFieldNoCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error) {
- var val interface{} = obj
-
- for i, field := range fields {
- if m, ok := val.(map[string]interface{}); ok {
- val, ok = m[field]
- if !ok {
- return nil, false, nil
- }
- } else {
- return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected map[string]interface{}", jsonPath(fields[:i+1]), val, val)
- }
- }
- return val, true, nil
-}
-
-// NestedString returns the string value of a nested field.
-// Returns false if value is not found and an error if not a string.
-func NestedString(obj map[string]interface{}, fields ...string) (string, bool, error) {
- val, found, err := nestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return "", found, err
- }
- s, ok := val.(string)
- if !ok {
- return "", false, fmt.Errorf("%v accessor error: %v is of the type %T, expected string", jsonPath(fields), val, val)
- }
- return s, true, nil
-}
-
-// NestedBool returns the bool value of a nested field.
-// Returns false if value is not found and an error if not a bool.
-func NestedBool(obj map[string]interface{}, fields ...string) (bool, bool, error) {
- val, found, err := nestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return false, found, err
- }
- b, ok := val.(bool)
- if !ok {
- return false, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected bool", jsonPath(fields), val, val)
- }
- return b, true, nil
-}
-
-// NestedFloat64 returns the float64 value of a nested field.
-// Returns false if value is not found and an error if not a float64.
-func NestedFloat64(obj map[string]interface{}, fields ...string) (float64, bool, error) {
- val, found, err := nestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return 0, found, err
- }
- f, ok := val.(float64)
- if !ok {
- return 0, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected float64", jsonPath(fields), val, val)
- }
- return f, true, nil
-}
-
-// NestedInt64 returns the int64 value of a nested field.
-// Returns false if value is not found and an error if not an int64.
-func NestedInt64(obj map[string]interface{}, fields ...string) (int64, bool, error) {
- val, found, err := nestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return 0, found, err
- }
- i, ok := val.(int64)
- if !ok {
- return 0, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected int64", jsonPath(fields), val, val)
- }
- return i, true, nil
-}
-
-// NestedStringSlice returns a copy of []string value of a nested field.
-// Returns false if value is not found and an error if not a []interface{} or contains non-string items in the slice.
-func NestedStringSlice(obj map[string]interface{}, fields ...string) ([]string, bool, error) {
- val, found, err := nestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- m, ok := val.([]interface{})
- if !ok {
- return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected []interface{}", jsonPath(fields), val, val)
- }
- strSlice := make([]string, 0, len(m))
- for _, v := range m {
- if str, ok := v.(string); ok {
- strSlice = append(strSlice, str)
- } else {
- return nil, false, fmt.Errorf("%v accessor error: contains non-string key in the slice: %v is of the type %T, expected string", jsonPath(fields), v, v)
- }
- }
- return strSlice, true, nil
-}
-
-// NestedSlice returns a deep copy of []interface{} value of a nested field.
-// Returns false if value is not found and an error if not a []interface{}.
-func NestedSlice(obj map[string]interface{}, fields ...string) ([]interface{}, bool, error) {
- val, found, err := nestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- _, ok := val.([]interface{})
- if !ok {
- return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected []interface{}", jsonPath(fields), val, val)
- }
- return runtime.DeepCopyJSONValue(val).([]interface{}), true, nil
-}
-
-// NestedStringMap returns a copy of map[string]string value of a nested field.
-// Returns false if value is not found and an error if not a map[string]interface{} or contains non-string values in the map.
-func NestedStringMap(obj map[string]interface{}, fields ...string) (map[string]string, bool, error) {
- m, found, err := nestedMapNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- strMap := make(map[string]string, len(m))
- for k, v := range m {
- if str, ok := v.(string); ok {
- strMap[k] = str
- } else {
- return nil, false, fmt.Errorf("%v accessor error: contains non-string key in the map: %v is of the type %T, expected string", jsonPath(fields), v, v)
- }
- }
- return strMap, true, nil
-}
-
-// NestedMap returns a deep copy of map[string]interface{} value of a nested field.
-// Returns false if value is not found and an error if not a map[string]interface{}.
-func NestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error) {
- m, found, err := nestedMapNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- return runtime.DeepCopyJSON(m), true, nil
-}
-
-// nestedMapNoCopy returns a map[string]interface{} value of a nested field.
-// Returns false if value is not found and an error if not a map[string]interface{}.
-func nestedMapNoCopy(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error) {
- val, found, err := nestedFieldNoCopy(obj, fields...)
- if !found || err != nil {
- return nil, found, err
- }
- m, ok := val.(map[string]interface{})
- if !ok {
- return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected map[string]interface{}", jsonPath(fields), val, val)
- }
- return m, true, nil
-}
-
-// SetNestedField sets the value of a nested field to a deep copy of the value provided.
-// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
-func SetNestedField(obj map[string]interface{}, value interface{}, fields ...string) error {
- return setNestedFieldNoCopy(obj, runtime.DeepCopyJSONValue(value), fields...)
-}
-
-func setNestedFieldNoCopy(obj map[string]interface{}, value interface{}, fields ...string) error {
- m := obj
-
- for i, field := range fields[:len(fields)-1] {
- if val, ok := m[field]; ok {
- if valMap, ok := val.(map[string]interface{}); ok {
- m = valMap
- } else {
- return fmt.Errorf("value cannot be set because %v is not a map[string]interface{}", jsonPath(fields[:i+1]))
- }
- } else {
- newVal := make(map[string]interface{})
- m[field] = newVal
- m = newVal
- }
- }
- m[fields[len(fields)-1]] = value
- return nil
-}
-
-// SetNestedStringSlice sets the string slice value of a nested field.
-// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
-func SetNestedStringSlice(obj map[string]interface{}, value []string, fields ...string) error {
- m := make([]interface{}, 0, len(value)) // convert []string into []interface{}
- for _, v := range value {
- m = append(m, v)
- }
- return setNestedFieldNoCopy(obj, m, fields...)
-}
-
-// SetNestedSlice sets the slice value of a nested field.
-// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
-func SetNestedSlice(obj map[string]interface{}, value []interface{}, fields ...string) error {
- return SetNestedField(obj, value, fields...)
-}
-
-// SetNestedStringMap sets the map[string]string value of a nested field.
-// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
-func SetNestedStringMap(obj map[string]interface{}, value map[string]string, fields ...string) error {
- m := make(map[string]interface{}, len(value)) // convert map[string]string into map[string]interface{}
- for k, v := range value {
- m[k] = v
- }
- return setNestedFieldNoCopy(obj, m, fields...)
-}
-
-// SetNestedMap sets the map[string]interface{} value of a nested field.
-// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
-func SetNestedMap(obj map[string]interface{}, value map[string]interface{}, fields ...string) error {
- return SetNestedField(obj, value, fields...)
-}
-
-// RemoveNestedField removes the nested field from the obj.
-func RemoveNestedField(obj map[string]interface{}, fields ...string) {
- m := obj
- for _, field := range fields[:len(fields)-1] {
- if x, ok := m[field].(map[string]interface{}); ok {
- m = x
- } else {
- return
- }
- }
- delete(m, fields[len(fields)-1])
-}
-
-func getNestedString(obj map[string]interface{}, fields ...string) string {
- val, found, err := NestedString(obj, fields...)
- if !found || err != nil {
- return ""
- }
- return val
-}
-
-func jsonPath(fields []string) string {
- return "." + strings.Join(fields, ".")
-}
-
-func extractOwnerReference(v map[string]interface{}) metav1.OwnerReference {
- // though this field is a *bool, but when decoded from JSON, it's
- // unmarshalled as bool.
- var controllerPtr *bool
- if controller, found, err := NestedBool(v, "controller"); err == nil && found {
- controllerPtr = &controller
- }
- var blockOwnerDeletionPtr *bool
- if blockOwnerDeletion, found, err := NestedBool(v, "blockOwnerDeletion"); err == nil && found {
- blockOwnerDeletionPtr = &blockOwnerDeletion
- }
- return metav1.OwnerReference{
- Kind: getNestedString(v, "kind"),
- Name: getNestedString(v, "name"),
- APIVersion: getNestedString(v, "apiVersion"),
- UID: types.UID(getNestedString(v, "uid")),
- Controller: controllerPtr,
- BlockOwnerDeletion: blockOwnerDeletionPtr,
- }
-}
-
-// UnstructuredJSONScheme is capable of converting JSON data into the Unstructured
-// type, which can be used for generic access to objects without a predefined scheme.
-// TODO: move into serializer/json.
-var UnstructuredJSONScheme runtime.Codec = unstructuredJSONScheme{}
-
-type unstructuredJSONScheme struct{}
-
-func (s unstructuredJSONScheme) Decode(data []byte, _ *schema.GroupVersionKind, obj runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
- var err error
- if obj != nil {
- err = s.decodeInto(data, obj)
- } else {
- obj, err = s.decode(data)
- }
-
- if err != nil {
- return nil, nil, err
- }
-
- gvk := obj.GetObjectKind().GroupVersionKind()
- if len(gvk.Kind) == 0 {
- return nil, &gvk, runtime.NewMissingKindErr(string(data))
- }
-
- return obj, &gvk, nil
-}
-
-func (unstructuredJSONScheme) Encode(obj runtime.Object, w io.Writer) error {
- switch t := obj.(type) {
- case *Unstructured:
- return json.NewEncoder(w).Encode(t.Object)
- case *UnstructuredList:
- items := make([]interface{}, 0, len(t.Items))
- for _, i := range t.Items {
- items = append(items, i.Object)
- }
- listObj := make(map[string]interface{}, len(t.Object)+1)
- for k, v := range t.Object { // Make a shallow copy
- listObj[k] = v
- }
- listObj["items"] = items
- return json.NewEncoder(w).Encode(listObj)
- case *runtime.Unknown:
- // TODO: Unstructured needs to deal with ContentType.
- _, err := w.Write(t.Raw)
- return err
- default:
- return json.NewEncoder(w).Encode(t)
- }
-}
-
-func (s unstructuredJSONScheme) decode(data []byte) (runtime.Object, error) {
- type detector struct {
- Items gojson.RawMessage
- }
- var det detector
- if err := json.Unmarshal(data, &det); err != nil {
- return nil, err
- }
-
- if det.Items != nil {
- list := &UnstructuredList{}
- err := s.decodeToList(data, list)
- return list, err
- }
-
- // No Items field, so it wasn't a list.
- unstruct := &Unstructured{}
- err := s.decodeToUnstructured(data, unstruct)
- return unstruct, err
-}
-
-func (s unstructuredJSONScheme) decodeInto(data []byte, obj runtime.Object) error {
- switch x := obj.(type) {
- case *Unstructured:
- return s.decodeToUnstructured(data, x)
- case *UnstructuredList:
- return s.decodeToList(data, x)
- case *runtime.VersionedObjects:
- o, err := s.decode(data)
- if err == nil {
- x.Objects = []runtime.Object{o}
- }
- return err
- default:
- return json.Unmarshal(data, x)
- }
-}
-
-func (unstructuredJSONScheme) decodeToUnstructured(data []byte, unstruct *Unstructured) error {
- m := make(map[string]interface{})
- if err := json.Unmarshal(data, &m); err != nil {
- return err
- }
-
- unstruct.Object = m
-
- return nil
-}
-
-func (s unstructuredJSONScheme) decodeToList(data []byte, list *UnstructuredList) error {
- type decodeList struct {
- Items []gojson.RawMessage
- }
-
- var dList decodeList
- if err := json.Unmarshal(data, &dList); err != nil {
- return err
- }
-
- if err := json.Unmarshal(data, &list.Object); err != nil {
- return err
- }
-
- // For typed lists, e.g., a PodList, API server doesn't set each item's
- // APIVersion and Kind. We need to set it.
- listAPIVersion := list.GetAPIVersion()
- listKind := list.GetKind()
- itemKind := strings.TrimSuffix(listKind, "List")
-
- delete(list.Object, "items")
- list.Items = make([]Unstructured, 0, len(dList.Items))
- for _, i := range dList.Items {
- unstruct := &Unstructured{}
- if err := s.decodeToUnstructured([]byte(i), unstruct); err != nil {
- return err
- }
- // This is hacky. Set the item's Kind and APIVersion to those inferred
- // from the List.
- if len(unstruct.GetKind()) == 0 && len(unstruct.GetAPIVersion()) == 0 {
- unstruct.SetKind(itemKind)
- unstruct.SetAPIVersion(listAPIVersion)
- }
- list.Items = append(list.Items, *unstruct)
- }
- return nil
-}
-
-// UnstructuredObjectConverter is an ObjectConverter for use with
-// Unstructured objects. Since it has no schema or type information,
-// it will only succeed for no-op conversions. This is provided as a
-// sane implementation for APIs that require an object converter.
-type UnstructuredObjectConverter struct{}
-
-func (UnstructuredObjectConverter) Convert(in, out, context interface{}) error {
- unstructIn, ok := in.(*Unstructured)
- if !ok {
- return fmt.Errorf("input type %T in not valid for unstructured conversion", in)
- }
-
- unstructOut, ok := out.(*Unstructured)
- if !ok {
- return fmt.Errorf("output type %T in not valid for unstructured conversion", out)
- }
-
- // maybe deep copy the map? It is documented in the
- // ObjectConverter interface that this function is not
- // guaranteed to not mutate the input. Or maybe set the input
- // object to nil.
- unstructOut.Object = unstructIn.Object
- return nil
-}
-
-func (UnstructuredObjectConverter) ConvertToVersion(in runtime.Object, target runtime.GroupVersioner) (runtime.Object, error) {
- if kind := in.GetObjectKind().GroupVersionKind(); !kind.Empty() {
- gvk, ok := target.KindForGroupVersionKinds([]schema.GroupVersionKind{kind})
- if !ok {
- // TODO: should this be a typed error?
- return nil, fmt.Errorf("%v is unstructured and is not suitable for converting to %q", kind, target)
- }
- in.GetObjectKind().SetGroupVersionKind(gvk)
- }
- return in, nil
-}
-
-func (UnstructuredObjectConverter) ConvertFieldLabel(version, kind, label, value string) (string, string, error) {
- return "", "", errors.New("unstructured cannot convert field labels")
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go
deleted file mode 100644
index 2a1333049..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go
+++ /dev/null
@@ -1,379 +0,0 @@
-/*
-Copyright 2015 The 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 unstructured
-
-import (
- "bytes"
- "errors"
- "fmt"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/types"
- utilruntime "k8s.io/apimachinery/pkg/util/runtime"
-)
-
-// Unstructured allows objects that do not have Golang structs registered to be manipulated
-// generically. This can be used to deal with the API objects from a plug-in. Unstructured
-// objects still have functioning TypeMeta features-- kind, version, etc.
-//
-// WARNING: This object has accessors for the v1 standard metadata. You *MUST NOT* use this
-// type if you are dealing with objects that are not in the server meta v1 schema.
-//
-// TODO: make the serialization part of this type distinct from the field accessors.
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-// +k8s:deepcopy-gen=true
-type Unstructured struct {
- // Object is a JSON compatible map with string, float, int, bool, []interface{}, or
- // map[string]interface{}
- // children.
- Object map[string]interface{}
-}
-
-var _ metav1.Object = &Unstructured{}
-var _ runtime.Unstructured = &Unstructured{}
-
-func (obj *Unstructured) GetObjectKind() schema.ObjectKind { return obj }
-
-func (obj *Unstructured) IsList() bool {
- field, ok := obj.Object["items"]
- if !ok {
- return false
- }
- _, ok = field.([]interface{})
- return ok
-}
-
-func (obj *Unstructured) EachListItem(fn func(runtime.Object) error) error {
- field, ok := obj.Object["items"]
- if !ok {
- return errors.New("content is not a list")
- }
- items, ok := field.([]interface{})
- if !ok {
- return fmt.Errorf("content is not a list: %T", field)
- }
- for _, item := range items {
- child, ok := item.(map[string]interface{})
- if !ok {
- return fmt.Errorf("items member is not an object: %T", child)
- }
- if err := fn(&Unstructured{Object: child}); err != nil {
- return err
- }
- }
- return nil
-}
-
-func (obj *Unstructured) UnstructuredContent() map[string]interface{} {
- if obj.Object == nil {
- obj.Object = make(map[string]interface{})
- }
- return obj.Object
-}
-
-func (obj *Unstructured) SetUnstructuredContent(content map[string]interface{}) {
- obj.Object = content
-}
-
-// MarshalJSON ensures that the unstructured object produces proper
-// JSON when passed to Go's standard JSON library.
-func (u *Unstructured) MarshalJSON() ([]byte, error) {
- var buf bytes.Buffer
- err := UnstructuredJSONScheme.Encode(u, &buf)
- return buf.Bytes(), err
-}
-
-// UnmarshalJSON ensures that the unstructured object properly decodes
-// JSON when passed to Go's standard JSON library.
-func (u *Unstructured) UnmarshalJSON(b []byte) error {
- _, _, err := UnstructuredJSONScheme.Decode(b, nil, u)
- return err
-}
-
-func (in *Unstructured) DeepCopy() *Unstructured {
- if in == nil {
- return nil
- }
- out := new(Unstructured)
- *out = *in
- out.Object = runtime.DeepCopyJSON(in.Object)
- return out
-}
-
-func (u *Unstructured) setNestedField(value interface{}, fields ...string) {
- if u.Object == nil {
- u.Object = make(map[string]interface{})
- }
- SetNestedField(u.Object, value, fields...)
-}
-
-func (u *Unstructured) setNestedSlice(value []string, fields ...string) {
- if u.Object == nil {
- u.Object = make(map[string]interface{})
- }
- SetNestedStringSlice(u.Object, value, fields...)
-}
-
-func (u *Unstructured) setNestedMap(value map[string]string, fields ...string) {
- if u.Object == nil {
- u.Object = make(map[string]interface{})
- }
- SetNestedStringMap(u.Object, value, fields...)
-}
-
-func (u *Unstructured) GetOwnerReferences() []metav1.OwnerReference {
- field, found, err := nestedFieldNoCopy(u.Object, "metadata", "ownerReferences")
- if !found || err != nil {
- return nil
- }
- original, ok := field.([]interface{})
- if !ok {
- return nil
- }
- ret := make([]metav1.OwnerReference, 0, len(original))
- for _, obj := range original {
- o, ok := obj.(map[string]interface{})
- if !ok {
- // expected map[string]interface{}, got something else
- return nil
- }
- ret = append(ret, extractOwnerReference(o))
- }
- return ret
-}
-
-func (u *Unstructured) SetOwnerReferences(references []metav1.OwnerReference) {
- newReferences := make([]interface{}, 0, len(references))
- for _, reference := range references {
- out, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&reference)
- if err != nil {
- utilruntime.HandleError(fmt.Errorf("unable to convert Owner Reference: %v", err))
- continue
- }
- newReferences = append(newReferences, out)
- }
- u.setNestedField(newReferences, "metadata", "ownerReferences")
-}
-
-func (u *Unstructured) GetAPIVersion() string {
- return getNestedString(u.Object, "apiVersion")
-}
-
-func (u *Unstructured) SetAPIVersion(version string) {
- u.setNestedField(version, "apiVersion")
-}
-
-func (u *Unstructured) GetKind() string {
- return getNestedString(u.Object, "kind")
-}
-
-func (u *Unstructured) SetKind(kind string) {
- u.setNestedField(kind, "kind")
-}
-
-func (u *Unstructured) GetNamespace() string {
- return getNestedString(u.Object, "metadata", "namespace")
-}
-
-func (u *Unstructured) SetNamespace(namespace string) {
- u.setNestedField(namespace, "metadata", "namespace")
-}
-
-func (u *Unstructured) GetName() string {
- return getNestedString(u.Object, "metadata", "name")
-}
-
-func (u *Unstructured) SetName(name string) {
- u.setNestedField(name, "metadata", "name")
-}
-
-func (u *Unstructured) GetGenerateName() string {
- return getNestedString(u.Object, "metadata", "generateName")
-}
-
-func (u *Unstructured) SetGenerateName(name string) {
- u.setNestedField(name, "metadata", "generateName")
-}
-
-func (u *Unstructured) GetUID() types.UID {
- return types.UID(getNestedString(u.Object, "metadata", "uid"))
-}
-
-func (u *Unstructured) SetUID(uid types.UID) {
- u.setNestedField(string(uid), "metadata", "uid")
-}
-
-func (u *Unstructured) GetResourceVersion() string {
- return getNestedString(u.Object, "metadata", "resourceVersion")
-}
-
-func (u *Unstructured) SetResourceVersion(version string) {
- u.setNestedField(version, "metadata", "resourceVersion")
-}
-
-func (u *Unstructured) GetGeneration() int64 {
- val, found, err := NestedInt64(u.Object, "metadata", "generation")
- if !found || err != nil {
- return 0
- }
- return val
-}
-
-func (u *Unstructured) SetGeneration(generation int64) {
- u.setNestedField(generation, "metadata", "generation")
-}
-
-func (u *Unstructured) GetSelfLink() string {
- return getNestedString(u.Object, "metadata", "selfLink")
-}
-
-func (u *Unstructured) SetSelfLink(selfLink string) {
- u.setNestedField(selfLink, "metadata", "selfLink")
-}
-
-func (u *Unstructured) GetContinue() string {
- return getNestedString(u.Object, "metadata", "continue")
-}
-
-func (u *Unstructured) SetContinue(c string) {
- u.setNestedField(c, "metadata", "continue")
-}
-
-func (u *Unstructured) GetCreationTimestamp() metav1.Time {
- var timestamp metav1.Time
- timestamp.UnmarshalQueryParameter(getNestedString(u.Object, "metadata", "creationTimestamp"))
- return timestamp
-}
-
-func (u *Unstructured) SetCreationTimestamp(timestamp metav1.Time) {
- ts, _ := timestamp.MarshalQueryParameter()
- if len(ts) == 0 || timestamp.Time.IsZero() {
- RemoveNestedField(u.Object, "metadata", "creationTimestamp")
- return
- }
- u.setNestedField(ts, "metadata", "creationTimestamp")
-}
-
-func (u *Unstructured) GetDeletionTimestamp() *metav1.Time {
- var timestamp metav1.Time
- timestamp.UnmarshalQueryParameter(getNestedString(u.Object, "metadata", "deletionTimestamp"))
- if timestamp.IsZero() {
- return nil
- }
- return &timestamp
-}
-
-func (u *Unstructured) SetDeletionTimestamp(timestamp *metav1.Time) {
- if timestamp == nil {
- RemoveNestedField(u.Object, "metadata", "deletionTimestamp")
- return
- }
- ts, _ := timestamp.MarshalQueryParameter()
- u.setNestedField(ts, "metadata", "deletionTimestamp")
-}
-
-func (u *Unstructured) GetDeletionGracePeriodSeconds() *int64 {
- val, found, err := NestedInt64(u.Object, "metadata", "deletionGracePeriodSeconds")
- if !found || err != nil {
- return nil
- }
- return &val
-}
-
-func (u *Unstructured) SetDeletionGracePeriodSeconds(deletionGracePeriodSeconds *int64) {
- if deletionGracePeriodSeconds == nil {
- RemoveNestedField(u.Object, "metadata", "deletionGracePeriodSeconds")
- return
- }
- u.setNestedField(*deletionGracePeriodSeconds, "metadata", "deletionGracePeriodSeconds")
-}
-
-func (u *Unstructured) GetLabels() map[string]string {
- m, _, _ := NestedStringMap(u.Object, "metadata", "labels")
- return m
-}
-
-func (u *Unstructured) SetLabels(labels map[string]string) {
- u.setNestedMap(labels, "metadata", "labels")
-}
-
-func (u *Unstructured) GetAnnotations() map[string]string {
- m, _, _ := NestedStringMap(u.Object, "metadata", "annotations")
- return m
-}
-
-func (u *Unstructured) SetAnnotations(annotations map[string]string) {
- u.setNestedMap(annotations, "metadata", "annotations")
-}
-
-func (u *Unstructured) SetGroupVersionKind(gvk schema.GroupVersionKind) {
- u.SetAPIVersion(gvk.GroupVersion().String())
- u.SetKind(gvk.Kind)
-}
-
-func (u *Unstructured) GroupVersionKind() schema.GroupVersionKind {
- gv, err := schema.ParseGroupVersion(u.GetAPIVersion())
- if err != nil {
- return schema.GroupVersionKind{}
- }
- gvk := gv.WithKind(u.GetKind())
- return gvk
-}
-
-func (u *Unstructured) GetInitializers() *metav1.Initializers {
- m, found, err := nestedMapNoCopy(u.Object, "metadata", "initializers")
- if !found || err != nil {
- return nil
- }
- out := &metav1.Initializers{}
- if err := runtime.DefaultUnstructuredConverter.FromUnstructured(m, out); err != nil {
- utilruntime.HandleError(fmt.Errorf("unable to retrieve initializers for object: %v", err))
- return nil
- }
- return out
-}
-
-func (u *Unstructured) SetInitializers(initializers *metav1.Initializers) {
- if initializers == nil {
- RemoveNestedField(u.Object, "metadata", "initializers")
- return
- }
- out, err := runtime.DefaultUnstructuredConverter.ToUnstructured(initializers)
- if err != nil {
- utilruntime.HandleError(fmt.Errorf("unable to retrieve initializers for object: %v", err))
- }
- u.setNestedField(out, "metadata", "initializers")
-}
-
-func (u *Unstructured) GetFinalizers() []string {
- val, _, _ := NestedStringSlice(u.Object, "metadata", "finalizers")
- return val
-}
-
-func (u *Unstructured) SetFinalizers(finalizers []string) {
- u.setNestedSlice(finalizers, "metadata", "finalizers")
-}
-
-func (u *Unstructured) GetClusterName() string {
- return getNestedString(u.Object, "metadata", "clusterName")
-}
-
-func (u *Unstructured) SetClusterName(clusterName string) {
- u.setNestedField(clusterName, "metadata", "clusterName")
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go
deleted file mode 100644
index 57d78a09d..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
-Copyright 2015 The 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 unstructured
-
-import (
- "bytes"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-var _ runtime.Unstructured = &UnstructuredList{}
-var _ metav1.ListInterface = &UnstructuredList{}
-
-// UnstructuredList allows lists that do not have Golang structs
-// registered to be manipulated generically. This can be used to deal
-// with the API lists from a plug-in.
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-// +k8s:deepcopy-gen=true
-type UnstructuredList struct {
- Object map[string]interface{}
-
- // Items is a list of unstructured objects.
- Items []Unstructured `json:"items"`
-}
-
-func (u *UnstructuredList) GetObjectKind() schema.ObjectKind { return u }
-
-func (u *UnstructuredList) IsList() bool { return true }
-
-func (u *UnstructuredList) EachListItem(fn func(runtime.Object) error) error {
- for i := range u.Items {
- if err := fn(&u.Items[i]); err != nil {
- return err
- }
- }
- return nil
-}
-
-// UnstructuredContent returns a map contain an overlay of the Items field onto
-// the Object field. Items always overwrites overlay. Changing "items" in the
-// returned object will affect items in the underlying Items field, but changing
-// the "items" slice itself will have no effect.
-// TODO: expose SetUnstructuredContent on runtime.Unstructured that allows
-// items to be changed.
-func (u *UnstructuredList) UnstructuredContent() map[string]interface{} {
- out := u.Object
- if out == nil {
- out = make(map[string]interface{})
- }
- items := make([]interface{}, len(u.Items))
- for i, item := range u.Items {
- items[i] = item.Object
- }
- out["items"] = items
- return out
-}
-
-// SetUnstructuredContent obeys the conventions of List and keeps Items and the items
-// array in sync. If items is not an array of objects in the incoming map, then any
-// mismatched item will be removed.
-func (obj *UnstructuredList) SetUnstructuredContent(content map[string]interface{}) {
- obj.Object = content
- if content == nil {
- obj.Items = nil
- return
- }
- items, ok := obj.Object["items"].([]interface{})
- if !ok || items == nil {
- items = []interface{}{}
- }
- unstructuredItems := make([]Unstructured, 0, len(items))
- newItems := make([]interface{}, 0, len(items))
- for _, item := range items {
- o, ok := item.(map[string]interface{})
- if !ok {
- continue
- }
- unstructuredItems = append(unstructuredItems, Unstructured{Object: o})
- newItems = append(newItems, o)
- }
- obj.Items = unstructuredItems
- obj.Object["items"] = newItems
-}
-
-func (u *UnstructuredList) DeepCopy() *UnstructuredList {
- if u == nil {
- return nil
- }
- out := new(UnstructuredList)
- *out = *u
- out.Object = runtime.DeepCopyJSON(u.Object)
- out.Items = make([]Unstructured, len(u.Items))
- for i := range u.Items {
- u.Items[i].DeepCopyInto(&out.Items[i])
- }
- return out
-}
-
-// MarshalJSON ensures that the unstructured list object produces proper
-// JSON when passed to Go's standard JSON library.
-func (u *UnstructuredList) MarshalJSON() ([]byte, error) {
- var buf bytes.Buffer
- err := UnstructuredJSONScheme.Encode(u, &buf)
- return buf.Bytes(), err
-}
-
-// UnmarshalJSON ensures that the unstructured list object properly
-// decodes JSON when passed to Go's standard JSON library.
-func (u *UnstructuredList) UnmarshalJSON(b []byte) error {
- _, _, err := UnstructuredJSONScheme.Decode(b, nil, u)
- return err
-}
-
-func (u *UnstructuredList) GetAPIVersion() string {
- return getNestedString(u.Object, "apiVersion")
-}
-
-func (u *UnstructuredList) SetAPIVersion(version string) {
- u.setNestedField(version, "apiVersion")
-}
-
-func (u *UnstructuredList) GetKind() string {
- return getNestedString(u.Object, "kind")
-}
-
-func (u *UnstructuredList) SetKind(kind string) {
- u.setNestedField(kind, "kind")
-}
-
-func (u *UnstructuredList) GetResourceVersion() string {
- return getNestedString(u.Object, "metadata", "resourceVersion")
-}
-
-func (u *UnstructuredList) SetResourceVersion(version string) {
- u.setNestedField(version, "metadata", "resourceVersion")
-}
-
-func (u *UnstructuredList) GetSelfLink() string {
- return getNestedString(u.Object, "metadata", "selfLink")
-}
-
-func (u *UnstructuredList) SetSelfLink(selfLink string) {
- u.setNestedField(selfLink, "metadata", "selfLink")
-}
-
-func (u *UnstructuredList) GetContinue() string {
- return getNestedString(u.Object, "metadata", "continue")
-}
-
-func (u *UnstructuredList) SetContinue(c string) {
- u.setNestedField(c, "metadata", "continue")
-}
-
-func (u *UnstructuredList) SetGroupVersionKind(gvk schema.GroupVersionKind) {
- u.SetAPIVersion(gvk.GroupVersion().String())
- u.SetKind(gvk.Kind)
-}
-
-func (u *UnstructuredList) GroupVersionKind() schema.GroupVersionKind {
- gv, err := schema.ParseGroupVersion(u.GetAPIVersion())
- if err != nil {
- return schema.GroupVersionKind{}
- }
- gvk := gv.WithKind(u.GetKind())
- return gvk
-}
-
-func (u *UnstructuredList) setNestedField(value interface{}, fields ...string) {
- if u.Object == nil {
- u.Object = make(map[string]interface{})
- }
- SetNestedField(u.Object, value, fields...)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/zz_generated.deepcopy.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/zz_generated.deepcopy.go
deleted file mode 100644
index e3bae45ec..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/zz_generated.deepcopy.go
+++ /dev/null
@@ -1,57 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// This file was autogenerated by deepcopy-gen. Do not edit it manually!
-
-package unstructured
-
-import (
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *Unstructured) DeepCopyInto(out *Unstructured) {
- clone := in.DeepCopy()
- *out = *clone
- return
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *Unstructured) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- } else {
- return nil
- }
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *UnstructuredList) DeepCopyInto(out *UnstructuredList) {
- clone := in.DeepCopy()
- *out = *clone
- return
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *UnstructuredList) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- } else {
- return nil
- }
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go
deleted file mode 100644
index 26c5a0cdc..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
-Copyright 2015 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package validation
-
-import (
- "fmt"
-
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/util/validation"
- "k8s.io/apimachinery/pkg/util/validation/field"
-)
-
-func ValidateLabelSelector(ps *metav1.LabelSelector, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- if ps == nil {
- return allErrs
- }
- allErrs = append(allErrs, ValidateLabels(ps.MatchLabels, fldPath.Child("matchLabels"))...)
- for i, expr := range ps.MatchExpressions {
- allErrs = append(allErrs, ValidateLabelSelectorRequirement(expr, fldPath.Child("matchExpressions").Index(i))...)
- }
- return allErrs
-}
-
-func ValidateLabelSelectorRequirement(sr metav1.LabelSelectorRequirement, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- switch sr.Operator {
- case metav1.LabelSelectorOpIn, metav1.LabelSelectorOpNotIn:
- if len(sr.Values) == 0 {
- allErrs = append(allErrs, field.Required(fldPath.Child("values"), "must be specified when `operator` is 'In' or 'NotIn'"))
- }
- case metav1.LabelSelectorOpExists, metav1.LabelSelectorOpDoesNotExist:
- if len(sr.Values) > 0 {
- allErrs = append(allErrs, field.Forbidden(fldPath.Child("values"), "may not be specified when `operator` is 'Exists' or 'DoesNotExist'"))
- }
- default:
- allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), sr.Operator, "not a valid selector operator"))
- }
- allErrs = append(allErrs, ValidateLabelName(sr.Key, fldPath.Child("key"))...)
- return allErrs
-}
-
-// ValidateLabelName validates that the label name is correctly defined.
-func ValidateLabelName(labelName string, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- for _, msg := range validation.IsQualifiedName(labelName) {
- allErrs = append(allErrs, field.Invalid(fldPath, labelName, msg))
- }
- return allErrs
-}
-
-// ValidateLabels validates that a set of labels are correctly defined.
-func ValidateLabels(labels map[string]string, fldPath *field.Path) field.ErrorList {
- allErrs := field.ErrorList{}
- for k, v := range labels {
- allErrs = append(allErrs, ValidateLabelName(k, fldPath)...)
- for _, msg := range validation.IsValidLabelValue(v) {
- allErrs = append(allErrs, field.Invalid(fldPath, v, msg))
- }
- }
- return allErrs
-}
-
-func ValidateDeleteOptions(options *metav1.DeleteOptions) field.ErrorList {
- allErrs := field.ErrorList{}
- if options.OrphanDependents != nil && options.PropagationPolicy != nil {
- allErrs = append(allErrs, field.Invalid(field.NewPath(""), options, "OrphanDependents and DeletionPropagation cannot be both set"))
- }
- if options.PropagationPolicy != nil &&
- *options.PropagationPolicy != metav1.DeletePropagationForeground &&
- *options.PropagationPolicy != metav1.DeletePropagationBackground &&
- *options.PropagationPolicy != metav1.DeletePropagationOrphan {
- allErrs = append(allErrs, field.Invalid(field.NewPath(""), options, fmt.Sprintf("DeletionPropagation need to be one of %q, %q, %q or nil", metav1.DeletePropagationForeground, metav1.DeletePropagationBackground, metav1.DeletePropagationOrphan)))
- }
- return allErrs
-}
-
-const UninitializedStatusUpdateErrorMsg string = `must not update status when the object is uninitialized`
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/conversion.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/conversion.go
deleted file mode 100644
index f3e5e4c98..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/conversion.go
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Copyright 2017 The 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 v1beta1
-
-import "k8s.io/apimachinery/pkg/conversion"
-
-// Convert_Slice_string_To_v1beta1_IncludeObjectPolicy allows converting a URL query parameter value
-func Convert_Slice_string_To_v1beta1_IncludeObjectPolicy(input *[]string, out *IncludeObjectPolicy, s conversion.Scope) error {
- if len(*input) > 0 {
- *out = IncludeObjectPolicy((*input)[0])
- }
- return nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/deepcopy.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/deepcopy.go
deleted file mode 100644
index 2dd440bb7..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/deepcopy.go
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
-Copyright 2017 The 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 v1beta1
-
-func (in *TableRow) DeepCopy() *TableRow {
- if in == nil {
- return nil
- }
-
- out := new(TableRow)
-
- if in.Cells != nil {
- out.Cells = make([]interface{}, len(in.Cells))
- for i := range in.Cells {
- out.Cells[i] = deepCopyJSON(in.Cells[i])
- }
- }
-
- if in.Conditions != nil {
- out.Conditions = make([]TableRowCondition, len(in.Conditions))
- for i := range in.Conditions {
- in.Conditions[i].DeepCopyInto(&out.Conditions[i])
- }
- }
-
- in.Object.DeepCopyInto(&out.Object)
- return out
-}
-
-func deepCopyJSON(x interface{}) interface{} {
- switch x := x.(type) {
- case map[string]interface{}:
- clone := make(map[string]interface{}, len(x))
- for k, v := range x {
- clone[k] = deepCopyJSON(v)
- }
- return clone
- case []interface{}:
- clone := make([]interface{}, len(x))
- for i := range x {
- clone[i] = deepCopyJSON(x[i])
- }
- return clone
- default:
- return x
- }
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/doc.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/doc.go
deleted file mode 100644
index dc461cc29..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/doc.go
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
-Copyright 2017 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// +k8s:deepcopy-gen=package
-// +k8s:openapi-gen=true
-// +k8s:defaulter-gen=TypeMeta
-
-// +groupName=meta.k8s.io
-package v1beta1
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.pb.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.pb.go
deleted file mode 100644
index dda05bea4..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.pb.go
+++ /dev/null
@@ -1,633 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Code generated by protoc-gen-gogo.
-// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto
-// DO NOT EDIT!
-
-/*
- Package v1beta1 is a generated protocol buffer package.
-
- It is generated from these files:
- k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto
-
- It has these top-level messages:
- PartialObjectMetadata
- PartialObjectMetadataList
- TableOptions
-*/
-package v1beta1
-
-import proto "github.com/gogo/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-import strings "strings"
-import reflect "reflect"
-
-import io "io"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
-
-func (m *PartialObjectMetadata) Reset() { *m = PartialObjectMetadata{} }
-func (*PartialObjectMetadata) ProtoMessage() {}
-func (*PartialObjectMetadata) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{0} }
-
-func (m *PartialObjectMetadataList) Reset() { *m = PartialObjectMetadataList{} }
-func (*PartialObjectMetadataList) ProtoMessage() {}
-func (*PartialObjectMetadataList) Descriptor() ([]byte, []int) {
- return fileDescriptorGenerated, []int{1}
-}
-
-func (m *TableOptions) Reset() { *m = TableOptions{} }
-func (*TableOptions) ProtoMessage() {}
-func (*TableOptions) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{2} }
-
-func init() {
- proto.RegisterType((*PartialObjectMetadata)(nil), "k8s.io.apimachinery.pkg.apis.meta.v1beta1.PartialObjectMetadata")
- proto.RegisterType((*PartialObjectMetadataList)(nil), "k8s.io.apimachinery.pkg.apis.meta.v1beta1.PartialObjectMetadataList")
- proto.RegisterType((*TableOptions)(nil), "k8s.io.apimachinery.pkg.apis.meta.v1beta1.TableOptions")
-}
-func (m *PartialObjectMetadata) Marshal() (dAtA []byte, err error) {
- size := m.Size()
- dAtA = make([]byte, size)
- n, err := m.MarshalTo(dAtA)
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *PartialObjectMetadata) MarshalTo(dAtA []byte) (int, error) {
- var i int
- _ = i
- var l int
- _ = l
- dAtA[i] = 0xa
- i++
- i = encodeVarintGenerated(dAtA, i, uint64(m.ObjectMeta.Size()))
- n1, err := m.ObjectMeta.MarshalTo(dAtA[i:])
- if err != nil {
- return 0, err
- }
- i += n1
- return i, nil
-}
-
-func (m *PartialObjectMetadataList) Marshal() (dAtA []byte, err error) {
- size := m.Size()
- dAtA = make([]byte, size)
- n, err := m.MarshalTo(dAtA)
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *PartialObjectMetadataList) MarshalTo(dAtA []byte) (int, error) {
- var i int
- _ = i
- var l int
- _ = l
- if len(m.Items) > 0 {
- for _, msg := range m.Items {
- dAtA[i] = 0xa
- i++
- i = encodeVarintGenerated(dAtA, i, uint64(msg.Size()))
- n, err := msg.MarshalTo(dAtA[i:])
- if err != nil {
- return 0, err
- }
- i += n
- }
- }
- return i, nil
-}
-
-func (m *TableOptions) Marshal() (dAtA []byte, err error) {
- size := m.Size()
- dAtA = make([]byte, size)
- n, err := m.MarshalTo(dAtA)
- if err != nil {
- return nil, err
- }
- return dAtA[:n], nil
-}
-
-func (m *TableOptions) MarshalTo(dAtA []byte) (int, error) {
- var i int
- _ = i
- var l int
- _ = l
- dAtA[i] = 0xa
- i++
- i = encodeVarintGenerated(dAtA, i, uint64(len(m.IncludeObject)))
- i += copy(dAtA[i:], m.IncludeObject)
- return i, nil
-}
-
-func encodeFixed64Generated(dAtA []byte, offset int, v uint64) int {
- dAtA[offset] = uint8(v)
- dAtA[offset+1] = uint8(v >> 8)
- dAtA[offset+2] = uint8(v >> 16)
- dAtA[offset+3] = uint8(v >> 24)
- dAtA[offset+4] = uint8(v >> 32)
- dAtA[offset+5] = uint8(v >> 40)
- dAtA[offset+6] = uint8(v >> 48)
- dAtA[offset+7] = uint8(v >> 56)
- return offset + 8
-}
-func encodeFixed32Generated(dAtA []byte, offset int, v uint32) int {
- dAtA[offset] = uint8(v)
- dAtA[offset+1] = uint8(v >> 8)
- dAtA[offset+2] = uint8(v >> 16)
- dAtA[offset+3] = uint8(v >> 24)
- return offset + 4
-}
-func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
- for v >= 1<<7 {
- dAtA[offset] = uint8(v&0x7f | 0x80)
- v >>= 7
- offset++
- }
- dAtA[offset] = uint8(v)
- return offset + 1
-}
-func (m *PartialObjectMetadata) Size() (n int) {
- var l int
- _ = l
- l = m.ObjectMeta.Size()
- n += 1 + l + sovGenerated(uint64(l))
- return n
-}
-
-func (m *PartialObjectMetadataList) Size() (n int) {
- var l int
- _ = l
- if len(m.Items) > 0 {
- for _, e := range m.Items {
- l = e.Size()
- n += 1 + l + sovGenerated(uint64(l))
- }
- }
- return n
-}
-
-func (m *TableOptions) Size() (n int) {
- var l int
- _ = l
- l = len(m.IncludeObject)
- n += 1 + l + sovGenerated(uint64(l))
- return n
-}
-
-func sovGenerated(x uint64) (n int) {
- for {
- n++
- x >>= 7
- if x == 0 {
- break
- }
- }
- return n
-}
-func sozGenerated(x uint64) (n int) {
- return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63))))
-}
-func (this *PartialObjectMetadata) String() string {
- if this == nil {
- return "nil"
- }
- s := strings.Join([]string{`&PartialObjectMetadata{`,
- `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_apimachinery_pkg_apis_meta_v1.ObjectMeta", 1), `&`, ``, 1) + `,`,
- `}`,
- }, "")
- return s
-}
-func (this *PartialObjectMetadataList) String() string {
- if this == nil {
- return "nil"
- }
- s := strings.Join([]string{`&PartialObjectMetadataList{`,
- `Items:` + strings.Replace(fmt.Sprintf("%v", this.Items), "PartialObjectMetadata", "PartialObjectMetadata", 1) + `,`,
- `}`,
- }, "")
- return s
-}
-func (this *TableOptions) String() string {
- if this == nil {
- return "nil"
- }
- s := strings.Join([]string{`&TableOptions{`,
- `IncludeObject:` + fmt.Sprintf("%v", this.IncludeObject) + `,`,
- `}`,
- }, "")
- return s
-}
-func valueToStringGenerated(v interface{}) string {
- rv := reflect.ValueOf(v)
- if rv.IsNil() {
- return "nil"
- }
- pv := reflect.Indirect(rv).Interface()
- return fmt.Sprintf("*%v", pv)
-}
-func (m *PartialObjectMetadata) Unmarshal(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflowGenerated
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= (uint64(b) & 0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: PartialObjectMetadata: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: PartialObjectMetadata: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflowGenerated
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= (int(b) & 0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLengthGenerated
- }
- postIndex := iNdEx + msglen
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
- return err
- }
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skipGenerated(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if skippy < 0 {
- return ErrInvalidLengthGenerated
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *PartialObjectMetadataList) Unmarshal(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflowGenerated
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= (uint64(b) & 0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: PartialObjectMetadataList: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: PartialObjectMetadataList: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType)
- }
- var msglen int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflowGenerated
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- msglen |= (int(b) & 0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- if msglen < 0 {
- return ErrInvalidLengthGenerated
- }
- postIndex := iNdEx + msglen
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.Items = append(m.Items, &PartialObjectMetadata{})
- if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
- return err
- }
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skipGenerated(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if skippy < 0 {
- return ErrInvalidLengthGenerated
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func (m *TableOptions) Unmarshal(dAtA []byte) error {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- preIndex := iNdEx
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflowGenerated
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= (uint64(b) & 0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- fieldNum := int32(wire >> 3)
- wireType := int(wire & 0x7)
- if wireType == 4 {
- return fmt.Errorf("proto: TableOptions: wiretype end group for non-group")
- }
- if fieldNum <= 0 {
- return fmt.Errorf("proto: TableOptions: illegal tag %d (wire type %d)", fieldNum, wire)
- }
- switch fieldNum {
- case 1:
- if wireType != 2 {
- return fmt.Errorf("proto: wrong wireType = %d for field IncludeObject", wireType)
- }
- var stringLen uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return ErrIntOverflowGenerated
- }
- if iNdEx >= l {
- return io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- stringLen |= (uint64(b) & 0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- intStringLen := int(stringLen)
- if intStringLen < 0 {
- return ErrInvalidLengthGenerated
- }
- postIndex := iNdEx + intStringLen
- if postIndex > l {
- return io.ErrUnexpectedEOF
- }
- m.IncludeObject = IncludeObjectPolicy(dAtA[iNdEx:postIndex])
- iNdEx = postIndex
- default:
- iNdEx = preIndex
- skippy, err := skipGenerated(dAtA[iNdEx:])
- if err != nil {
- return err
- }
- if skippy < 0 {
- return ErrInvalidLengthGenerated
- }
- if (iNdEx + skippy) > l {
- return io.ErrUnexpectedEOF
- }
- iNdEx += skippy
- }
- }
-
- if iNdEx > l {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
-func skipGenerated(dAtA []byte) (n int, err error) {
- l := len(dAtA)
- iNdEx := 0
- for iNdEx < l {
- var wire uint64
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return 0, ErrIntOverflowGenerated
- }
- if iNdEx >= l {
- return 0, io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- wire |= (uint64(b) & 0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- wireType := int(wire & 0x7)
- switch wireType {
- case 0:
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return 0, ErrIntOverflowGenerated
- }
- if iNdEx >= l {
- return 0, io.ErrUnexpectedEOF
- }
- iNdEx++
- if dAtA[iNdEx-1] < 0x80 {
- break
- }
- }
- return iNdEx, nil
- case 1:
- iNdEx += 8
- return iNdEx, nil
- case 2:
- var length int
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return 0, ErrIntOverflowGenerated
- }
- if iNdEx >= l {
- return 0, io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- length |= (int(b) & 0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- iNdEx += length
- if length < 0 {
- return 0, ErrInvalidLengthGenerated
- }
- return iNdEx, nil
- case 3:
- for {
- var innerWire uint64
- var start int = iNdEx
- for shift := uint(0); ; shift += 7 {
- if shift >= 64 {
- return 0, ErrIntOverflowGenerated
- }
- if iNdEx >= l {
- return 0, io.ErrUnexpectedEOF
- }
- b := dAtA[iNdEx]
- iNdEx++
- innerWire |= (uint64(b) & 0x7F) << shift
- if b < 0x80 {
- break
- }
- }
- innerWireType := int(innerWire & 0x7)
- if innerWireType == 4 {
- break
- }
- next, err := skipGenerated(dAtA[start:])
- if err != nil {
- return 0, err
- }
- iNdEx = start + next
- }
- return iNdEx, nil
- case 4:
- return iNdEx, nil
- case 5:
- iNdEx += 4
- return iNdEx, nil
- default:
- return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
- }
- }
- panic("unreachable")
-}
-
-var (
- ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling")
- ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow")
-)
-
-func init() {
- proto.RegisterFile("k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto", fileDescriptorGenerated)
-}
-
-var fileDescriptorGenerated = []byte{
- // 391 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x91, 0xbd, 0x6e, 0xd4, 0x40,
- 0x10, 0xc7, 0xbd, 0x42, 0x11, 0x64, 0x43, 0x1a, 0x23, 0xa4, 0x70, 0xc5, 0x3a, 0xba, 0x2a, 0x48,
- 0x64, 0x97, 0x04, 0x84, 0x28, 0x91, 0xbb, 0x48, 0xa0, 0x44, 0x16, 0x15, 0x15, 0x6b, 0x7b, 0xf0,
- 0x2d, 0xb6, 0x77, 0xad, 0xdd, 0x71, 0xa4, 0x6b, 0x10, 0x8f, 0xc0, 0x63, 0x5d, 0x99, 0x32, 0x95,
- 0xc5, 0x99, 0xb7, 0xa0, 0x42, 0xfe, 0x10, 0xf9, 0xb8, 0x3b, 0xe5, 0xba, 0x99, 0xff, 0xe8, 0xf7,
- 0xf3, 0x8c, 0x97, 0x46, 0xf9, 0x7b, 0xc7, 0x95, 0x11, 0x79, 0x1d, 0x83, 0xd5, 0x80, 0xe0, 0xc4,
- 0x25, 0xe8, 0xd4, 0x58, 0x31, 0x0e, 0x64, 0xa5, 0x4a, 0x99, 0xcc, 0x94, 0x06, 0x3b, 0x17, 0x55,
- 0x9e, 0x75, 0x81, 0x13, 0x25, 0xa0, 0x14, 0x97, 0x27, 0x31, 0xa0, 0x3c, 0x11, 0x19, 0x68, 0xb0,
- 0x12, 0x21, 0xe5, 0x95, 0x35, 0x68, 0xfc, 0x97, 0x03, 0xca, 0x6f, 0xa3, 0xbc, 0xca, 0xb3, 0x2e,
- 0x70, 0xbc, 0x43, 0xf9, 0x88, 0x4e, 0x8e, 0x33, 0x85, 0xb3, 0x3a, 0xe6, 0x89, 0x29, 0x45, 0x66,
- 0x32, 0x23, 0x7a, 0x43, 0x5c, 0x7f, 0xeb, 0xbb, 0xbe, 0xe9, 0xab, 0xc1, 0x3c, 0x79, 0xbb, 0xcd,
- 0x52, 0xf7, 0xf7, 0x99, 0x6c, 0x3c, 0xc5, 0xd6, 0x1a, 0x55, 0x09, 0x2b, 0xc0, 0xbb, 0x87, 0x00,
- 0x97, 0xcc, 0xa0, 0x94, 0x2b, 0xdc, 0x9b, 0x4d, 0x5c, 0x8d, 0xaa, 0x10, 0x4a, 0xa3, 0x43, 0x7b,
- 0x1f, 0x9a, 0xce, 0xe9, 0xf3, 0x0b, 0x69, 0x51, 0xc9, 0xe2, 0x3c, 0xfe, 0x0e, 0x09, 0x7e, 0x02,
- 0x94, 0xa9, 0x44, 0xe9, 0x7f, 0xa5, 0x4f, 0xca, 0xb1, 0x3e, 0x20, 0x87, 0xe4, 0x68, 0xef, 0xf4,
- 0x35, 0xdf, 0xe6, 0xcf, 0xf2, 0x1b, 0x4f, 0xe8, 0x2f, 0x9a, 0xc0, 0x6b, 0x9b, 0x80, 0xde, 0x64,
- 0xd1, 0x7f, 0xeb, 0xf4, 0x07, 0x7d, 0xb1, 0xf6, 0xd3, 0x1f, 0x95, 0x43, 0x5f, 0xd2, 0x1d, 0x85,
- 0x50, 0xba, 0x03, 0x72, 0xf8, 0xe8, 0x68, 0xef, 0xf4, 0x03, 0xdf, 0xfa, 0x55, 0xf9, 0x5a, 0x69,
- 0xb8, 0xdb, 0x36, 0xc1, 0xce, 0x59, 0xa7, 0x8c, 0x06, 0xf3, 0x34, 0xa6, 0x4f, 0x3f, 0xcb, 0xb8,
- 0x80, 0xf3, 0x0a, 0x95, 0xd1, 0xce, 0x8f, 0xe8, 0xbe, 0xd2, 0x49, 0x51, 0xa7, 0x30, 0xa0, 0xfd,
- 0xd9, 0xbb, 0xe1, 0xab, 0xf1, 0x88, 0xfd, 0xb3, 0xdb, 0xc3, 0xbf, 0x4d, 0xf0, 0xec, 0x4e, 0x70,
- 0x61, 0x0a, 0x95, 0xcc, 0xa3, 0xbb, 0x8a, 0xf0, 0x78, 0xb1, 0x64, 0xde, 0xd5, 0x92, 0x79, 0xd7,
- 0x4b, 0xe6, 0xfd, 0x6c, 0x19, 0x59, 0xb4, 0x8c, 0x5c, 0xb5, 0x8c, 0x5c, 0xb7, 0x8c, 0xfc, 0x6e,
- 0x19, 0xf9, 0xf5, 0x87, 0x79, 0x5f, 0x1e, 0x8f, 0xab, 0xff, 0x0b, 0x00, 0x00, 0xff, 0xff, 0x73,
- 0xdf, 0x3a, 0x0c, 0x10, 0x03, 0x00, 0x00,
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto
deleted file mode 100644
index a9060bf96..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-
-// This file was autogenerated by go-to-protobuf. Do not edit it manually!
-
-syntax = 'proto2';
-
-package k8s.io.apimachinery.pkg.apis.meta.v1beta1;
-
-import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto";
-import "k8s.io/apimachinery/pkg/runtime/generated.proto";
-import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto";
-import "k8s.io/apimachinery/pkg/util/intstr/generated.proto";
-
-// Package-wide variables from generator "generated".
-option go_package = "v1beta1";
-
-// PartialObjectMetadata is a generic representation of any object with ObjectMeta. It allows clients
-// to get access to a particular ObjectMeta schema without knowing the details of the version.
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-message PartialObjectMetadata {
- // Standard object's metadata.
- // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
- // +optional
- optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1;
-}
-
-// PartialObjectMetadataList contains a list of objects containing only their metadata
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-message PartialObjectMetadataList {
- // items contains each of the included items.
- repeated PartialObjectMetadata items = 1;
-}
-
-// TableOptions are used when a Table is requested by the caller.
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-message TableOptions {
- // includeObject decides whether to include each object along with its columnar information.
- // Specifying "None" will return no object, specifying "Object" will return the full object contents, and
- // specifying "Metadata" (the default) will return the object's metadata in the PartialObjectMetadata kind
- // in version v1beta1 of the meta.k8s.io API group.
- optional string includeObject = 1;
-}
-
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/register.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/register.go
deleted file mode 100644
index d13254b41..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/register.go
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
-Copyright 2017 The 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 v1beta1
-
-import (
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-// GroupName is the group name for this API.
-const GroupName = "meta.k8s.io"
-
-// SchemeGroupVersion is group version used to register these objects
-var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1beta1"}
-
-// Kind takes an unqualified kind and returns a Group qualified GroupKind
-func Kind(kind string) schema.GroupKind {
- return SchemeGroupVersion.WithKind(kind).GroupKind()
-}
-
-// scheme is the registry for the common types that adhere to the meta v1beta1 API spec.
-var scheme = runtime.NewScheme()
-
-// ParameterCodec knows about query parameters used with the meta v1beta1 API spec.
-var ParameterCodec = runtime.NewParameterCodec(scheme)
-
-func init() {
- scheme.AddKnownTypes(SchemeGroupVersion,
- &Table{},
- &TableOptions{},
- &PartialObjectMetadata{},
- &PartialObjectMetadataList{},
- )
-
- if err := scheme.AddConversionFuncs(
- Convert_Slice_string_To_v1beta1_IncludeObjectPolicy,
- ); err != nil {
- panic(err)
- }
-
- // register manually. This usually goes through the SchemeBuilder, which we cannot use here.
- //scheme.AddGeneratedDeepCopyFuncs(GetGeneratedDeepCopyFuncs()...)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types.go
deleted file mode 100644
index 7b7c47d82..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types.go
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
-Copyright 2017 The 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 v1beta1 is alpha objects from meta that will be introduced.
-package v1beta1
-
-import (
- "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
-)
-
-// TODO: Table does not generate to protobuf because of the interface{} - fix protobuf
-// generation to support a meta type that can accept any valid JSON.
-
-// Table is a tabular representation of a set of API resources. The server transforms the
-// object into a set of preferred columns for quickly reviewing the objects.
-// +protobuf=false
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-type Table struct {
- v1.TypeMeta `json:",inline"`
- // Standard list metadata.
- // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
- // +optional
- v1.ListMeta `json:"metadata,omitempty"`
-
- // columnDefinitions describes each column in the returned items array. The number of cells per row
- // will always match the number of column definitions.
- ColumnDefinitions []TableColumnDefinition `json:"columnDefinitions"`
- // rows is the list of items in the table.
- Rows []TableRow `json:"rows"`
-}
-
-// TableColumnDefinition contains information about a column returned in the Table.
-// +protobuf=false
-type TableColumnDefinition struct {
- // name is a human readable name for the column.
- Name string `json:"name"`
- // type is an OpenAPI type definition for this column.
- // See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more.
- Type string `json:"type"`
- // format is an optional OpenAPI type definition for this column. The 'name' format is applied
- // to the primary identifier column to assist in clients identifying column is the resource name.
- // See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more.
- Format string `json:"format"`
- // description is a human readable description of this column.
- Description string `json:"description"`
- // priority is an integer defining the relative importance of this column compared to others. Lower
- // numbers are considered higher priority. Columns that may be omitted in limited space scenarios
- // should be given a higher priority.
- Priority int32 `json:"priority"`
-}
-
-// TableRow is an individual row in a table.
-// +protobuf=false
-type TableRow struct {
- // cells will be as wide as headers and may contain strings, numbers, booleans, simple maps, or lists, or
- // null. See the type field of the column definition for a more detailed description.
- Cells []interface{} `json:"cells"`
- // conditions describe additional status of a row that are relevant for a human user.
- // +optional
- Conditions []TableRowCondition `json:"conditions,omitempty"`
- // This field contains the requested additional information about each object based on the includeObject
- // policy when requesting the Table. If "None", this field is empty, if "Object" this will be the
- // default serialization of the object for the current API version, and if "Metadata" (the default) will
- // contain the object metadata. Check the returned kind and apiVersion of the object before parsing.
- // +optional
- Object runtime.RawExtension `json:"object,omitempty"`
-}
-
-// TableRowCondition allows a row to be marked with additional information.
-// +protobuf=false
-type TableRowCondition struct {
- // Type of row condition.
- Type RowConditionType `json:"type"`
- // Status of the condition, one of True, False, Unknown.
- Status ConditionStatus `json:"status"`
- // (brief) machine readable reason for the condition's last transition.
- // +optional
- Reason string `json:"reason,omitempty"`
- // Human readable message indicating details about last transition.
- // +optional
- Message string `json:"message,omitempty"`
-}
-
-type RowConditionType string
-
-// These are valid conditions of a row. This list is not exhaustive and new conditions may be
-// included by other resources.
-const (
- // RowCompleted means the underlying resource has reached completion and may be given less
- // visual priority than other resources.
- RowCompleted RowConditionType = "Completed"
-)
-
-type ConditionStatus string
-
-// These are valid condition statuses. "ConditionTrue" means a resource is in the condition.
-// "ConditionFalse" means a resource is not in the condition. "ConditionUnknown" means kubernetes
-// can't decide if a resource is in the condition or not. In the future, we could add other
-// intermediate conditions, e.g. ConditionDegraded.
-const (
- ConditionTrue ConditionStatus = "True"
- ConditionFalse ConditionStatus = "False"
- ConditionUnknown ConditionStatus = "Unknown"
-)
-
-// IncludeObjectPolicy controls which portion of the object is returned with a Table.
-type IncludeObjectPolicy string
-
-const (
- // IncludeNone returns no object.
- IncludeNone IncludeObjectPolicy = "None"
- // IncludeMetadata serializes the object containing only its metadata field.
- IncludeMetadata IncludeObjectPolicy = "Metadata"
- // IncludeObject contains the full object.
- IncludeObject IncludeObjectPolicy = "Object"
-)
-
-// TableOptions are used when a Table is requested by the caller.
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-type TableOptions struct {
- v1.TypeMeta `json:",inline"`
- // includeObject decides whether to include each object along with its columnar information.
- // Specifying "None" will return no object, specifying "Object" will return the full object contents, and
- // specifying "Metadata" (the default) will return the object's metadata in the PartialObjectMetadata kind
- // in version v1beta1 of the meta.k8s.io API group.
- IncludeObject IncludeObjectPolicy `json:"includeObject,omitempty" protobuf:"bytes,1,opt,name=includeObject,casttype=IncludeObjectPolicy"`
-}
-
-// PartialObjectMetadata is a generic representation of any object with ObjectMeta. It allows clients
-// to get access to a particular ObjectMeta schema without knowing the details of the version.
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-type PartialObjectMetadata struct {
- v1.TypeMeta `json:",inline"`
- // Standard object's metadata.
- // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
- // +optional
- v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
-}
-
-// PartialObjectMetadataList contains a list of objects containing only their metadata
-// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
-type PartialObjectMetadataList struct {
- v1.TypeMeta `json:",inline"`
-
- // items contains each of the included items.
- Items []*PartialObjectMetadata `json:"items" protobuf:"bytes,1,rep,name=items"`
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types_swagger_doc_generated.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types_swagger_doc_generated.go
deleted file mode 100644
index 2680fbf7e..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types_swagger_doc_generated.go
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
-Copyright 2016 The 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 v1beta1
-
-// This file contains a collection of methods that can be used from go-restful to
-// generate Swagger API documentation for its models. Please read this PR for more
-// information on the implementation: https://github.com/emicklei/go-restful/pull/215
-//
-// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if
-// they are on one line! For multiple line or blocks that you want to ignore use ---.
-// Any context after a --- is ignored.
-//
-// Those methods can be generated by using hack/update-generated-swagger-docs.sh
-
-// AUTO-GENERATED FUNCTIONS START HERE
-var map_PartialObjectMetadata = map[string]string{
- "": "PartialObjectMetadata is a generic representation of any object with ObjectMeta. It allows clients to get access to a particular ObjectMeta schema without knowing the details of the version.",
- "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata",
-}
-
-func (PartialObjectMetadata) SwaggerDoc() map[string]string {
- return map_PartialObjectMetadata
-}
-
-var map_PartialObjectMetadataList = map[string]string{
- "": "PartialObjectMetadataList contains a list of objects containing only their metadata",
- "items": "items contains each of the included items.",
-}
-
-func (PartialObjectMetadataList) SwaggerDoc() map[string]string {
- return map_PartialObjectMetadataList
-}
-
-var map_Table = map[string]string{
- "": "Table is a tabular representation of a set of API resources. The server transforms the object into a set of preferred columns for quickly reviewing the objects.",
- "metadata": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
- "columnDefinitions": "columnDefinitions describes each column in the returned items array. The number of cells per row will always match the number of column definitions.",
- "rows": "rows is the list of items in the table.",
-}
-
-func (Table) SwaggerDoc() map[string]string {
- return map_Table
-}
-
-var map_TableColumnDefinition = map[string]string{
- "": "TableColumnDefinition contains information about a column returned in the Table.",
- "name": "name is a human readable name for the column.",
- "type": "type is an OpenAPI type definition for this column. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more.",
- "format": "format is an optional OpenAPI type definition for this column. The 'name' format is applied to the primary identifier column to assist in clients identifying column is the resource name. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more.",
- "description": "description is a human readable description of this column.",
- "priority": "priority is an integer defining the relative importance of this column compared to others. Lower numbers are considered higher priority. Columns that may be omitted in limited space scenarios should be given a higher priority.",
-}
-
-func (TableColumnDefinition) SwaggerDoc() map[string]string {
- return map_TableColumnDefinition
-}
-
-var map_TableOptions = map[string]string{
- "": "TableOptions are used when a Table is requested by the caller.",
- "includeObject": "includeObject decides whether to include each object along with its columnar information. Specifying \"None\" will return no object, specifying \"Object\" will return the full object contents, and specifying \"Metadata\" (the default) will return the object's metadata in the PartialObjectMetadata kind in version v1beta1 of the meta.k8s.io API group.",
-}
-
-func (TableOptions) SwaggerDoc() map[string]string {
- return map_TableOptions
-}
-
-var map_TableRow = map[string]string{
- "": "TableRow is an individual row in a table.",
- "cells": "cells will be as wide as headers and may contain strings, numbers, booleans, simple maps, or lists, or null. See the type field of the column definition for a more detailed description.",
- "conditions": "conditions describe additional status of a row that are relevant for a human user.",
- "object": "This field contains the requested additional information about each object based on the includeObject policy when requesting the Table. If \"None\", this field is empty, if \"Object\" this will be the default serialization of the object for the current API version, and if \"Metadata\" (the default) will contain the object metadata. Check the returned kind and apiVersion of the object before parsing.",
-}
-
-func (TableRow) SwaggerDoc() map[string]string {
- return map_TableRow
-}
-
-var map_TableRowCondition = map[string]string{
- "": "TableRowCondition allows a row to be marked with additional information.",
- "type": "Type of row condition.",
- "status": "Status of the condition, one of True, False, Unknown.",
- "reason": "(brief) machine readable reason for the condition's last transition.",
- "message": "Human readable message indicating details about last transition.",
-}
-
-func (TableRowCondition) SwaggerDoc() map[string]string {
- return map_TableRowCondition
-}
-
-// AUTO-GENERATED FUNCTIONS END HERE
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/zz_generated.deepcopy.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/zz_generated.deepcopy.go
deleted file mode 100644
index a1f58daa3..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/zz_generated.deepcopy.go
+++ /dev/null
@@ -1,194 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// This file was autogenerated by deepcopy-gen. Do not edit it manually!
-
-package v1beta1
-
-import (
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *PartialObjectMetadata) DeepCopyInto(out *PartialObjectMetadata) {
- *out = *in
- out.TypeMeta = in.TypeMeta
- in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PartialObjectMetadata.
-func (in *PartialObjectMetadata) DeepCopy() *PartialObjectMetadata {
- if in == nil {
- return nil
- }
- out := new(PartialObjectMetadata)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *PartialObjectMetadata) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- } else {
- return nil
- }
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *PartialObjectMetadataList) DeepCopyInto(out *PartialObjectMetadataList) {
- *out = *in
- out.TypeMeta = in.TypeMeta
- if in.Items != nil {
- in, out := &in.Items, &out.Items
- *out = make([]*PartialObjectMetadata, len(*in))
- for i := range *in {
- if (*in)[i] == nil {
- (*out)[i] = nil
- } else {
- (*out)[i] = new(PartialObjectMetadata)
- (*in)[i].DeepCopyInto((*out)[i])
- }
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PartialObjectMetadataList.
-func (in *PartialObjectMetadataList) DeepCopy() *PartialObjectMetadataList {
- if in == nil {
- return nil
- }
- out := new(PartialObjectMetadataList)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *PartialObjectMetadataList) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- } else {
- return nil
- }
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *Table) DeepCopyInto(out *Table) {
- *out = *in
- out.TypeMeta = in.TypeMeta
- out.ListMeta = in.ListMeta
- if in.ColumnDefinitions != nil {
- in, out := &in.ColumnDefinitions, &out.ColumnDefinitions
- *out = make([]TableColumnDefinition, len(*in))
- copy(*out, *in)
- }
- if in.Rows != nil {
- in, out := &in.Rows, &out.Rows
- *out = make([]TableRow, len(*in))
- for i := range *in {
- (*in)[i].DeepCopyInto(&(*out)[i])
- }
- }
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Table.
-func (in *Table) DeepCopy() *Table {
- if in == nil {
- return nil
- }
- out := new(Table)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *Table) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- } else {
- return nil
- }
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *TableColumnDefinition) DeepCopyInto(out *TableColumnDefinition) {
- *out = *in
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TableColumnDefinition.
-func (in *TableColumnDefinition) DeepCopy() *TableColumnDefinition {
- if in == nil {
- return nil
- }
- out := new(TableColumnDefinition)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *TableOptions) DeepCopyInto(out *TableOptions) {
- *out = *in
- out.TypeMeta = in.TypeMeta
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TableOptions.
-func (in *TableOptions) DeepCopy() *TableOptions {
- if in == nil {
- return nil
- }
- out := new(TableOptions)
- in.DeepCopyInto(out)
- return out
-}
-
-// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
-func (in *TableOptions) DeepCopyObject() runtime.Object {
- if c := in.DeepCopy(); c != nil {
- return c
- } else {
- return nil
- }
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *TableRow) DeepCopyInto(out *TableRow) {
- clone := in.DeepCopy()
- *out = *clone
- return
-}
-
-// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
-func (in *TableRowCondition) DeepCopyInto(out *TableRowCondition) {
- *out = *in
- return
-}
-
-// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TableRowCondition.
-func (in *TableRowCondition) DeepCopy() *TableRowCondition {
- if in == nil {
- return nil
- }
- out := new(TableRowCondition)
- in.DeepCopyInto(out)
- return out
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/zz_generated.defaults.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/zz_generated.defaults.go
deleted file mode 100644
index b61dda74c..000000000
--- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/zz_generated.defaults.go
+++ /dev/null
@@ -1,32 +0,0 @@
-// +build !ignore_autogenerated
-
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// This file was autogenerated by defaulter-gen. Do not edit it manually!
-
-package v1beta1
-
-import (
- runtime "k8s.io/apimachinery/pkg/runtime"
-)
-
-// RegisterDefaults adds defaulters functions to the given scheme.
-// Public to allow building arbitrary schemes.
-// All generated defaulters are covering - they call all nested defaulters.
-func RegisterDefaults(scheme *runtime.Scheme) error {
- return nil
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/cache/cache.go b/vendor/k8s.io/apimachinery/pkg/util/cache/cache.go
deleted file mode 100644
index 9a09fe54d..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/cache/cache.go
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
-Copyright 2014 The 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 cache
-
-import (
- "sync"
-)
-
-const (
- shardsCount int = 32
-)
-
-type Cache []*cacheShard
-
-func NewCache(maxSize int) Cache {
- if maxSize < shardsCount {
- maxSize = shardsCount
- }
- cache := make(Cache, shardsCount)
- for i := 0; i < shardsCount; i++ {
- cache[i] = &cacheShard{
- items: make(map[uint64]interface{}),
- maxSize: maxSize / shardsCount,
- }
- }
- return cache
-}
-
-func (c Cache) getShard(index uint64) *cacheShard {
- return c[index%uint64(shardsCount)]
-}
-
-// Returns true if object already existed, false otherwise.
-func (c *Cache) Add(index uint64, obj interface{}) bool {
- return c.getShard(index).add(index, obj)
-}
-
-func (c *Cache) Get(index uint64) (obj interface{}, found bool) {
- return c.getShard(index).get(index)
-}
-
-type cacheShard struct {
- items map[uint64]interface{}
- sync.RWMutex
- maxSize int
-}
-
-// Returns true if object already existed, false otherwise.
-func (s *cacheShard) add(index uint64, obj interface{}) bool {
- s.Lock()
- defer s.Unlock()
- _, isOverwrite := s.items[index]
- if !isOverwrite && len(s.items) >= s.maxSize {
- var randomKey uint64
- for randomKey = range s.items {
- break
- }
- delete(s.items, randomKey)
- }
- s.items[index] = obj
- return isOverwrite
-}
-
-func (s *cacheShard) get(index uint64) (obj interface{}, found bool) {
- s.RLock()
- defer s.RUnlock()
- obj, found = s.items[index]
- return
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go b/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go
deleted file mode 100644
index f6b307aa6..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
-Copyright 2016 The 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 cache
-
-import (
- "sync"
- "time"
-
- "github.com/hashicorp/golang-lru"
-)
-
-// Clock defines an interface for obtaining the current time
-type Clock interface {
- Now() time.Time
-}
-
-// realClock implements the Clock interface by calling time.Now()
-type realClock struct{}
-
-func (realClock) Now() time.Time { return time.Now() }
-
-// LRUExpireCache is a cache that ensures the mostly recently accessed keys are returned with
-// a ttl beyond which keys are forcibly expired.
-type LRUExpireCache struct {
- // clock is used to obtain the current time
- clock Clock
-
- cache *lru.Cache
- lock sync.Mutex
-}
-
-// NewLRUExpireCache creates an expiring cache with the given size
-func NewLRUExpireCache(maxSize int) *LRUExpireCache {
- return NewLRUExpireCacheWithClock(maxSize, realClock{})
-}
-
-// NewLRUExpireCacheWithClock creates an expiring cache with the given size, using the specified clock to obtain the current time.
-func NewLRUExpireCacheWithClock(maxSize int, clock Clock) *LRUExpireCache {
- cache, err := lru.New(maxSize)
- if err != nil {
- // if called with an invalid size
- panic(err)
- }
- return &LRUExpireCache{clock: clock, cache: cache}
-}
-
-type cacheEntry struct {
- value interface{}
- expireTime time.Time
-}
-
-// Add adds the value to the cache at key with the specified maximum duration.
-func (c *LRUExpireCache) Add(key interface{}, value interface{}, ttl time.Duration) {
- c.lock.Lock()
- defer c.lock.Unlock()
- c.cache.Add(key, &cacheEntry{value, c.clock.Now().Add(ttl)})
-}
-
-// Get returns the value at the specified key from the cache if it exists and is not
-// expired, or returns false.
-func (c *LRUExpireCache) Get(key interface{}) (interface{}, bool) {
- c.lock.Lock()
- defer c.lock.Unlock()
- e, ok := c.cache.Get(key)
- if !ok {
- return nil, false
- }
- if c.clock.Now().After(e.(*cacheEntry).expireTime) {
- c.cache.Remove(key)
- return nil, false
- }
- return e.(*cacheEntry).value, true
-}
-
-// Remove removes the specified key from the cache if it exists
-func (c *LRUExpireCache) Remove(key interface{}) {
- c.lock.Lock()
- defer c.lock.Unlock()
- c.cache.Remove(key)
-}
-
-// Keys returns all the keys in the cache, even if they are expired. Subsequent calls to
-// get may return not found. It returns all keys from oldest to newest.
-func (c *LRUExpireCache) Keys() []interface{} {
- c.lock.Lock()
- defer c.lock.Unlock()
- return c.cache.Keys()
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/diff/diff.go b/vendor/k8s.io/apimachinery/pkg/util/diff/diff.go
deleted file mode 100644
index 3d5ec14bf..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/diff/diff.go
+++ /dev/null
@@ -1,273 +0,0 @@
-/*
-Copyright 2014 The 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 diff
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "reflect"
- "sort"
- "strings"
- "text/tabwriter"
-
- "github.com/davecgh/go-spew/spew"
-
- "k8s.io/apimachinery/pkg/util/validation/field"
-)
-
-// StringDiff diffs a and b and returns a human readable diff.
-func StringDiff(a, b string) string {
- ba := []byte(a)
- bb := []byte(b)
- out := []byte{}
- i := 0
- for ; i < len(ba) && i < len(bb); i++ {
- if ba[i] != bb[i] {
- break
- }
- out = append(out, ba[i])
- }
- out = append(out, []byte("\n\nA: ")...)
- out = append(out, ba[i:]...)
- out = append(out, []byte("\n\nB: ")...)
- out = append(out, bb[i:]...)
- out = append(out, []byte("\n\n")...)
- return string(out)
-}
-
-// ObjectDiff writes the two objects out as JSON and prints out the identical part of
-// the objects followed by the remaining part of 'a' and finally the remaining part of 'b'.
-// For debugging tests.
-func ObjectDiff(a, b interface{}) string {
- ab, err := json.Marshal(a)
- if err != nil {
- panic(fmt.Sprintf("a: %v", err))
- }
- bb, err := json.Marshal(b)
- if err != nil {
- panic(fmt.Sprintf("b: %v", err))
- }
- return StringDiff(string(ab), string(bb))
-}
-
-// ObjectGoPrintDiff is like ObjectDiff, but uses go-spew to print the objects,
-// which shows absolutely everything by recursing into every single pointer
-// (go's %#v formatters OTOH stop at a certain point). This is needed when you
-// can't figure out why reflect.DeepEqual is returning false and nothing is
-// showing you differences. This will.
-func ObjectGoPrintDiff(a, b interface{}) string {
- s := spew.ConfigState{DisableMethods: true}
- return StringDiff(
- s.Sprintf("%#v", a),
- s.Sprintf("%#v", b),
- )
-}
-
-func ObjectReflectDiff(a, b interface{}) string {
- vA, vB := reflect.ValueOf(a), reflect.ValueOf(b)
- if vA.Type() != vB.Type() {
- return fmt.Sprintf("type A %T and type B %T do not match", a, b)
- }
- diffs := objectReflectDiff(field.NewPath("object"), vA, vB)
- if len(diffs) == 0 {
- return "<no diffs>"
- }
- out := []string{""}
- for _, d := range diffs {
- out = append(out,
- fmt.Sprintf("%s:", d.path),
- limit(fmt.Sprintf(" a: %#v", d.a), 80),
- limit(fmt.Sprintf(" b: %#v", d.b), 80),
- )
- }
- return strings.Join(out, "\n")
-}
-
-func limit(s string, max int) string {
- if len(s) > max {
- return s[:max]
- }
- return s
-}
-
-func public(s string) bool {
- if len(s) == 0 {
- return false
- }
- return s[:1] == strings.ToUpper(s[:1])
-}
-
-type diff struct {
- path *field.Path
- a, b interface{}
-}
-
-type orderedDiffs []diff
-
-func (d orderedDiffs) Len() int { return len(d) }
-func (d orderedDiffs) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
-func (d orderedDiffs) Less(i, j int) bool {
- a, b := d[i].path.String(), d[j].path.String()
- if a < b {
- return true
- }
- return false
-}
-
-func objectReflectDiff(path *field.Path, a, b reflect.Value) []diff {
- switch a.Type().Kind() {
- case reflect.Struct:
- var changes []diff
- for i := 0; i < a.Type().NumField(); i++ {
- if !public(a.Type().Field(i).Name) {
- if reflect.DeepEqual(a.Interface(), b.Interface()) {
- continue
- }
- return []diff{{path: path, a: fmt.Sprintf("%#v", a), b: fmt.Sprintf("%#v", b)}}
- }
- if sub := objectReflectDiff(path.Child(a.Type().Field(i).Name), a.Field(i), b.Field(i)); len(sub) > 0 {
- changes = append(changes, sub...)
- }
- }
- return changes
- case reflect.Ptr, reflect.Interface:
- if a.IsNil() || b.IsNil() {
- switch {
- case a.IsNil() && b.IsNil():
- return nil
- case a.IsNil():
- return []diff{{path: path, a: nil, b: b.Interface()}}
- default:
- return []diff{{path: path, a: a.Interface(), b: nil}}
- }
- }
- return objectReflectDiff(path, a.Elem(), b.Elem())
- case reflect.Chan:
- if !reflect.DeepEqual(a.Interface(), b.Interface()) {
- return []diff{{path: path, a: a.Interface(), b: b.Interface()}}
- }
- return nil
- case reflect.Slice:
- lA, lB := a.Len(), b.Len()
- l := lA
- if lB < lA {
- l = lB
- }
- if lA == lB && lA == 0 {
- if a.IsNil() != b.IsNil() {
- return []diff{{path: path, a: a.Interface(), b: b.Interface()}}
- }
- return nil
- }
- var diffs []diff
- for i := 0; i < l; i++ {
- if !reflect.DeepEqual(a.Index(i), b.Index(i)) {
- diffs = append(diffs, objectReflectDiff(path.Index(i), a.Index(i), b.Index(i))...)
- }
- }
- for i := l; i < lA; i++ {
- diffs = append(diffs, diff{path: path.Index(i), a: a.Index(i), b: nil})
- }
- for i := l; i < lB; i++ {
- diffs = append(diffs, diff{path: path.Index(i), a: nil, b: b.Index(i)})
- }
- return diffs
- case reflect.Map:
- if reflect.DeepEqual(a.Interface(), b.Interface()) {
- return nil
- }
- aKeys := make(map[interface{}]interface{})
- for _, key := range a.MapKeys() {
- aKeys[key.Interface()] = a.MapIndex(key).Interface()
- }
- var missing []diff
- for _, key := range b.MapKeys() {
- if _, ok := aKeys[key.Interface()]; ok {
- delete(aKeys, key.Interface())
- if reflect.DeepEqual(a.MapIndex(key).Interface(), b.MapIndex(key).Interface()) {
- continue
- }
- missing = append(missing, objectReflectDiff(path.Key(fmt.Sprintf("%s", key.Interface())), a.MapIndex(key), b.MapIndex(key))...)
- continue
- }
- missing = append(missing, diff{path: path.Key(fmt.Sprintf("%s", key.Interface())), a: nil, b: b.MapIndex(key).Interface()})
- }
- for key, value := range aKeys {
- missing = append(missing, diff{path: path.Key(fmt.Sprintf("%s", key)), a: value, b: nil})
- }
- if len(missing) == 0 {
- missing = append(missing, diff{path: path, a: a.Interface(), b: b.Interface()})
- }
- sort.Sort(orderedDiffs(missing))
- return missing
- default:
- if reflect.DeepEqual(a.Interface(), b.Interface()) {
- return nil
- }
- if !a.CanInterface() {
- return []diff{{path: path, a: fmt.Sprintf("%#v", a), b: fmt.Sprintf("%#v", b)}}
- }
- return []diff{{path: path, a: a.Interface(), b: b.Interface()}}
- }
-}
-
-// ObjectGoPrintSideBySide prints a and b as textual dumps side by side,
-// enabling easy visual scanning for mismatches.
-func ObjectGoPrintSideBySide(a, b interface{}) string {
- s := spew.ConfigState{
- Indent: " ",
- // Extra deep spew.
- DisableMethods: true,
- }
- sA := s.Sdump(a)
- sB := s.Sdump(b)
-
- linesA := strings.Split(sA, "\n")
- linesB := strings.Split(sB, "\n")
- width := 0
- for _, s := range linesA {
- l := len(s)
- if l > width {
- width = l
- }
- }
- for _, s := range linesB {
- l := len(s)
- if l > width {
- width = l
- }
- }
- buf := &bytes.Buffer{}
- w := tabwriter.NewWriter(buf, width, 0, 1, ' ', 0)
- max := len(linesA)
- if len(linesB) > max {
- max = len(linesB)
- }
- for i := 0; i < max; i++ {
- var a, b string
- if i < len(linesA) {
- a = linesA[i]
- }
- if i < len(linesB) {
- b = linesB[i]
- }
- fmt.Fprintf(w, "%s\t%s\n", a, b)
- }
- w.Flush()
- return buf.String()
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/mergepatch/errors.go b/vendor/k8s.io/apimachinery/pkg/util/mergepatch/errors.go
deleted file mode 100644
index 16501d5af..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/mergepatch/errors.go
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
-Copyright 2017 The 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 mergepatch
-
-import (
- "errors"
- "fmt"
- "reflect"
-)
-
-var (
- ErrBadJSONDoc = errors.New("invalid JSON document")
- ErrNoListOfLists = errors.New("lists of lists are not supported")
- ErrBadPatchFormatForPrimitiveList = errors.New("invalid patch format of primitive list")
- ErrBadPatchFormatForRetainKeys = errors.New("invalid patch format of retainKeys")
- ErrBadPatchFormatForSetElementOrderList = errors.New("invalid patch format of setElementOrder list")
- ErrPatchContentNotMatchRetainKeys = errors.New("patch content doesn't match retainKeys list")
- ErrUnsupportedStrategicMergePatchFormat = errors.New("strategic merge patch format is not supported")
-)
-
-func ErrNoMergeKey(m map[string]interface{}, k string) error {
- return fmt.Errorf("map: %v does not contain declared merge key: %s", m, k)
-}
-
-func ErrBadArgType(expected, actual interface{}) error {
- return fmt.Errorf("expected a %s, but received a %s",
- reflect.TypeOf(expected),
- reflect.TypeOf(actual))
-}
-
-func ErrBadArgKind(expected, actual interface{}) error {
- var expectedKindString, actualKindString string
- if expected == nil {
- expectedKindString = "nil"
- } else {
- expectedKindString = reflect.TypeOf(expected).Kind().String()
- }
- if actual == nil {
- actualKindString = "nil"
- } else {
- actualKindString = reflect.TypeOf(actual).Kind().String()
- }
- return fmt.Errorf("expected a %s, but received a %s", expectedKindString, actualKindString)
-}
-
-func ErrBadPatchType(t interface{}, m map[string]interface{}) error {
- return fmt.Errorf("unknown patch type: %s in map: %v", t, m)
-}
-
-// IsPreconditionFailed returns true if the provided error indicates
-// a precondition failed.
-func IsPreconditionFailed(err error) bool {
- _, ok := err.(ErrPreconditionFailed)
- return ok
-}
-
-type ErrPreconditionFailed struct {
- message string
-}
-
-func NewErrPreconditionFailed(target map[string]interface{}) ErrPreconditionFailed {
- s := fmt.Sprintf("precondition failed for: %v", target)
- return ErrPreconditionFailed{s}
-}
-
-func (err ErrPreconditionFailed) Error() string {
- return err.message
-}
-
-type ErrConflict struct {
- message string
-}
-
-func NewErrConflict(patch, current string) ErrConflict {
- s := fmt.Sprintf("patch:\n%s\nconflicts with changes made from original to current:\n%s\n", patch, current)
- return ErrConflict{s}
-}
-
-func (err ErrConflict) Error() string {
- return err.message
-}
-
-// IsConflict returns true if the provided error indicates
-// a conflict between the patch and the current configuration.
-func IsConflict(err error) bool {
- _, ok := err.(ErrConflict)
- return ok
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go b/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go
deleted file mode 100644
index 9261290a7..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
-Copyright 2017 The 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 mergepatch
-
-import (
- "fmt"
- "reflect"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/ghodss/yaml"
-)
-
-// PreconditionFunc asserts that an incompatible change is not present within a patch.
-type PreconditionFunc func(interface{}) bool
-
-// RequireKeyUnchanged returns a precondition function that fails if the provided key
-// is present in the patch (indicating that its value has changed).
-func RequireKeyUnchanged(key string) PreconditionFunc {
- return func(patch interface{}) bool {
- patchMap, ok := patch.(map[string]interface{})
- if !ok {
- return true
- }
-
- // The presence of key means that its value has been changed, so the test fails.
- _, ok = patchMap[key]
- return !ok
- }
-}
-
-// RequireMetadataKeyUnchanged creates a precondition function that fails
-// if the metadata.key is present in the patch (indicating its value
-// has changed).
-func RequireMetadataKeyUnchanged(key string) PreconditionFunc {
- return func(patch interface{}) bool {
- patchMap, ok := patch.(map[string]interface{})
- if !ok {
- return true
- }
- patchMap1, ok := patchMap["metadata"]
- if !ok {
- return true
- }
- patchMap2, ok := patchMap1.(map[string]interface{})
- if !ok {
- return true
- }
- _, ok = patchMap2[key]
- return !ok
- }
-}
-
-func ToYAMLOrError(v interface{}) string {
- y, err := toYAML(v)
- if err != nil {
- return err.Error()
- }
-
- return y
-}
-
-func toYAML(v interface{}) (string, error) {
- y, err := yaml.Marshal(v)
- if err != nil {
- return "", fmt.Errorf("yaml marshal failed:%v\n%v\n", err, spew.Sdump(v))
- }
-
- return string(y), nil
-}
-
-// HasConflicts returns true if the left and right JSON interface objects overlap with
-// different values in any key. All keys are required to be strings. Since patches of the
-// same Type have congruent keys, this is valid for multiple patch types. This method
-// supports JSON merge patch semantics.
-//
-// NOTE: Numbers with different types (e.g. int(0) vs int64(0)) will be detected as conflicts.
-// Make sure the unmarshaling of left and right are consistent (e.g. use the same library).
-func HasConflicts(left, right interface{}) (bool, error) {
- switch typedLeft := left.(type) {
- case map[string]interface{}:
- switch typedRight := right.(type) {
- case map[string]interface{}:
- for key, leftValue := range typedLeft {
- rightValue, ok := typedRight[key]
- if !ok {
- continue
- }
- if conflict, err := HasConflicts(leftValue, rightValue); err != nil || conflict {
- return conflict, err
- }
- }
-
- return false, nil
- default:
- return true, nil
- }
- case []interface{}:
- switch typedRight := right.(type) {
- case []interface{}:
- if len(typedLeft) != len(typedRight) {
- return true, nil
- }
-
- for i := range typedLeft {
- if conflict, err := HasConflicts(typedLeft[i], typedRight[i]); err != nil || conflict {
- return conflict, err
- }
- }
-
- return false, nil
- default:
- return true, nil
- }
- case string, float64, bool, int, int64, nil:
- return !reflect.DeepEqual(left, right), nil
- default:
- return true, fmt.Errorf("unknown type: %v", reflect.TypeOf(left))
- }
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/errors.go b/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/errors.go
deleted file mode 100644
index ab66d0452..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/errors.go
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
-Copyright 2017 The 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 strategicpatch
-
-import (
- "fmt"
-)
-
-type LookupPatchMetaError struct {
- Path string
- Err error
-}
-
-func (e LookupPatchMetaError) Error() string {
- return fmt.Sprintf("LookupPatchMetaError(%s): %v", e.Path, e.Err)
-}
-
-type FieldNotFoundError struct {
- Path string
- Field string
-}
-
-func (e FieldNotFoundError) Error() string {
- return fmt.Sprintf("unable to find api field %q in %s", e.Field, e.Path)
-}
-
-type InvalidTypeError struct {
- Path string
- Expected string
- Actual string
-}
-
-func (e InvalidTypeError) Error() string {
- return fmt.Sprintf("invalid type for %s: got %q, expected %q", e.Path, e.Actual, e.Expected)
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go b/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go
deleted file mode 100644
index c31de15e7..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
-Copyright 2017 The 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 strategicpatch
-
-import (
- "errors"
- "fmt"
- "reflect"
-
- "k8s.io/apimachinery/pkg/util/mergepatch"
- forkedjson "k8s.io/apimachinery/third_party/forked/golang/json"
- openapi "k8s.io/kube-openapi/pkg/util/proto"
-)
-
-type PatchMeta struct {
- patchStrategies []string
- patchMergeKey string
-}
-
-func (pm PatchMeta) GetPatchStrategies() []string {
- if pm.patchStrategies == nil {
- return []string{}
- }
- return pm.patchStrategies
-}
-
-func (pm PatchMeta) SetPatchStrategies(ps []string) {
- pm.patchStrategies = ps
-}
-
-func (pm PatchMeta) GetPatchMergeKey() string {
- return pm.patchMergeKey
-}
-
-func (pm PatchMeta) SetPatchMergeKey(pmk string) {
- pm.patchMergeKey = pmk
-}
-
-type LookupPatchMeta interface {
- // LookupPatchMetadataForStruct gets subschema and the patch metadata (e.g. patch strategy and merge key) for map.
- LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error)
- // LookupPatchMetadataForSlice get subschema and the patch metadata for slice.
- LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error)
- // Get the type name of the field
- Name() string
-}
-
-type PatchMetaFromStruct struct {
- T reflect.Type
-}
-
-func NewPatchMetaFromStruct(dataStruct interface{}) (PatchMetaFromStruct, error) {
- t, err := getTagStructType(dataStruct)
- return PatchMetaFromStruct{T: t}, err
-}
-
-var _ LookupPatchMeta = PatchMetaFromStruct{}
-
-func (s PatchMetaFromStruct) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) {
- fieldType, fieldPatchStrategies, fieldPatchMergeKey, err := forkedjson.LookupPatchMetadataForStruct(s.T, key)
- if err != nil {
- return nil, PatchMeta{}, err
- }
-
- return PatchMetaFromStruct{T: fieldType},
- PatchMeta{
- patchStrategies: fieldPatchStrategies,
- patchMergeKey: fieldPatchMergeKey,
- }, nil
-}
-
-func (s PatchMetaFromStruct) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) {
- subschema, patchMeta, err := s.LookupPatchMetadataForStruct(key)
- if err != nil {
- return nil, PatchMeta{}, err
- }
- elemPatchMetaFromStruct := subschema.(PatchMetaFromStruct)
- t := elemPatchMetaFromStruct.T
-
- var elemType reflect.Type
- switch t.Kind() {
- // If t is an array or a slice, get the element type.
- // If element is still an array or a slice, return an error.
- // Otherwise, return element type.
- case reflect.Array, reflect.Slice:
- elemType = t.Elem()
- if elemType.Kind() == reflect.Array || elemType.Kind() == reflect.Slice {
- return nil, PatchMeta{}, errors.New("unexpected slice of slice")
- }
- // If t is an pointer, get the underlying element.
- // If the underlying element is neither an array nor a slice, the pointer is pointing to a slice,
- // e.g. https://github.com/kubernetes/kubernetes/blob/bc22e206c79282487ea0bf5696d5ccec7e839a76/staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch_test.go#L2782-L2822
- // If the underlying element is either an array or a slice, return its element type.
- case reflect.Ptr:
- t = t.Elem()
- if t.Kind() == reflect.Array || t.Kind() == reflect.Slice {
- t = t.Elem()
- }
- elemType = t
- default:
- return nil, PatchMeta{}, fmt.Errorf("expected slice or array type, but got: %s", s.T.Kind().String())
- }
-
- return PatchMetaFromStruct{T: elemType}, patchMeta, nil
-}
-
-func (s PatchMetaFromStruct) Name() string {
- return s.T.Kind().String()
-}
-
-func getTagStructType(dataStruct interface{}) (reflect.Type, error) {
- if dataStruct == nil {
- return nil, mergepatch.ErrBadArgKind(struct{}{}, nil)
- }
-
- t := reflect.TypeOf(dataStruct)
- // Get the underlying type for pointers
- if t.Kind() == reflect.Ptr {
- t = t.Elem()
- }
-
- if t.Kind() != reflect.Struct {
- return nil, mergepatch.ErrBadArgKind(struct{}{}, dataStruct)
- }
-
- return t, nil
-}
-
-func GetTagStructTypeOrDie(dataStruct interface{}) reflect.Type {
- t, err := getTagStructType(dataStruct)
- if err != nil {
- panic(err)
- }
- return t
-}
-
-type PatchMetaFromOpenAPI struct {
- Schema openapi.Schema
-}
-
-func NewPatchMetaFromOpenAPI(s openapi.Schema) PatchMetaFromOpenAPI {
- return PatchMetaFromOpenAPI{Schema: s}
-}
-
-var _ LookupPatchMeta = PatchMetaFromOpenAPI{}
-
-func (s PatchMetaFromOpenAPI) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) {
- if s.Schema == nil {
- return nil, PatchMeta{}, nil
- }
- kindItem := NewKindItem(key, s.Schema.GetPath())
- s.Schema.Accept(kindItem)
-
- err := kindItem.Error()
- if err != nil {
- return nil, PatchMeta{}, err
- }
- return PatchMetaFromOpenAPI{Schema: kindItem.subschema},
- kindItem.patchmeta, nil
-}
-
-func (s PatchMetaFromOpenAPI) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) {
- if s.Schema == nil {
- return nil, PatchMeta{}, nil
- }
- sliceItem := NewSliceItem(key, s.Schema.GetPath())
- s.Schema.Accept(sliceItem)
-
- err := sliceItem.Error()
- if err != nil {
- return nil, PatchMeta{}, err
- }
- return PatchMetaFromOpenAPI{Schema: sliceItem.subschema},
- sliceItem.patchmeta, nil
-}
-
-func (s PatchMetaFromOpenAPI) Name() string {
- schema := s.Schema
- return schema.GetName()
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go b/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go
deleted file mode 100644
index 2f6ade2be..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go
+++ /dev/null
@@ -1,2151 +0,0 @@
-/*
-Copyright 2014 The 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 strategicpatch
-
-import (
- "fmt"
- "reflect"
- "sort"
- "strings"
-
- "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
- "k8s.io/apimachinery/pkg/util/json"
- "k8s.io/apimachinery/pkg/util/mergepatch"
-)
-
-// An alternate implementation of JSON Merge Patch
-// (https://tools.ietf.org/html/rfc7386) which supports the ability to annotate
-// certain fields with metadata that indicates whether the elements of JSON
-// lists should be merged or replaced.
-//
-// For more information, see the PATCH section of docs/devel/api-conventions.md.
-//
-// Some of the content of this package was borrowed with minor adaptations from
-// evanphx/json-patch and openshift/origin.
-
-const (
- directiveMarker = "$patch"
- deleteDirective = "delete"
- replaceDirective = "replace"
- mergeDirective = "merge"
-
- retainKeysStrategy = "retainKeys"
-
- deleteFromPrimitiveListDirectivePrefix = "$deleteFromPrimitiveList"
- retainKeysDirective = "$" + retainKeysStrategy
- setElementOrderDirectivePrefix = "$setElementOrder"
-)
-
-// JSONMap is a representations of JSON object encoded as map[string]interface{}
-// where the children can be either map[string]interface{}, []interface{} or
-// primitive type).
-// Operating on JSONMap representation is much faster as it doesn't require any
-// json marshaling and/or unmarshaling operations.
-type JSONMap map[string]interface{}
-
-type DiffOptions struct {
- // SetElementOrder determines whether we generate the $setElementOrder parallel list.
- SetElementOrder bool
- // IgnoreChangesAndAdditions indicates if we keep the changes and additions in the patch.
- IgnoreChangesAndAdditions bool
- // IgnoreDeletions indicates if we keep the deletions in the patch.
- IgnoreDeletions bool
- // We introduce a new value retainKeys for patchStrategy.
- // It indicates that all fields needing to be preserved must be
- // present in the `retainKeys` list.
- // And the fields that are present will be merged with live object.
- // All the missing fields will be cleared when patching.
- BuildRetainKeysDirective bool
-}
-
-type MergeOptions struct {
- // MergeParallelList indicates if we are merging the parallel list.
- // We don't merge parallel list when calling mergeMap() in CreateThreeWayMergePatch()
- // which is called client-side.
- // We merge parallel list iff when calling mergeMap() in StrategicMergeMapPatch()
- // which is called server-side
- MergeParallelList bool
- // IgnoreUnmatchedNulls indicates if we should process the unmatched nulls.
- IgnoreUnmatchedNulls bool
-}
-
-// The following code is adapted from github.com/openshift/origin/pkg/util/jsonmerge.
-// Instead of defining a Delta that holds an original, a patch and a set of preconditions,
-// the reconcile method accepts a set of preconditions as an argument.
-
-// CreateTwoWayMergePatch creates a patch that can be passed to StrategicMergePatch from an original
-// document and a modified document, which are passed to the method as json encoded content. It will
-// return a patch that yields the modified document when applied to the original document, or an error
-// if either of the two documents is invalid.
-func CreateTwoWayMergePatch(original, modified []byte, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) ([]byte, error) {
- schema, err := NewPatchMetaFromStruct(dataStruct)
- if err != nil {
- return nil, err
- }
-
- return CreateTwoWayMergePatchUsingLookupPatchMeta(original, modified, schema, fns...)
-}
-
-func CreateTwoWayMergePatchUsingLookupPatchMeta(
- original, modified []byte, schema LookupPatchMeta, fns ...mergepatch.PreconditionFunc) ([]byte, error) {
- originalMap := map[string]interface{}{}
- if len(original) > 0 {
- if err := json.Unmarshal(original, &originalMap); err != nil {
- return nil, mergepatch.ErrBadJSONDoc
- }
- }
-
- modifiedMap := map[string]interface{}{}
- if len(modified) > 0 {
- if err := json.Unmarshal(modified, &modifiedMap); err != nil {
- return nil, mergepatch.ErrBadJSONDoc
- }
- }
-
- patchMap, err := CreateTwoWayMergeMapPatchUsingLookupPatchMeta(originalMap, modifiedMap, schema, fns...)
- if err != nil {
- return nil, err
- }
-
- return json.Marshal(patchMap)
-}
-
-// CreateTwoWayMergeMapPatch creates a patch from an original and modified JSON objects,
-// encoded JSONMap.
-// The serialized version of the map can then be passed to StrategicMergeMapPatch.
-func CreateTwoWayMergeMapPatch(original, modified JSONMap, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) (JSONMap, error) {
- schema, err := NewPatchMetaFromStruct(dataStruct)
- if err != nil {
- return nil, err
- }
-
- return CreateTwoWayMergeMapPatchUsingLookupPatchMeta(original, modified, schema, fns...)
-}
-
-func CreateTwoWayMergeMapPatchUsingLookupPatchMeta(original, modified JSONMap, schema LookupPatchMeta, fns ...mergepatch.PreconditionFunc) (JSONMap, error) {
- diffOptions := DiffOptions{
- SetElementOrder: true,
- }
- patchMap, err := diffMaps(original, modified, schema, diffOptions)
- if err != nil {
- return nil, err
- }
-
- // Apply the preconditions to the patch, and return an error if any of them fail.
- for _, fn := range fns {
- if !fn(patchMap) {
- return nil, mergepatch.NewErrPreconditionFailed(patchMap)
- }
- }
-
- return patchMap, nil
-}
-
-// Returns a (recursive) strategic merge patch that yields modified when applied to original.
-// Including:
-// - Adding fields to the patch present in modified, missing from original
-// - Setting fields to the patch present in modified and original with different values
-// - Delete fields present in original, missing from modified through
-// - IFF map field - set to nil in patch
-// - IFF list of maps && merge strategy - use deleteDirective for the elements
-// - IFF list of primitives && merge strategy - use parallel deletion list
-// - IFF list of maps or primitives with replace strategy (default) - set patch value to the value in modified
-// - Build $retainKeys directive for fields with retainKeys patch strategy
-func diffMaps(original, modified map[string]interface{}, schema LookupPatchMeta, diffOptions DiffOptions) (map[string]interface{}, error) {
- patch := map[string]interface{}{}
-
- // This will be used to build the $retainKeys directive sent in the patch
- retainKeysList := make([]interface{}, 0, len(modified))
-
- // Compare each value in the modified map against the value in the original map
- for key, modifiedValue := range modified {
- // Get the underlying type for pointers
- if diffOptions.BuildRetainKeysDirective && modifiedValue != nil {
- retainKeysList = append(retainKeysList, key)
- }
-
- originalValue, ok := original[key]
- if !ok {
- // Key was added, so add to patch
- if !diffOptions.IgnoreChangesAndAdditions {
- patch[key] = modifiedValue
- }
- continue
- }
-
- // The patch may have a patch directive
- // TODO: figure out if we need this. This shouldn't be needed by apply. When would the original map have patch directives in it?
- foundDirectiveMarker, err := handleDirectiveMarker(key, originalValue, modifiedValue, patch)
- if err != nil {
- return nil, err
- }
- if foundDirectiveMarker {
- continue
- }
-
- if reflect.TypeOf(originalValue) != reflect.TypeOf(modifiedValue) {
- // Types have changed, so add to patch
- if !diffOptions.IgnoreChangesAndAdditions {
- patch[key] = modifiedValue
- }
- continue
- }
-
- // Types are the same, so compare values
- switch originalValueTyped := originalValue.(type) {
- case map[string]interface{}:
- modifiedValueTyped := modifiedValue.(map[string]interface{})
- err = handleMapDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions)
- case []interface{}:
- modifiedValueTyped := modifiedValue.([]interface{})
- err = handleSliceDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions)
- default:
- replacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions)
- }
- if err != nil {
- return nil, err
- }
- }
-
- updatePatchIfMissing(original, modified, patch, diffOptions)
- // Insert the retainKeysList iff there are values present in the retainKeysList and
- // either of the following is true:
- // - the patch is not empty
- // - there are additional field in original that need to be cleared
- if len(retainKeysList) > 0 &&
- (len(patch) > 0 || hasAdditionalNewField(original, modified)) {
- patch[retainKeysDirective] = sortScalars(retainKeysList)
- }
- return patch, nil
-}
-
-// handleDirectiveMarker handles how to diff directive marker between 2 objects
-func handleDirectiveMarker(key string, originalValue, modifiedValue interface{}, patch map[string]interface{}) (bool, error) {
- if key == directiveMarker {
- originalString, ok := originalValue.(string)
- if !ok {
- return false, fmt.Errorf("invalid value for special key: %s", directiveMarker)
- }
- modifiedString, ok := modifiedValue.(string)
- if !ok {
- return false, fmt.Errorf("invalid value for special key: %s", directiveMarker)
- }
- if modifiedString != originalString {
- patch[directiveMarker] = modifiedValue
- }
- return true, nil
- }
- return false, nil
-}
-
-// handleMapDiff diff between 2 maps `originalValueTyped` and `modifiedValue`,
-// puts the diff in the `patch` associated with `key`
-// key is the key associated with originalValue and modifiedValue.
-// originalValue, modifiedValue are the old and new value respectively.They are both maps
-// patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue
-// diffOptions contains multiple options to control how we do the diff.
-func handleMapDiff(key string, originalValue, modifiedValue, patch map[string]interface{},
- schema LookupPatchMeta, diffOptions DiffOptions) error {
- subschema, patchMeta, err := schema.LookupPatchMetadataForStruct(key)
-
- if err != nil {
- // We couldn't look up metadata for the field
- // If the values are identical, this doesn't matter, no patch is needed
- if reflect.DeepEqual(originalValue, modifiedValue) {
- return nil
- }
- // Otherwise, return the error
- return err
- }
- retainKeys, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
- if err != nil {
- return err
- }
- diffOptions.BuildRetainKeysDirective = retainKeys
- switch patchStrategy {
- // The patch strategic from metadata tells us to replace the entire object instead of diffing it
- case replaceDirective:
- if !diffOptions.IgnoreChangesAndAdditions {
- patch[key] = modifiedValue
- }
- default:
- patchValue, err := diffMaps(originalValue, modifiedValue, subschema, diffOptions)
- if err != nil {
- return err
- }
- // Maps were not identical, use provided patch value
- if len(patchValue) > 0 {
- patch[key] = patchValue
- }
- }
- return nil
-}
-
-// handleSliceDiff diff between 2 slices `originalValueTyped` and `modifiedValue`,
-// puts the diff in the `patch` associated with `key`
-// key is the key associated with originalValue and modifiedValue.
-// originalValue, modifiedValue are the old and new value respectively.They are both slices
-// patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue
-// diffOptions contains multiple options to control how we do the diff.
-func handleSliceDiff(key string, originalValue, modifiedValue []interface{}, patch map[string]interface{},
- schema LookupPatchMeta, diffOptions DiffOptions) error {
- subschema, patchMeta, err := schema.LookupPatchMetadataForSlice(key)
- if err != nil {
- // We couldn't look up metadata for the field
- // If the values are identical, this doesn't matter, no patch is needed
- if reflect.DeepEqual(originalValue, modifiedValue) {
- return nil
- }
- // Otherwise, return the error
- return err
- }
- retainKeys, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
- if err != nil {
- return err
- }
- switch patchStrategy {
- // Merge the 2 slices using mergePatchKey
- case mergeDirective:
- diffOptions.BuildRetainKeysDirective = retainKeys
- addList, deletionList, setOrderList, err := diffLists(originalValue, modifiedValue, subschema, patchMeta.GetPatchMergeKey(), diffOptions)
- if err != nil {
- return err
- }
- if len(addList) > 0 {
- patch[key] = addList
- }
- // generate a parallel list for deletion
- if len(deletionList) > 0 {
- parallelDeletionListKey := fmt.Sprintf("%s/%s", deleteFromPrimitiveListDirectivePrefix, key)
- patch[parallelDeletionListKey] = deletionList
- }
- if len(setOrderList) > 0 {
- parallelSetOrderListKey := fmt.Sprintf("%s/%s", setElementOrderDirectivePrefix, key)
- patch[parallelSetOrderListKey] = setOrderList
- }
- default:
- replacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions)
- }
- return nil
-}
-
-// replacePatchFieldIfNotEqual updates the patch if original and modified are not deep equal
-// if diffOptions.IgnoreChangesAndAdditions is false.
-// original is the old value, maybe either the live cluster object or the last applied configuration
-// modified is the new value, is always the users new config
-func replacePatchFieldIfNotEqual(key string, original, modified interface{},
- patch map[string]interface{}, diffOptions DiffOptions) {
- if diffOptions.IgnoreChangesAndAdditions {
- // Ignoring changes - do nothing
- return
- }
- if reflect.DeepEqual(original, modified) {
- // Contents are identical - do nothing
- return
- }
- // Create a patch to replace the old value with the new one
- patch[key] = modified
-}
-
-// updatePatchIfMissing iterates over `original` when ignoreDeletions is false.
-// Clear the field whose key is not present in `modified`.
-// original is the old value, maybe either the live cluster object or the last applied configuration
-// modified is the new value, is always the users new config
-func updatePatchIfMissing(original, modified, patch map[string]interface{}, diffOptions DiffOptions) {
- if diffOptions.IgnoreDeletions {
- // Ignoring deletion - do nothing
- return
- }
- // Add nils for deleted values
- for key := range original {
- if _, found := modified[key]; !found {
- patch[key] = nil
- }
- }
-}
-
-// validateMergeKeyInLists checks if each map in the list has the mentryerge key.
-func validateMergeKeyInLists(mergeKey string, lists ...[]interface{}) error {
- for _, list := range lists {
- for _, item := range list {
- m, ok := item.(map[string]interface{})
- if !ok {
- return mergepatch.ErrBadArgType(m, item)
- }
- if _, ok = m[mergeKey]; !ok {
- return mergepatch.ErrNoMergeKey(m, mergeKey)
- }
- }
- }
- return nil
-}
-
-// normalizeElementOrder sort `patch` list by `patchOrder` and sort `serverOnly` list by `serverOrder`.
-// Then it merges the 2 sorted lists.
-// It guarantee the relative order in the patch list and in the serverOnly list is kept.
-// `patch` is a list of items in the patch, and `serverOnly` is a list of items in the live object.
-// `patchOrder` is the order we want `patch` list to have and
-// `serverOrder` is the order we want `serverOnly` list to have.
-// kind is the kind of each item in the lists `patch` and `serverOnly`.
-func normalizeElementOrder(patch, serverOnly, patchOrder, serverOrder []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error) {
- patch, err := normalizeSliceOrder(patch, patchOrder, mergeKey, kind)
- if err != nil {
- return nil, err
- }
- serverOnly, err = normalizeSliceOrder(serverOnly, serverOrder, mergeKey, kind)
- if err != nil {
- return nil, err
- }
- all := mergeSortedSlice(serverOnly, patch, serverOrder, mergeKey, kind)
-
- return all, nil
-}
-
-// mergeSortedSlice merges the 2 sorted lists by serverOrder with best effort.
-// It will insert each item in `left` list to `right` list. In most cases, the 2 lists will be interleaved.
-// The relative order of left and right are guaranteed to be kept.
-// They have higher precedence than the order in the live list.
-// The place for a item in `left` is found by:
-// scan from the place of last insertion in `right` to the end of `right`,
-// the place is before the first item that is greater than the item we want to insert.
-// example usage: using server-only items as left and patch items as right. We insert server-only items
-// to patch list. We use the order of live object as record for comparison.
-func mergeSortedSlice(left, right, serverOrder []interface{}, mergeKey string, kind reflect.Kind) []interface{} {
- // Returns if l is less than r, and if both have been found.
- // If l and r both present and l is in front of r, l is less than r.
- less := func(l, r interface{}) (bool, bool) {
- li := index(serverOrder, l, mergeKey, kind)
- ri := index(serverOrder, r, mergeKey, kind)
- if li >= 0 && ri >= 0 {
- return li < ri, true
- } else {
- return false, false
- }
- }
-
- // left and right should be non-overlapping.
- size := len(left) + len(right)
- i, j := 0, 0
- s := make([]interface{}, size, size)
-
- for k := 0; k < size; k++ {
- if i >= len(left) && j < len(right) {
- // have items left in `right` list
- s[k] = right[j]
- j++
- } else if j >= len(right) && i < len(left) {
- // have items left in `left` list
- s[k] = left[i]
- i++
- } else {
- // compare them if i and j are both in bound
- less, foundBoth := less(left[i], right[j])
- if foundBoth && less {
- s[k] = left[i]
- i++
- } else {
- s[k] = right[j]
- j++
- }
- }
- }
- return s
-}
-
-// index returns the index of the item in the given items, or -1 if it doesn't exist
-// l must NOT be a slice of slices, this should be checked before calling.
-func index(l []interface{}, valToLookUp interface{}, mergeKey string, kind reflect.Kind) int {
- var getValFn func(interface{}) interface{}
- // Get the correct `getValFn` based on item `kind`.
- // It should return the value of merge key for maps and
- // return the item for other kinds.
- switch kind {
- case reflect.Map:
- getValFn = func(item interface{}) interface{} {
- typedItem, ok := item.(map[string]interface{})
- if !ok {
- return nil
- }
- val := typedItem[mergeKey]
- return val
- }
- default:
- getValFn = func(item interface{}) interface{} {
- return item
- }
- }
-
- for i, v := range l {
- if getValFn(valToLookUp) == getValFn(v) {
- return i
- }
- }
- return -1
-}
-
-// extractToDeleteItems takes a list and
-// returns 2 lists: one contains items that should be kept and the other contains items to be deleted.
-func extractToDeleteItems(l []interface{}) ([]interface{}, []interface{}, error) {
- var nonDelete, toDelete []interface{}
- for _, v := range l {
- m, ok := v.(map[string]interface{})
- if !ok {
- return nil, nil, mergepatch.ErrBadArgType(m, v)
- }
-
- directive, foundDirective := m[directiveMarker]
- if foundDirective && directive == deleteDirective {
- toDelete = append(toDelete, v)
- } else {
- nonDelete = append(nonDelete, v)
- }
- }
- return nonDelete, toDelete, nil
-}
-
-// normalizeSliceOrder sort `toSort` list by `order`
-func normalizeSliceOrder(toSort, order []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error) {
- var toDelete []interface{}
- if kind == reflect.Map {
- // make sure each item in toSort, order has merge key
- err := validateMergeKeyInLists(mergeKey, toSort, order)
- if err != nil {
- return nil, err
- }
- toSort, toDelete, err = extractToDeleteItems(toSort)
- if err != nil {
- return nil, err
- }
- }
-
- sort.SliceStable(toSort, func(i, j int) bool {
- if ii := index(order, toSort[i], mergeKey, kind); ii >= 0 {
- if ij := index(order, toSort[j], mergeKey, kind); ij >= 0 {
- return ii < ij
- }
- }
- return true
- })
- toSort = append(toSort, toDelete...)
- return toSort, nil
-}
-
-// Returns a (recursive) strategic merge patch, a parallel deletion list if necessary and
-// another list to set the order of the list
-// Only list of primitives with merge strategy will generate a parallel deletion list.
-// These two lists should yield modified when applied to original, for lists with merge semantics.
-func diffLists(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, []interface{}, error) {
- if len(original) == 0 {
- // Both slices are empty - do nothing
- if len(modified) == 0 || diffOptions.IgnoreChangesAndAdditions {
- return nil, nil, nil, nil
- }
-
- // Old slice was empty - add all elements from the new slice
- return modified, nil, nil, nil
- }
-
- elementType, err := sliceElementType(original, modified)
- if err != nil {
- return nil, nil, nil, err
- }
-
- var patchList, deleteList, setOrderList []interface{}
- kind := elementType.Kind()
- switch kind {
- case reflect.Map:
- patchList, deleteList, err = diffListsOfMaps(original, modified, schema, mergeKey, diffOptions)
- if err != nil {
- return nil, nil, nil, err
- }
- patchList, err = normalizeSliceOrder(patchList, modified, mergeKey, kind)
- if err != nil {
- return nil, nil, nil, err
- }
- orderSame, err := isOrderSame(original, modified, mergeKey)
- if err != nil {
- return nil, nil, nil, err
- }
- // append the deletions to the end of the patch list.
- patchList = append(patchList, deleteList...)
- deleteList = nil
- // generate the setElementOrder list when there are content changes or order changes
- if diffOptions.SetElementOrder &&
- ((!diffOptions.IgnoreChangesAndAdditions && (len(patchList) > 0 || !orderSame)) ||
- (!diffOptions.IgnoreDeletions && len(patchList) > 0)) {
- // Generate a list of maps that each item contains only the merge key.
- setOrderList = make([]interface{}, len(modified))
- for i, v := range modified {
- typedV := v.(map[string]interface{})
- setOrderList[i] = map[string]interface{}{
- mergeKey: typedV[mergeKey],
- }
- }
- }
- case reflect.Slice:
- // Lists of Lists are not permitted by the api
- return nil, nil, nil, mergepatch.ErrNoListOfLists
- default:
- patchList, deleteList, err = diffListsOfScalars(original, modified, diffOptions)
- if err != nil {
- return nil, nil, nil, err
- }
- patchList, err = normalizeSliceOrder(patchList, modified, mergeKey, kind)
- // generate the setElementOrder list when there are content changes or order changes
- if diffOptions.SetElementOrder && ((!diffOptions.IgnoreDeletions && len(deleteList) > 0) ||
- (!diffOptions.IgnoreChangesAndAdditions && !reflect.DeepEqual(original, modified))) {
- setOrderList = modified
- }
- }
- return patchList, deleteList, setOrderList, err
-}
-
-// isOrderSame checks if the order in a list has changed
-func isOrderSame(original, modified []interface{}, mergeKey string) (bool, error) {
- if len(original) != len(modified) {
- return false, nil
- }
- for i, modifiedItem := range modified {
- equal, err := mergeKeyValueEqual(original[i], modifiedItem, mergeKey)
- if err != nil || !equal {
- return equal, err
- }
- }
- return true, nil
-}
-
-// diffListsOfScalars returns 2 lists, the first one is addList and the second one is deletionList.
-// Argument diffOptions.IgnoreChangesAndAdditions controls if calculate addList. true means not calculate.
-// Argument diffOptions.IgnoreDeletions controls if calculate deletionList. true means not calculate.
-// original may be changed, but modified is guaranteed to not be changed
-func diffListsOfScalars(original, modified []interface{}, diffOptions DiffOptions) ([]interface{}, []interface{}, error) {
- modifiedCopy := make([]interface{}, len(modified))
- copy(modifiedCopy, modified)
- // Sort the scalars for easier calculating the diff
- originalScalars := sortScalars(original)
- modifiedScalars := sortScalars(modifiedCopy)
-
- originalIndex, modifiedIndex := 0, 0
- addList := []interface{}{}
- deletionList := []interface{}{}
-
- for {
- originalInBounds := originalIndex < len(originalScalars)
- modifiedInBounds := modifiedIndex < len(modifiedScalars)
- if !originalInBounds && !modifiedInBounds {
- break
- }
- // we need to compare the string representation of the scalar,
- // because the scalar is an interface which doesn't support either < or >
- // And that's how func sortScalars compare scalars.
- var originalString, modifiedString string
- var originalValue, modifiedValue interface{}
- if originalInBounds {
- originalValue = originalScalars[originalIndex]
- originalString = fmt.Sprintf("%v", originalValue)
- }
- if modifiedInBounds {
- modifiedValue = modifiedScalars[modifiedIndex]
- modifiedString = fmt.Sprintf("%v", modifiedValue)
- }
-
- originalV, modifiedV := compareListValuesAtIndex(originalInBounds, modifiedInBounds, originalString, modifiedString)
- switch {
- case originalV == nil && modifiedV == nil:
- originalIndex++
- modifiedIndex++
- case originalV != nil && modifiedV == nil:
- if !diffOptions.IgnoreDeletions {
- deletionList = append(deletionList, originalValue)
- }
- originalIndex++
- case originalV == nil && modifiedV != nil:
- if !diffOptions.IgnoreChangesAndAdditions {
- addList = append(addList, modifiedValue)
- }
- modifiedIndex++
- default:
- return nil, nil, fmt.Errorf("Unexpected returned value from compareListValuesAtIndex: %v and %v", originalV, modifiedV)
- }
- }
-
- return addList, deduplicateScalars(deletionList), nil
-}
-
-// If first return value is non-nil, list1 contains an element not present in list2
-// If second return value is non-nil, list2 contains an element not present in list1
-func compareListValuesAtIndex(list1Inbounds, list2Inbounds bool, list1Value, list2Value string) (interface{}, interface{}) {
- bothInBounds := list1Inbounds && list2Inbounds
- switch {
- // scalars are identical
- case bothInBounds && list1Value == list2Value:
- return nil, nil
- // only list2 is in bound
- case !list1Inbounds:
- fallthrough
- // list2 has additional scalar
- case bothInBounds && list1Value > list2Value:
- return nil, list2Value
- // only original is in bound
- case !list2Inbounds:
- fallthrough
- // original has additional scalar
- case bothInBounds && list1Value < list2Value:
- return list1Value, nil
- default:
- return nil, nil
- }
-}
-
-// diffListsOfMaps takes a pair of lists and
-// returns a (recursive) strategic merge patch list contains additions and changes and
-// a deletion list contains deletions
-func diffListsOfMaps(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, error) {
- patch := make([]interface{}, 0, len(modified))
- deletionList := make([]interface{}, 0, len(original))
-
- originalSorted, err := sortMergeListsByNameArray(original, schema, mergeKey, false)
- if err != nil {
- return nil, nil, err
- }
- modifiedSorted, err := sortMergeListsByNameArray(modified, schema, mergeKey, false)
- if err != nil {
- return nil, nil, err
- }
-
- originalIndex, modifiedIndex := 0, 0
- for {
- originalInBounds := originalIndex < len(originalSorted)
- modifiedInBounds := modifiedIndex < len(modifiedSorted)
- bothInBounds := originalInBounds && modifiedInBounds
- if !originalInBounds && !modifiedInBounds {
- break
- }
-
- var originalElementMergeKeyValueString, modifiedElementMergeKeyValueString string
- var originalElementMergeKeyValue, modifiedElementMergeKeyValue interface{}
- var originalElement, modifiedElement map[string]interface{}
- if originalInBounds {
- originalElement, originalElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(originalIndex, mergeKey, originalSorted)
- if err != nil {
- return nil, nil, err
- }
- originalElementMergeKeyValueString = fmt.Sprintf("%v", originalElementMergeKeyValue)
- }
- if modifiedInBounds {
- modifiedElement, modifiedElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(modifiedIndex, mergeKey, modifiedSorted)
- if err != nil {
- return nil, nil, err
- }
- modifiedElementMergeKeyValueString = fmt.Sprintf("%v", modifiedElementMergeKeyValue)
- }
-
- switch {
- case bothInBounds && ItemMatchesOriginalAndModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):
- // Merge key values are equal, so recurse
- patchValue, err := diffMaps(originalElement, modifiedElement, schema, diffOptions)
- if err != nil {
- return nil, nil, err
- }
- if len(patchValue) > 0 {
- patchValue[mergeKey] = modifiedElementMergeKeyValue
- patch = append(patch, patchValue)
- }
- originalIndex++
- modifiedIndex++
- // only modified is in bound
- case !originalInBounds:
- fallthrough
- // modified has additional map
- case bothInBounds && ItemAddedToModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):
- if !diffOptions.IgnoreChangesAndAdditions {
- patch = append(patch, modifiedElement)
- }
- modifiedIndex++
- // only original is in bound
- case !modifiedInBounds:
- fallthrough
- // original has additional map
- case bothInBounds && ItemRemovedFromModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):
- if !diffOptions.IgnoreDeletions {
- // Item was deleted, so add delete directive
- deletionList = append(deletionList, CreateDeleteDirective(mergeKey, originalElementMergeKeyValue))
- }
- originalIndex++
- }
- }
-
- return patch, deletionList, nil
-}
-
-// getMapAndMergeKeyValueByIndex return a map in the list and its merge key value given the index of the map.
-func getMapAndMergeKeyValueByIndex(index int, mergeKey string, listOfMaps []interface{}) (map[string]interface{}, interface{}, error) {
- m, ok := listOfMaps[index].(map[string]interface{})
- if !ok {
- return nil, nil, mergepatch.ErrBadArgType(m, listOfMaps[index])
- }
-
- val, ok := m[mergeKey]
- if !ok {
- return nil, nil, mergepatch.ErrNoMergeKey(m, mergeKey)
- }
- return m, val, nil
-}
-
-// StrategicMergePatch applies a strategic merge patch. The patch and the original document
-// must be json encoded content. A patch can be created from an original and a modified document
-// by calling CreateStrategicMergePatch.
-func StrategicMergePatch(original, patch []byte, dataStruct interface{}) ([]byte, error) {
- schema, err := NewPatchMetaFromStruct(dataStruct)
- if err != nil {
- return nil, err
- }
-
- return StrategicMergePatchUsingLookupPatchMeta(original, patch, schema)
-}
-
-func StrategicMergePatchUsingLookupPatchMeta(original, patch []byte, schema LookupPatchMeta) ([]byte, error) {
- originalMap, err := handleUnmarshal(original)
- if err != nil {
- return nil, err
- }
- patchMap, err := handleUnmarshal(patch)
- if err != nil {
- return nil, err
- }
-
- result, err := StrategicMergeMapPatchUsingLookupPatchMeta(originalMap, patchMap, schema)
- if err != nil {
- return nil, err
- }
-
- return json.Marshal(result)
-}
-
-func handleUnmarshal(j []byte) (map[string]interface{}, error) {
- if j == nil {
- j = []byte("{}")
- }
-
- m := map[string]interface{}{}
- err := json.Unmarshal(j, &m)
- if err != nil {
- return nil, mergepatch.ErrBadJSONDoc
- }
- return m, nil
-}
-
-// StrategicMergeMapPatch applies a strategic merge patch. The original and patch documents
-// must be JSONMap. A patch can be created from an original and modified document by
-// calling CreateTwoWayMergeMapPatch.
-// Warning: the original and patch JSONMap objects are mutated by this function and should not be reused.
-func StrategicMergeMapPatch(original, patch JSONMap, dataStruct interface{}) (JSONMap, error) {
- schema, err := NewPatchMetaFromStruct(dataStruct)
- if err != nil {
- return nil, err
- }
-
- // We need the go struct tags `patchMergeKey` and `patchStrategy` for fields that support a strategic merge patch.
- // For native resources, we can easily figure out these tags since we know the fields.
-
- // Because custom resources are decoded as Unstructured and because we're missing the metadata about how to handle
- // each field in a strategic merge patch, we can't find the go struct tags. Hence, we can't easily do a strategic merge
- // for custom resources. So we should fail fast and return an error.
- if _, ok := dataStruct.(*unstructured.Unstructured); ok {
- return nil, mergepatch.ErrUnsupportedStrategicMergePatchFormat
- }
-
- return StrategicMergeMapPatchUsingLookupPatchMeta(original, patch, schema)
-}
-
-func StrategicMergeMapPatchUsingLookupPatchMeta(original, patch JSONMap, schema LookupPatchMeta) (JSONMap, error) {
- mergeOptions := MergeOptions{
- MergeParallelList: true,
- IgnoreUnmatchedNulls: true,
- }
- return mergeMap(original, patch, schema, mergeOptions)
-}
-
-// handleDirectiveInMergeMap handles the patch directive when merging 2 maps.
-func handleDirectiveInMergeMap(directive interface{}, patch map[string]interface{}) (map[string]interface{}, error) {
- if directive == replaceDirective {
- // If the patch contains "$patch: replace", don't merge it, just use the
- // patch directly. Later on, we can add a single level replace that only
- // affects the map that the $patch is in.
- delete(patch, directiveMarker)
- return patch, nil
- }
-
- if directive == deleteDirective {
- // If the patch contains "$patch: delete", don't merge it, just return
- // an empty map.
- return map[string]interface{}{}, nil
- }
-
- return nil, mergepatch.ErrBadPatchType(directive, patch)
-}
-
-func containsDirectiveMarker(item interface{}) bool {
- m, ok := item.(map[string]interface{})
- if ok {
- if _, foundDirectiveMarker := m[directiveMarker]; foundDirectiveMarker {
- return true
- }
- }
- return false
-}
-
-func mergeKeyValueEqual(left, right interface{}, mergeKey string) (bool, error) {
- if len(mergeKey) == 0 {
- return left == right, nil
- }
- typedLeft, ok := left.(map[string]interface{})
- if !ok {
- return false, mergepatch.ErrBadArgType(typedLeft, left)
- }
- typedRight, ok := right.(map[string]interface{})
- if !ok {
- return false, mergepatch.ErrBadArgType(typedRight, right)
- }
- mergeKeyLeft, ok := typedLeft[mergeKey]
- if !ok {
- return false, mergepatch.ErrNoMergeKey(typedLeft, mergeKey)
- }
- mergeKeyRight, ok := typedRight[mergeKey]
- if !ok {
- return false, mergepatch.ErrNoMergeKey(typedRight, mergeKey)
- }
- return mergeKeyLeft == mergeKeyRight, nil
-}
-
-// extractKey trims the prefix and return the original key
-func extractKey(s, prefix string) (string, error) {
- substrings := strings.SplitN(s, "/", 2)
- if len(substrings) <= 1 || substrings[0] != prefix {
- switch prefix {
- case deleteFromPrimitiveListDirectivePrefix:
- return "", mergepatch.ErrBadPatchFormatForPrimitiveList
- case setElementOrderDirectivePrefix:
- return "", mergepatch.ErrBadPatchFormatForSetElementOrderList
- default:
- return "", fmt.Errorf("fail to find unknown prefix %q in %s\n", prefix, s)
- }
- }
- return substrings[1], nil
-}
-
-// validatePatchUsingSetOrderList verifies:
-// the relative order of any two items in the setOrderList list matches that in the patch list.
-// the items in the patch list must be a subset or the same as the $setElementOrder list (deletions are ignored).
-func validatePatchWithSetOrderList(patchList, setOrderList interface{}, mergeKey string) error {
- typedSetOrderList, ok := setOrderList.([]interface{})
- if !ok {
- return mergepatch.ErrBadPatchFormatForSetElementOrderList
- }
- typedPatchList, ok := patchList.([]interface{})
- if !ok {
- return mergepatch.ErrBadPatchFormatForSetElementOrderList
- }
- if len(typedSetOrderList) == 0 || len(typedPatchList) == 0 {
- return nil
- }
-
- var nonDeleteList, toDeleteList []interface{}
- var err error
- if len(mergeKey) > 0 {
- nonDeleteList, toDeleteList, err = extractToDeleteItems(typedPatchList)
- if err != nil {
- return err
- }
- } else {
- nonDeleteList = typedPatchList
- }
-
- patchIndex, setOrderIndex := 0, 0
- for patchIndex < len(nonDeleteList) && setOrderIndex < len(typedSetOrderList) {
- if containsDirectiveMarker(nonDeleteList[patchIndex]) {
- patchIndex++
- continue
- }
- mergeKeyEqual, err := mergeKeyValueEqual(nonDeleteList[patchIndex], typedSetOrderList[setOrderIndex], mergeKey)
- if err != nil {
- return err
- }
- if mergeKeyEqual {
- patchIndex++
- }
- setOrderIndex++
- }
- // If patchIndex is inbound but setOrderIndex if out of bound mean there are items mismatching between the patch list and setElementOrder list.
- // the second check is is a sanity check, and should always be true if the first is true.
- if patchIndex < len(nonDeleteList) && setOrderIndex >= len(typedSetOrderList) {
- return fmt.Errorf("The order in patch list:\n%v\n doesn't match %s list:\n%v\n", typedPatchList, setElementOrderDirectivePrefix, setOrderList)
- }
- typedPatchList = append(nonDeleteList, toDeleteList...)
- return nil
-}
-
-// preprocessDeletionListForMerging preprocesses the deletion list.
-// it returns shouldContinue, isDeletionList, noPrefixKey
-func preprocessDeletionListForMerging(key string, original map[string]interface{},
- patchVal interface{}, mergeDeletionList bool) (bool, bool, string, error) {
- // If found a parallel list for deletion and we are going to merge the list,
- // overwrite the key to the original key and set flag isDeleteList
- foundParallelListPrefix := strings.HasPrefix(key, deleteFromPrimitiveListDirectivePrefix)
- if foundParallelListPrefix {
- if !mergeDeletionList {
- original[key] = patchVal
- return true, false, "", nil
- }
- originalKey, err := extractKey(key, deleteFromPrimitiveListDirectivePrefix)
- return false, true, originalKey, err
- }
- return false, false, "", nil
-}
-
-// applyRetainKeysDirective looks for a retainKeys directive and applies to original
-// - if no directive exists do nothing
-// - if directive is found, clear keys in original missing from the directive list
-// - validate that all keys present in the patch are present in the retainKeys directive
-// note: original may be another patch request, e.g. applying the add+modified patch to the deletions patch. In this case it may have directives
-func applyRetainKeysDirective(original, patch map[string]interface{}, options MergeOptions) error {
- retainKeysInPatch, foundInPatch := patch[retainKeysDirective]
- if !foundInPatch {
- return nil
- }
- // cleanup the directive
- delete(patch, retainKeysDirective)
-
- if !options.MergeParallelList {
- // If original is actually a patch, make sure the retainKeys directives are the same in both patches if present in both.
- // If not present in the original patch, copy from the modified patch.
- retainKeysInOriginal, foundInOriginal := original[retainKeysDirective]
- if foundInOriginal {
- if !reflect.DeepEqual(retainKeysInOriginal, retainKeysInPatch) {
- // This error actually should never happen.
- return fmt.Errorf("%v and %v are not deep equal: this may happen when calculating the 3-way diff patch", retainKeysInOriginal, retainKeysInPatch)
- }
- } else {
- original[retainKeysDirective] = retainKeysInPatch
- }
- return nil
- }
-
- retainKeysList, ok := retainKeysInPatch.([]interface{})
- if !ok {
- return mergepatch.ErrBadPatchFormatForRetainKeys
- }
-
- // validate patch to make sure all fields in the patch are present in the retainKeysList.
- // The map is used only as a set, the value is never referenced
- m := map[interface{}]struct{}{}
- for _, v := range retainKeysList {
- m[v] = struct{}{}
- }
- for k, v := range patch {
- if v == nil || strings.HasPrefix(k, deleteFromPrimitiveListDirectivePrefix) ||
- strings.HasPrefix(k, setElementOrderDirectivePrefix) {
- continue
- }
- // If there is an item present in the patch but not in the retainKeys list,
- // the patch is invalid.
- if _, found := m[k]; !found {
- return mergepatch.ErrBadPatchFormatForRetainKeys
- }
- }
-
- // clear not present fields
- for k := range original {
- if _, found := m[k]; !found {
- delete(original, k)
- }
- }
- return nil
-}
-
-// mergePatchIntoOriginal processes $setElementOrder list.
-// When not merging the directive, it will make sure $setElementOrder list exist only in original.
-// When merging the directive, it will try to find the $setElementOrder list and
-// its corresponding patch list, validate it and merge it.
-// Then, sort them by the relative order in setElementOrder, patch list and live list.
-// The precedence is $setElementOrder > order in patch list > order in live list.
-// This function will delete the item after merging it to prevent process it again in the future.
-// Ref: https://git.k8s.io/community/contributors/design-proposals/cli/preserve-order-in-strategic-merge-patch.md
-func mergePatchIntoOriginal(original, patch map[string]interface{}, schema LookupPatchMeta, mergeOptions MergeOptions) error {
- for key, patchV := range patch {
- // Do nothing if there is no ordering directive
- if !strings.HasPrefix(key, setElementOrderDirectivePrefix) {
- continue
- }
-
- setElementOrderInPatch := patchV
- // Copies directive from the second patch (`patch`) to the first patch (`original`)
- // and checks they are equal and delete the directive in the second patch
- if !mergeOptions.MergeParallelList {
- setElementOrderListInOriginal, ok := original[key]
- if ok {
- // check if the setElementOrder list in original and the one in patch matches
- if !reflect.DeepEqual(setElementOrderListInOriginal, setElementOrderInPatch) {
- return mergepatch.ErrBadPatchFormatForSetElementOrderList
- }
- } else {
- // move the setElementOrder list from patch to original
- original[key] = setElementOrderInPatch
- }
- }
- delete(patch, key)
-
- var (
- ok bool
- originalFieldValue, patchFieldValue, merged []interface{}
- patchStrategy string
- patchMeta PatchMeta
- subschema LookupPatchMeta
- )
- typedSetElementOrderList, ok := setElementOrderInPatch.([]interface{})
- if !ok {
- return mergepatch.ErrBadArgType(typedSetElementOrderList, setElementOrderInPatch)
- }
- // Trim the setElementOrderDirectivePrefix to get the key of the list field in original.
- originalKey, err := extractKey(key, setElementOrderDirectivePrefix)
- if err != nil {
- return err
- }
- // try to find the list with `originalKey` in `original` and `modified` and merge them.
- originalList, foundOriginal := original[originalKey]
- patchList, foundPatch := patch[originalKey]
- if foundOriginal {
- originalFieldValue, ok = originalList.([]interface{})
- if !ok {
- return mergepatch.ErrBadArgType(originalFieldValue, originalList)
- }
- }
- if foundPatch {
- patchFieldValue, ok = patchList.([]interface{})
- if !ok {
- return mergepatch.ErrBadArgType(patchFieldValue, patchList)
- }
- }
- subschema, patchMeta, err = schema.LookupPatchMetadataForSlice(originalKey)
- if err != nil {
- return err
- }
- _, patchStrategy, err = extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
- if err != nil {
- return err
- }
- // Check for consistency between the element order list and the field it applies to
- err = validatePatchWithSetOrderList(patchFieldValue, typedSetElementOrderList, patchMeta.GetPatchMergeKey())
- if err != nil {
- return err
- }
-
- switch {
- case foundOriginal && !foundPatch:
- // no change to list contents
- merged = originalFieldValue
- case !foundOriginal && foundPatch:
- // list was added
- merged = patchFieldValue
- case foundOriginal && foundPatch:
- merged, err = mergeSliceHandler(originalList, patchList, subschema,
- patchStrategy, patchMeta.GetPatchMergeKey(), false, mergeOptions)
- if err != nil {
- return err
- }
- case !foundOriginal && !foundPatch:
- continue
- }
-
- // Split all items into patch items and server-only items and then enforce the order.
- var patchItems, serverOnlyItems []interface{}
- if len(patchMeta.GetPatchMergeKey()) == 0 {
- // Primitives doesn't need merge key to do partitioning.
- patchItems, serverOnlyItems = partitionPrimitivesByPresentInList(merged, typedSetElementOrderList)
-
- } else {
- // Maps need merge key to do partitioning.
- patchItems, serverOnlyItems, err = partitionMapsByPresentInList(merged, typedSetElementOrderList, patchMeta.GetPatchMergeKey())
- if err != nil {
- return err
- }
- }
-
- elementType, err := sliceElementType(originalFieldValue, patchFieldValue)
- if err != nil {
- return err
- }
- kind := elementType.Kind()
- // normalize merged list
- // typedSetElementOrderList contains all the relative order in typedPatchList,
- // so don't need to use typedPatchList
- both, err := normalizeElementOrder(patchItems, serverOnlyItems, typedSetElementOrderList, originalFieldValue, patchMeta.GetPatchMergeKey(), kind)
- if err != nil {
- return err
- }
- original[originalKey] = both
- // delete patch list from patch to prevent process again in the future
- delete(patch, originalKey)
- }
- return nil
-}
-
-// partitionPrimitivesByPresentInList partitions elements into 2 slices, the first containing items present in partitionBy, the other not.
-func partitionPrimitivesByPresentInList(original, partitionBy []interface{}) ([]interface{}, []interface{}) {
- patch := make([]interface{}, 0, len(original))
- serverOnly := make([]interface{}, 0, len(original))
- inPatch := map[interface{}]bool{}
- for _, v := range partitionBy {
- inPatch[v] = true
- }
- for _, v := range original {
- if !inPatch[v] {
- serverOnly = append(serverOnly, v)
- } else {
- patch = append(patch, v)
- }
- }
- return patch, serverOnly
-}
-
-// partitionMapsByPresentInList partitions elements into 2 slices, the first containing items present in partitionBy, the other not.
-func partitionMapsByPresentInList(original, partitionBy []interface{}, mergeKey string) ([]interface{}, []interface{}, error) {
- patch := make([]interface{}, 0, len(original))
- serverOnly := make([]interface{}, 0, len(original))
- for _, v := range original {
- typedV, ok := v.(map[string]interface{})
- if !ok {
- return nil, nil, mergepatch.ErrBadArgType(typedV, v)
- }
- mergeKeyValue, foundMergeKey := typedV[mergeKey]
- if !foundMergeKey {
- return nil, nil, mergepatch.ErrNoMergeKey(typedV, mergeKey)
- }
- _, _, found, err := findMapInSliceBasedOnKeyValue(partitionBy, mergeKey, mergeKeyValue)
- if err != nil {
- return nil, nil, err
- }
- if !found {
- serverOnly = append(serverOnly, v)
- } else {
- patch = append(patch, v)
- }
- }
- return patch, serverOnly, nil
-}
-
-// Merge fields from a patch map into the original map. Note: This may modify
-// both the original map and the patch because getting a deep copy of a map in
-// golang is highly non-trivial.
-// flag mergeOptions.MergeParallelList controls if using the parallel list to delete or keeping the list.
-// If patch contains any null field (e.g. field_1: null) that is not
-// present in original, then to propagate it to the end result use
-// mergeOptions.IgnoreUnmatchedNulls == false.
-func mergeMap(original, patch map[string]interface{}, schema LookupPatchMeta, mergeOptions MergeOptions) (map[string]interface{}, error) {
- if v, ok := patch[directiveMarker]; ok {
- return handleDirectiveInMergeMap(v, patch)
- }
-
- // nil is an accepted value for original to simplify logic in other places.
- // If original is nil, replace it with an empty map and then apply the patch.
- if original == nil {
- original = map[string]interface{}{}
- }
-
- err := applyRetainKeysDirective(original, patch, mergeOptions)
- if err != nil {
- return nil, err
- }
-
- // Process $setElementOrder list and other lists sharing the same key.
- // When not merging the directive, it will make sure $setElementOrder list exist only in original.
- // When merging the directive, it will process $setElementOrder and its patch list together.
- // This function will delete the merged elements from patch so they will not be reprocessed
- err = mergePatchIntoOriginal(original, patch, schema, mergeOptions)
- if err != nil {
- return nil, err
- }
-
- // Start merging the patch into the original.
- for k, patchV := range patch {
- skipProcessing, isDeleteList, noPrefixKey, err := preprocessDeletionListForMerging(k, original, patchV, mergeOptions.MergeParallelList)
- if err != nil {
- return nil, err
- }
- if skipProcessing {
- continue
- }
- if len(noPrefixKey) > 0 {
- k = noPrefixKey
- }
-
- // If the value of this key is null, delete the key if it exists in the
- // original. Otherwise, check if we want to preserve it or skip it.
- // Preserving the null value is useful when we want to send an explicit
- // delete to the API server.
- if patchV == nil {
- if _, ok := original[k]; ok {
- delete(original, k)
- }
- if mergeOptions.IgnoreUnmatchedNulls {
- continue
- }
- }
-
- _, ok := original[k]
- if !ok {
- // If it's not in the original document, just take the patch value.
- original[k] = patchV
- continue
- }
-
- originalType := reflect.TypeOf(original[k])
- patchType := reflect.TypeOf(patchV)
- if originalType != patchType {
- original[k] = patchV
- continue
- }
- // If they're both maps or lists, recurse into the value.
- switch originalType.Kind() {
- case reflect.Map:
- subschema, patchMeta, err2 := schema.LookupPatchMetadataForStruct(k)
- if err2 != nil {
- return nil, err2
- }
- _, patchStrategy, err2 := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
- if err2 != nil {
- return nil, err2
- }
- original[k], err = mergeMapHandler(original[k], patchV, subschema, patchStrategy, mergeOptions)
- case reflect.Slice:
- subschema, patchMeta, err2 := schema.LookupPatchMetadataForSlice(k)
- if err2 != nil {
- return nil, err2
- }
- _, patchStrategy, err2 := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
- if err2 != nil {
- return nil, err2
- }
- original[k], err = mergeSliceHandler(original[k], patchV, subschema, patchStrategy, patchMeta.GetPatchMergeKey(), isDeleteList, mergeOptions)
- default:
- original[k] = patchV
- }
- if err != nil {
- return nil, err
- }
- }
- return original, nil
-}
-
-// mergeMapHandler handles how to merge `patchV` whose key is `key` with `original` respecting
-// fieldPatchStrategy and mergeOptions.
-func mergeMapHandler(original, patch interface{}, schema LookupPatchMeta,
- fieldPatchStrategy string, mergeOptions MergeOptions) (map[string]interface{}, error) {
- typedOriginal, typedPatch, err := mapTypeAssertion(original, patch)
- if err != nil {
- return nil, err
- }
-
- if fieldPatchStrategy != replaceDirective {
- return mergeMap(typedOriginal, typedPatch, schema, mergeOptions)
- } else {
- return typedPatch, nil
- }
-}
-
-// mergeSliceHandler handles how to merge `patchV` whose key is `key` with `original` respecting
-// fieldPatchStrategy, fieldPatchMergeKey, isDeleteList and mergeOptions.
-func mergeSliceHandler(original, patch interface{}, schema LookupPatchMeta,
- fieldPatchStrategy, fieldPatchMergeKey string, isDeleteList bool, mergeOptions MergeOptions) ([]interface{}, error) {
- typedOriginal, typedPatch, err := sliceTypeAssertion(original, patch)
- if err != nil {
- return nil, err
- }
-
- if fieldPatchStrategy == mergeDirective {
- return mergeSlice(typedOriginal, typedPatch, schema, fieldPatchMergeKey, mergeOptions, isDeleteList)
- } else {
- return typedPatch, nil
- }
-}
-
-// Merge two slices together. Note: This may modify both the original slice and
-// the patch because getting a deep copy of a slice in golang is highly
-// non-trivial.
-func mergeSlice(original, patch []interface{}, schema LookupPatchMeta, mergeKey string, mergeOptions MergeOptions, isDeleteList bool) ([]interface{}, error) {
- if len(original) == 0 && len(patch) == 0 {
- return original, nil
- }
-
- // All the values must be of the same type, but not a list.
- t, err := sliceElementType(original, patch)
- if err != nil {
- return nil, err
- }
-
- var merged []interface{}
- kind := t.Kind()
- // If the elements are not maps, merge the slices of scalars.
- if kind != reflect.Map {
- if mergeOptions.MergeParallelList && isDeleteList {
- return deleteFromSlice(original, patch), nil
- }
- // Maybe in the future add a "concat" mode that doesn't
- // deduplicate.
- both := append(original, patch...)
- merged = deduplicateScalars(both)
-
- } else {
- if mergeKey == "" {
- return nil, fmt.Errorf("cannot merge lists without merge key for %s", schema.Name())
- }
-
- original, patch, err = mergeSliceWithSpecialElements(original, patch, mergeKey)
- if err != nil {
- return nil, err
- }
-
- merged, err = mergeSliceWithoutSpecialElements(original, patch, mergeKey, schema, mergeOptions)
- if err != nil {
- return nil, err
- }
- }
-
- // enforce the order
- var patchItems, serverOnlyItems []interface{}
- if len(mergeKey) == 0 {
- patchItems, serverOnlyItems = partitionPrimitivesByPresentInList(merged, patch)
- } else {
- patchItems, serverOnlyItems, err = partitionMapsByPresentInList(merged, patch, mergeKey)
- if err != nil {
- return nil, err
- }
- }
- return normalizeElementOrder(patchItems, serverOnlyItems, patch, original, mergeKey, kind)
-}
-
-// mergeSliceWithSpecialElements handles special elements with directiveMarker
-// before merging the slices. It returns a updated `original` and a patch without special elements.
-// original and patch must be slices of maps, they should be checked before calling this function.
-func mergeSliceWithSpecialElements(original, patch []interface{}, mergeKey string) ([]interface{}, []interface{}, error) {
- patchWithoutSpecialElements := []interface{}{}
- replace := false
- for _, v := range patch {
- typedV := v.(map[string]interface{})
- patchType, ok := typedV[directiveMarker]
- if !ok {
- patchWithoutSpecialElements = append(patchWithoutSpecialElements, v)
- } else {
- switch patchType {
- case deleteDirective:
- mergeValue, ok := typedV[mergeKey]
- if ok {
- var err error
- original, err = deleteMatchingEntries(original, mergeKey, mergeValue)
- if err != nil {
- return nil, nil, err
- }
- } else {
- return nil, nil, mergepatch.ErrNoMergeKey(typedV, mergeKey)
- }
- case replaceDirective:
- replace = true
- // Continue iterating through the array to prune any other $patch elements.
- case mergeDirective:
- return nil, nil, fmt.Errorf("merging lists cannot yet be specified in the patch")
- default:
- return nil, nil, mergepatch.ErrBadPatchType(patchType, typedV)
- }
- }
- }
- if replace {
- return patchWithoutSpecialElements, nil, nil
- }
- return original, patchWithoutSpecialElements, nil
-}
-
-// delete all matching entries (based on merge key) from a merging list
-func deleteMatchingEntries(original []interface{}, mergeKey string, mergeValue interface{}) ([]interface{}, error) {
- for {
- _, originalKey, found, err := findMapInSliceBasedOnKeyValue(original, mergeKey, mergeValue)
- if err != nil {
- return nil, err
- }
-
- if !found {
- break
- }
- // Delete the element at originalKey.
- original = append(original[:originalKey], original[originalKey+1:]...)
- }
- return original, nil
-}
-
-// mergeSliceWithoutSpecialElements merges slices with non-special elements.
-// original and patch must be slices of maps, they should be checked before calling this function.
-func mergeSliceWithoutSpecialElements(original, patch []interface{}, mergeKey string, schema LookupPatchMeta, mergeOptions MergeOptions) ([]interface{}, error) {
- for _, v := range patch {
- typedV := v.(map[string]interface{})
- mergeValue, ok := typedV[mergeKey]
- if !ok {
- return nil, mergepatch.ErrNoMergeKey(typedV, mergeKey)
- }
-
- // If we find a value with this merge key value in original, merge the
- // maps. Otherwise append onto original.
- originalMap, originalKey, found, err := findMapInSliceBasedOnKeyValue(original, mergeKey, mergeValue)
- if err != nil {
- return nil, err
- }
-
- if found {
- var mergedMaps interface{}
- var err error
- // Merge into original.
- mergedMaps, err = mergeMap(originalMap, typedV, schema, mergeOptions)
- if err != nil {
- return nil, err
- }
-
- original[originalKey] = mergedMaps
- } else {
- original = append(original, v)
- }
- }
- return original, nil
-}
-
-// deleteFromSlice uses the parallel list to delete the items in a list of scalars
-func deleteFromSlice(current, toDelete []interface{}) []interface{} {
- toDeleteMap := map[interface{}]interface{}{}
- processed := make([]interface{}, 0, len(current))
- for _, v := range toDelete {
- toDeleteMap[v] = true
- }
- for _, v := range current {
- if _, found := toDeleteMap[v]; !found {
- processed = append(processed, v)
- }
- }
- return processed
-}
-
-// This method no longer panics if any element of the slice is not a map.
-func findMapInSliceBasedOnKeyValue(m []interface{}, key string, value interface{}) (map[string]interface{}, int, bool, error) {
- for k, v := range m {
- typedV, ok := v.(map[string]interface{})
- if !ok {
- return nil, 0, false, fmt.Errorf("value for key %v is not a map", k)
- }
-
- valueToMatch, ok := typedV[key]
- if ok && valueToMatch == value {
- return typedV, k, true, nil
- }
- }
-
- return nil, 0, false, nil
-}
-
-// This function takes a JSON map and sorts all the lists that should be merged
-// by key. This is needed by tests because in JSON, list order is significant,
-// but in Strategic Merge Patch, merge lists do not have significant order.
-// Sorting the lists allows for order-insensitive comparison of patched maps.
-func sortMergeListsByName(mapJSON []byte, schema LookupPatchMeta) ([]byte, error) {
- var m map[string]interface{}
- err := json.Unmarshal(mapJSON, &m)
- if err != nil {
- return nil, mergepatch.ErrBadJSONDoc
- }
-
- newM, err := sortMergeListsByNameMap(m, schema)
- if err != nil {
- return nil, err
- }
-
- return json.Marshal(newM)
-}
-
-// Function sortMergeListsByNameMap recursively sorts the merge lists by its mergeKey in a map.
-func sortMergeListsByNameMap(s map[string]interface{}, schema LookupPatchMeta) (map[string]interface{}, error) {
- newS := map[string]interface{}{}
- for k, v := range s {
- if k == retainKeysDirective {
- typedV, ok := v.([]interface{})
- if !ok {
- return nil, mergepatch.ErrBadPatchFormatForRetainKeys
- }
- v = sortScalars(typedV)
- } else if strings.HasPrefix(k, deleteFromPrimitiveListDirectivePrefix) {
- typedV, ok := v.([]interface{})
- if !ok {
- return nil, mergepatch.ErrBadPatchFormatForPrimitiveList
- }
- v = sortScalars(typedV)
- } else if strings.HasPrefix(k, setElementOrderDirectivePrefix) {
- _, ok := v.([]interface{})
- if !ok {
- return nil, mergepatch.ErrBadPatchFormatForSetElementOrderList
- }
- } else if k != directiveMarker {
- // recurse for map and slice.
- switch typedV := v.(type) {
- case map[string]interface{}:
- subschema, _, err := schema.LookupPatchMetadataForStruct(k)
- if err != nil {
- return nil, err
- }
- v, err = sortMergeListsByNameMap(typedV, subschema)
- if err != nil {
- return nil, err
- }
- case []interface{}:
- subschema, patchMeta, err := schema.LookupPatchMetadataForSlice(k)
- if err != nil {
- return nil, err
- }
- _, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
- if err != nil {
- return nil, err
- }
- if patchStrategy == mergeDirective {
- var err error
- v, err = sortMergeListsByNameArray(typedV, subschema, patchMeta.GetPatchMergeKey(), true)
- if err != nil {
- return nil, err
- }
- }
- }
- }
-
- newS[k] = v
- }
-
- return newS, nil
-}
-
-// Function sortMergeListsByNameMap recursively sorts the merge lists by its mergeKey in an array.
-func sortMergeListsByNameArray(s []interface{}, schema LookupPatchMeta, mergeKey string, recurse bool) ([]interface{}, error) {
- if len(s) == 0 {
- return s, nil
- }
-
- // We don't support lists of lists yet.
- t, err := sliceElementType(s)
- if err != nil {
- return nil, err
- }
-
- // If the elements are not maps...
- if t.Kind() != reflect.Map {
- // Sort the elements, because they may have been merged out of order.
- return deduplicateAndSortScalars(s), nil
- }
-
- // Elements are maps - if one of the keys of the map is a map or a
- // list, we may need to recurse into it.
- newS := []interface{}{}
- for _, elem := range s {
- if recurse {
- typedElem := elem.(map[string]interface{})
- newElem, err := sortMergeListsByNameMap(typedElem, schema)
- if err != nil {
- return nil, err
- }
-
- newS = append(newS, newElem)
- } else {
- newS = append(newS, elem)
- }
- }
-
- // Sort the maps.
- newS = sortMapsBasedOnField(newS, mergeKey)
- return newS, nil
-}
-
-func sortMapsBasedOnField(m []interface{}, fieldName string) []interface{} {
- mapM := mapSliceFromSlice(m)
- ss := SortableSliceOfMaps{mapM, fieldName}
- sort.Sort(ss)
- newS := sliceFromMapSlice(ss.s)
- return newS
-}
-
-func mapSliceFromSlice(m []interface{}) []map[string]interface{} {
- newM := []map[string]interface{}{}
- for _, v := range m {
- vt := v.(map[string]interface{})
- newM = append(newM, vt)
- }
-
- return newM
-}
-
-func sliceFromMapSlice(s []map[string]interface{}) []interface{} {
- newS := []interface{}{}
- for _, v := range s {
- newS = append(newS, v)
- }
-
- return newS
-}
-
-type SortableSliceOfMaps struct {
- s []map[string]interface{}
- k string // key to sort on
-}
-
-func (ss SortableSliceOfMaps) Len() int {
- return len(ss.s)
-}
-
-func (ss SortableSliceOfMaps) Less(i, j int) bool {
- iStr := fmt.Sprintf("%v", ss.s[i][ss.k])
- jStr := fmt.Sprintf("%v", ss.s[j][ss.k])
- return sort.StringsAreSorted([]string{iStr, jStr})
-}
-
-func (ss SortableSliceOfMaps) Swap(i, j int) {
- tmp := ss.s[i]
- ss.s[i] = ss.s[j]
- ss.s[j] = tmp
-}
-
-func deduplicateAndSortScalars(s []interface{}) []interface{} {
- s = deduplicateScalars(s)
- return sortScalars(s)
-}
-
-func sortScalars(s []interface{}) []interface{} {
- ss := SortableSliceOfScalars{s}
- sort.Sort(ss)
- return ss.s
-}
-
-func deduplicateScalars(s []interface{}) []interface{} {
- // Clever algorithm to deduplicate.
- length := len(s) - 1
- for i := 0; i < length; i++ {
- for j := i + 1; j <= length; j++ {
- if s[i] == s[j] {
- s[j] = s[length]
- s = s[0:length]
- length--
- j--
- }
- }
- }
-
- return s
-}
-
-type SortableSliceOfScalars struct {
- s []interface{}
-}
-
-func (ss SortableSliceOfScalars) Len() int {
- return len(ss.s)
-}
-
-func (ss SortableSliceOfScalars) Less(i, j int) bool {
- iStr := fmt.Sprintf("%v", ss.s[i])
- jStr := fmt.Sprintf("%v", ss.s[j])
- return sort.StringsAreSorted([]string{iStr, jStr})
-}
-
-func (ss SortableSliceOfScalars) Swap(i, j int) {
- tmp := ss.s[i]
- ss.s[i] = ss.s[j]
- ss.s[j] = tmp
-}
-
-// Returns the type of the elements of N slice(s). If the type is different,
-// another slice or undefined, returns an error.
-func sliceElementType(slices ...[]interface{}) (reflect.Type, error) {
- var prevType reflect.Type
- for _, s := range slices {
- // Go through elements of all given slices and make sure they are all the same type.
- for _, v := range s {
- currentType := reflect.TypeOf(v)
- if prevType == nil {
- prevType = currentType
- // We don't support lists of lists yet.
- if prevType.Kind() == reflect.Slice {
- return nil, mergepatch.ErrNoListOfLists
- }
- } else {
- if prevType != currentType {
- return nil, fmt.Errorf("list element types are not identical: %v", fmt.Sprint(slices))
- }
- prevType = currentType
- }
- }
- }
-
- if prevType == nil {
- return nil, fmt.Errorf("no elements in any of the given slices")
- }
-
- return prevType, nil
-}
-
-// MergingMapsHaveConflicts returns true if the left and right JSON interface
-// objects overlap with different values in any key. All keys are required to be
-// strings. Since patches of the same Type have congruent keys, this is valid
-// for multiple patch types. This method supports strategic merge patch semantics.
-func MergingMapsHaveConflicts(left, right map[string]interface{}, schema LookupPatchMeta) (bool, error) {
- return mergingMapFieldsHaveConflicts(left, right, schema, "", "")
-}
-
-func mergingMapFieldsHaveConflicts(
- left, right interface{},
- schema LookupPatchMeta,
- fieldPatchStrategy, fieldPatchMergeKey string,
-) (bool, error) {
- switch leftType := left.(type) {
- case map[string]interface{}:
- rightType, ok := right.(map[string]interface{})
- if !ok {
- return true, nil
- }
- leftMarker, okLeft := leftType[directiveMarker]
- rightMarker, okRight := rightType[directiveMarker]
- // if one or the other has a directive marker,
- // then we need to consider that before looking at the individual keys,
- // since a directive operates on the whole map.
- if okLeft || okRight {
- // if one has a directive marker and the other doesn't,
- // then we have a conflict, since one is deleting or replacing the whole map,
- // and the other is doing things to individual keys.
- if okLeft != okRight {
- return true, nil
- }
- // if they both have markers, but they are not the same directive,
- // then we have a conflict because they're doing different things to the map.
- if leftMarker != rightMarker {
- return true, nil
- }
- }
- if fieldPatchStrategy == replaceDirective {
- return false, nil
- }
- // Check the individual keys.
- return mapsHaveConflicts(leftType, rightType, schema)
-
- case []interface{}:
- rightType, ok := right.([]interface{})
- if !ok {
- return true, nil
- }
- return slicesHaveConflicts(leftType, rightType, schema, fieldPatchStrategy, fieldPatchMergeKey)
- case string, float64, bool, int, int64, nil:
- return !reflect.DeepEqual(left, right), nil
- default:
- return true, fmt.Errorf("unknown type: %v", reflect.TypeOf(left))
- }
-}
-
-func mapsHaveConflicts(typedLeft, typedRight map[string]interface{}, schema LookupPatchMeta) (bool, error) {
- for key, leftValue := range typedLeft {
- if key != directiveMarker && key != retainKeysDirective {
- if rightValue, ok := typedRight[key]; ok {
- var subschema LookupPatchMeta
- var patchMeta PatchMeta
- var patchStrategy string
- var err error
- switch leftValue.(type) {
- case []interface{}:
- subschema, patchMeta, err = schema.LookupPatchMetadataForSlice(key)
- if err != nil {
- return true, err
- }
- _, patchStrategy, err = extractRetainKeysPatchStrategy(patchMeta.patchStrategies)
- if err != nil {
- return true, err
- }
- case map[string]interface{}:
- subschema, patchMeta, err = schema.LookupPatchMetadataForStruct(key)
- if err != nil {
- return true, err
- }
- _, patchStrategy, err = extractRetainKeysPatchStrategy(patchMeta.patchStrategies)
- if err != nil {
- return true, err
- }
- }
-
- if hasConflicts, err := mergingMapFieldsHaveConflicts(leftValue, rightValue,
- subschema, patchStrategy, patchMeta.GetPatchMergeKey()); hasConflicts {
- return true, err
- }
- }
- }
- }
-
- return false, nil
-}
-
-func slicesHaveConflicts(
- typedLeft, typedRight []interface{},
- schema LookupPatchMeta,
- fieldPatchStrategy, fieldPatchMergeKey string,
-) (bool, error) {
- elementType, err := sliceElementType(typedLeft, typedRight)
- if err != nil {
- return true, err
- }
-
- if fieldPatchStrategy == mergeDirective {
- // Merging lists of scalars have no conflicts by definition
- // So we only need to check further if the elements are maps
- if elementType.Kind() != reflect.Map {
- return false, nil
- }
-
- // Build a map for each slice and then compare the two maps
- leftMap, err := sliceOfMapsToMapOfMaps(typedLeft, fieldPatchMergeKey)
- if err != nil {
- return true, err
- }
-
- rightMap, err := sliceOfMapsToMapOfMaps(typedRight, fieldPatchMergeKey)
- if err != nil {
- return true, err
- }
-
- return mapsOfMapsHaveConflicts(leftMap, rightMap, schema)
- }
-
- // Either we don't have type information, or these are non-merging lists
- if len(typedLeft) != len(typedRight) {
- return true, nil
- }
-
- // Sort scalar slices to prevent ordering issues
- // We have no way to sort non-merging lists of maps
- if elementType.Kind() != reflect.Map {
- typedLeft = deduplicateAndSortScalars(typedLeft)
- typedRight = deduplicateAndSortScalars(typedRight)
- }
-
- // Compare the slices element by element in order
- // This test will fail if the slices are not sorted
- for i := range typedLeft {
- if hasConflicts, err := mergingMapFieldsHaveConflicts(typedLeft[i], typedRight[i], schema, "", ""); hasConflicts {
- return true, err
- }
- }
-
- return false, nil
-}
-
-func sliceOfMapsToMapOfMaps(slice []interface{}, mergeKey string) (map[string]interface{}, error) {
- result := make(map[string]interface{}, len(slice))
- for _, value := range slice {
- typedValue, ok := value.(map[string]interface{})
- if !ok {
- return nil, fmt.Errorf("invalid element type in merging list:%v", slice)
- }
-
- mergeValue, ok := typedValue[mergeKey]
- if !ok {
- return nil, fmt.Errorf("cannot find merge key `%s` in merging list element:%v", mergeKey, typedValue)
- }
-
- result[fmt.Sprintf("%s", mergeValue)] = typedValue
- }
-
- return result, nil
-}
-
-func mapsOfMapsHaveConflicts(typedLeft, typedRight map[string]interface{}, schema LookupPatchMeta) (bool, error) {
- for key, leftValue := range typedLeft {
- if rightValue, ok := typedRight[key]; ok {
- if hasConflicts, err := mergingMapFieldsHaveConflicts(leftValue, rightValue, schema, "", ""); hasConflicts {
- return true, err
- }
- }
- }
-
- return false, nil
-}
-
-// CreateThreeWayMergePatch reconciles a modified configuration with an original configuration,
-// while preserving any changes or deletions made to the original configuration in the interim,
-// and not overridden by the current configuration. All three documents must be passed to the
-// method as json encoded content. It will return a strategic merge patch, or an error if any
-// of the documents is invalid, or if there are any preconditions that fail against the modified
-// configuration, or, if overwrite is false and there are conflicts between the modified and current
-// configurations. Conflicts are defined as keys changed differently from original to modified
-// than from original to current. In other words, a conflict occurs if modified changes any key
-// in a way that is different from how it is changed in current (e.g., deleting it, changing its
-// value). We also propagate values fields that do not exist in original but are explicitly
-// defined in modified.
-func CreateThreeWayMergePatch(original, modified, current []byte, schema LookupPatchMeta, overwrite bool, fns ...mergepatch.PreconditionFunc) ([]byte, error) {
- originalMap := map[string]interface{}{}
- if len(original) > 0 {
- if err := json.Unmarshal(original, &originalMap); err != nil {
- return nil, mergepatch.ErrBadJSONDoc
- }
- }
-
- modifiedMap := map[string]interface{}{}
- if len(modified) > 0 {
- if err := json.Unmarshal(modified, &modifiedMap); err != nil {
- return nil, mergepatch.ErrBadJSONDoc
- }
- }
-
- currentMap := map[string]interface{}{}
- if len(current) > 0 {
- if err := json.Unmarshal(current, &currentMap); err != nil {
- return nil, mergepatch.ErrBadJSONDoc
- }
- }
-
- // The patch is the difference from current to modified without deletions, plus deletions
- // from original to modified. To find it, we compute deletions, which are the deletions from
- // original to modified, and delta, which is the difference from current to modified without
- // deletions, and then apply delta to deletions as a patch, which should be strictly additive.
- deltaMapDiffOptions := DiffOptions{
- IgnoreDeletions: true,
- SetElementOrder: true,
- }
- deltaMap, err := diffMaps(currentMap, modifiedMap, schema, deltaMapDiffOptions)
- if err != nil {
- return nil, err
- }
- deletionsMapDiffOptions := DiffOptions{
- SetElementOrder: true,
- IgnoreChangesAndAdditions: true,
- }
- deletionsMap, err := diffMaps(originalMap, modifiedMap, schema, deletionsMapDiffOptions)
- if err != nil {
- return nil, err
- }
-
- mergeOptions := MergeOptions{}
- patchMap, err := mergeMap(deletionsMap, deltaMap, schema, mergeOptions)
- if err != nil {
- return nil, err
- }
-
- // Apply the preconditions to the patch, and return an error if any of them fail.
- for _, fn := range fns {
- if !fn(patchMap) {
- return nil, mergepatch.NewErrPreconditionFailed(patchMap)
- }
- }
-
- // If overwrite is false, and the patch contains any keys that were changed differently,
- // then return a conflict error.
- if !overwrite {
- changeMapDiffOptions := DiffOptions{}
- changedMap, err := diffMaps(originalMap, currentMap, schema, changeMapDiffOptions)
- if err != nil {
- return nil, err
- }
-
- hasConflicts, err := MergingMapsHaveConflicts(patchMap, changedMap, schema)
- if err != nil {
- return nil, err
- }
-
- if hasConflicts {
- return nil, mergepatch.NewErrConflict(mergepatch.ToYAMLOrError(patchMap), mergepatch.ToYAMLOrError(changedMap))
- }
- }
-
- return json.Marshal(patchMap)
-}
-
-func ItemAddedToModifiedSlice(original, modified string) bool { return original > modified }
-
-func ItemRemovedFromModifiedSlice(original, modified string) bool { return original < modified }
-
-func ItemMatchesOriginalAndModifiedSlice(original, modified string) bool { return original == modified }
-
-func CreateDeleteDirective(mergeKey string, mergeKeyValue interface{}) map[string]interface{} {
- return map[string]interface{}{mergeKey: mergeKeyValue, directiveMarker: deleteDirective}
-}
-
-func mapTypeAssertion(original, patch interface{}) (map[string]interface{}, map[string]interface{}, error) {
- typedOriginal, ok := original.(map[string]interface{})
- if !ok {
- return nil, nil, mergepatch.ErrBadArgType(typedOriginal, original)
- }
- typedPatch, ok := patch.(map[string]interface{})
- if !ok {
- return nil, nil, mergepatch.ErrBadArgType(typedPatch, patch)
- }
- return typedOriginal, typedPatch, nil
-}
-
-func sliceTypeAssertion(original, patch interface{}) ([]interface{}, []interface{}, error) {
- typedOriginal, ok := original.([]interface{})
- if !ok {
- return nil, nil, mergepatch.ErrBadArgType(typedOriginal, original)
- }
- typedPatch, ok := patch.([]interface{})
- if !ok {
- return nil, nil, mergepatch.ErrBadArgType(typedPatch, patch)
- }
- return typedOriginal, typedPatch, nil
-}
-
-// extractRetainKeysPatchStrategy process patch strategy, which is a string may contains multiple
-// patch strategies separated by ",". It returns a boolean var indicating if it has
-// retainKeys strategies and a string for the other strategy.
-func extractRetainKeysPatchStrategy(strategies []string) (bool, string, error) {
- switch len(strategies) {
- case 0:
- return false, "", nil
- case 1:
- singleStrategy := strategies[0]
- switch singleStrategy {
- case retainKeysStrategy:
- return true, "", nil
- default:
- return false, singleStrategy, nil
- }
- case 2:
- switch {
- case strategies[0] == retainKeysStrategy:
- return true, strategies[1], nil
- case strategies[1] == retainKeysStrategy:
- return true, strategies[0], nil
- default:
- return false, "", fmt.Errorf("unexpected patch strategy: %v", strategies)
- }
- default:
- return false, "", fmt.Errorf("unexpected patch strategy: %v", strategies)
- }
-}
-
-// hasAdditionalNewField returns if original map has additional key with non-nil value than modified.
-func hasAdditionalNewField(original, modified map[string]interface{}) bool {
- for k, v := range original {
- if v == nil {
- continue
- }
- if _, found := modified[k]; !found {
- return true
- }
- }
- return false
-}
diff --git a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/types.go b/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/types.go
deleted file mode 100644
index f84d65aac..000000000
--- a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/types.go
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
-Copyright 2017 The 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 strategicpatch
-
-import (
- "errors"
- "strings"
-
- "k8s.io/apimachinery/pkg/util/mergepatch"
- openapi "k8s.io/kube-openapi/pkg/util/proto"
-)
-
-const (
- patchStrategyOpenapiextensionKey = "x-kubernetes-patch-strategy"
- patchMergeKeyOpenapiextensionKey = "x-kubernetes-patch-merge-key"
-)
-
-type LookupPatchItem interface {
- openapi.SchemaVisitor
-
- Error() error
- Path() *openapi.Path
-}
-
-type kindItem struct {
- key string
- path *openapi.Path
- err error
- patchmeta PatchMeta
- subschema openapi.Schema
- hasVisitKind bool
-}
-
-func NewKindItem(key string, path *openapi.Path) *kindItem {
- return &kindItem{
- key: key,
- path: path,
- }
-}
-
-var _ LookupPatchItem = &kindItem{}
-
-func (item *kindItem) Error() error {
- return item.err
-}
-
-func (item *kindItem) Path() *openapi.Path {
- return item.path
-}
-
-func (item *kindItem) VisitPrimitive(schema *openapi.Primitive) {
- item.err = errors.New("expected kind, but got primitive")
-}
-
-func (item *kindItem) VisitArray(schema *openapi.Array) {
- item.err = errors.New("expected kind, but got slice")
-}
-
-func (item *kindItem) VisitMap(schema *openapi.Map) {
- item.err = errors.New("expected kind, but got map")
-}
-
-func (item *kindItem) VisitReference(schema openapi.Reference) {
- if !item.hasVisitKind {
- schema.SubSchema().Accept(item)
- }
-}
-
-func (item *kindItem) VisitKind(schema *openapi.Kind) {
- subschema, ok := schema.Fields[item.key]
- if !ok {
- item.err = FieldNotFoundError{Path: schema.GetPath().String(), Field: item.key}
- return
- }
-
- mergeKey, patchStrategies, err := parsePatchMetadata(subschema.GetExtensions())
- if err != nil {
- item.err = err
- return
- }
- item.patchmeta = PatchMeta{
- patchStrategies: patchStrategies,
- patchMergeKey: mergeKey,
- }
- item.subschema = subschema
-}
-
-type sliceItem struct {
- key string
- path *openapi.Path
- err error
- patchmeta PatchMeta
- subschema openapi.Schema
- hasVisitKind bool
-}
-
-func NewSliceItem(key string, path *openapi.Path) *sliceItem {
- return &sliceItem{
- key: key,
- path: path,
- }
-}
-
-var _ LookupPatchItem = &sliceItem{}
-
-func (item *sliceItem) Error() error {
- return item.err
-}
-
-func (item *sliceItem) Path() *openapi.Path {
- return item.path
-}
-
-func (item *sliceItem) VisitPrimitive(schema *openapi.Primitive) {
- item.err = errors.New("expected slice, but got primitive")
-}
-
-func (item *sliceItem) VisitArray(schema *openapi.Array) {
- if !item.hasVisitKind {
- item.err = errors.New("expected visit kind first, then visit array")
- }
- subschema := schema.SubType
- item.subschema = subschema
-}
-
-func (item *sliceItem) VisitMap(schema *openapi.Map) {
- item.err = errors.New("expected slice, but got map")
-}
-
-func (item *sliceItem) VisitReference(schema openapi.Reference) {
- if !item.hasVisitKind {
- schema.SubSchema().Accept(item)
- } else {
- item.subschema = schema.SubSchema()
- }
-}
-
-func (item *sliceItem) VisitKind(schema *openapi.Kind) {
- subschema, ok := schema.Fields[item.key]
- if !ok {
- item.err = FieldNotFoundError{Path: schema.GetPath().String(), Field: item.key}
- return
- }
-
- mergeKey, patchStrategies, err := parsePatchMetadata(subschema.GetExtensions())
- if err != nil {
- item.err = err
- return
- }
- item.patchmeta = PatchMeta{
- patchStrategies: patchStrategies,
- patchMergeKey: mergeKey,
- }
- item.hasVisitKind = true
- subschema.Accept(item)
-}
-
-func parsePatchMetadata(extensions map[string]interface{}) (string, []string, error) {
- ps, foundPS := extensions[patchStrategyOpenapiextensionKey]
- var patchStrategies []string
- var mergeKey, patchStrategy string
- var ok bool
- if foundPS {
- patchStrategy, ok = ps.(string)
- if ok {
- patchStrategies = strings.Split(patchStrategy, ",")
- } else {
- return "", nil, mergepatch.ErrBadArgType(patchStrategy, ps)
- }
- }
- mk, foundMK := extensions[patchMergeKeyOpenapiextensionKey]
- if foundMK {
- mergeKey, ok = mk.(string)
- if !ok {
- return "", nil, mergepatch.ErrBadArgType(mergeKey, mk)
- }
- }
- return mergeKey, patchStrategies, nil
-}