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