PageRenderTime 54ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/k8s.io/kubernetes/pkg/runtime/serializer/codec_factory.go

https://gitlab.com/admin-github-cloud/bootkube
Go | 364 lines | 238 code | 44 blank | 82 comment | 42 complexity | 3ad628451acdd115e04f3c91dbd2a660 MD5 | raw file
  1. /*
  2. Copyright 2014 The Kubernetes Authors All rights reserved.
  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 serializer
  14. import (
  15. "io"
  16. "k8s.io/kubernetes/pkg/api/unversioned"
  17. "k8s.io/kubernetes/pkg/runtime"
  18. "k8s.io/kubernetes/pkg/runtime/serializer/json"
  19. "k8s.io/kubernetes/pkg/runtime/serializer/recognizer"
  20. "k8s.io/kubernetes/pkg/runtime/serializer/versioning"
  21. )
  22. // serializerExtensions are for serializers that are conditionally compiled in
  23. var serializerExtensions = []func(*runtime.Scheme) (serializerType, bool){}
  24. type serializerType struct {
  25. AcceptContentTypes []string
  26. ContentType string
  27. FileExtensions []string
  28. // EncodesAsText should be true if this content type can be represented safely in UTF-8
  29. EncodesAsText bool
  30. Serializer runtime.Serializer
  31. PrettySerializer runtime.Serializer
  32. // RawSerializer serializes an object without adding a type wrapper. Some serializers, like JSON
  33. // automatically include identifying type information with the JSON. Others, like Protobuf, need
  34. // a wrapper object that includes type information. This serializer should be set if the serializer
  35. // can serialize / deserialize objects without type info. Note that this serializer will always
  36. // be expected to pass into or a gvk to Decode, since no type information will be available on
  37. // the object itself.
  38. RawSerializer runtime.Serializer
  39. // Specialize gives the type the opportunity to return a different serializer implementation if
  40. // the content type contains alternate operations. Here it is used to implement "pretty" as an
  41. // option to application/json, but could also be used to allow serializers to perform type
  42. // defaulting or alter output.
  43. Specialize func(map[string]string) (runtime.Serializer, bool)
  44. AcceptStreamContentTypes []string
  45. StreamContentType string
  46. Framer runtime.Framer
  47. StreamSerializer runtime.Serializer
  48. StreamSpecialize func(map[string]string) (runtime.Serializer, bool)
  49. }
  50. func newSerializersForScheme(scheme *runtime.Scheme, mf json.MetaFactory) []serializerType {
  51. jsonSerializer := json.NewSerializer(mf, scheme, scheme, false)
  52. jsonPrettySerializer := json.NewSerializer(mf, scheme, scheme, true)
  53. yamlSerializer := json.NewYAMLSerializer(mf, scheme, scheme)
  54. serializers := []serializerType{
  55. {
  56. AcceptContentTypes: []string{"application/json"},
  57. ContentType: "application/json",
  58. FileExtensions: []string{"json"},
  59. EncodesAsText: true,
  60. Serializer: jsonSerializer,
  61. PrettySerializer: jsonPrettySerializer,
  62. AcceptStreamContentTypes: []string{"application/json", "application/json;stream=watch"},
  63. StreamContentType: "application/json",
  64. Framer: json.Framer,
  65. StreamSerializer: jsonSerializer,
  66. },
  67. {
  68. AcceptContentTypes: []string{"application/yaml"},
  69. ContentType: "application/yaml",
  70. FileExtensions: []string{"yaml"},
  71. EncodesAsText: true,
  72. Serializer: yamlSerializer,
  73. // TODO: requires runtime.RawExtension to properly distinguish when the nested content is
  74. // yaml, because the yaml encoder invokes MarshalJSON first
  75. //AcceptStreamContentTypes: []string{"application/yaml", "application/yaml;stream=watch"},
  76. //StreamContentType: "application/yaml;stream=watch",
  77. //Framer: json.YAMLFramer,
  78. //StreamSerializer: yamlSerializer,
  79. },
  80. }
  81. for _, fn := range serializerExtensions {
  82. if serializer, ok := fn(scheme); ok {
  83. serializers = append(serializers, serializer)
  84. }
  85. }
  86. return serializers
  87. }
  88. // CodecFactory provides methods for retrieving codecs and serializers for specific
  89. // versions and content types.
  90. type CodecFactory struct {
  91. scheme *runtime.Scheme
  92. serializers []serializerType
  93. universal runtime.Decoder
  94. accepts []string
  95. streamingAccepts []string
  96. legacySerializer runtime.Serializer
  97. }
  98. // NewCodecFactory provides methods for retrieving serializers for the supported wire formats
  99. // and conversion wrappers to define preferred internal and external versions. In the future,
  100. // as the internal version is used less, callers may instead use a defaulting serializer and
  101. // only convert objects which are shared internally (Status, common API machinery).
  102. // TODO: allow other codecs to be compiled in?
  103. // TODO: accept a scheme interface
  104. func NewCodecFactory(scheme *runtime.Scheme) CodecFactory {
  105. serializers := newSerializersForScheme(scheme, json.DefaultMetaFactory)
  106. return newCodecFactory(scheme, serializers)
  107. }
  108. // newCodecFactory is a helper for testing that allows a different metafactory to be specified.
  109. func newCodecFactory(scheme *runtime.Scheme, serializers []serializerType) CodecFactory {
  110. decoders := make([]runtime.Decoder, 0, len(serializers))
  111. accepts := []string{}
  112. alreadyAccepted := make(map[string]struct{})
  113. var legacySerializer runtime.Serializer
  114. for _, d := range serializers {
  115. decoders = append(decoders, d.Serializer)
  116. for _, mediaType := range d.AcceptContentTypes {
  117. if _, ok := alreadyAccepted[mediaType]; ok {
  118. continue
  119. }
  120. alreadyAccepted[mediaType] = struct{}{}
  121. accepts = append(accepts, mediaType)
  122. if mediaType == "application/json" {
  123. legacySerializer = d.Serializer
  124. }
  125. }
  126. }
  127. if legacySerializer == nil {
  128. legacySerializer = serializers[0].Serializer
  129. }
  130. streamAccepts := []string{}
  131. alreadyAccepted = make(map[string]struct{})
  132. for _, d := range serializers {
  133. if len(d.StreamContentType) == 0 {
  134. continue
  135. }
  136. for _, mediaType := range d.AcceptStreamContentTypes {
  137. if _, ok := alreadyAccepted[mediaType]; ok {
  138. continue
  139. }
  140. alreadyAccepted[mediaType] = struct{}{}
  141. streamAccepts = append(streamAccepts, mediaType)
  142. }
  143. }
  144. return CodecFactory{
  145. scheme: scheme,
  146. serializers: serializers,
  147. universal: recognizer.NewDecoder(decoders...),
  148. accepts: accepts,
  149. streamingAccepts: streamAccepts,
  150. legacySerializer: legacySerializer,
  151. }
  152. }
  153. var _ runtime.NegotiatedSerializer = &CodecFactory{}
  154. // SupportedMediaTypes returns the RFC2046 media types that this factory has serializers for.
  155. func (f CodecFactory) SupportedMediaTypes() []string {
  156. return f.accepts
  157. }
  158. // SupportedStreamingMediaTypes returns the RFC2046 media types that this factory has stream serializers for.
  159. func (f CodecFactory) SupportedStreamingMediaTypes() []string {
  160. return f.streamingAccepts
  161. }
  162. // LegacyCodec encodes output to a given API version, and decodes output into the internal form from
  163. // any recognized source. The returned codec will always encode output to JSON.
  164. //
  165. // This method is deprecated - clients and servers should negotiate a serializer by mime-type and
  166. // invoke CodecForVersions. Callers that need only to read data should use UniversalDecoder().
  167. func (f CodecFactory) LegacyCodec(version ...unversioned.GroupVersion) runtime.Codec {
  168. return versioning.NewCodecForScheme(f.scheme, f.legacySerializer, f.universal, version, nil)
  169. }
  170. // UniversalDeserializer can convert any stored data recognized by this factory into a Go object that satisfies
  171. // runtime.Object. It does not perform conversion. It does not perform defaulting.
  172. func (f CodecFactory) UniversalDeserializer() runtime.Decoder {
  173. return f.universal
  174. }
  175. // UniversalDecoder returns a runtime.Decoder capable of decoding all known API objects in all known formats. Used
  176. // by clients that do not need to encode objects but want to deserialize API objects stored on disk. Only decodes
  177. // objects in groups registered with the scheme. The GroupVersions passed may be used to select alternate
  178. // versions of objects to return - by default, runtime.APIVersionInternal is used. If any versions are specified,
  179. // unrecognized groups will be returned in the version they are encoded as (no conversion). This decoder performs
  180. // defaulting.
  181. //
  182. // TODO: the decoder will eventually be removed in favor of dealing with objects in their versioned form
  183. func (f CodecFactory) UniversalDecoder(versions ...unversioned.GroupVersion) runtime.Decoder {
  184. return f.CodecForVersions(nil, f.universal, nil, versions)
  185. }
  186. // CodecFor creates a codec with the provided serializer. If an object is decoded and its group is not in the list,
  187. // it will default to runtime.APIVersionInternal. If encode is not specified for an object's group, the object is not
  188. // converted. If encode or decode are nil, no conversion is performed.
  189. func (f CodecFactory) CodecForVersions(encoder runtime.Encoder, decoder runtime.Decoder, encode []unversioned.GroupVersion, decode []unversioned.GroupVersion) runtime.Codec {
  190. return versioning.NewCodecForScheme(f.scheme, encoder, decoder, encode, decode)
  191. }
  192. // DecoderToVersion returns a decoder that targets the provided group version.
  193. func (f CodecFactory) DecoderToVersion(decoder runtime.Decoder, gv unversioned.GroupVersion) runtime.Decoder {
  194. return f.CodecForVersions(nil, decoder, nil, []unversioned.GroupVersion{gv})
  195. }
  196. // EncoderForVersion returns an encoder that targets the provided group version.
  197. func (f CodecFactory) EncoderForVersion(encoder runtime.Encoder, gv unversioned.GroupVersion) runtime.Encoder {
  198. return f.CodecForVersions(encoder, nil, []unversioned.GroupVersion{gv}, nil)
  199. }
  200. // SerializerForMediaType returns a serializer that matches the provided RFC2046 mediaType, or false if no such
  201. // serializer exists
  202. func (f CodecFactory) SerializerForMediaType(mediaType string, params map[string]string) (runtime.SerializerInfo, bool) {
  203. for _, s := range f.serializers {
  204. for _, accepted := range s.AcceptContentTypes {
  205. if accepted == mediaType {
  206. // specialization abstracts variants to the content type
  207. if s.Specialize != nil && len(params) > 0 {
  208. serializer, ok := s.Specialize(params)
  209. // TODO: return formatted mediaType+params
  210. return runtime.SerializerInfo{Serializer: serializer, MediaType: s.ContentType, EncodesAsText: s.EncodesAsText}, ok
  211. }
  212. // legacy support for ?pretty=1 continues, but this is more formally defined
  213. if v, ok := params["pretty"]; ok && v == "1" && s.PrettySerializer != nil {
  214. return runtime.SerializerInfo{Serializer: s.PrettySerializer, MediaType: s.ContentType, EncodesAsText: s.EncodesAsText}, true
  215. }
  216. // return the base variant
  217. return runtime.SerializerInfo{Serializer: s.Serializer, MediaType: s.ContentType, EncodesAsText: s.EncodesAsText}, true
  218. }
  219. }
  220. }
  221. return runtime.SerializerInfo{}, false
  222. }
  223. // StreamingSerializerForMediaType returns a serializer that matches the provided RFC2046 mediaType, or false if no such
  224. // serializer exists
  225. func (f CodecFactory) StreamingSerializerForMediaType(mediaType string, params map[string]string) (runtime.StreamSerializerInfo, bool) {
  226. for _, s := range f.serializers {
  227. for _, accepted := range s.AcceptStreamContentTypes {
  228. if accepted == mediaType {
  229. // TODO: accept params
  230. nested, ok := f.SerializerForMediaType(s.ContentType, nil)
  231. if !ok {
  232. panic("no serializer defined for internal content type")
  233. }
  234. if s.StreamSpecialize != nil && len(params) > 0 {
  235. serializer, ok := s.StreamSpecialize(params)
  236. // TODO: return formatted mediaType+params
  237. return runtime.StreamSerializerInfo{
  238. SerializerInfo: runtime.SerializerInfo{
  239. Serializer: serializer,
  240. MediaType: s.StreamContentType,
  241. EncodesAsText: s.EncodesAsText,
  242. },
  243. Framer: s.Framer,
  244. Embedded: nested,
  245. }, ok
  246. }
  247. return runtime.StreamSerializerInfo{
  248. SerializerInfo: runtime.SerializerInfo{
  249. Serializer: s.StreamSerializer,
  250. MediaType: s.StreamContentType,
  251. EncodesAsText: s.EncodesAsText,
  252. },
  253. Framer: s.Framer,
  254. Embedded: nested,
  255. }, true
  256. }
  257. }
  258. }
  259. return runtime.StreamSerializerInfo{}, false
  260. }
  261. // SerializerForFileExtension returns a serializer for the provided extension, or false if no serializer matches.
  262. func (f CodecFactory) SerializerForFileExtension(extension string) (runtime.Serializer, bool) {
  263. for _, s := range f.serializers {
  264. for _, ext := range s.FileExtensions {
  265. if extension == ext {
  266. return s.Serializer, true
  267. }
  268. }
  269. }
  270. return nil, false
  271. }
  272. // DirectCodecFactory provides methods for retrieving "DirectCodec"s, which do not do conversion.
  273. type DirectCodecFactory struct {
  274. CodecFactory
  275. }
  276. // EncoderForVersion returns an encoder that does not do conversion. gv is ignored.
  277. func (f DirectCodecFactory) EncoderForVersion(serializer runtime.Encoder, gv unversioned.GroupVersion) runtime.Encoder {
  278. return DirectCodec{
  279. runtime.NewCodec(serializer, nil),
  280. f.CodecFactory.scheme,
  281. }
  282. }
  283. // DecoderToVersion returns an decoder that does not do conversion. gv is ignored.
  284. func (f DirectCodecFactory) DecoderToVersion(serializer runtime.Decoder, gv unversioned.GroupVersion) runtime.Decoder {
  285. return DirectCodec{
  286. runtime.NewCodec(nil, serializer),
  287. nil,
  288. }
  289. }
  290. // DirectCodec is a codec that does not do conversion. It sets the gvk during serialization, and removes the gvk during deserialization.
  291. type DirectCodec struct {
  292. runtime.Serializer
  293. runtime.ObjectTyper
  294. }
  295. // EncodeToStream does not do conversion. It sets the gvk during serialization. overrides are ignored.
  296. func (c DirectCodec) Encode(obj runtime.Object, stream io.Writer) error {
  297. gvks, _, err := c.ObjectTyper.ObjectKinds(obj)
  298. if err != nil {
  299. return err
  300. }
  301. kind := obj.GetObjectKind()
  302. oldGVK := kind.GroupVersionKind()
  303. kind.SetGroupVersionKind(gvks[0])
  304. err = c.Serializer.Encode(obj, stream)
  305. kind.SetGroupVersionKind(oldGVK)
  306. return err
  307. }
  308. // Decode does not do conversion. It removes the gvk during deserialization.
  309. func (c DirectCodec) Decode(data []byte, defaults *unversioned.GroupVersionKind, into runtime.Object) (runtime.Object, *unversioned.GroupVersionKind, error) {
  310. obj, gvk, err := c.Serializer.Decode(data, defaults, into)
  311. if obj != nil {
  312. kind := obj.GetObjectKind()
  313. // clearing the gvk is just a convention of a codec
  314. kind.SetGroupVersionKind(unversioned.GroupVersionKind{})
  315. }
  316. return obj, gvk, err
  317. }