versioning.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 versioning
  14. import (
  15. "io"
  16. "reflect"
  17. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  18. "k8s.io/apimachinery/pkg/runtime"
  19. "k8s.io/apimachinery/pkg/runtime/schema"
  20. )
  21. // NewDefaultingCodecForScheme is a convenience method for callers that are using a scheme.
  22. func NewDefaultingCodecForScheme(
  23. // TODO: I should be a scheme interface?
  24. scheme *runtime.Scheme,
  25. encoder runtime.Encoder,
  26. decoder runtime.Decoder,
  27. encodeVersion runtime.GroupVersioner,
  28. decodeVersion runtime.GroupVersioner,
  29. ) runtime.Codec {
  30. return NewCodec(encoder, decoder, runtime.UnsafeObjectConvertor(scheme), scheme, scheme, scheme, encodeVersion, decodeVersion, scheme.Name())
  31. }
  32. // NewCodec takes objects in their internal versions and converts them to external versions before
  33. // serializing them. It assumes the serializer provided to it only deals with external versions.
  34. // This class is also a serializer, but is generally used with a specific version.
  35. func NewCodec(
  36. encoder runtime.Encoder,
  37. decoder runtime.Decoder,
  38. convertor runtime.ObjectConvertor,
  39. creater runtime.ObjectCreater,
  40. typer runtime.ObjectTyper,
  41. defaulter runtime.ObjectDefaulter,
  42. encodeVersion runtime.GroupVersioner,
  43. decodeVersion runtime.GroupVersioner,
  44. originalSchemeName string,
  45. ) runtime.Codec {
  46. internal := &codec{
  47. encoder: encoder,
  48. decoder: decoder,
  49. convertor: convertor,
  50. creater: creater,
  51. typer: typer,
  52. defaulter: defaulter,
  53. encodeVersion: encodeVersion,
  54. decodeVersion: decodeVersion,
  55. originalSchemeName: originalSchemeName,
  56. }
  57. return internal
  58. }
  59. type codec struct {
  60. encoder runtime.Encoder
  61. decoder runtime.Decoder
  62. convertor runtime.ObjectConvertor
  63. creater runtime.ObjectCreater
  64. typer runtime.ObjectTyper
  65. defaulter runtime.ObjectDefaulter
  66. encodeVersion runtime.GroupVersioner
  67. decodeVersion runtime.GroupVersioner
  68. // originalSchemeName is optional, but when filled in it holds the name of the scheme from which this codec originates
  69. originalSchemeName string
  70. }
  71. // Decode attempts a decode of the object, then tries to convert it to the internal version. If into is provided and the decoding is
  72. // successful, the returned runtime.Object will be the value passed as into. Note that this may bypass conversion if you pass an
  73. // into that matches the serialized version.
  74. func (c *codec) Decode(data []byte, defaultGVK *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
  75. versioned, isVersioned := into.(*runtime.VersionedObjects)
  76. if isVersioned {
  77. into = versioned.Last()
  78. }
  79. // If the into object is unstructured and expresses an opinion about its group/version,
  80. // create a new instance of the type so we always exercise the conversion path (skips short-circuiting on `into == obj`)
  81. decodeInto := into
  82. if into != nil {
  83. if _, ok := into.(runtime.Unstructured); ok && !into.GetObjectKind().GroupVersionKind().GroupVersion().Empty() {
  84. decodeInto = reflect.New(reflect.TypeOf(into).Elem()).Interface().(runtime.Object)
  85. }
  86. }
  87. obj, gvk, err := c.decoder.Decode(data, defaultGVK, decodeInto)
  88. if err != nil {
  89. return nil, gvk, err
  90. }
  91. if d, ok := obj.(runtime.NestedObjectDecoder); ok {
  92. if err := d.DecodeNestedObjects(DirectDecoder{c.decoder}); err != nil {
  93. return nil, gvk, err
  94. }
  95. }
  96. // if we specify a target, use generic conversion.
  97. if into != nil {
  98. if into == obj {
  99. if isVersioned {
  100. return versioned, gvk, nil
  101. }
  102. return into, gvk, nil
  103. }
  104. // perform defaulting if requested
  105. if c.defaulter != nil {
  106. // create a copy to ensure defaulting is not applied to the original versioned objects
  107. if isVersioned {
  108. versioned.Objects = []runtime.Object{obj.DeepCopyObject()}
  109. }
  110. c.defaulter.Default(obj)
  111. } else {
  112. if isVersioned {
  113. versioned.Objects = []runtime.Object{obj}
  114. }
  115. }
  116. if err := c.convertor.Convert(obj, into, c.decodeVersion); err != nil {
  117. return nil, gvk, err
  118. }
  119. if isVersioned {
  120. versioned.Objects = append(versioned.Objects, into)
  121. return versioned, gvk, nil
  122. }
  123. return into, gvk, nil
  124. }
  125. // Convert if needed.
  126. if isVersioned {
  127. // create a copy, because ConvertToVersion does not guarantee non-mutation of objects
  128. versioned.Objects = []runtime.Object{obj.DeepCopyObject()}
  129. }
  130. // perform defaulting if requested
  131. if c.defaulter != nil {
  132. c.defaulter.Default(obj)
  133. }
  134. out, err := c.convertor.ConvertToVersion(obj, c.decodeVersion)
  135. if err != nil {
  136. return nil, gvk, err
  137. }
  138. if isVersioned {
  139. if versioned.Last() != out {
  140. versioned.Objects = append(versioned.Objects, out)
  141. }
  142. return versioned, gvk, nil
  143. }
  144. return out, gvk, nil
  145. }
  146. // Encode ensures the provided object is output in the appropriate group and version, invoking
  147. // conversion if necessary. Unversioned objects (according to the ObjectTyper) are output as is.
  148. func (c *codec) Encode(obj runtime.Object, w io.Writer) error {
  149. switch obj := obj.(type) {
  150. case *runtime.Unknown:
  151. return c.encoder.Encode(obj, w)
  152. case runtime.Unstructured:
  153. // An unstructured list can contain objects of multiple group version kinds. don't short-circuit just
  154. // because the top-level type matches our desired destination type. actually send the object to the converter
  155. // to give it a chance to convert the list items if needed.
  156. if _, ok := obj.(*unstructured.UnstructuredList); !ok {
  157. // avoid conversion roundtrip if GVK is the right one already or is empty (yes, this is a hack, but the old behaviour we rely on in kubectl)
  158. objGVK := obj.GetObjectKind().GroupVersionKind()
  159. if len(objGVK.Version) == 0 {
  160. return c.encoder.Encode(obj, w)
  161. }
  162. targetGVK, ok := c.encodeVersion.KindForGroupVersionKinds([]schema.GroupVersionKind{objGVK})
  163. if !ok {
  164. return runtime.NewNotRegisteredGVKErrForTarget(c.originalSchemeName, objGVK, c.encodeVersion)
  165. }
  166. if targetGVK == objGVK {
  167. return c.encoder.Encode(obj, w)
  168. }
  169. }
  170. }
  171. gvks, isUnversioned, err := c.typer.ObjectKinds(obj)
  172. if err != nil {
  173. return err
  174. }
  175. if c.encodeVersion == nil || isUnversioned {
  176. if e, ok := obj.(runtime.NestedObjectEncoder); ok {
  177. if err := e.EncodeNestedObjects(DirectEncoder{Encoder: c.encoder, ObjectTyper: c.typer}); err != nil {
  178. return err
  179. }
  180. }
  181. objectKind := obj.GetObjectKind()
  182. old := objectKind.GroupVersionKind()
  183. objectKind.SetGroupVersionKind(gvks[0])
  184. err = c.encoder.Encode(obj, w)
  185. objectKind.SetGroupVersionKind(old)
  186. return err
  187. }
  188. // Perform a conversion if necessary
  189. objectKind := obj.GetObjectKind()
  190. old := objectKind.GroupVersionKind()
  191. out, err := c.convertor.ConvertToVersion(obj, c.encodeVersion)
  192. if err != nil {
  193. return err
  194. }
  195. if e, ok := out.(runtime.NestedObjectEncoder); ok {
  196. if err := e.EncodeNestedObjects(DirectEncoder{Version: c.encodeVersion, Encoder: c.encoder, ObjectTyper: c.typer}); err != nil {
  197. return err
  198. }
  199. }
  200. // Conversion is responsible for setting the proper group, version, and kind onto the outgoing object
  201. err = c.encoder.Encode(out, w)
  202. // restore the old GVK, in case conversion returned the same object
  203. objectKind.SetGroupVersionKind(old)
  204. return err
  205. }
  206. // DirectEncoder serializes an object and ensures the GVK is set.
  207. type DirectEncoder struct {
  208. Version runtime.GroupVersioner
  209. runtime.Encoder
  210. runtime.ObjectTyper
  211. }
  212. // Encode does not do conversion. It sets the gvk during serialization.
  213. func (e DirectEncoder) Encode(obj runtime.Object, stream io.Writer) error {
  214. gvks, _, err := e.ObjectTyper.ObjectKinds(obj)
  215. if err != nil {
  216. if runtime.IsNotRegisteredError(err) {
  217. return e.Encoder.Encode(obj, stream)
  218. }
  219. return err
  220. }
  221. kind := obj.GetObjectKind()
  222. oldGVK := kind.GroupVersionKind()
  223. gvk := gvks[0]
  224. if e.Version != nil {
  225. preferredGVK, ok := e.Version.KindForGroupVersionKinds(gvks)
  226. if ok {
  227. gvk = preferredGVK
  228. }
  229. }
  230. kind.SetGroupVersionKind(gvk)
  231. err = e.Encoder.Encode(obj, stream)
  232. kind.SetGroupVersionKind(oldGVK)
  233. return err
  234. }
  235. // DirectDecoder clears the group version kind of a deserialized object.
  236. type DirectDecoder struct {
  237. runtime.Decoder
  238. }
  239. // Decode does not do conversion. It removes the gvk during deserialization.
  240. func (d DirectDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
  241. obj, gvk, err := d.Decoder.Decode(data, defaults, into)
  242. if obj != nil {
  243. kind := obj.GetObjectKind()
  244. // clearing the gvk is just a convention of a codec
  245. kind.SetGroupVersionKind(schema.GroupVersionKind{})
  246. }
  247. return obj, gvk, err
  248. }