serialization_proto_test.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /*
  2. Copyright 2015 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 testing
  14. import (
  15. "bytes"
  16. "encoding/hex"
  17. "fmt"
  18. "math/rand"
  19. "reflect"
  20. "testing"
  21. "github.com/gogo/protobuf/proto"
  22. "k8s.io/api/core/v1"
  23. "k8s.io/apimachinery/pkg/api/apitesting/fuzzer"
  24. apiequality "k8s.io/apimachinery/pkg/api/equality"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/runtime"
  27. "k8s.io/apimachinery/pkg/runtime/schema"
  28. "k8s.io/apimachinery/pkg/runtime/serializer/protobuf"
  29. "k8s.io/apimachinery/pkg/util/diff"
  30. "k8s.io/kubernetes/pkg/api/legacyscheme"
  31. api "k8s.io/kubernetes/pkg/apis/core"
  32. _ "k8s.io/kubernetes/pkg/apis/extensions"
  33. _ "k8s.io/kubernetes/pkg/apis/extensions/v1beta1"
  34. )
  35. func TestUniversalDeserializer(t *testing.T) {
  36. expected := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "test"}, TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Pod"}}
  37. d := legacyscheme.Codecs.UniversalDeserializer()
  38. for _, mediaType := range []string{"application/json", "application/yaml", "application/vnd.kubernetes.protobuf"} {
  39. info, ok := runtime.SerializerInfoForMediaType(legacyscheme.Codecs.SupportedMediaTypes(), mediaType)
  40. if !ok {
  41. t.Fatal(mediaType)
  42. }
  43. buf := &bytes.Buffer{}
  44. if err := info.Serializer.Encode(expected, buf); err != nil {
  45. t.Fatalf("%s: %v", mediaType, err)
  46. }
  47. obj, _, err := d.Decode(buf.Bytes(), &schema.GroupVersionKind{Kind: "Pod", Version: "v1"}, nil)
  48. if err != nil {
  49. t.Fatalf("%s: %v", mediaType, err)
  50. }
  51. if !apiequality.Semantic.DeepEqual(expected, obj) {
  52. t.Fatalf("%s: %#v", mediaType, obj)
  53. }
  54. }
  55. }
  56. func TestAllFieldsHaveTags(t *testing.T) {
  57. for gvk, obj := range legacyscheme.Scheme.AllKnownTypes() {
  58. if gvk.Version == runtime.APIVersionInternal {
  59. // internal versions are not serialized to protobuf
  60. continue
  61. }
  62. if gvk.Group == "componentconfig" {
  63. // component config is not serialized to protobuf
  64. continue
  65. }
  66. if err := fieldsHaveProtobufTags(obj); err != nil {
  67. t.Errorf("type %s as gvk %v is missing tags: %v", obj, gvk, err)
  68. }
  69. }
  70. }
  71. func fieldsHaveProtobufTags(obj reflect.Type) error {
  72. switch obj.Kind() {
  73. case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Array:
  74. return fieldsHaveProtobufTags(obj.Elem())
  75. case reflect.Struct:
  76. for i := 0; i < obj.NumField(); i++ {
  77. f := obj.Field(i)
  78. if f.Name == "TypeMeta" && f.Type.Name() == "TypeMeta" {
  79. // TypeMeta is not included in external protobuf because we use an envelope type with TypeMeta
  80. continue
  81. }
  82. if len(f.Tag.Get("json")) > 0 && len(f.Tag.Get("protobuf")) == 0 {
  83. return fmt.Errorf("field %s in %s has a 'json' tag but no protobuf tag", f.Name, obj)
  84. }
  85. }
  86. }
  87. return nil
  88. }
  89. func TestProtobufRoundTrip(t *testing.T) {
  90. obj := &v1.Pod{}
  91. fuzzer.FuzzerFor(FuzzerFuncs, rand.NewSource(benchmarkSeed), legacyscheme.Codecs).Fuzz(obj)
  92. // InitContainers are turned into annotations by conversion.
  93. obj.Spec.InitContainers = nil
  94. obj.Status.InitContainerStatuses = nil
  95. data, err := obj.Marshal()
  96. if err != nil {
  97. t.Fatal(err)
  98. }
  99. out := &v1.Pod{}
  100. if err := out.Unmarshal(data); err != nil {
  101. t.Fatal(err)
  102. }
  103. if !apiequality.Semantic.Equalities.DeepEqual(out, obj) {
  104. t.Logf("marshal\n%s", hex.Dump(data))
  105. t.Fatalf("Unmarshal is unequal\n%s", diff.ObjectGoPrintDiff(out, obj))
  106. }
  107. }
  108. // BenchmarkEncodeCodec measures the cost of performing a codec encode, which includes
  109. // reflection (to clear APIVersion and Kind)
  110. func BenchmarkEncodeCodecProtobuf(b *testing.B) {
  111. items := benchmarkItems(b)
  112. width := len(items)
  113. s := protobuf.NewSerializer(nil, nil)
  114. b.ResetTimer()
  115. for i := 0; i < b.N; i++ {
  116. if _, err := runtime.Encode(s, &items[i%width]); err != nil {
  117. b.Fatal(err)
  118. }
  119. }
  120. b.StopTimer()
  121. }
  122. // BenchmarkEncodeCodecFromInternalProtobuf measures the cost of performing a codec encode,
  123. // including conversions and any type setting. This is a "full" encode.
  124. func BenchmarkEncodeCodecFromInternalProtobuf(b *testing.B) {
  125. items := benchmarkItems(b)
  126. width := len(items)
  127. encodable := make([]api.Pod, width)
  128. for i := range items {
  129. if err := legacyscheme.Scheme.Convert(&items[i], &encodable[i], nil); err != nil {
  130. b.Fatal(err)
  131. }
  132. }
  133. s := protobuf.NewSerializer(nil, nil)
  134. codec := legacyscheme.Codecs.EncoderForVersion(s, v1.SchemeGroupVersion)
  135. b.ResetTimer()
  136. for i := 0; i < b.N; i++ {
  137. if _, err := runtime.Encode(codec, &encodable[i%width]); err != nil {
  138. b.Fatal(err)
  139. }
  140. }
  141. b.StopTimer()
  142. }
  143. func BenchmarkEncodeProtobufGeneratedMarshal(b *testing.B) {
  144. items := benchmarkItems(b)
  145. width := len(items)
  146. b.ResetTimer()
  147. for i := 0; i < b.N; i++ {
  148. if _, err := items[i%width].Marshal(); err != nil {
  149. b.Fatal(err)
  150. }
  151. }
  152. b.StopTimer()
  153. }
  154. // BenchmarkDecodeCodecToInternalProtobuf measures the cost of performing a codec decode,
  155. // including conversions and any type setting. This is a "full" decode.
  156. func BenchmarkDecodeCodecToInternalProtobuf(b *testing.B) {
  157. items := benchmarkItems(b)
  158. width := len(items)
  159. s := protobuf.NewSerializer(legacyscheme.Scheme, legacyscheme.Scheme)
  160. encoder := legacyscheme.Codecs.EncoderForVersion(s, v1.SchemeGroupVersion)
  161. var encoded [][]byte
  162. for i := range items {
  163. data, err := runtime.Encode(encoder, &items[i])
  164. if err != nil {
  165. b.Fatal(err)
  166. }
  167. encoded = append(encoded, data)
  168. }
  169. decoder := legacyscheme.Codecs.DecoderToVersion(s, api.SchemeGroupVersion)
  170. b.ResetTimer()
  171. for i := 0; i < b.N; i++ {
  172. if _, err := runtime.Decode(decoder, encoded[i%width]); err != nil {
  173. b.Fatal(err)
  174. }
  175. }
  176. b.StopTimer()
  177. }
  178. // BenchmarkDecodeJSON provides a baseline for regular JSON decode performance
  179. func BenchmarkDecodeIntoProtobuf(b *testing.B) {
  180. items := benchmarkItems(b)
  181. width := len(items)
  182. encoded := make([][]byte, width)
  183. for i := range items {
  184. data, err := (&items[i]).Marshal()
  185. if err != nil {
  186. b.Fatal(err)
  187. }
  188. encoded[i] = data
  189. validate := &v1.Pod{}
  190. if err := proto.Unmarshal(data, validate); err != nil {
  191. b.Fatalf("Failed to unmarshal %d: %v\n%#v", i, err, items[i])
  192. }
  193. }
  194. for i := 0; i < b.N; i++ {
  195. obj := v1.Pod{}
  196. if err := proto.Unmarshal(encoded[i%width], &obj); err != nil {
  197. b.Fatal(err)
  198. }
  199. }
  200. }