interfaces.go 17 KB

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