Update ingress godeps

This commit is contained in:
Manuel de Brito Fontes 2016-08-10 14:53:55 -04:00
parent d43021b3f1
commit 28db8fb16d
1068 changed files with 461467 additions and 117300 deletions

View file

@ -80,12 +80,14 @@ func EncodeOrDie(e Encoder, obj Object) string {
// invokes the ObjectCreator to instantiate a new gvk. Returns an error if the typer cannot find the object.
func UseOrCreateObject(t ObjectTyper, c ObjectCreater, gvk unversioned.GroupVersionKind, obj Object) (Object, error) {
if obj != nil {
into, _, err := t.ObjectKinds(obj)
kinds, _, err := t.ObjectKinds(obj)
if err != nil {
return nil, err
}
if gvk == into[0] {
return obj, nil
for _, kind := range kinds {
if gvk == kind {
return obj, nil
}
}
}
return c.New(gvk)
@ -143,16 +145,16 @@ func (c *parameterCodec) DecodeParameters(parameters url.Values, from unversione
}
targetGVK := targetGVKs[0]
if targetGVK.GroupVersion() == from {
return c.convertor.Convert(&parameters, into)
return c.convertor.Convert(&parameters, into, nil)
}
input, err := c.creator.New(from.WithKind(targetGVK.Kind))
if err != nil {
return err
}
if err := c.convertor.Convert(&parameters, input); err != nil {
if err := c.convertor.Convert(&parameters, input, nil); err != nil {
return err
}
return c.convertor.Convert(input, into)
return c.convertor.Convert(input, into, nil)
}
// EncodeParameters converts the provided object into the to version, then converts that object to url.Values.
@ -196,3 +198,83 @@ func (s base64Serializer) Decode(data []byte, defaults *unversioned.GroupVersion
}
return s.Serializer.Decode(out[:n], defaults, into)
}
var (
// InternalGroupVersioner will always prefer the internal version for a given group version kind.
InternalGroupVersioner GroupVersioner = internalGroupVersioner{}
// DisabledGroupVersioner will reject all kinds passed to it.
DisabledGroupVersioner GroupVersioner = disabledGroupVersioner{}
)
type internalGroupVersioner struct{}
// KindForGroupVersionKinds returns an internal Kind if one is found, or converts the first provided kind to the internal version.
func (internalGroupVersioner) KindForGroupVersionKinds(kinds []unversioned.GroupVersionKind) (unversioned.GroupVersionKind, bool) {
for _, kind := range kinds {
if kind.Version == APIVersionInternal {
return kind, true
}
}
for _, kind := range kinds {
return unversioned.GroupVersionKind{Group: kind.Group, Version: APIVersionInternal, Kind: kind.Kind}, true
}
return unversioned.GroupVersionKind{}, false
}
type disabledGroupVersioner struct{}
// KindForGroupVersionKinds returns false for any input.
func (disabledGroupVersioner) KindForGroupVersionKinds(kinds []unversioned.GroupVersionKind) (unversioned.GroupVersionKind, bool) {
return unversioned.GroupVersionKind{}, false
}
// GroupVersioners implements GroupVersioner and resolves to the first exact match for any kind.
type GroupVersioners []GroupVersioner
// KindForGroupVersionKinds returns the first match of any of the group versioners, or false if no match occured.
func (gvs GroupVersioners) KindForGroupVersionKinds(kinds []unversioned.GroupVersionKind) (unversioned.GroupVersionKind, bool) {
for _, gv := range gvs {
target, ok := gv.KindForGroupVersionKinds(kinds)
if !ok {
continue
}
return target, true
}
return unversioned.GroupVersionKind{}, false
}
// Assert that unversioned.GroupVersion and GroupVersions implement GroupVersioner
var _ GroupVersioner = unversioned.GroupVersion{}
var _ GroupVersioner = unversioned.GroupVersions{}
var _ GroupVersioner = multiGroupVersioner{}
type multiGroupVersioner struct {
target unversioned.GroupVersion
acceptedGroupKinds []unversioned.GroupKind
}
// NewMultiGroupVersioner returns the provided group version for any kind that matches one of the provided group kinds.
// Kind may be empty in the provided group kind, in which case any kind will match.
func NewMultiGroupVersioner(gv unversioned.GroupVersion, groupKinds ...unversioned.GroupKind) GroupVersioner {
if len(groupKinds) == 0 || (len(groupKinds) == 1 && groupKinds[0].Group == gv.Group) {
return gv
}
return multiGroupVersioner{target: gv, acceptedGroupKinds: groupKinds}
}
// KindForGroupVersionKinds returns the target group version if any kind matches any of the original group kinds. It will
// use the originating kind where possible.
func (v multiGroupVersioner) KindForGroupVersionKinds(kinds []unversioned.GroupVersionKind) (unversioned.GroupVersionKind, bool) {
for _, src := range kinds {
for _, kind := range v.acceptedGroupKinds {
if kind.Group != src.Group {
continue
}
if len(kind.Kind) > 0 && kind.Kind != src.Kind {
continue
}
return v.target.WithKind(src.Kind), true
}
}
return unversioned.GroupVersionKind{}, false
}

View file

@ -1,63 +0,0 @@
// +build !ignore_autogenerated
/*
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.
*/
// This file was autogenerated by deepcopy-gen. Do not edit it manually!
package runtime
import (
conversion "k8s.io/kubernetes/pkg/conversion"
)
func DeepCopy_runtime_RawExtension(in RawExtension, out *RawExtension, c *conversion.Cloner) error {
if in.Raw != nil {
in, out := in.Raw, &out.Raw
*out = make([]byte, len(in))
copy(*out, in)
} else {
out.Raw = nil
}
if in.Object == nil {
out.Object = nil
} else if newVal, err := c.DeepCopy(in.Object); err != nil {
return err
} else {
out.Object = newVal.(Object)
}
return nil
}
func DeepCopy_runtime_TypeMeta(in TypeMeta, out *TypeMeta, c *conversion.Cloner) error {
out.APIVersion = in.APIVersion
out.Kind = in.Kind
return nil
}
func DeepCopy_runtime_Unknown(in Unknown, out *Unknown, c *conversion.Cloner) error {
out.TypeMeta = in.TypeMeta
if in.Raw != nil {
in, out := in.Raw, &out.Raw
*out = make([]byte, len(in))
copy(*out, in)
} else {
out.Raw = nil
}
out.ContentEncoding = in.ContentEncoding
out.ContentType = in.ContentType
return nil
}

View file

@ -84,7 +84,7 @@ type missingVersionErr struct {
}
// IsMissingVersion returns true if the error indicates that the provided object
// is missing a 'Versioj' field.
// is missing a 'Version' field.
func NewMissingVersionErr(data string) error {
return &missingVersionErr{data}
}

View file

@ -35,6 +35,9 @@ 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.
@ -42,17 +45,21 @@ var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
func (m *RawExtension) Reset() { *m = RawExtension{} }
func (m *RawExtension) String() string { return proto.CompactTextString(m) }
func (*RawExtension) ProtoMessage() {}
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
const _ = proto.GoGoProtoPackageIsVersion1
func (m *TypeMeta) Reset() { *m = TypeMeta{} }
func (m *TypeMeta) String() string { return proto.CompactTextString(m) }
func (*TypeMeta) ProtoMessage() {}
func (m *RawExtension) Reset() { *m = RawExtension{} }
func (*RawExtension) ProtoMessage() {}
func (*RawExtension) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{0} }
func (m *Unknown) Reset() { *m = Unknown{} }
func (m *Unknown) String() string { return proto.CompactTextString(m) }
func (*Unknown) ProtoMessage() {}
func (m *TypeMeta) Reset() { *m = TypeMeta{} }
func (*TypeMeta) ProtoMessage() {}
func (*TypeMeta) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{1} }
func (m *Unknown) Reset() { *m = Unknown{} }
func (*Unknown) ProtoMessage() {}
func (*Unknown) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{2} }
func init() {
proto.RegisterType((*RawExtension)(nil), "k8s.io.kubernetes.pkg.runtime.RawExtension")
@ -225,6 +232,48 @@ func sovGenerated(x uint64) (n int) {
func sozGenerated(x uint64) (n int) {
return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *RawExtension) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&RawExtension{`,
`Raw:` + valueToStringGenerated(this.Raw) + `,`,
`}`,
}, "")
return s
}
func (this *TypeMeta) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TypeMeta{`,
`APIVersion:` + fmt.Sprintf("%v", this.APIVersion) + `,`,
`Kind:` + fmt.Sprintf("%v", this.Kind) + `,`,
`}`,
}, "")
return s
}
func (this *Unknown) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&Unknown{`,
`TypeMeta:` + strings.Replace(strings.Replace(this.TypeMeta.String(), "TypeMeta", "TypeMeta", 1), `&`, ``, 1) + `,`,
`Raw:` + valueToStringGenerated(this.Raw) + `,`,
`ContentEncoding:` + fmt.Sprintf("%v", this.ContentEncoding) + `,`,
`ContentType:` + fmt.Sprintf("%v", this.ContentType) + `,`,
`}`,
}, "")
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 *RawExtension) Unmarshal(data []byte) error {
l := len(data)
iNdEx := 0
@ -687,3 +736,31 @@ var (
ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow")
)
var fileDescriptorGenerated = []byte{
// 380 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x7c, 0x90, 0xcf, 0x4e, 0x2a, 0x31,
0x14, 0xc6, 0x19, 0x20, 0x81, 0x5b, 0x48, 0xb8, 0xe9, 0x5d, 0xdc, 0x91, 0x44, 0x20, 0x6c, 0x94,
0x05, 0x6d, 0x24, 0x31, 0x71, 0xcb, 0x10, 0x16, 0xc6, 0x98, 0x98, 0x89, 0xb8, 0x70, 0xe5, 0x30,
0xd4, 0xb1, 0x19, 0x69, 0x27, 0x9d, 0x4e, 0xd0, 0x9d, 0x8f, 0xe0, 0x63, 0xb1, 0x64, 0xe9, 0x8a,
0x28, 0x3e, 0x83, 0x7b, 0x4b, 0x29, 0x7f, 0x04, 0xe2, 0xe2, 0x24, 0x33, 0xe7, 0xfc, 0xbe, 0xef,
0x7c, 0xa7, 0xa0, 0x19, 0x9e, 0xc5, 0x88, 0x72, 0x1c, 0x26, 0x7d, 0x22, 0x18, 0x91, 0x24, 0xc6,
0x51, 0x18, 0x60, 0x91, 0x30, 0x49, 0x87, 0x04, 0x07, 0x84, 0x11, 0xe1, 0x49, 0x32, 0x40, 0x91,
0xe0, 0x92, 0xc3, 0xc3, 0x05, 0x8e, 0xd6, 0x38, 0x52, 0x38, 0x32, 0x78, 0xb9, 0x19, 0x50, 0xf9,
0x90, 0xf4, 0x91, 0xcf, 0x87, 0x38, 0xe0, 0x01, 0xc7, 0x5a, 0xd5, 0x4f, 0xee, 0xf5, 0x9f, 0xfe,
0xd1, 0x5f, 0x0b, 0xb7, 0x72, 0x6b, 0xff, 0x72, 0x2f, 0xa2, 0x58, 0x90, 0x98, 0x27, 0xc2, 0xdf,
0x49, 0x50, 0x3e, 0xd9, 0xaf, 0x49, 0x24, 0x7d, 0xc4, 0x94, 0xc9, 0x58, 0x8a, 0x6d, 0x49, 0xbd,
0x01, 0x8a, 0xae, 0x37, 0xea, 0x3e, 0x49, 0xc2, 0x62, 0xca, 0x19, 0x3c, 0x00, 0x19, 0xe1, 0x8d,
0x6c, 0xab, 0x66, 0x1d, 0x17, 0x9d, 0xdc, 0x6c, 0x5a, 0xcd, 0xa8, 0xb1, 0x3b, 0xef, 0xd5, 0xef,
0x40, 0xfe, 0xfa, 0x39, 0x22, 0x97, 0x44, 0x7a, 0xb0, 0x05, 0x80, 0x4a, 0x72, 0x43, 0xc4, 0x5c,
0xa4, 0xe9, 0x3f, 0x0e, 0x1c, 0x4f, 0xab, 0x29, 0xa5, 0x00, 0xed, 0xab, 0x73, 0x33, 0x71, 0x37,
0x28, 0x58, 0x03, 0xd9, 0x90, 0xb2, 0x81, 0x9d, 0xd6, 0x74, 0xd1, 0xd0, 0xd9, 0x0b, 0xd5, 0x73,
0xf5, 0xa4, 0xfe, 0x65, 0x81, 0x5c, 0x8f, 0x85, 0x8c, 0x8f, 0x18, 0xec, 0x81, 0xbc, 0x34, 0xdb,
0xb4, 0x7f, 0xa1, 0x75, 0x84, 0x7e, 0x7d, 0x60, 0xb4, 0x0c, 0xe7, 0xfc, 0x35, 0xd6, 0xab, 0xb8,
0xee, 0xca, 0x6a, 0x79, 0x5f, 0x7a, 0xf7, 0x3e, 0xd8, 0x06, 0x25, 0x9f, 0x33, 0xf5, 0x10, 0xb2,
0xcb, 0x7c, 0x3e, 0xa0, 0x2c, 0xb0, 0x33, 0x3a, 0xea, 0x7f, 0xe3, 0x57, 0xea, 0xfc, 0x1c, 0xbb,
0xdb, 0x3c, 0x3c, 0x05, 0x05, 0xd3, 0x9a, 0xaf, 0xb6, 0xb3, 0x5a, 0xfe, 0xcf, 0xc8, 0x0b, 0x9d,
0xf5, 0xc8, 0xdd, 0xe4, 0x9c, 0xc6, 0xf8, 0xa3, 0x92, 0x9a, 0xa8, 0x7a, 0x53, 0xf5, 0x32, 0xab,
0x58, 0x63, 0x55, 0x13, 0x55, 0xef, 0xaa, 0x5e, 0x3f, 0x2b, 0xa9, 0xdb, 0x9c, 0x39, 0xf2, 0x3b,
0x00, 0x00, 0xff, 0xff, 0x32, 0xc1, 0x73, 0x2d, 0x94, 0x02, 0x00, 0x00,
}

View file

@ -35,7 +35,7 @@ var _ ObjectConvertor = unsafeObjectConvertor{}
// ConvertToVersion converts in to the provided outVersion without copying the input first, which
// is only safe if the output object is not mutated or reused.
func (c unsafeObjectConvertor) ConvertToVersion(in Object, outVersion unversioned.GroupVersion) (Object, error) {
func (c unsafeObjectConvertor) ConvertToVersion(in Object, outVersion GroupVersioner) (Object, error) {
return c.Scheme.UnsafeConvertToVersion(in, outVersion)
}

View file

@ -30,12 +30,23 @@ const (
APIVersionInternal = "__internal"
)
// GroupVersioner refines a set of possible conversion targets into a single option.
type GroupVersioner interface {
// KindForGroupVersionKinds returns a desired target group version kind for the given input, or returns ok false if no
// target is known. In general, if the return target is not in the input list, the caller is expected to invoke
// Scheme.New(target) and then perform a conversion between the current Go type and the destination Go type.
// Sophisticated implementations may use additional information about the input kinds to pick a destination kind.
KindForGroupVersionKinds(kinds []unversioned.GroupVersionKind) (target unversioned.GroupVersionKind, ok bool)
}
// Encoders write objects to a serialized form
type Encoder interface {
// Encode writes an object to a stream. Implementations may return errors if the versions are
// incompatible, or if no conversion is defined.
Encode(obj Object, w io.Writer) error
}
// Decoders attempt to load an object from data.
type Decoder interface {
// Decode attempts to deserialize the provided data using either the innate typing of the scheme or the
// default kind, group, and version provided. It returns a decoded object as well as the kind, group, and
@ -117,12 +128,10 @@ type NegotiatedSerializer interface {
// EncoderForVersion returns an encoder that ensures objects being written to the provided
// serializer are in the provided group version.
// TODO: take multiple group versions
EncoderForVersion(serializer Encoder, gv unversioned.GroupVersion) Encoder
EncoderForVersion(serializer Encoder, gv GroupVersioner) Encoder
// DecoderForVersion returns a decoder that ensures objects being read by the provided
// serializer are in the provided group version by default.
// TODO: take multiple group versions
DecoderToVersion(serializer Decoder, gv unversioned.GroupVersion) Decoder
DecoderToVersion(serializer Decoder, gv GroupVersioner) Decoder
}
// StorageSerializer is an interface used for obtaining encoders, decoders, and serializers
@ -139,29 +148,41 @@ type StorageSerializer interface {
// EncoderForVersion returns an encoder that ensures objects being written to the provided
// serializer are in the provided group version.
// TODO: take multiple group versions
EncoderForVersion(serializer Encoder, gv unversioned.GroupVersion) Encoder
EncoderForVersion(serializer Encoder, gv GroupVersioner) Encoder
// DecoderForVersion returns a decoder that ensures objects being read by the provided
// serializer are in the provided group version by default.
// TODO: take multiple group versions
DecoderToVersion(serializer Decoder, gv unversioned.GroupVersion) Decoder
DecoderToVersion(serializer Decoder, gv GroupVersioner) Decoder
}
// NestedObjectEncoder is an optional interface that objects may implement to be given
// an opportunity to encode any nested Objects / RawExtensions during serialization.
type NestedObjectEncoder interface {
EncodeNestedObjects(e Encoder) error
}
// NestedObjectDecoder is an optional interface that objects may implement to be given
// an opportunity to decode any nested Objects / RawExtensions during serialization.
type NestedObjectDecoder interface {
DecodeNestedObjects(d Decoder) error
}
///////////////////////////////////////////////////////////////////////////////
// Non-codec interfaces
type ObjectVersioner interface {
ConvertToVersion(in Object, outVersion unversioned.GroupVersion) (out Object, err error)
ConvertToVersion(in Object, gv GroupVersioner) (out Object, err error)
}
// ObjectConvertor converts an object to a different version.
type ObjectConvertor interface {
// Convert attempts to convert one object into another, or returns an error. This method does
// not guarantee the in object is not mutated.
Convert(in, out interface{}) error
// not guarantee the in object is not mutated. The context argument will be passed to
// all nested conversions.
Convert(in, out, context interface{}) error
// ConvertToVersion takes the provided object and converts it the provided version. This
// method does not guarantee that the in object is not mutated.
ConvertToVersion(in Object, outVersion unversioned.GroupVersion) (out Object, err error)
// method does not guarantee that the in object is not mutated. This method is similar to
// Convert() but handles specific details of choosing the correct output version.
ConvertToVersion(in Object, gv GroupVersioner) (out Object, err error)
ConvertFieldLabel(version, kind, label, value string) (string, string, error)
}

View file

@ -211,6 +211,11 @@ func (s *Scheme) KnownTypes(gv unversioned.GroupVersion) map[string]reflect.Type
return types
}
// AllKnownTypes returns the all known types.
func (s *Scheme) AllKnownTypes() map[unversioned.GroupVersionKind]reflect.Type {
return s.gvkToType
}
// ObjectKind returns the group,version,kind of the go object and true if this object
// is considered unversioned, or an error if it's not a pointer or is unregistered.
func (s *Scheme) ObjectKind(obj Object) (unversioned.GroupVersionKind, bool, error) {
@ -232,7 +237,7 @@ func (s *Scheme) ObjectKinds(obj Object) ([]unversioned.GroupVersionKind, bool,
gvks, ok := s.typeToGVK[t]
if !ok {
return nil, false, &notRegisteredErr{t: t}
return nil, false, NewNotRegisteredErr(unversioned.GroupVersionKind{}, t)
}
_, unversionedType := s.unversionedTypes[t]
@ -270,7 +275,7 @@ func (s *Scheme) New(kind unversioned.GroupVersionKind) (Object, error) {
if t, exists := s.unversionedKinds[kind.Kind]; exists {
return reflect.New(t).Interface().(Object), nil
}
return nil, &notRegisteredErr{gvk: kind}
return nil, NewNotRegisteredErr(kind, nil)
}
// AddGenericConversionFunc adds a function that accepts the ConversionFunc call pattern
@ -357,9 +362,9 @@ func (s *Scheme) AddDeepCopyFuncs(deepCopyFuncs ...interface{}) error {
// Similar to AddDeepCopyFuncs, but registers deep-copy functions that were
// automatically generated.
func (s *Scheme) AddGeneratedDeepCopyFuncs(deepCopyFuncs ...interface{}) error {
for _, f := range deepCopyFuncs {
if err := s.cloner.RegisterGeneratedDeepCopyFunc(f); err != nil {
func (s *Scheme) AddGeneratedDeepCopyFuncs(deepCopyFuncs ...conversion.GeneratedDeepCopyFunc) error {
for _, fn := range deepCopyFuncs {
if err := s.cloner.RegisterGeneratedDeepCopyFunc(fn); err != nil {
return err
}
}
@ -433,23 +438,13 @@ func (s *Scheme) DeepCopy(src interface{}) (interface{}, error) {
// Convert will attempt to convert in into out. Both must be pointers. For easy
// testing of conversion functions. Returns an error if the conversion isn't
// possible. You can call this with types that haven't been registered (for example,
// a to test conversion of types that are nested within registered types), but in
// that case, the conversion.Scope object passed to your conversion functions won't
// have SrcVersion or DestVersion fields set correctly in Meta().
func (s *Scheme) Convert(in, out interface{}) error {
inVersion := unversioned.GroupVersion{Group: "unknown", Version: "unknown"}
outVersion := unversioned.GroupVersion{Group: "unknown", Version: "unknown"}
if inObj, ok := in.(Object); ok {
if gvks, _, err := s.ObjectKinds(inObj); err == nil {
inVersion = gvks[0].GroupVersion()
}
}
if outObj, ok := out.(Object); ok {
if gvks, _, err := s.ObjectKinds(outObj); err == nil {
outVersion = gvks[0].GroupVersion()
}
}
flags, meta := s.generateConvertMeta(inVersion, outVersion, in)
// a to test conversion of types that are nested within registered types). The
// context interface is passed to the convertor.
// TODO: identify whether context should be hidden, or behind a formal context/scope
// interface
func (s *Scheme) Convert(in, out interface{}, context interface{}) error {
flags, meta := s.generateConvertMeta(in)
meta.Context = context
if flags == 0 {
flags = conversion.AllowDifferentFieldTypeNames
}
@ -473,73 +468,20 @@ func (s *Scheme) ConvertFieldLabel(version, kind, label, value string) (string,
// version within this scheme. Will return an error if the provided version does not
// contain the inKind (or a mapping by name defined with AddKnownTypeWithName). Will also
// return an error if the conversion does not result in a valid Object being
// returned. The serializer handles loading/serializing nested objects.
func (s *Scheme) ConvertToVersion(in Object, outVersion unversioned.GroupVersion) (Object, error) {
switch in.(type) {
case *Unknown, *Unstructured, *UnstructuredList:
old := in.GetObjectKind().GroupVersionKind()
defer in.GetObjectKind().SetGroupVersionKind(old)
setTargetVersion(in, s, outVersion)
return in, nil
}
t := reflect.TypeOf(in)
if t.Kind() != reflect.Ptr {
return nil, fmt.Errorf("only pointer types may be converted: %v", t)
}
t = t.Elem()
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf("only pointers to struct types may be converted: %v", t)
}
var kind unversioned.GroupVersionKind
if unversionedKind, ok := s.unversionedTypes[t]; ok {
kind = unversionedKind
} else {
kinds, ok := s.typeToGVK[t]
if !ok || len(kinds) == 0 {
return nil, fmt.Errorf("%v is not a registered type and cannot be converted into version %q", t, outVersion)
}
kind = kinds[0]
}
outKind := outVersion.WithKind(kind.Kind)
inKinds, _, err := s.ObjectKinds(in)
if err != nil {
return nil, err
}
out, err := s.New(outKind)
if err != nil {
return nil, err
}
flags, meta := s.generateConvertMeta(inKinds[0].GroupVersion(), outVersion, in)
if err := s.converter.Convert(in, out, flags, meta); err != nil {
return nil, err
}
setTargetVersion(out, s, outVersion)
return out, nil
// returned. Passes target down to the conversion methods as the Context on the scope.
func (s *Scheme) ConvertToVersion(in Object, target GroupVersioner) (Object, error) {
return s.convertToVersion(true, in, target)
}
// UnsafeConvertToVersion will convert in to the provided outVersion if such a conversion is possible,
// UnsafeConvertToVersion will convert in to the provided target if such a conversion is possible,
// but does not guarantee the output object does not share fields with the input object. It attempts to be as
// efficient as possible when doing conversion.
func (s *Scheme) UnsafeConvertToVersion(in Object, outVersion unversioned.GroupVersion) (Object, error) {
switch t := in.(type) {
case *Unknown:
t.APIVersion = outVersion.String()
return t, nil
case *Unstructured:
t.SetAPIVersion(outVersion.String())
return t, nil
case *UnstructuredList:
t.SetAPIVersion(outVersion.String())
return t, nil
}
func (s *Scheme) UnsafeConvertToVersion(in Object, target GroupVersioner) (Object, error) {
return s.convertToVersion(false, in, target)
}
// convertToVersion handles conversion with an optional copy.
func (s *Scheme) convertToVersion(copy bool, in Object, target GroupVersioner) (Object, error) {
// determine the incoming kinds with as few allocations as possible.
t := reflect.TypeOf(in)
if t.Kind() != reflect.Ptr {
@ -551,64 +493,69 @@ func (s *Scheme) UnsafeConvertToVersion(in Object, outVersion unversioned.GroupV
}
kinds, ok := s.typeToGVK[t]
if !ok || len(kinds) == 0 {
return nil, fmt.Errorf("%v is not a registered type and cannot be converted into version %q", t, outVersion)
return nil, NewNotRegisteredErr(unversioned.GroupVersionKind{}, t)
}
// if the Go type is also registered to the destination kind, no conversion is necessary
for i := range kinds {
if kinds[i].Version == outVersion.Version && kinds[i].Group == outVersion.Group {
setTargetKind(in, kinds[i])
return in, nil
gvk, ok := target.KindForGroupVersionKinds(kinds)
if !ok {
// TODO: should this be a typed error?
return nil, fmt.Errorf("%v is not suitable for converting to %q", t, target)
}
// target wants to use the existing type, set kind and return (no conversion necessary)
for _, kind := range kinds {
if gvk == kind {
return copyAndSetTargetKind(copy, s, in, gvk)
}
}
// type is unversioned, no conversion necessary
// it should be possible to avoid this allocation
if unversionedKind, ok := s.unversionedTypes[t]; ok {
kind := unversionedKind
outKind := outVersion.WithKind(kind.Kind)
setTargetKind(in, outKind)
return in, nil
if gvk, ok := target.KindForGroupVersionKinds([]unversioned.GroupVersionKind{unversionedKind}); ok {
return copyAndSetTargetKind(copy, s, in, gvk)
}
return copyAndSetTargetKind(copy, s, in, unversionedKind)
}
// allocate a new object as the target using the target kind
// TODO: this should look in the target group version and find the first kind that matches, rather than the
// first kind registered in typeToGVK
kind := kinds[0]
kind.Version = outVersion.Version
kind.Group = outVersion.Group
out, err := s.New(kind)
out, err := s.New(gvk)
if err != nil {
return nil, err
}
// TODO: try to avoid the allocations here - in fast paths we are not likely to need these flags or meta
flags, meta := s.converter.DefaultMeta(t)
if copy {
copied, err := s.Copy(in)
if err != nil {
return nil, err
}
in = copied
}
flags, meta := s.generateConvertMeta(in)
meta.Context = target
if err := s.converter.Convert(in, out, flags, meta); err != nil {
return nil, err
}
setTargetKind(out, kind)
setTargetKind(out, gvk)
return out, nil
}
// generateConvertMeta constructs the meta value we pass to Convert.
func (s *Scheme) generateConvertMeta(srcGroupVersion, destGroupVersion unversioned.GroupVersion, in interface{}) (conversion.FieldMatchingFlags, *conversion.Meta) {
func (s *Scheme) generateConvertMeta(in interface{}) (conversion.FieldMatchingFlags, *conversion.Meta) {
return s.converter.DefaultMeta(reflect.TypeOf(in))
}
// setTargetVersion is deprecated and should be replaced by use of setTargetKind
func setTargetVersion(obj Object, raw *Scheme, gv unversioned.GroupVersion) {
if gv.Version == APIVersionInternal {
// internal is a special case
obj.GetObjectKind().SetGroupVersionKind(unversioned.GroupVersionKind{})
return
}
if gvks, _, _ := raw.ObjectKinds(obj); len(gvks) > 0 {
obj.GetObjectKind().SetGroupVersionKind(unversioned.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: gvks[0].Kind})
} else {
obj.GetObjectKind().SetGroupVersionKind(unversioned.GroupVersionKind{Group: gv.Group, Version: gv.Version})
// copyAndSetTargetKind performs a conditional copy before returning the object, or an error if copy was not successful.
func copyAndSetTargetKind(copy bool, copier ObjectCopier, obj Object, kind unversioned.GroupVersionKind) (Object, error) {
if copy {
copied, err := copier.Copy(obj)
if err != nil {
return nil, err
}
obj = copied
}
setTargetKind(obj, kind)
return obj, nil
}
// setTargetKind sets the kind on an object, taking into account whether the target kind is the internal version.

48
vendor/k8s.io/kubernetes/pkg/runtime/scheme_builder.go generated vendored Normal file
View file

@ -0,0 +1,48 @@
/*
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 runtime
// SchemeBuilder collects functions that add things to a scheme. It's to allow
// code to compile without explicitly referencing generated types. You should
// declare one in each package that will have generated deep copy or conversion
// functions.
type SchemeBuilder []func(*Scheme) error
// AddToScheme applies all the stored functions to the scheme. A non-nil error
// indicates that one function failed and the attempt was abandoned.
func (sb *SchemeBuilder) AddToScheme(s *Scheme) error {
for _, f := range *sb {
if err := f(s); err != nil {
return err
}
}
return nil
}
// Register adds a scheme setup function to the list.
func (sb *SchemeBuilder) Register(funcs ...func(*Scheme) error) {
for _, f := range funcs {
*sb = append(*sb, f)
}
}
// NewSchemeBuilder calls Register for you.
func NewSchemeBuilder(funcs ...func(*Scheme) error) SchemeBuilder {
var sb SchemeBuilder
sb.Register(funcs...)
return sb
}

View file

@ -17,8 +17,6 @@ limitations under the License.
package serializer
import (
"io"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/runtime/serializer/json"
@ -188,13 +186,17 @@ func (f CodecFactory) SupportedStreamingMediaTypes() []string {
return f.streamingAccepts
}
// LegacyCodec encodes output to a given API version, and decodes output into the internal form from
// any recognized source. The returned codec will always encode output to JSON.
// LegacyCodec encodes output to a given API versions, and decodes output into the internal form from
// any recognized source. The returned codec will always encode output to JSON. If a type is not
// found in the list of versions an error will be returned.
//
// This method is deprecated - clients and servers should negotiate a serializer by mime-type and
// invoke CodecForVersions. Callers that need only to read data should use UniversalDecoder().
//
// TODO: make this call exist only in pkg/api, and initialize it with the set of default versions.
// All other callers will be forced to request a Codec directly.
func (f CodecFactory) LegacyCodec(version ...unversioned.GroupVersion) runtime.Codec {
return versioning.NewCodecForScheme(f.scheme, f.legacySerializer, f.universal, version, nil)
return versioning.NewCodecForScheme(f.scheme, f.legacySerializer, f.universal, unversioned.GroupVersions(version), runtime.InternalGroupVersioner)
}
// UniversalDeserializer can convert any stored data recognized by this factory into a Go object that satisfies
@ -211,25 +213,39 @@ func (f CodecFactory) UniversalDeserializer() runtime.Decoder {
// defaulting.
//
// TODO: the decoder will eventually be removed in favor of dealing with objects in their versioned form
// TODO: only accept a group versioner
func (f CodecFactory) UniversalDecoder(versions ...unversioned.GroupVersion) runtime.Decoder {
return f.CodecForVersions(nil, f.universal, nil, versions)
var versioner runtime.GroupVersioner
if len(versions) == 0 {
versioner = runtime.InternalGroupVersioner
} else {
versioner = unversioned.GroupVersions(versions)
}
return f.CodecForVersions(nil, f.universal, nil, versioner)
}
// CodecFor creates a codec with the provided serializer. If an object is decoded and its group is not in the list,
// CodecForVersions creates a codec with the provided serializer. If an object is decoded and its group is not in the list,
// it will default to runtime.APIVersionInternal. If encode is not specified for an object's group, the object is not
// converted. If encode or decode are nil, no conversion is performed.
func (f CodecFactory) CodecForVersions(encoder runtime.Encoder, decoder runtime.Decoder, encode []unversioned.GroupVersion, decode []unversioned.GroupVersion) runtime.Codec {
func (f CodecFactory) CodecForVersions(encoder runtime.Encoder, decoder runtime.Decoder, encode runtime.GroupVersioner, decode runtime.GroupVersioner) runtime.Codec {
// TODO: these are for backcompat, remove them in the future
if encode == nil {
encode = runtime.DisabledGroupVersioner
}
if decode == nil {
decode = runtime.InternalGroupVersioner
}
return versioning.NewCodecForScheme(f.scheme, encoder, decoder, encode, decode)
}
// DecoderToVersion returns a decoder that targets the provided group version.
func (f CodecFactory) DecoderToVersion(decoder runtime.Decoder, gv unversioned.GroupVersion) runtime.Decoder {
return f.CodecForVersions(nil, decoder, nil, []unversioned.GroupVersion{gv})
func (f CodecFactory) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {
return f.CodecForVersions(nil, decoder, nil, gv)
}
// EncoderForVersion returns an encoder that targets the provided group version.
func (f CodecFactory) EncoderForVersion(encoder runtime.Encoder, gv unversioned.GroupVersion) runtime.Encoder {
return f.CodecForVersions(encoder, nil, []unversioned.GroupVersion{gv}, nil)
func (f CodecFactory) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {
return f.CodecForVersions(encoder, nil, gv, nil)
}
// SerializerForMediaType returns a serializer that matches the provided RFC2046 mediaType, or false if no such
@ -317,48 +333,16 @@ type DirectCodecFactory struct {
}
// EncoderForVersion returns an encoder that does not do conversion. gv is ignored.
func (f DirectCodecFactory) EncoderForVersion(serializer runtime.Encoder, gv unversioned.GroupVersion) runtime.Encoder {
return DirectCodec{
runtime.NewCodec(serializer, nil),
f.CodecFactory.scheme,
func (f DirectCodecFactory) EncoderForVersion(serializer runtime.Encoder, _ runtime.GroupVersioner) runtime.Encoder {
return versioning.DirectEncoder{
Encoder: serializer,
ObjectTyper: f.CodecFactory.scheme,
}
}
// DecoderToVersion returns an decoder that does not do conversion. gv is ignored.
func (f DirectCodecFactory) DecoderToVersion(serializer runtime.Decoder, gv unversioned.GroupVersion) runtime.Decoder {
return DirectCodec{
runtime.NewCodec(nil, serializer),
nil,
func (f DirectCodecFactory) DecoderToVersion(serializer runtime.Decoder, _ runtime.GroupVersioner) runtime.Decoder {
return versioning.DirectDecoder{
Decoder: serializer,
}
}
// DirectCodec is a codec that does not do conversion. It sets the gvk during serialization, and removes the gvk during deserialization.
type DirectCodec struct {
runtime.Serializer
runtime.ObjectTyper
}
// EncodeToStream does not do conversion. It sets the gvk during serialization. overrides are ignored.
func (c DirectCodec) Encode(obj runtime.Object, stream io.Writer) error {
gvks, _, err := c.ObjectTyper.ObjectKinds(obj)
if err != nil {
return err
}
kind := obj.GetObjectKind()
oldGVK := kind.GroupVersionKind()
kind.SetGroupVersionKind(gvks[0])
err = c.Serializer.Encode(obj, stream)
kind.SetGroupVersionKind(oldGVK)
return err
}
// Decode does not do conversion. It removes the gvk during deserialization.
func (c DirectCodec) Decode(data []byte, defaults *unversioned.GroupVersionKind, into runtime.Object) (runtime.Object, *unversioned.GroupVersionKind, error) {
obj, gvk, err := c.Serializer.Decode(data, defaults, into)
if obj != nil {
kind := obj.GetObjectKind()
// clearing the gvk is just a convention of a codec
kind.SetGroupVersionKind(unversioned.GroupVersionKind{})
}
return obj, gvk, err
}

View file

@ -25,6 +25,7 @@ import (
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/runtime/serializer/recognizer"
"k8s.io/kubernetes/pkg/util/framer"
utilyaml "k8s.io/kubernetes/pkg/util/yaml"
)
@ -63,6 +64,7 @@ type Serializer struct {
// Serializer implements Serializer
var _ runtime.Serializer = &Serializer{}
var _ recognizer.RecognizingDecoder = &Serializer{}
// Decode attempts to convert the provided data into YAML or JSON, extract the stored schema kind, apply the provided default gvk, and then
// load that data into an object matching the desired schema kind or the provided into. If into is *runtime.Unknown, the raw data will be

View file

@ -17,7 +17,6 @@ limitations under the License.
package serializer
import (
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/runtime"
)
@ -48,10 +47,10 @@ func (n *negotiatedSerializerWrapper) StreamingSerializerForMediaType(mediaType
return n.streamInfo, true
}
func (n *negotiatedSerializerWrapper) EncoderForVersion(e runtime.Encoder, _ unversioned.GroupVersion) runtime.Encoder {
func (n *negotiatedSerializerWrapper) EncoderForVersion(e runtime.Encoder, _ runtime.GroupVersioner) runtime.Encoder {
return e
}
func (n *negotiatedSerializerWrapper) DecoderToVersion(d runtime.Decoder, _gv unversioned.GroupVersion) runtime.Decoder {
func (n *negotiatedSerializerWrapper) DecoderToVersion(d runtime.Decoder, _gv runtime.GroupVersioner) runtime.Decoder {
return d
}

View file

@ -26,6 +26,7 @@ import (
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/runtime/serializer/recognizer"
"k8s.io/kubernetes/pkg/util/framer"
)
@ -76,6 +77,7 @@ type Serializer struct {
}
var _ runtime.Serializer = &Serializer{}
var _ recognizer.RecognizingDecoder = &Serializer{}
// Decode attempts to convert the provided data into a protobuf message, extract the stored schema kind, apply the provided default
// gvk, and then load that data into an object matching the desired schema kind or the provided into. If into is *runtime.Unknown,
@ -124,7 +126,7 @@ func (s *Serializer) Decode(originalData []byte, gvk *unversioned.GroupVersionKi
if intoUnknown, ok := into.(*runtime.Unknown); ok && intoUnknown != nil {
*intoUnknown = unk
if len(intoUnknown.ContentType) == 0 {
if ok, _, _ := s.RecognizesData(bytes.NewBuffer(unk.Raw)); ok {
intoUnknown.ContentType = s.contentType
}
return intoUnknown, &actual, nil
@ -167,17 +169,30 @@ func (s *Serializer) Decode(originalData []byte, gvk *unversioned.GroupVersionKi
// Encode serializes the provided object to the given writer.
func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error {
var unk runtime.Unknown
kind := obj.GetObjectKind().GroupVersionKind()
unk = runtime.Unknown{
TypeMeta: runtime.TypeMeta{
Kind: kind.Kind,
APIVersion: kind.GroupVersion().String(),
},
}
prefixSize := uint64(len(s.prefix))
var unk runtime.Unknown
switch t := obj.(type) {
case *runtime.Unknown:
estimatedSize := prefixSize + uint64(t.Size())
data := make([]byte, estimatedSize)
i, err := t.MarshalTo(data[prefixSize:])
if err != nil {
return err
}
copy(data, s.prefix)
_, err = w.Write(data[:prefixSize+uint64(i)])
return err
default:
kind := obj.GetObjectKind().GroupVersionKind()
unk = runtime.Unknown{
TypeMeta: runtime.TypeMeta{
Kind: kind.Kind,
APIVersion: kind.GroupVersion().String(),
},
}
}
switch t := obj.(type) {
case bufferedMarshaller:
// this path performs a single allocation during write but requires the caller to implement
@ -224,19 +239,19 @@ func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error {
}
// RecognizesData implements the RecognizingDecoder interface.
func (s *Serializer) RecognizesData(peek io.Reader) (bool, error) {
func (s *Serializer) RecognizesData(peek io.Reader) (bool, bool, error) {
prefix := make([]byte, 4)
n, err := peek.Read(prefix)
if err != nil {
if err == io.EOF {
return false, nil
return false, false, nil
}
return false, err
return false, false, err
}
if n != 4 {
return false, nil
return false, false, nil
}
return bytes.Equal(s.prefix, prefix), nil
return bytes.Equal(s.prefix, prefix), false, nil
}
// copyKindDefaults defaults dst to the value in src if dst does not have a value set.

View file

@ -17,59 +17,20 @@ limitations under the License.
package versioning
import (
"fmt"
"io"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/runtime"
)
// EnableCrossGroupDecoding modifies the given decoder in place, if it is a codec
// from this package. It allows objects from one group to be auto-decoded into
// another group. 'destGroup' must already exist in the codec.
// TODO: this is an encapsulation violation and should be refactored
func EnableCrossGroupDecoding(d runtime.Decoder, sourceGroup, destGroup string) error {
internal, ok := d.(*codec)
if !ok {
return fmt.Errorf("unsupported decoder type")
}
dest, ok := internal.decodeVersion[destGroup]
if !ok {
return fmt.Errorf("group %q is not a possible destination group in the given codec", destGroup)
}
internal.decodeVersion[sourceGroup] = dest
return nil
}
// EnableCrossGroupEncoding modifies the given encoder in place, if it is a codec
// from this package. It allows objects from one group to be auto-decoded into
// another group. 'destGroup' must already exist in the codec.
// TODO: this is an encapsulation violation and should be refactored
func EnableCrossGroupEncoding(e runtime.Encoder, sourceGroup, destGroup string) error {
internal, ok := e.(*codec)
if !ok {
return fmt.Errorf("unsupported encoder type")
}
dest, ok := internal.encodeVersion[destGroup]
if !ok {
return fmt.Errorf("group %q is not a possible destination group in the given codec", destGroup)
}
internal.encodeVersion[sourceGroup] = dest
return nil
}
// NewCodecForScheme is a convenience method for callers that are using a scheme.
func NewCodecForScheme(
// TODO: I should be a scheme interface?
scheme *runtime.Scheme,
encoder runtime.Encoder,
decoder runtime.Decoder,
encodeVersion []unversioned.GroupVersion,
decodeVersion []unversioned.GroupVersion,
encodeVersion runtime.GroupVersioner,
decodeVersion runtime.GroupVersioner,
) runtime.Codec {
return NewCodec(encoder, decoder, runtime.UnsafeObjectConvertor(scheme), scheme, scheme, scheme, encodeVersion, decodeVersion)
}
@ -84,8 +45,8 @@ func NewCodec(
creater runtime.ObjectCreater,
copier runtime.ObjectCopier,
typer runtime.ObjectTyper,
encodeVersion []unversioned.GroupVersion,
decodeVersion []unversioned.GroupVersion,
encodeVersion runtime.GroupVersioner,
decodeVersion runtime.GroupVersioner,
) runtime.Codec {
internal := &codec{
encoder: encoder,
@ -94,33 +55,10 @@ func NewCodec(
creater: creater,
copier: copier,
typer: typer,
}
if encodeVersion != nil {
internal.encodeVersion = make(map[string]unversioned.GroupVersion)
for _, v := range encodeVersion {
// first one for a group wins. This is consistent with best to worst order throughout the codebase
if _, ok := internal.encodeVersion[v.Group]; ok {
continue
}
internal.encodeVersion[v.Group] = v
}
if len(internal.encodeVersion) == 1 {
for _, v := range internal.encodeVersion {
internal.preferredEncodeVersion = []unversioned.GroupVersion{v}
}
}
}
if decodeVersion != nil {
internal.decodeVersion = make(map[string]unversioned.GroupVersion)
for _, v := range decodeVersion {
// first one for a group wins. This is consistent with best to worst order throughout the codebase
if _, ok := internal.decodeVersion[v.Group]; ok {
continue
}
internal.decodeVersion[v.Group] = v
}
}
encodeVersion: encodeVersion,
decodeVersion: decodeVersion,
}
return internal
}
@ -132,10 +70,8 @@ type codec struct {
copier runtime.ObjectCopier
typer runtime.ObjectTyper
encodeVersion map[string]unversioned.GroupVersion
decodeVersion map[string]unversioned.GroupVersion
preferredEncodeVersion []unversioned.GroupVersion
encodeVersion runtime.GroupVersioner
decodeVersion runtime.GroupVersioner
}
// Decode attempts a decode of the object, then tries to convert it to the internal version. If into is provided and the decoding is
@ -152,6 +88,12 @@ func (c *codec) Decode(data []byte, defaultGVK *unversioned.GroupVersionKind, in
return nil, gvk, err
}
if d, ok := obj.(runtime.NestedObjectDecoder); ok {
if err := d.DecodeNestedObjects(DirectDecoder{c.decoder}); err != nil {
return nil, gvk, err
}
}
// if we specify a target, use generic conversion.
if into != nil {
if into == obj {
@ -160,7 +102,7 @@ func (c *codec) Decode(data []byte, defaultGVK *unversioned.GroupVersionKind, in
}
return into, gvk, nil
}
if err := c.convertor.Convert(obj, into); err != nil {
if err := c.convertor.Convert(obj, into, c.decodeVersion); err != nil {
return nil, gvk, err
}
if isVersioned {
@ -170,37 +112,7 @@ func (c *codec) Decode(data []byte, defaultGVK *unversioned.GroupVersionKind, in
return into, gvk, nil
}
// invoke a version conversion
group := gvk.Group
if defaultGVK != nil {
group = defaultGVK.Group
}
var targetGV unversioned.GroupVersion
if c.decodeVersion == nil {
// convert to internal by default
targetGV.Group = group
targetGV.Version = runtime.APIVersionInternal
} else {
gv, ok := c.decodeVersion[group]
if !ok {
// unknown objects are left in their original version
if isVersioned {
versioned.Objects = []runtime.Object{obj}
return versioned, gvk, nil
}
return obj, gvk, nil
}
targetGV = gv
}
if gvk.GroupVersion() == targetGV {
if isVersioned {
versioned.Objects = []runtime.Object{obj}
return versioned, gvk, nil
}
return obj, gvk, nil
}
// Convert if needed.
if isVersioned {
// create a copy, because ConvertToVersion does not guarantee non-mutation of objects
copied, err := c.copier.Copy(obj)
@ -209,14 +121,14 @@ func (c *codec) Decode(data []byte, defaultGVK *unversioned.GroupVersionKind, in
}
versioned.Objects = []runtime.Object{copied}
}
// Convert if needed.
out, err := c.convertor.ConvertToVersion(obj, targetGV)
out, err := c.convertor.ConvertToVersion(obj, c.decodeVersion)
if err != nil {
return nil, gvk, err
}
if isVersioned {
versioned.Objects = append(versioned.Objects, out)
if versioned.Last() != out {
versioned.Objects = append(versioned.Objects, out)
}
return versioned, gvk, nil
}
return out, gvk, nil
@ -225,51 +137,86 @@ func (c *codec) Decode(data []byte, defaultGVK *unversioned.GroupVersionKind, in
// Encode ensures the provided object is output in the appropriate group and version, invoking
// conversion if necessary. Unversioned objects (according to the ObjectTyper) are output as is.
func (c *codec) Encode(obj runtime.Object, w io.Writer) error {
if _, ok := obj.(*runtime.Unknown); ok {
switch obj.(type) {
case *runtime.Unknown, *runtime.Unstructured, *runtime.UnstructuredList:
return c.encoder.Encode(obj, w)
}
gvks, isUnversioned, err := c.typer.ObjectKinds(obj)
if err != nil {
return err
}
gvk := gvks[0]
if c.encodeVersion == nil || isUnversioned {
if e, ok := obj.(runtime.NestedObjectEncoder); ok {
if err := e.EncodeNestedObjects(DirectEncoder{Encoder: c.encoder, ObjectTyper: c.typer}); err != nil {
return err
}
}
objectKind := obj.GetObjectKind()
old := objectKind.GroupVersionKind()
objectKind.SetGroupVersionKind(gvk)
objectKind.SetGroupVersionKind(gvks[0])
err = c.encoder.Encode(obj, w)
objectKind.SetGroupVersionKind(old)
return err
}
targetGV, ok := c.encodeVersion[gvk.Group]
// attempt a conversion to the sole encode version
if !ok && c.preferredEncodeVersion != nil {
ok = true
targetGV = c.preferredEncodeVersion[0]
}
// if no fallback is available, error
if !ok {
return fmt.Errorf("the codec does not recognize group %q for kind %q and cannot encode it", gvk.Group, gvk.Kind)
}
// Perform a conversion if necessary
objectKind := obj.GetObjectKind()
old := objectKind.GroupVersionKind()
out, err := c.convertor.ConvertToVersion(obj, targetGV)
out, err := c.convertor.ConvertToVersion(obj, c.encodeVersion)
if err != nil {
if ok {
return err
}
if e, ok := out.(runtime.NestedObjectEncoder); ok {
if err := e.EncodeNestedObjects(DirectEncoder{Encoder: c.encoder, ObjectTyper: c.typer}); err != nil {
return err
}
} else {
obj = out
}
// Conversion is responsible for setting the proper group, version, and kind onto the outgoing object
err = c.encoder.Encode(obj, w)
err = c.encoder.Encode(out, w)
// restore the old GVK, in case conversion returned the same object
objectKind.SetGroupVersionKind(old)
return err
}
// DirectEncoder serializes an object and ensures the GVK is set.
type DirectEncoder struct {
runtime.Encoder
runtime.ObjectTyper
}
// Encode does not do conversion. It sets the gvk during serialization.
func (e DirectEncoder) Encode(obj runtime.Object, stream io.Writer) error {
gvks, _, err := e.ObjectTyper.ObjectKinds(obj)
if err != nil {
if runtime.IsNotRegisteredError(err) {
return e.Encoder.Encode(obj, stream)
}
return err
}
kind := obj.GetObjectKind()
oldGVK := kind.GroupVersionKind()
kind.SetGroupVersionKind(gvks[0])
err = e.Encoder.Encode(obj, stream)
kind.SetGroupVersionKind(oldGVK)
return err
}
// DirectDecoder clears the group version kind of a deserialized object.
type DirectDecoder struct {
runtime.Decoder
}
// Decode does not do conversion. It removes the gvk during deserialization.
func (d DirectDecoder) Decode(data []byte, defaults *unversioned.GroupVersionKind, into runtime.Object) (runtime.Object, *unversioned.GroupVersionKind, error) {
obj, gvk, err := d.Decoder.Decode(data, defaults, into)
if obj != nil {
kind := obj.GetObjectKind()
// clearing the gvk is just a convention of a codec
kind.SetGroupVersionKind(unversioned.GroupVersionKind{})
}
return obj, gvk, err
}

View file

@ -17,6 +17,7 @@ limitations under the License.
package runtime
import (
"bytes"
"fmt"
"github.com/golang/glog"
@ -138,6 +139,21 @@ type Unstructured struct {
Object map[string]interface{}
}
// 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 getNestedField(obj map[string]interface{}, fields ...string) interface{} {
var val interface{} = obj
for _, field := range fields {
@ -440,6 +456,14 @@ 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")
}
// 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.
@ -450,6 +474,21 @@ type UnstructuredList struct {
Items []*Unstructured `json:"items"`
}
// 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) setNestedField(value interface{}, fields ...string) {
if u.Object == nil {
u.Object = make(map[string]interface{})

View file

@ -95,6 +95,7 @@ func (s unstructuredJSONScheme) decode(data []byte) (Object, error) {
err := s.decodeToUnstructured(data, unstruct)
return unstruct, err
}
func (s unstructuredJSONScheme) decodeInto(data []byte, obj Object) error {
switch x := obj.(type) {
case *Unstructured:
@ -102,10 +103,9 @@ func (s unstructuredJSONScheme) decodeInto(data []byte, obj Object) error {
case *UnstructuredList:
return s.decodeToList(data, x)
case *VersionedObjects:
u := new(Unstructured)
err := s.decodeToUnstructured(data, u)
o, err := s.decode(data)
if err == nil {
x.Objects = []Object{u}
x.Objects = []Object{o}
}
return err
default:
@ -168,7 +168,7 @@ func (s unstructuredJSONScheme) decodeToList(data []byte, list *UnstructuredList
// sane implementation for APIs that require an object converter.
type UnstructuredObjectConverter struct{}
func (UnstructuredObjectConverter) Convert(in, out interface{}) error {
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)
@ -187,9 +187,14 @@ func (UnstructuredObjectConverter) Convert(in, out interface{}) error {
return nil
}
func (UnstructuredObjectConverter) ConvertToVersion(in Object, outVersion unversioned.GroupVersion) (Object, error) {
if gvk := in.GetObjectKind().GroupVersionKind(); gvk.GroupVersion() != outVersion {
return nil, errors.New("unstructured converter cannot convert versions")
func (UnstructuredObjectConverter) ConvertToVersion(in Object, target GroupVersioner) (Object, error) {
if kind := in.GetObjectKind().GroupVersionKind(); !kind.Empty() {
gvk, ok := target.KindForGroupVersionKinds([]unversioned.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
}

View file

@ -0,0 +1,75 @@
// +build !ignore_autogenerated
/*
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.
*/
// This file was autogenerated by deepcopy-gen. Do not edit it manually!
package runtime
import (
conversion "k8s.io/kubernetes/pkg/conversion"
)
func DeepCopy_runtime_RawExtension(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*RawExtension)
out := out.(*RawExtension)
if in.Raw != nil {
in, out := &in.Raw, &out.Raw
*out = make([]byte, len(*in))
copy(*out, *in)
} else {
out.Raw = nil
}
if in.Object == nil {
out.Object = nil
} else if newVal, err := c.DeepCopy(&in.Object); err != nil {
return err
} else {
out.Object = *newVal.(*Object)
}
return nil
}
}
func DeepCopy_runtime_TypeMeta(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*TypeMeta)
out := out.(*TypeMeta)
out.APIVersion = in.APIVersion
out.Kind = in.Kind
return nil
}
}
func DeepCopy_runtime_Unknown(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*Unknown)
out := out.(*Unknown)
out.TypeMeta = in.TypeMeta
if in.Raw != nil {
in, out := &in.Raw, &out.Raw
*out = make([]byte, len(*in))
copy(*out, *in)
} else {
out.Raw = nil
}
out.ContentEncoding = in.ContentEncoding
out.ContentType = in.ContentType
return nil
}
}