codec_factory.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 serializer
  14. import (
  15. "k8s.io/apimachinery/pkg/runtime"
  16. "k8s.io/apimachinery/pkg/runtime/schema"
  17. "k8s.io/apimachinery/pkg/runtime/serializer/json"
  18. "k8s.io/apimachinery/pkg/runtime/serializer/protobuf"
  19. "k8s.io/apimachinery/pkg/runtime/serializer/recognizer"
  20. "k8s.io/apimachinery/pkg/runtime/serializer/versioning"
  21. )
  22. func newSerializersForScheme(scheme *runtime.Scheme, mf json.MetaFactory, options CodecFactoryOptions) []runtime.SerializerInfo {
  23. jsonSerializer := json.NewSerializerWithOptions(
  24. mf, scheme, scheme,
  25. json.SerializerOptions{Yaml: false, Pretty: false, Strict: options.Strict, StreamingCollectionsEncoding: options.StreamingCollectionsEncodingToJSON},
  26. )
  27. jsonSerializerType := runtime.SerializerInfo{
  28. MediaType: runtime.ContentTypeJSON,
  29. MediaTypeType: "application",
  30. MediaTypeSubType: "json",
  31. EncodesAsText: true,
  32. Serializer: jsonSerializer,
  33. StrictSerializer: json.NewSerializerWithOptions(
  34. mf, scheme, scheme,
  35. json.SerializerOptions{Yaml: false, Pretty: false, Strict: true, StreamingCollectionsEncoding: options.StreamingCollectionsEncodingToJSON},
  36. ),
  37. StreamSerializer: &runtime.StreamSerializerInfo{
  38. EncodesAsText: true,
  39. Serializer: jsonSerializer,
  40. Framer: json.Framer,
  41. },
  42. }
  43. if options.Pretty {
  44. jsonSerializerType.PrettySerializer = json.NewSerializerWithOptions(
  45. mf, scheme, scheme,
  46. json.SerializerOptions{Yaml: false, Pretty: true, Strict: options.Strict},
  47. )
  48. }
  49. yamlSerializer := json.NewSerializerWithOptions(
  50. mf, scheme, scheme,
  51. json.SerializerOptions{Yaml: true, Pretty: false, Strict: options.Strict},
  52. )
  53. strictYAMLSerializer := json.NewSerializerWithOptions(
  54. mf, scheme, scheme,
  55. json.SerializerOptions{Yaml: true, Pretty: false, Strict: true},
  56. )
  57. protoSerializer := protobuf.NewSerializerWithOptions(scheme, scheme, protobuf.SerializerOptions{
  58. StreamingCollectionsEncoding: options.StreamingCollectionsEncodingToProtobuf,
  59. })
  60. protoRawSerializer := protobuf.NewRawSerializer(scheme, scheme)
  61. serializers := []runtime.SerializerInfo{
  62. jsonSerializerType,
  63. {
  64. MediaType: runtime.ContentTypeYAML,
  65. MediaTypeType: "application",
  66. MediaTypeSubType: "yaml",
  67. EncodesAsText: true,
  68. Serializer: yamlSerializer,
  69. StrictSerializer: strictYAMLSerializer,
  70. },
  71. {
  72. MediaType: runtime.ContentTypeProtobuf,
  73. MediaTypeType: "application",
  74. MediaTypeSubType: "vnd.kubernetes.protobuf",
  75. Serializer: protoSerializer,
  76. // note, strict decoding is unsupported for protobuf,
  77. // fall back to regular serializing
  78. StrictSerializer: protoSerializer,
  79. StreamSerializer: &runtime.StreamSerializerInfo{
  80. Serializer: protoRawSerializer,
  81. Framer: protobuf.LengthDelimitedFramer,
  82. },
  83. },
  84. }
  85. for _, f := range options.serializers {
  86. serializers = append(serializers, f(scheme, scheme))
  87. }
  88. return serializers
  89. }
  90. // CodecFactory provides methods for retrieving codecs and serializers for specific
  91. // versions and content types.
  92. type CodecFactory struct {
  93. scheme *runtime.Scheme
  94. universal runtime.Decoder
  95. accepts []runtime.SerializerInfo
  96. legacySerializer runtime.Serializer
  97. }
  98. // CodecFactoryOptions holds the options for configuring CodecFactory behavior
  99. type CodecFactoryOptions struct {
  100. // Strict configures all serializers in strict mode
  101. Strict bool
  102. // Pretty includes a pretty serializer along with the non-pretty one
  103. Pretty bool
  104. StreamingCollectionsEncodingToJSON bool
  105. StreamingCollectionsEncodingToProtobuf bool
  106. serializers []func(runtime.ObjectCreater, runtime.ObjectTyper) runtime.SerializerInfo
  107. }
  108. // CodecFactoryOptionsMutator takes a pointer to an options struct and then modifies it.
  109. // Functions implementing this type can be passed to the NewCodecFactory() constructor.
  110. type CodecFactoryOptionsMutator func(*CodecFactoryOptions)
  111. // EnablePretty enables including a pretty serializer along with the non-pretty one
  112. func EnablePretty(options *CodecFactoryOptions) {
  113. options.Pretty = true
  114. }
  115. // DisablePretty disables including a pretty serializer along with the non-pretty one
  116. func DisablePretty(options *CodecFactoryOptions) {
  117. options.Pretty = false
  118. }
  119. // EnableStrict enables configuring all serializers in strict mode
  120. func EnableStrict(options *CodecFactoryOptions) {
  121. options.Strict = true
  122. }
  123. // DisableStrict disables configuring all serializers in strict mode
  124. func DisableStrict(options *CodecFactoryOptions) {
  125. options.Strict = false
  126. }
  127. // WithSerializer configures a serializer to be supported in addition to the default serializers.
  128. func WithSerializer(f func(runtime.ObjectCreater, runtime.ObjectTyper) runtime.SerializerInfo) CodecFactoryOptionsMutator {
  129. return func(options *CodecFactoryOptions) {
  130. options.serializers = append(options.serializers, f)
  131. }
  132. }
  133. func WithStreamingCollectionEncodingToJSON() CodecFactoryOptionsMutator {
  134. return func(options *CodecFactoryOptions) {
  135. options.StreamingCollectionsEncodingToJSON = true
  136. }
  137. }
  138. func WithStreamingCollectionEncodingToProtobuf() CodecFactoryOptionsMutator {
  139. return func(options *CodecFactoryOptions) {
  140. options.StreamingCollectionsEncodingToProtobuf = true
  141. }
  142. }
  143. // NewCodecFactory provides methods for retrieving serializers for the supported wire formats
  144. // and conversion wrappers to define preferred internal and external versions. In the future,
  145. // as the internal version is used less, callers may instead use a defaulting serializer and
  146. // only convert objects which are shared internally (Status, common API machinery).
  147. //
  148. // Mutators can be passed to change the CodecFactoryOptions before construction of the factory.
  149. // It is recommended to explicitly pass mutators instead of relying on defaults.
  150. // By default, Pretty is enabled -- this is conformant with previously supported behavior.
  151. //
  152. // TODO: allow other codecs to be compiled in?
  153. // TODO: accept a scheme interface
  154. func NewCodecFactory(scheme *runtime.Scheme, mutators ...CodecFactoryOptionsMutator) CodecFactory {
  155. options := CodecFactoryOptions{Pretty: true}
  156. for _, fn := range mutators {
  157. fn(&options)
  158. }
  159. serializers := newSerializersForScheme(scheme, json.DefaultMetaFactory, options)
  160. return newCodecFactory(scheme, serializers)
  161. }
  162. // newCodecFactory is a helper for testing that allows a different metafactory to be specified.
  163. func newCodecFactory(scheme *runtime.Scheme, serializers []runtime.SerializerInfo) CodecFactory {
  164. decoders := make([]runtime.Decoder, 0, len(serializers))
  165. var accepts []runtime.SerializerInfo
  166. alreadyAccepted := make(map[string]struct{})
  167. var legacySerializer runtime.Serializer
  168. for _, d := range serializers {
  169. decoders = append(decoders, d.Serializer)
  170. if _, ok := alreadyAccepted[d.MediaType]; ok {
  171. continue
  172. }
  173. alreadyAccepted[d.MediaType] = struct{}{}
  174. acceptedSerializerShallowCopy := d
  175. if d.StreamSerializer != nil {
  176. cloned := *d.StreamSerializer
  177. acceptedSerializerShallowCopy.StreamSerializer = &cloned
  178. }
  179. accepts = append(accepts, acceptedSerializerShallowCopy)
  180. if d.MediaType == runtime.ContentTypeJSON {
  181. legacySerializer = d.Serializer
  182. }
  183. }
  184. if legacySerializer == nil {
  185. legacySerializer = serializers[0].Serializer
  186. }
  187. return CodecFactory{
  188. scheme: scheme,
  189. universal: recognizer.NewDecoder(decoders...),
  190. accepts: accepts,
  191. legacySerializer: legacySerializer,
  192. }
  193. }
  194. // WithoutConversion returns a NegotiatedSerializer that performs no conversion, even if the
  195. // caller requests it.
  196. func (f CodecFactory) WithoutConversion() runtime.NegotiatedSerializer {
  197. return WithoutConversionCodecFactory{f}
  198. }
  199. // SupportedMediaTypes returns the RFC2046 media types that this factory has serializers for.
  200. func (f CodecFactory) SupportedMediaTypes() []runtime.SerializerInfo {
  201. return f.accepts
  202. }
  203. // LegacyCodec encodes output to a given API versions, and decodes output into the internal form from
  204. // any recognized source. The returned codec will always encode output to JSON. If a type is not
  205. // found in the list of versions an error will be returned.
  206. //
  207. // This method is deprecated - clients and servers should negotiate a serializer by mime-type and
  208. // invoke CodecForVersions. Callers that need only to read data should use UniversalDecoder().
  209. //
  210. // TODO: make this call exist only in pkg/api, and initialize it with the set of default versions.
  211. // All other callers will be forced to request a Codec directly.
  212. func (f CodecFactory) LegacyCodec(version ...schema.GroupVersion) runtime.Codec {
  213. return versioning.NewDefaultingCodecForScheme(f.scheme, f.legacySerializer, f.universal, schema.GroupVersions(version), runtime.InternalGroupVersioner)
  214. }
  215. // UniversalDeserializer can convert any stored data recognized by this factory into a Go object that satisfies
  216. // runtime.Object. It does not perform conversion. It does not perform defaulting.
  217. func (f CodecFactory) UniversalDeserializer() runtime.Decoder {
  218. return f.universal
  219. }
  220. // UniversalDecoder returns a runtime.Decoder capable of decoding all known API objects in all known formats. Used
  221. // by clients that do not need to encode objects but want to deserialize API objects stored on disk. Only decodes
  222. // objects in groups registered with the scheme. The GroupVersions passed may be used to select alternate
  223. // versions of objects to return - by default, runtime.APIVersionInternal is used. If any versions are specified,
  224. // unrecognized groups will be returned in the version they are encoded as (no conversion). This decoder performs
  225. // defaulting.
  226. //
  227. // TODO: the decoder will eventually be removed in favor of dealing with objects in their versioned form
  228. // TODO: only accept a group versioner
  229. func (f CodecFactory) UniversalDecoder(versions ...schema.GroupVersion) runtime.Decoder {
  230. var versioner runtime.GroupVersioner
  231. if len(versions) == 0 {
  232. versioner = runtime.InternalGroupVersioner
  233. } else {
  234. versioner = schema.GroupVersions(versions)
  235. }
  236. return f.CodecForVersions(nil, f.universal, nil, versioner)
  237. }
  238. // CodecForVersions creates a codec with the provided serializer. If an object is decoded and its group is not in the list,
  239. // it will default to runtime.APIVersionInternal. If encode is not specified for an object's group, the object is not
  240. // converted. If encode or decode are nil, no conversion is performed.
  241. func (f CodecFactory) CodecForVersions(encoder runtime.Encoder, decoder runtime.Decoder, encode runtime.GroupVersioner, decode runtime.GroupVersioner) runtime.Codec {
  242. // TODO: these are for backcompat, remove them in the future
  243. if encode == nil {
  244. encode = runtime.DisabledGroupVersioner
  245. }
  246. if decode == nil {
  247. decode = runtime.InternalGroupVersioner
  248. }
  249. return versioning.NewDefaultingCodecForScheme(f.scheme, encoder, decoder, encode, decode)
  250. }
  251. // DecoderToVersion returns a decoder that targets the provided group version.
  252. func (f CodecFactory) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {
  253. return f.CodecForVersions(nil, decoder, nil, gv)
  254. }
  255. // EncoderForVersion returns an encoder that targets the provided group version.
  256. func (f CodecFactory) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {
  257. return f.CodecForVersions(encoder, nil, gv, nil)
  258. }
  259. // WithoutConversionCodecFactory is a CodecFactory that will explicitly ignore requests to perform conversion.
  260. // This wrapper is used while code migrates away from using conversion (such as external clients) and in the future
  261. // will be unnecessary when we change the signature of NegotiatedSerializer.
  262. type WithoutConversionCodecFactory struct {
  263. CodecFactory
  264. }
  265. // EncoderForVersion returns an encoder that does not do conversion, but does set the group version kind of the object
  266. // when serialized.
  267. func (f WithoutConversionCodecFactory) EncoderForVersion(serializer runtime.Encoder, version runtime.GroupVersioner) runtime.Encoder {
  268. return runtime.WithVersionEncoder{
  269. Version: version,
  270. Encoder: serializer,
  271. ObjectTyper: f.CodecFactory.scheme,
  272. }
  273. }
  274. // DecoderToVersion returns an decoder that does not do conversion.
  275. func (f WithoutConversionCodecFactory) DecoderToVersion(serializer runtime.Decoder, _ runtime.GroupVersioner) runtime.Decoder {
  276. return runtime.WithoutVersionDecoder{
  277. Decoder: serializer,
  278. }
  279. }