github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/runtime/interfaces.go (about)

     1  /*
     2  Copyright 2014 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package runtime
    18  
    19  import (
    20  	"io"
    21  	"net/url"
    22  
    23  	"github.com/spotmaxtech/k8s-apimachinery-v0260/pkg/runtime/schema"
    24  )
    25  
    26  const (
    27  	// APIVersionInternal may be used if you are registering a type that should not
    28  	// be considered stable or serialized - it is a convention only and has no
    29  	// special behavior in this package.
    30  	APIVersionInternal = "__internal"
    31  )
    32  
    33  // GroupVersioner refines a set of possible conversion targets into a single option.
    34  type GroupVersioner interface {
    35  	// KindForGroupVersionKinds returns a desired target group version kind for the given input, or returns ok false if no
    36  	// target is known. In general, if the return target is not in the input list, the caller is expected to invoke
    37  	// Scheme.New(target) and then perform a conversion between the current Go type and the destination Go type.
    38  	// Sophisticated implementations may use additional information about the input kinds to pick a destination kind.
    39  	KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (target schema.GroupVersionKind, ok bool)
    40  	// Identifier returns string representation of the object.
    41  	// Identifiers of two different encoders should be equal only if for every input
    42  	// kinds they return the same result.
    43  	Identifier() string
    44  }
    45  
    46  // Identifier represents an identifier.
    47  // Identitier of two different objects should be equal if and only if for every
    48  // input the output they produce is exactly the same.
    49  type Identifier string
    50  
    51  // Encoder writes objects to a serialized form
    52  type Encoder interface {
    53  	// Encode writes an object to a stream. Implementations may return errors if the versions are
    54  	// incompatible, or if no conversion is defined.
    55  	Encode(obj Object, w io.Writer) error
    56  	// Identifier returns an identifier of the encoder.
    57  	// Identifiers of two different encoders should be equal if and only if for every input
    58  	// object it will be encoded to the same representation by both of them.
    59  	//
    60  	// Identifier is intended for use with CacheableObject#CacheEncode method. In order to
    61  	// correctly handle CacheableObject, Encode() method should look similar to below, where
    62  	// doEncode() is the encoding logic of implemented encoder:
    63  	//   func (e *MyEncoder) Encode(obj Object, w io.Writer) error {
    64  	//     if co, ok := obj.(CacheableObject); ok {
    65  	//       return co.CacheEncode(e.Identifier(), e.doEncode, w)
    66  	//     }
    67  	//     return e.doEncode(obj, w)
    68  	//   }
    69  	Identifier() Identifier
    70  }
    71  
    72  // MemoryAllocator is responsible for allocating memory.
    73  // By encapsulating memory allocation into its own interface, we can reuse the memory
    74  // across many operations in places we know it can significantly improve the performance.
    75  type MemoryAllocator interface {
    76  	// Allocate reserves memory for n bytes.
    77  	// Note that implementations of this method are not required to zero the returned array.
    78  	// It is the caller's responsibility to clean the memory if needed.
    79  	Allocate(n uint64) []byte
    80  }
    81  
    82  // EncoderWithAllocator  serializes objects in a way that allows callers to manage any additional memory allocations.
    83  type EncoderWithAllocator interface {
    84  	Encoder
    85  	// EncodeWithAllocator writes an object to a stream as Encode does.
    86  	// In addition, it allows for providing a memory allocator for efficient memory usage during object serialization
    87  	EncodeWithAllocator(obj Object, w io.Writer, memAlloc MemoryAllocator) error
    88  }
    89  
    90  // Decoder attempts to load an object from data.
    91  type Decoder interface {
    92  	// Decode attempts to deserialize the provided data using either the innate typing of the scheme or the
    93  	// default kind, group, and version provided. It returns a decoded object as well as the kind, group, and
    94  	// version from the serialized data, or an error. If into is non-nil, it will be used as the target type
    95  	// and implementations may choose to use it rather than reallocating an object. However, the object is not
    96  	// guaranteed to be populated. The returned object is not guaranteed to match into. If defaults are
    97  	// provided, they are applied to the data by default. If no defaults or partial defaults are provided, the
    98  	// type of the into may be used to guide conversion decisions.
    99  	Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error)
   100  }
   101  
   102  // Serializer is the core interface for transforming objects into a serialized format and back.
   103  // Implementations may choose to perform conversion of the object, but no assumptions should be made.
   104  type Serializer interface {
   105  	Encoder
   106  	Decoder
   107  }
   108  
   109  // Codec is a Serializer that deals with the details of versioning objects. It offers the same
   110  // interface as Serializer, so this is a marker to consumers that care about the version of the objects
   111  // they receive.
   112  type Codec Serializer
   113  
   114  // ParameterCodec defines methods for serializing and deserializing API objects to url.Values and
   115  // performing any necessary conversion. Unlike the normal Codec, query parameters are not self describing
   116  // and the desired version must be specified.
   117  type ParameterCodec interface {
   118  	// DecodeParameters takes the given url.Values in the specified group version and decodes them
   119  	// into the provided object, or returns an error.
   120  	DecodeParameters(parameters url.Values, from schema.GroupVersion, into Object) error
   121  	// EncodeParameters encodes the provided object as query parameters or returns an error.
   122  	EncodeParameters(obj Object, to schema.GroupVersion) (url.Values, error)
   123  }
   124  
   125  // Framer is a factory for creating readers and writers that obey a particular framing pattern.
   126  type Framer interface {
   127  	NewFrameReader(r io.ReadCloser) io.ReadCloser
   128  	NewFrameWriter(w io.Writer) io.Writer
   129  }
   130  
   131  // SerializerInfo contains information about a specific serialization format
   132  type SerializerInfo struct {
   133  	// MediaType is the value that represents this serializer over the wire.
   134  	MediaType string
   135  	// MediaTypeType is the first part of the MediaType ("application" in "application/json").
   136  	MediaTypeType string
   137  	// MediaTypeSubType is the second part of the MediaType ("json" in "application/json").
   138  	MediaTypeSubType string
   139  	// EncodesAsText indicates this serializer can be encoded to UTF-8 safely.
   140  	EncodesAsText bool
   141  	// Serializer is the individual object serializer for this media type.
   142  	Serializer Serializer
   143  	// PrettySerializer, if set, can serialize this object in a form biased towards
   144  	// readability.
   145  	PrettySerializer Serializer
   146  	// StrictSerializer, if set, deserializes this object strictly,
   147  	// erring on unknown fields.
   148  	StrictSerializer Serializer
   149  	// StreamSerializer, if set, describes the streaming serialization format
   150  	// for this media type.
   151  	StreamSerializer *StreamSerializerInfo
   152  }
   153  
   154  // StreamSerializerInfo contains information about a specific stream serialization format
   155  type StreamSerializerInfo struct {
   156  	// EncodesAsText indicates this serializer can be encoded to UTF-8 safely.
   157  	EncodesAsText bool
   158  	// Serializer is the top level object serializer for this type when streaming
   159  	Serializer
   160  	// Framer is the factory for retrieving streams that separate objects on the wire
   161  	Framer
   162  }
   163  
   164  // NegotiatedSerializer is an interface used for obtaining encoders, decoders, and serializers
   165  // for multiple supported media types. This would commonly be accepted by a server component
   166  // that performs HTTP content negotiation to accept multiple formats.
   167  type NegotiatedSerializer interface {
   168  	// SupportedMediaTypes is the media types supported for reading and writing single objects.
   169  	SupportedMediaTypes() []SerializerInfo
   170  
   171  	// EncoderForVersion returns an encoder that ensures objects being written to the provided
   172  	// serializer are in the provided group version.
   173  	EncoderForVersion(serializer Encoder, gv GroupVersioner) Encoder
   174  	// DecoderToVersion returns a decoder that ensures objects being read by the provided
   175  	// serializer are in the provided group version by default.
   176  	DecoderToVersion(serializer Decoder, gv GroupVersioner) Decoder
   177  }
   178  
   179  // ClientNegotiator handles turning an HTTP content type into the appropriate encoder.
   180  // Use NewClientNegotiator or NewVersionedClientNegotiator to create this interface from
   181  // a NegotiatedSerializer.
   182  type ClientNegotiator interface {
   183  	// Encoder returns the appropriate encoder for the provided contentType (e.g. application/json)
   184  	// and any optional mediaType parameters (e.g. pretty=1), or an error. If no serializer is found
   185  	// a NegotiateError will be returned. The current client implementations consider params to be
   186  	// optional modifiers to the contentType and will ignore unrecognized parameters.
   187  	Encoder(contentType string, params map[string]string) (Encoder, error)
   188  	// Decoder returns the appropriate decoder for the provided contentType (e.g. application/json)
   189  	// and any optional mediaType parameters (e.g. pretty=1), or an error. If no serializer is found
   190  	// a NegotiateError will be returned. The current client implementations consider params to be
   191  	// optional modifiers to the contentType and will ignore unrecognized parameters.
   192  	Decoder(contentType string, params map[string]string) (Decoder, error)
   193  	// StreamDecoder returns the appropriate stream decoder for the provided contentType (e.g.
   194  	// application/json) and any optional mediaType parameters (e.g. pretty=1), or an error. If no
   195  	// serializer is found a NegotiateError will be returned. The Serializer and Framer will always
   196  	// be returned if a Decoder is returned. The current client implementations consider params to be
   197  	// optional modifiers to the contentType and will ignore unrecognized parameters.
   198  	StreamDecoder(contentType string, params map[string]string) (Decoder, Serializer, Framer, error)
   199  }
   200  
   201  // StorageSerializer is an interface used for obtaining encoders, decoders, and serializers
   202  // that can read and write data at rest. This would commonly be used by client tools that must
   203  // read files, or server side storage interfaces that persist restful objects.
   204  type StorageSerializer interface {
   205  	// SupportedMediaTypes are the media types supported for reading and writing objects.
   206  	SupportedMediaTypes() []SerializerInfo
   207  
   208  	// UniversalDeserializer returns a Serializer that can read objects in multiple supported formats
   209  	// by introspecting the data at rest.
   210  	UniversalDeserializer() Decoder
   211  
   212  	// EncoderForVersion returns an encoder that ensures objects being written to the provided
   213  	// serializer are in the provided group version.
   214  	EncoderForVersion(serializer Encoder, gv GroupVersioner) Encoder
   215  	// DecoderForVersion returns a decoder that ensures objects being read by the provided
   216  	// serializer are in the provided group version by default.
   217  	DecoderToVersion(serializer Decoder, gv GroupVersioner) Decoder
   218  }
   219  
   220  // NestedObjectEncoder is an optional interface that objects may implement to be given
   221  // an opportunity to encode any nested Objects / RawExtensions during serialization.
   222  type NestedObjectEncoder interface {
   223  	EncodeNestedObjects(e Encoder) error
   224  }
   225  
   226  // NestedObjectDecoder is an optional interface that objects may implement to be given
   227  // an opportunity to decode any nested Objects / RawExtensions during serialization.
   228  // It is possible for DecodeNestedObjects to return a non-nil error but for the decoding
   229  // to have succeeded in the case of strict decoding errors (e.g. unknown/duplicate fields).
   230  // As such it is important for callers of DecodeNestedObjects to check to confirm whether
   231  // an error is a runtime.StrictDecodingError before short circuiting.
   232  // Similarly, implementations of DecodeNestedObjects should ensure that a runtime.StrictDecodingError
   233  // is only returned when the rest of decoding has succeeded.
   234  type NestedObjectDecoder interface {
   235  	DecodeNestedObjects(d Decoder) error
   236  }
   237  
   238  ///////////////////////////////////////////////////////////////////////////////
   239  // Non-codec interfaces
   240  
   241  type ObjectDefaulter interface {
   242  	// Default takes an object (must be a pointer) and applies any default values.
   243  	// Defaulters may not error.
   244  	Default(in Object)
   245  }
   246  
   247  type ObjectVersioner interface {
   248  	ConvertToVersion(in Object, gv GroupVersioner) (out Object, err error)
   249  }
   250  
   251  // ObjectConvertor converts an object to a different version.
   252  type ObjectConvertor interface {
   253  	// Convert attempts to convert one object into another, or returns an error. This
   254  	// method does not mutate the in object, but the in and out object might share data structures,
   255  	// i.e. the out object cannot be mutated without mutating the in object as well.
   256  	// The context argument will be passed to all nested conversions.
   257  	Convert(in, out, context interface{}) error
   258  	// ConvertToVersion takes the provided object and converts it the provided version. This
   259  	// method does not mutate the in object, but the in and out object might share data structures,
   260  	// i.e. the out object cannot be mutated without mutating the in object as well.
   261  	// This method is similar to Convert() but handles specific details of choosing the correct
   262  	// output version.
   263  	ConvertToVersion(in Object, gv GroupVersioner) (out Object, err error)
   264  	ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error)
   265  }
   266  
   267  // ObjectTyper contains methods for extracting the APIVersion and Kind
   268  // of objects.
   269  type ObjectTyper interface {
   270  	// ObjectKinds returns the all possible group,version,kind of the provided object, true if
   271  	// the object is unversioned, or an error if the object is not recognized
   272  	// (IsNotRegisteredError will return true).
   273  	ObjectKinds(Object) ([]schema.GroupVersionKind, bool, error)
   274  	// Recognizes returns true if the scheme is able to handle the provided version and kind,
   275  	// or more precisely that the provided version is a possible conversion or decoding
   276  	// target.
   277  	Recognizes(gvk schema.GroupVersionKind) bool
   278  }
   279  
   280  // ObjectCreater contains methods for instantiating an object by kind and version.
   281  type ObjectCreater interface {
   282  	New(kind schema.GroupVersionKind) (out Object, err error)
   283  }
   284  
   285  // EquivalentResourceMapper provides information about resources that address the same underlying data as a specified resource
   286  type EquivalentResourceMapper interface {
   287  	// EquivalentResourcesFor returns a list of resources that address the same underlying data as resource.
   288  	// If subresource is specified, only equivalent resources which also have the same subresource are included.
   289  	// The specified resource can be included in the returned list.
   290  	EquivalentResourcesFor(resource schema.GroupVersionResource, subresource string) []schema.GroupVersionResource
   291  	// KindFor returns the kind expected by the specified resource[/subresource].
   292  	// A zero value is returned if the kind is unknown.
   293  	KindFor(resource schema.GroupVersionResource, subresource string) schema.GroupVersionKind
   294  }
   295  
   296  // EquivalentResourceRegistry provides an EquivalentResourceMapper interface,
   297  // and allows registering known resource[/subresource] -> kind
   298  type EquivalentResourceRegistry interface {
   299  	EquivalentResourceMapper
   300  	// RegisterKindFor registers the existence of the specified resource[/subresource] along with its expected kind.
   301  	RegisterKindFor(resource schema.GroupVersionResource, subresource string, kind schema.GroupVersionKind)
   302  }
   303  
   304  // ResourceVersioner provides methods for setting and retrieving
   305  // the resource version from an API object.
   306  type ResourceVersioner interface {
   307  	SetResourceVersion(obj Object, version string) error
   308  	ResourceVersion(obj Object) (string, error)
   309  }
   310  
   311  // Namer provides methods for retrieving name and namespace of an API object.
   312  type Namer interface {
   313  	// Name returns the name of a given object.
   314  	Name(obj Object) (string, error)
   315  	// Namespace returns the name of a given object.
   316  	Namespace(obj Object) (string, error)
   317  }
   318  
   319  // Object interface must be supported by all API types registered with Scheme. Since objects in a scheme are
   320  // expected to be serialized to the wire, the interface an Object must provide to the Scheme allows
   321  // serializers to set the kind, version, and group the object is represented as. An Object may choose
   322  // to return a no-op ObjectKindAccessor in cases where it is not expected to be serialized.
   323  type Object interface {
   324  	GetObjectKind() schema.ObjectKind
   325  	DeepCopyObject() Object
   326  }
   327  
   328  // CacheableObject allows an object to cache its different serializations
   329  // to avoid performing the same serialization multiple times.
   330  type CacheableObject interface {
   331  	// CacheEncode writes an object to a stream. The <encode> function will
   332  	// be used in case of cache miss. The <encode> function takes ownership
   333  	// of the object.
   334  	// If CacheableObject is a wrapper, then deep-copy of the wrapped object
   335  	// should be passed to <encode> function.
   336  	// CacheEncode assumes that for two different calls with the same <id>,
   337  	// <encode> function will also be the same.
   338  	CacheEncode(id Identifier, encode func(Object, io.Writer) error, w io.Writer) error
   339  	// GetObject returns a deep-copy of an object to be encoded - the caller of
   340  	// GetObject() is the owner of returned object. The reason for making a copy
   341  	// is to avoid bugs, where caller modifies the object and forgets to copy it,
   342  	// thus modifying the object for everyone.
   343  	// The object returned by GetObject should be the same as the one that is supposed
   344  	// to be passed to <encode> function in CacheEncode method.
   345  	// If CacheableObject is a wrapper, the copy of wrapped object should be returned.
   346  	GetObject() Object
   347  }
   348  
   349  // Unstructured objects store values as map[string]interface{}, with only values that can be serialized
   350  // to JSON allowed.
   351  type Unstructured interface {
   352  	Object
   353  	// NewEmptyInstance returns a new instance of the concrete type containing only kind/apiVersion and no other data.
   354  	// This should be called instead of reflect.New() for unstructured types because the go type alone does not preserve kind/apiVersion info.
   355  	NewEmptyInstance() Unstructured
   356  	// UnstructuredContent returns a non-nil map with this object's contents. Values may be
   357  	// []interface{}, map[string]interface{}, or any primitive type. Contents are typically serialized to
   358  	// and from JSON. SetUnstructuredContent should be used to mutate the contents.
   359  	UnstructuredContent() map[string]interface{}
   360  	// SetUnstructuredContent updates the object content to match the provided map.
   361  	SetUnstructuredContent(map[string]interface{})
   362  	// IsList returns true if this type is a list or matches the list convention - has an array called "items".
   363  	IsList() bool
   364  	// EachListItem should pass a single item out of the list as an Object to the provided function. Any
   365  	// error should terminate the iteration. If IsList() returns false, this method should return an error
   366  	// instead of calling the provided function.
   367  	EachListItem(func(Object) error) error
   368  }