pkg/runtime/serializer/codec_factory.go

对原始decoder、encoder的封装:

  1. 在decoder中会清除对象的GroupVersionKind
  2. 在encoder中,会在序列化时写入GroupVersionKind
  1. // WithoutConversionCodecFactory is a CodecFactory that will explicitly ignore requests to perform conversion.
  2. // This wrapper is used while code migrates away from using conversion (such as external clients) and in the future
  3. // will be unnecessary when we change the signature of NegotiatedSerializer.
  4. type WithoutConversionCodecFactory struct {
  5. CodecFactory
  6. }
  7. // EncoderForVersion returns an encoder that does not do conversion, but does set the group version kind of the object
  8. // when serialized.
  9. func (f WithoutConversionCodecFactory) EncoderForVersion(serializer runtime.Encoder, version runtime.GroupVersioner) runtime.Encoder {
  10. return runtime.WithVersionEncoder{
  11. Version: version,
  12. Encoder: serializer,
  13. ObjectTyper: f.CodecFactory.scheme,
  14. }
  15. }
  16. // DecoderToVersion returns an decoder that does not do conversion.
  17. func (f WithoutConversionCodecFactory) DecoderToVersion(serializer runtime.Decoder, _ runtime.GroupVersioner) runtime.Decoder {
  18. return runtime.WithoutVersionDecoder{
  19. Decoder: serializer,
  20. }
  21. }

WithoutVersionDecoder:

  1. // WithoutVersionDecoder clears the group version kind of a deserialized object.
  2. type WithoutVersionDecoder struct {
  3. Decoder
  4. }
  5. // Decode does not do conversion. It removes the gvk during deserialization.
  6. func (d WithoutVersionDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {
  7. obj, gvk, err := d.Decoder.Decode(data, defaults, into)
  8. if obj != nil {
  9. kind := obj.GetObjectKind()
  10. // clearing the gvk is just a convention of a codec
  11. kind.SetGroupVersionKind(schema.GroupVersionKind{})
  12. }
  13. return obj, gvk, err
  14. }

WithVersionEncoder:

  1. // WithVersionEncoder serializes an object and ensures the GVK is set.
  2. type WithVersionEncoder struct {
  3. Version GroupVersioner
  4. Encoder
  5. ObjectTyper
  6. }
  7. // Encode does not do conversion. It sets the gvk during serialization.
  8. func (e WithVersionEncoder) Encode(obj Object, stream io.Writer) error {
  9. gvks, _, err := e.ObjectTyper.ObjectKinds(obj)
  10. if err != nil {
  11. if IsNotRegisteredError(err) {
  12. return e.Encoder.Encode(obj, stream)
  13. }
  14. return err
  15. }
  16. kind := obj.GetObjectKind()
  17. oldGVK := kind.GroupVersionKind()
  18. gvk := gvks[0]
  19. if e.Version != nil {
  20. preferredGVK, ok := e.Version.KindForGroupVersionKinds(gvks)
  21. if ok {
  22. gvk = preferredGVK
  23. }
  24. }
  25. kind.SetGroupVersionKind(gvk)
  26. err = e.Encoder.Encode(obj, stream)
  27. kind.SetGroupVersionKind(oldGVK)
  28. return err
  29. }