You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

289 lines
8.2 KiB

  1. /*
  2. *
  3. * Copyright 2014 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package grpc
  19. import (
  20. "bytes"
  21. "compress/gzip"
  22. "io"
  23. "math"
  24. "reflect"
  25. "testing"
  26. "github.com/golang/protobuf/proto"
  27. "google.golang.org/grpc/codes"
  28. "google.golang.org/grpc/encoding"
  29. protoenc "google.golang.org/grpc/encoding/proto"
  30. "google.golang.org/grpc/internal/transport"
  31. "google.golang.org/grpc/status"
  32. perfpb "google.golang.org/grpc/test/codec_perf"
  33. )
  34. type fullReader struct {
  35. reader io.Reader
  36. }
  37. func (f fullReader) Read(p []byte) (int, error) {
  38. return io.ReadFull(f.reader, p)
  39. }
  40. var _ CallOption = EmptyCallOption{} // ensure EmptyCallOption implements the interface
  41. func (s) TestSimpleParsing(t *testing.T) {
  42. bigMsg := bytes.Repeat([]byte{'x'}, 1<<24)
  43. for _, test := range []struct {
  44. // input
  45. p []byte
  46. // outputs
  47. err error
  48. b []byte
  49. pt payloadFormat
  50. }{
  51. {nil, io.EOF, nil, compressionNone},
  52. {[]byte{0, 0, 0, 0, 0}, nil, nil, compressionNone},
  53. {[]byte{0, 0, 0, 0, 1, 'a'}, nil, []byte{'a'}, compressionNone},
  54. {[]byte{1, 0}, io.ErrUnexpectedEOF, nil, compressionNone},
  55. {[]byte{0, 0, 0, 0, 10, 'a'}, io.ErrUnexpectedEOF, nil, compressionNone},
  56. // Check that messages with length >= 2^24 are parsed.
  57. {append([]byte{0, 1, 0, 0, 0}, bigMsg...), nil, bigMsg, compressionNone},
  58. } {
  59. buf := fullReader{bytes.NewReader(test.p)}
  60. parser := &parser{r: buf}
  61. pt, b, err := parser.recvMsg(math.MaxInt32)
  62. if err != test.err || !bytes.Equal(b, test.b) || pt != test.pt {
  63. t.Fatalf("parser{%v}.recvMsg(_) = %v, %v, %v\nwant %v, %v, %v", test.p, pt, b, err, test.pt, test.b, test.err)
  64. }
  65. }
  66. }
  67. func (s) TestMultipleParsing(t *testing.T) {
  68. // Set a byte stream consists of 3 messages with their headers.
  69. p := []byte{0, 0, 0, 0, 1, 'a', 0, 0, 0, 0, 2, 'b', 'c', 0, 0, 0, 0, 1, 'd'}
  70. b := fullReader{bytes.NewReader(p)}
  71. parser := &parser{r: b}
  72. wantRecvs := []struct {
  73. pt payloadFormat
  74. data []byte
  75. }{
  76. {compressionNone, []byte("a")},
  77. {compressionNone, []byte("bc")},
  78. {compressionNone, []byte("d")},
  79. }
  80. for i, want := range wantRecvs {
  81. pt, data, err := parser.recvMsg(math.MaxInt32)
  82. if err != nil || pt != want.pt || !reflect.DeepEqual(data, want.data) {
  83. t.Fatalf("after %d calls, parser{%v}.recvMsg(_) = %v, %v, %v\nwant %v, %v, <nil>",
  84. i, p, pt, data, err, want.pt, want.data)
  85. }
  86. }
  87. pt, data, err := parser.recvMsg(math.MaxInt32)
  88. if err != io.EOF {
  89. t.Fatalf("after %d recvMsgs calls, parser{%v}.recvMsg(_) = %v, %v, %v\nwant _, _, %v",
  90. len(wantRecvs), p, pt, data, err, io.EOF)
  91. }
  92. }
  93. func (s) TestEncode(t *testing.T) {
  94. for _, test := range []struct {
  95. // input
  96. msg proto.Message
  97. // outputs
  98. hdr []byte
  99. data []byte
  100. err error
  101. }{
  102. {nil, []byte{0, 0, 0, 0, 0}, []byte{}, nil},
  103. } {
  104. data, err := encode(encoding.GetCodec(protoenc.Name), test.msg)
  105. if err != test.err || !bytes.Equal(data, test.data) {
  106. t.Errorf("encode(_, %v) = %v, %v; want %v, %v", test.msg, data, err, test.data, test.err)
  107. continue
  108. }
  109. if hdr, _ := msgHeader(data, nil); !bytes.Equal(hdr, test.hdr) {
  110. t.Errorf("msgHeader(%v, false) = %v; want %v", data, hdr, test.hdr)
  111. }
  112. }
  113. }
  114. func (s) TestCompress(t *testing.T) {
  115. bestCompressor, err := NewGZIPCompressorWithLevel(gzip.BestCompression)
  116. if err != nil {
  117. t.Fatalf("Could not initialize gzip compressor with best compression.")
  118. }
  119. bestSpeedCompressor, err := NewGZIPCompressorWithLevel(gzip.BestSpeed)
  120. if err != nil {
  121. t.Fatalf("Could not initialize gzip compressor with best speed compression.")
  122. }
  123. defaultCompressor, err := NewGZIPCompressorWithLevel(gzip.BestSpeed)
  124. if err != nil {
  125. t.Fatalf("Could not initialize gzip compressor with default compression.")
  126. }
  127. level5, err := NewGZIPCompressorWithLevel(5)
  128. if err != nil {
  129. t.Fatalf("Could not initialize gzip compressor with level 5 compression.")
  130. }
  131. for _, test := range []struct {
  132. // input
  133. data []byte
  134. cp Compressor
  135. dc Decompressor
  136. // outputs
  137. err error
  138. }{
  139. {make([]byte, 1024), NewGZIPCompressor(), NewGZIPDecompressor(), nil},
  140. {make([]byte, 1024), bestCompressor, NewGZIPDecompressor(), nil},
  141. {make([]byte, 1024), bestSpeedCompressor, NewGZIPDecompressor(), nil},
  142. {make([]byte, 1024), defaultCompressor, NewGZIPDecompressor(), nil},
  143. {make([]byte, 1024), level5, NewGZIPDecompressor(), nil},
  144. } {
  145. b := new(bytes.Buffer)
  146. if err := test.cp.Do(b, test.data); err != test.err {
  147. t.Fatalf("Compressor.Do(_, %v) = %v, want %v", test.data, err, test.err)
  148. }
  149. if b.Len() >= len(test.data) {
  150. t.Fatalf("The compressor fails to compress data.")
  151. }
  152. if p, err := test.dc.Do(b); err != nil || !bytes.Equal(test.data, p) {
  153. t.Fatalf("Decompressor.Do(%v) = %v, %v, want %v, <nil>", b, p, err, test.data)
  154. }
  155. }
  156. }
  157. func (s) TestToRPCErr(t *testing.T) {
  158. for _, test := range []struct {
  159. // input
  160. errIn error
  161. // outputs
  162. errOut error
  163. }{
  164. {transport.ErrConnClosing, status.Error(codes.Unavailable, transport.ErrConnClosing.Desc)},
  165. {io.ErrUnexpectedEOF, status.Error(codes.Internal, io.ErrUnexpectedEOF.Error())},
  166. } {
  167. err := toRPCErr(test.errIn)
  168. if _, ok := status.FromError(err); !ok {
  169. t.Fatalf("toRPCErr{%v} returned type %T, want %T", test.errIn, err, status.Error(codes.Unknown, ""))
  170. }
  171. if !reflect.DeepEqual(err, test.errOut) {
  172. t.Fatalf("toRPCErr{%v} = %v \nwant %v", test.errIn, err, test.errOut)
  173. }
  174. }
  175. }
  176. func (s) TestParseDialTarget(t *testing.T) {
  177. for _, test := range []struct {
  178. target, wantNet, wantAddr string
  179. }{
  180. {"unix:etcd:0", "unix", "etcd:0"},
  181. {"unix:///tmp/unix-3", "unix", "/tmp/unix-3"},
  182. {"unix://domain", "unix", "domain"},
  183. {"unix://etcd:0", "unix", "etcd:0"},
  184. {"unix:///etcd:0", "unix", "/etcd:0"},
  185. {"passthrough://unix://domain", "tcp", "passthrough://unix://domain"},
  186. {"https://google.com:443", "tcp", "https://google.com:443"},
  187. {"dns:///google.com", "tcp", "dns:///google.com"},
  188. {"/unix/socket/address", "tcp", "/unix/socket/address"},
  189. } {
  190. gotNet, gotAddr := parseDialTarget(test.target)
  191. if gotNet != test.wantNet || gotAddr != test.wantAddr {
  192. t.Errorf("parseDialTarget(%q) = %s, %s want %s, %s", test.target, gotNet, gotAddr, test.wantNet, test.wantAddr)
  193. }
  194. }
  195. }
  196. // bmEncode benchmarks encoding a Protocol Buffer message containing mSize
  197. // bytes.
  198. func bmEncode(b *testing.B, mSize int) {
  199. cdc := encoding.GetCodec(protoenc.Name)
  200. msg := &perfpb.Buffer{Body: make([]byte, mSize)}
  201. encodeData, _ := encode(cdc, msg)
  202. encodedSz := int64(len(encodeData))
  203. b.ReportAllocs()
  204. b.ResetTimer()
  205. for i := 0; i < b.N; i++ {
  206. encode(cdc, msg)
  207. }
  208. b.SetBytes(encodedSz)
  209. }
  210. func BenchmarkEncode1B(b *testing.B) {
  211. bmEncode(b, 1)
  212. }
  213. func BenchmarkEncode1KiB(b *testing.B) {
  214. bmEncode(b, 1024)
  215. }
  216. func BenchmarkEncode8KiB(b *testing.B) {
  217. bmEncode(b, 8*1024)
  218. }
  219. func BenchmarkEncode64KiB(b *testing.B) {
  220. bmEncode(b, 64*1024)
  221. }
  222. func BenchmarkEncode512KiB(b *testing.B) {
  223. bmEncode(b, 512*1024)
  224. }
  225. func BenchmarkEncode1MiB(b *testing.B) {
  226. bmEncode(b, 1024*1024)
  227. }
  228. // bmCompressor benchmarks a compressor of a Protocol Buffer message containing
  229. // mSize bytes.
  230. func bmCompressor(b *testing.B, mSize int, cp Compressor) {
  231. payload := make([]byte, mSize)
  232. cBuf := bytes.NewBuffer(make([]byte, mSize))
  233. b.ReportAllocs()
  234. b.ResetTimer()
  235. for i := 0; i < b.N; i++ {
  236. cp.Do(cBuf, payload)
  237. cBuf.Reset()
  238. }
  239. }
  240. func BenchmarkGZIPCompressor1B(b *testing.B) {
  241. bmCompressor(b, 1, NewGZIPCompressor())
  242. }
  243. func BenchmarkGZIPCompressor1KiB(b *testing.B) {
  244. bmCompressor(b, 1024, NewGZIPCompressor())
  245. }
  246. func BenchmarkGZIPCompressor8KiB(b *testing.B) {
  247. bmCompressor(b, 8*1024, NewGZIPCompressor())
  248. }
  249. func BenchmarkGZIPCompressor64KiB(b *testing.B) {
  250. bmCompressor(b, 64*1024, NewGZIPCompressor())
  251. }
  252. func BenchmarkGZIPCompressor512KiB(b *testing.B) {
  253. bmCompressor(b, 512*1024, NewGZIPCompressor())
  254. }
  255. func BenchmarkGZIPCompressor1MiB(b *testing.B) {
  256. bmCompressor(b, 1024*1024, NewGZIPCompressor())
  257. }