interfaces.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. // NondeterministicEncoder is implemented by Encoders that can serialize objects more efficiently in
  62. // cases where the output does not need to be deterministic.
  63. type NondeterministicEncoder interface {
  64. Encoder
  65. // EncodeNondeterministic writes an object to the stream. Unlike the Encode method of
  66. // Encoder, EncodeNondeterministic does not guarantee that any two invocations will write
  67. // the same sequence of bytes to the io.Writer. Any differences will not be significant to a
  68. // generic decoder. For example, map entries and struct fields might be encoded in any
  69. // order.
  70. EncodeNondeterministic(Object, io.Writer) error
  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. // EncoderWithAllocator serializes objects in a way that allows callers to manage any additional memory allocations.
  82. type EncoderWithAllocator interface {
  83. Encoder
  84. // EncodeWithAllocator writes an object to a stream as Encode does.
  85. // In addition, it allows for providing a memory allocator for efficient memory usage during object serialization
  86. EncodeWithAllocator(obj Object, w io.Writer, memAlloc MemoryAllocator) error
  87. }
  88. // Decoder attempts to load an object from data.
  89. type Decoder interface {
  90. // Decode attempts to deserialize the provided data using either the innate typing of the scheme or the
  91. // default kind, group, and version provided. It returns a decoded object as well as the kind, group, and
  92. // version from the serialized data, or an error. If into is non-nil, it will be used as the target type
  93. // and implementations may choose to use it rather than reallocating an object. However, the object is not
  94. // guaranteed to be populated. The returned object is not guaranteed to match into. If defaults are
  95. // provided, they are applied to the data by default. If no defaults or partial defaults are provided, the
  96. // type of the into may be used to guide conversion decisions.
  97. Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error)
  98. }
  99. // Serializer is the core interface for transforming objects into a serialized format and back.
  100. // Implementations may choose to perform conversion of the object, but no assumptions should be made.
  101. type Serializer interface {
  102. Encoder
  103. Decoder
  104. }
  105. // Codec is a Serializer that deals with the details of versioning objects. It offers the same
  106. // interface as Serializer, so this is a marker to consumers that care about the version of the objects
  107. // they receive.
  108. type Codec Serializer
  109. // ParameterCodec defines methods for serializing and deserializing API objects to url.Values and
  110. // performing any necessary conversion. Unlike the normal Codec, query parameters are not self describing
  111. // and the desired version must be specified.
  112. type ParameterCodec interface {
  113. // DecodeParameters takes the given url.Values in the specified group version and decodes them
  114. // into the provided object, or returns an error.
  115. DecodeParameters(parameters url.Values, from schema.GroupVersion, into Object) error
  116. // EncodeParameters encodes the provided object as query parameters or returns an error.
  117. EncodeParameters(obj Object, to schema.GroupVersion) (url.Values, error)
  118. }
  119. // Framer is a factory for creating readers and writers that obey a particular framing pattern.
  120. type Framer interface {
  121. NewFrameReader(r io.ReadCloser) io.ReadCloser
  122. NewFrameWriter(w io.Writer) io.Writer
  123. }
  124. // SerializerInfo contains information about a specific serialization format
  125. type SerializerInfo struct {
  126. // MediaType is the value that represents this serializer over the wire.
  127. MediaType string
  128. // MediaTypeType is the first part of the MediaType ("application" in "application/json").
  129. MediaTypeType string
  130. // MediaTypeSubType is the second part of the MediaType ("json" in "application/json").
  131. MediaTypeSubType string
  132. // EncodesAsText indicates this serializer can be encoded to UTF-8 safely.
  133. EncodesAsText bool
  134. // Serializer is the individual object serializer for this media type.
  135. Serializer Serializer
  136. // PrettySerializer, if set, can serialize this object in a form biased towards
  137. // readability.
  138. PrettySerializer Serializer
  139. // StrictSerializer, if set, deserializes this object strictly,
  140. // erring on unknown fields.
  141. StrictSerializer Serializer
  142. // StreamSerializer, if set, describes the streaming serialization format
  143. // for this media type.
  144. StreamSerializer *StreamSerializerInfo
  145. }
  146. // StreamSerializerInfo contains information about a specific stream serialization format
  147. type StreamSerializerInfo struct {
  148. // EncodesAsText indicates this serializer can be encoded to UTF-8 safely.
  149. EncodesAsText bool
  150. // Serializer is the top level object serializer for this type when streaming
  151. Serializer
  152. // Framer is the factory for retrieving streams that separate objects on the wire
  153. Framer
  154. }
  155. // NegotiatedSerializer is an interface used for obtaining encoders, decoders, and serializers
  156. // for multiple supported media types. This would commonly be accepted by a server component
  157. // that performs HTTP content negotiation to accept multiple formats.
  158. type NegotiatedSerializer interface {
  159. // SupportedMediaTypes is the media types supported for reading and writing single objects.
  160. SupportedMediaTypes() []SerializerInfo
  161. // EncoderForVersion returns an encoder that ensures objects being written to the provided
  162. // serializer are in the provided group version.
  163. EncoderForVersion(serializer Encoder, gv GroupVersioner) Encoder
  164. // DecoderToVersion returns a decoder that ensures objects being read by the provided
  165. // serializer are in the provided group version by default.
  166. DecoderToVersion(serializer Decoder, gv GroupVersioner) Decoder
  167. }
  168. // ClientNegotiator handles turning an HTTP content type into the appropriate encoder.
  169. // Use NewClientNegotiator or NewVersionedClientNegotiator to create this interface from
  170. // a NegotiatedSerializer.
  171. type ClientNegotiator interface {
  172. // Encoder returns the appropriate encoder for the provided contentType (e.g. application/json)
  173. // and any optional mediaType parameters (e.g. pretty=1), or an error. If no serializer is found
  174. // a NegotiateError will be returned. The current client implementations consider params to be
  175. // optional modifiers to the contentType and will ignore unrecognized parameters.
  176. Encoder(contentType string, params map[string]string) (Encoder, error)
  177. // Decoder returns the appropriate decoder for the provided contentType (e.g. application/json)
  178. // and any optional mediaType parameters (e.g. pretty=1), or an error. If no serializer is found
  179. // a NegotiateError will be returned. The current client implementations consider params to be
  180. // optional modifiers to the contentType and will ignore unrecognized parameters.
  181. Decoder(contentType string, params map[string]string) (Decoder, error)
  182. // StreamDecoder returns the appropriate stream decoder for the provided contentType (e.g.
  183. // application/json) and any optional mediaType parameters (e.g. pretty=1), or an error. If no
  184. // serializer is found a NegotiateError will be returned. The Serializer and Framer will always
  185. // be returned if a Decoder is returned. The current client implementations consider params to be
  186. // optional modifiers to the contentType and will ignore unrecognized parameters.
  187. StreamDecoder(contentType string, params map[string]string) (Decoder, Serializer, Framer, error)
  188. }
  189. // StorageSerializer is an interface used for obtaining encoders, decoders, and serializers
  190. // that can read and write data at rest. This would commonly be used by client tools that must
  191. // read files, or server side storage interfaces that persist restful objects.
  192. type StorageSerializer interface {
  193. // SupportedMediaTypes are the media types supported for reading and writing objects.
  194. SupportedMediaTypes() []SerializerInfo
  195. // UniversalDeserializer returns a Serializer that can read objects in multiple supported formats
  196. // by introspecting the data at rest.
  197. UniversalDeserializer() Decoder
  198. // EncoderForVersion returns an encoder that ensures objects being written to the provided
  199. // serializer are in the provided group version.
  200. EncoderForVersion(serializer Encoder, gv GroupVersioner) Encoder
  201. // DecoderForVersion returns a decoder that ensures objects being read by the provided
  202. // serializer are in the provided group version by default.
  203. DecoderToVersion(serializer Decoder, gv GroupVersioner) Decoder
  204. }
  205. // NestedObjectEncoder is an optional interface that objects may implement to be given
  206. // an opportunity to encode any nested Objects / RawExtensions during serialization.
  207. type NestedObjectEncoder interface {
  208. EncodeNestedObjects(e Encoder) error
  209. }
  210. // NestedObjectDecoder is an optional interface that objects may implement to be given
  211. // an opportunity to decode any nested Objects / RawExtensions during serialization.
  212. // It is possible for DecodeNestedObjects to return a non-nil error but for the decoding
  213. // to have succeeded in the case of strict decoding errors (e.g. unknown/duplicate fields).
  214. // As such it is important for callers of DecodeNestedObjects to check to confirm whether
  215. // an error is a runtime.StrictDecodingError before short circuiting.
  216. // Similarly, implementations of DecodeNestedObjects should ensure that a runtime.StrictDecodingError
  217. // is only returned when the rest of decoding has succeeded.
  218. type NestedObjectDecoder interface {
  219. DecodeNestedObjects(d Decoder) error
  220. }
  221. ///////////////////////////////////////////////////////////////////////////////
  222. // Non-codec interfaces
  223. type ObjectDefaulter interface {
  224. // Default takes an object (must be a pointer) and applies any default values.
  225. // Defaulters may not error.
  226. Default(in Object)
  227. }
  228. type ObjectVersioner interface {
  229. ConvertToVersion(in Object, gv GroupVersioner) (out Object, err error)
  230. PrioritizedVersionsForGroup(group string) []schema.GroupVersion
  231. }
  232. // ObjectConvertor converts an object to a different version.
  233. type ObjectConvertor interface {
  234. // Convert attempts to convert one object into another, or returns an error. This
  235. // method does not mutate the in object, but the in and out object might share data structures,
  236. // i.e. the out object cannot be mutated without mutating the in object as well.
  237. // The context argument will be passed to all nested conversions.
  238. Convert(in, out, context interface{}) error
  239. // ConvertToVersion takes the provided object and converts it the provided version. This
  240. // method does not mutate the in object, but the in and out object might share data structures,
  241. // i.e. the out object cannot be mutated without mutating the in object as well.
  242. // This method is similar to Convert() but handles specific details of choosing the correct
  243. // output version.
  244. ConvertToVersion(in Object, gv GroupVersioner) (out Object, err error)
  245. ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error)
  246. }
  247. // ObjectTyper contains methods for extracting the APIVersion and Kind
  248. // of objects.
  249. type ObjectTyper interface {
  250. // ObjectKinds returns the all possible group,version,kind of the provided object, true if
  251. // the object is unversioned, or an error if the object is not recognized
  252. // (IsNotRegisteredError will return true).
  253. ObjectKinds(Object) ([]schema.GroupVersionKind, bool, error)
  254. // Recognizes returns true if the scheme is able to handle the provided version and kind,
  255. // or more precisely that the provided version is a possible conversion or decoding
  256. // target.
  257. Recognizes(gvk schema.GroupVersionKind) bool
  258. }
  259. // ObjectCreater contains methods for instantiating an object by kind and version.
  260. type ObjectCreater interface {
  261. New(kind schema.GroupVersionKind) (out Object, err error)
  262. }
  263. // EquivalentResourceMapper provides information about resources that address the same underlying data as a specified resource
  264. type EquivalentResourceMapper interface {
  265. // EquivalentResourcesFor returns a list of resources that address the same underlying data as resource.
  266. // If subresource is specified, only equivalent resources which also have the same subresource are included.
  267. // The specified resource can be included in the returned list.
  268. EquivalentResourcesFor(resource schema.GroupVersionResource, subresource string) []schema.GroupVersionResource
  269. // KindFor returns the kind expected by the specified resource[/subresource].
  270. // A zero value is returned if the kind is unknown.
  271. KindFor(resource schema.GroupVersionResource, subresource string) schema.GroupVersionKind
  272. }
  273. // EquivalentResourceRegistry provides an EquivalentResourceMapper interface,
  274. // and allows registering known resource[/subresource] -> kind
  275. type EquivalentResourceRegistry interface {
  276. EquivalentResourceMapper
  277. // RegisterKindFor registers the existence of the specified resource[/subresource] along with its expected kind.
  278. RegisterKindFor(resource schema.GroupVersionResource, subresource string, kind schema.GroupVersionKind)
  279. }
  280. // ResourceVersioner provides methods for setting and retrieving
  281. // the resource version from an API object.
  282. type ResourceVersioner interface {
  283. SetResourceVersion(obj Object, version string) error
  284. ResourceVersion(obj Object) (string, error)
  285. }
  286. // Namer provides methods for retrieving name and namespace of an API object.
  287. type Namer interface {
  288. // Name returns the name of a given object.
  289. Name(obj Object) (string, error)
  290. // Namespace returns the name of a given object.
  291. Namespace(obj Object) (string, error)
  292. }
  293. // Object interface must be supported by all API types registered with Scheme. Since objects in a scheme are
  294. // expected to be serialized to the wire, the interface an Object must provide to the Scheme allows
  295. // serializers to set the kind, version, and group the object is represented as. An Object may choose
  296. // to return a no-op ObjectKindAccessor in cases where it is not expected to be serialized.
  297. type Object interface {
  298. GetObjectKind() schema.ObjectKind
  299. DeepCopyObject() Object
  300. }
  301. // CacheableObject allows an object to cache its different serializations
  302. // to avoid performing the same serialization multiple times.
  303. type CacheableObject interface {
  304. // CacheEncode writes an object to a stream. The <encode> function will
  305. // be used in case of cache miss. The <encode> function takes ownership
  306. // of the object.
  307. // If CacheableObject is a wrapper, then deep-copy of the wrapped object
  308. // should be passed to <encode> function.
  309. // CacheEncode assumes that for two different calls with the same <id>,
  310. // <encode> function will also be the same.
  311. CacheEncode(id Identifier, encode func(Object, io.Writer) error, w io.Writer) error
  312. // GetObject returns a deep-copy of an object to be encoded - the caller of
  313. // GetObject() is the owner of returned object. The reason for making a copy
  314. // is to avoid bugs, where caller modifies the object and forgets to copy it,
  315. // thus modifying the object for everyone.
  316. // The object returned by GetObject should be the same as the one that is supposed
  317. // to be passed to <encode> function in CacheEncode method.
  318. // If CacheableObject is a wrapper, the copy of wrapped object should be returned.
  319. GetObject() Object
  320. }
  321. // Unstructured objects store values as map[string]interface{}, with only values that can be serialized
  322. // to JSON allowed.
  323. type Unstructured interface {
  324. Object
  325. // NewEmptyInstance returns a new instance of the concrete type containing only kind/apiVersion and no other data.
  326. // This should be called instead of reflect.New() for unstructured types because the go type alone does not preserve kind/apiVersion info.
  327. NewEmptyInstance() Unstructured
  328. // UnstructuredContent returns a non-nil map with this object's contents. Values may be
  329. // []interface{}, map[string]interface{}, or any primitive type. Contents are typically serialized to
  330. // and from JSON. SetUnstructuredContent should be used to mutate the contents.
  331. UnstructuredContent() map[string]interface{}
  332. // SetUnstructuredContent updates the object content to match the provided map.
  333. SetUnstructuredContent(map[string]interface{})
  334. // IsList returns true if this type is a list or matches the list convention - has an array called "items".
  335. IsList() bool
  336. // EachListItem should pass a single item out of the list as an Object to the provided function. Any
  337. // error should terminate the iteration. If IsList() returns false, this method should return an error
  338. // instead of calling the provided function.
  339. EachListItem(func(Object) error) error
  340. // EachListItemWithAlloc works like EachListItem, but avoids retaining references to a slice of items.
  341. // It does this by making a shallow copy of non-pointer items before passing them to fn.
  342. //
  343. // If the items passed to fn are not retained, or are retained for the same duration, use EachListItem instead for memory efficiency.
  344. EachListItemWithAlloc(func(Object) error) error
  345. }
  346. // ApplyConfiguration is an interface that root apply configuration types implement.
  347. type ApplyConfiguration interface {
  348. // IsApplyConfiguration is implemented if the object is the root of an apply configuration.
  349. IsApplyConfiguration()
  350. }