interfaces.go 19 KB

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