rpc_util.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /*
  2. *
  3. * Copyright 2014, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. package grpc
  34. import (
  35. "bytes"
  36. "compress/gzip"
  37. "encoding/binary"
  38. "fmt"
  39. "io"
  40. "io/ioutil"
  41. "math"
  42. "math/rand"
  43. "os"
  44. "time"
  45. "github.com/golang/protobuf/proto"
  46. "golang.org/x/net/context"
  47. "google.golang.org/grpc/codes"
  48. "google.golang.org/grpc/metadata"
  49. "google.golang.org/grpc/transport"
  50. )
  51. // Codec defines the interface gRPC uses to encode and decode messages.
  52. type Codec interface {
  53. // Marshal returns the wire format of v.
  54. Marshal(v interface{}) ([]byte, error)
  55. // Unmarshal parses the wire format into v.
  56. Unmarshal(data []byte, v interface{}) error
  57. // String returns the name of the Codec implementation. The returned
  58. // string will be used as part of content type in transmission.
  59. String() string
  60. }
  61. // protoCodec is a Codec implemetation with protobuf. It is the default codec for gRPC.
  62. type protoCodec struct{}
  63. func (protoCodec) Marshal(v interface{}) ([]byte, error) {
  64. return proto.Marshal(v.(proto.Message))
  65. }
  66. func (protoCodec) Unmarshal(data []byte, v interface{}) error {
  67. return proto.Unmarshal(data, v.(proto.Message))
  68. }
  69. func (protoCodec) String() string {
  70. return "proto"
  71. }
  72. // Compressor defines the interface gRPC uses to compress a message.
  73. type Compressor interface {
  74. // Do compresses p into w.
  75. Do(w io.Writer, p []byte) error
  76. // Type returns the compression algorithm the Compressor uses.
  77. Type() string
  78. }
  79. // NewGZIPCompressor creates a Compressor based on GZIP.
  80. func NewGZIPCompressor() Compressor {
  81. return &gzipCompressor{}
  82. }
  83. type gzipCompressor struct {
  84. }
  85. func (c *gzipCompressor) Do(w io.Writer, p []byte) error {
  86. z := gzip.NewWriter(w)
  87. if _, err := z.Write(p); err != nil {
  88. return err
  89. }
  90. return z.Close()
  91. }
  92. func (c *gzipCompressor) Type() string {
  93. return "gzip"
  94. }
  95. // Decompressor defines the interface gRPC uses to decompress a message.
  96. type Decompressor interface {
  97. // Do reads the data from r and uncompress them.
  98. Do(r io.Reader) ([]byte, error)
  99. // Type returns the compression algorithm the Decompressor uses.
  100. Type() string
  101. }
  102. type gzipDecompressor struct {
  103. }
  104. // NewGZIPDecompressor creates a Decompressor based on GZIP.
  105. func NewGZIPDecompressor() Decompressor {
  106. return &gzipDecompressor{}
  107. }
  108. func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) {
  109. z, err := gzip.NewReader(r)
  110. if err != nil {
  111. return nil, err
  112. }
  113. defer z.Close()
  114. return ioutil.ReadAll(z)
  115. }
  116. func (d *gzipDecompressor) Type() string {
  117. return "gzip"
  118. }
  119. // callInfo contains all related configuration and information about an RPC.
  120. type callInfo struct {
  121. failFast bool
  122. headerMD metadata.MD
  123. trailerMD metadata.MD
  124. traceInfo traceInfo // in trace.go
  125. }
  126. // CallOption configures a Call before it starts or extracts information from
  127. // a Call after it completes.
  128. type CallOption interface {
  129. // before is called before the call is sent to any server. If before
  130. // returns a non-nil error, the RPC fails with that error.
  131. before(*callInfo) error
  132. // after is called after the call has completed. after cannot return an
  133. // error, so any failures should be reported via output parameters.
  134. after(*callInfo)
  135. }
  136. type beforeCall func(c *callInfo) error
  137. func (o beforeCall) before(c *callInfo) error { return o(c) }
  138. func (o beforeCall) after(c *callInfo) {}
  139. type afterCall func(c *callInfo)
  140. func (o afterCall) before(c *callInfo) error { return nil }
  141. func (o afterCall) after(c *callInfo) { o(c) }
  142. // Header returns a CallOptions that retrieves the header metadata
  143. // for a unary RPC.
  144. func Header(md *metadata.MD) CallOption {
  145. return afterCall(func(c *callInfo) {
  146. *md = c.headerMD
  147. })
  148. }
  149. // Trailer returns a CallOptions that retrieves the trailer metadata
  150. // for a unary RPC.
  151. func Trailer(md *metadata.MD) CallOption {
  152. return afterCall(func(c *callInfo) {
  153. *md = c.trailerMD
  154. })
  155. }
  156. // The format of the payload: compressed or not?
  157. type payloadFormat uint8
  158. const (
  159. compressionNone payloadFormat = iota // no compression
  160. compressionMade
  161. )
  162. // parser reads complelete gRPC messages from the underlying reader.
  163. type parser struct {
  164. // r is the underlying reader.
  165. // See the comment on recvMsg for the permissible
  166. // error types.
  167. r io.Reader
  168. // The header of a gRPC message. Find more detail
  169. // at http://www.grpc.io/docs/guides/wire.html.
  170. header [5]byte
  171. }
  172. // recvMsg reads a complete gRPC message from the stream.
  173. //
  174. // It returns the message and its payload (compression/encoding)
  175. // format. The caller owns the returned msg memory.
  176. //
  177. // If there is an error, possible values are:
  178. // * io.EOF, when no messages remain
  179. // * io.ErrUnexpectedEOF
  180. // * of type transport.ConnectionError
  181. // * of type transport.StreamError
  182. // No other error values or types must be returned, which also means
  183. // that the underlying io.Reader must not return an incompatible
  184. // error.
  185. func (p *parser) recvMsg() (pf payloadFormat, msg []byte, err error) {
  186. if _, err := io.ReadFull(p.r, p.header[:]); err != nil {
  187. return 0, nil, err
  188. }
  189. pf = payloadFormat(p.header[0])
  190. length := binary.BigEndian.Uint32(p.header[1:])
  191. if length == 0 {
  192. return pf, nil, nil
  193. }
  194. // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead
  195. // of making it for each message:
  196. msg = make([]byte, int(length))
  197. if _, err := io.ReadFull(p.r, msg); err != nil {
  198. if err == io.EOF {
  199. err = io.ErrUnexpectedEOF
  200. }
  201. return 0, nil, err
  202. }
  203. return pf, msg, nil
  204. }
  205. // encode serializes msg and prepends the message header. If msg is nil, it
  206. // generates the message header of 0 message length.
  207. func encode(c Codec, msg interface{}, cp Compressor, cbuf *bytes.Buffer) ([]byte, error) {
  208. var b []byte
  209. var length uint
  210. if msg != nil {
  211. var err error
  212. // TODO(zhaoq): optimize to reduce memory alloc and copying.
  213. b, err = c.Marshal(msg)
  214. if err != nil {
  215. return nil, err
  216. }
  217. if cp != nil {
  218. if err := cp.Do(cbuf, b); err != nil {
  219. return nil, err
  220. }
  221. b = cbuf.Bytes()
  222. }
  223. length = uint(len(b))
  224. }
  225. if length > math.MaxUint32 {
  226. return nil, Errorf(codes.InvalidArgument, "grpc: message too large (%d bytes)", length)
  227. }
  228. const (
  229. payloadLen = 1
  230. sizeLen = 4
  231. )
  232. var buf = make([]byte, payloadLen+sizeLen+len(b))
  233. // Write payload format
  234. if cp == nil {
  235. buf[0] = byte(compressionNone)
  236. } else {
  237. buf[0] = byte(compressionMade)
  238. }
  239. // Write length of b into buf
  240. binary.BigEndian.PutUint32(buf[1:], uint32(length))
  241. // Copy encoded msg to buf
  242. copy(buf[5:], b)
  243. return buf, nil
  244. }
  245. func checkRecvPayload(pf payloadFormat, recvCompress string, dc Decompressor) error {
  246. switch pf {
  247. case compressionNone:
  248. case compressionMade:
  249. if recvCompress == "" {
  250. return transport.StreamErrorf(codes.InvalidArgument, "grpc: invalid grpc-encoding %q with compression enabled", recvCompress)
  251. }
  252. if dc == nil || recvCompress != dc.Type() {
  253. return transport.StreamErrorf(codes.InvalidArgument, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
  254. }
  255. default:
  256. return transport.StreamErrorf(codes.InvalidArgument, "grpc: received unexpected payload format %d", pf)
  257. }
  258. return nil
  259. }
  260. func recv(p *parser, c Codec, s *transport.Stream, dc Decompressor, m interface{}) error {
  261. pf, d, err := p.recvMsg()
  262. if err != nil {
  263. return err
  264. }
  265. if err := checkRecvPayload(pf, s.RecvCompress(), dc); err != nil {
  266. return err
  267. }
  268. if pf == compressionMade {
  269. d, err = dc.Do(bytes.NewReader(d))
  270. if err != nil {
  271. return transport.StreamErrorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
  272. }
  273. }
  274. if err := c.Unmarshal(d, m); err != nil {
  275. return transport.StreamErrorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err)
  276. }
  277. return nil
  278. }
  279. // rpcError defines the status from an RPC.
  280. type rpcError struct {
  281. code codes.Code
  282. desc string
  283. }
  284. func (e rpcError) Error() string {
  285. return fmt.Sprintf("rpc error: code = %d desc = %s", e.code, e.desc)
  286. }
  287. // Code returns the error code for err if it was produced by the rpc system.
  288. // Otherwise, it returns codes.Unknown.
  289. func Code(err error) codes.Code {
  290. if err == nil {
  291. return codes.OK
  292. }
  293. if e, ok := err.(rpcError); ok {
  294. return e.code
  295. }
  296. return codes.Unknown
  297. }
  298. // ErrorDesc returns the error description of err if it was produced by the rpc system.
  299. // Otherwise, it returns err.Error() or empty string when err is nil.
  300. func ErrorDesc(err error) string {
  301. if err == nil {
  302. return ""
  303. }
  304. if e, ok := err.(rpcError); ok {
  305. return e.desc
  306. }
  307. return err.Error()
  308. }
  309. // Errorf returns an error containing an error code and a description;
  310. // Errorf returns nil if c is OK.
  311. func Errorf(c codes.Code, format string, a ...interface{}) error {
  312. if c == codes.OK {
  313. return nil
  314. }
  315. return rpcError{
  316. code: c,
  317. desc: fmt.Sprintf(format, a...),
  318. }
  319. }
  320. // toRPCErr converts an error into a rpcError.
  321. func toRPCErr(err error) error {
  322. switch e := err.(type) {
  323. case rpcError:
  324. return err
  325. case transport.StreamError:
  326. return rpcError{
  327. code: e.Code,
  328. desc: e.Desc,
  329. }
  330. case transport.ConnectionError:
  331. return rpcError{
  332. code: codes.Internal,
  333. desc: e.Desc,
  334. }
  335. }
  336. return Errorf(codes.Unknown, "%v", err)
  337. }
  338. // convertCode converts a standard Go error into its canonical code. Note that
  339. // this is only used to translate the error returned by the server applications.
  340. func convertCode(err error) codes.Code {
  341. switch err {
  342. case nil:
  343. return codes.OK
  344. case io.EOF:
  345. return codes.OutOfRange
  346. case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF:
  347. return codes.FailedPrecondition
  348. case os.ErrInvalid:
  349. return codes.InvalidArgument
  350. case context.Canceled:
  351. return codes.Canceled
  352. case context.DeadlineExceeded:
  353. return codes.DeadlineExceeded
  354. }
  355. switch {
  356. case os.IsExist(err):
  357. return codes.AlreadyExists
  358. case os.IsNotExist(err):
  359. return codes.NotFound
  360. case os.IsPermission(err):
  361. return codes.PermissionDenied
  362. }
  363. return codes.Unknown
  364. }
  365. const (
  366. // how long to wait after the first failure before retrying
  367. baseDelay = 1.0 * time.Second
  368. // upper bound of backoff delay
  369. maxDelay = 120 * time.Second
  370. // backoff increases by this factor on each retry
  371. backoffFactor = 1.6
  372. // backoff is randomized downwards by this factor
  373. backoffJitter = 0.2
  374. )
  375. func backoff(retries int) (t time.Duration) {
  376. if retries == 0 {
  377. return baseDelay
  378. }
  379. backoff, max := float64(baseDelay), float64(maxDelay)
  380. for backoff < max && retries > 0 {
  381. backoff *= backoffFactor
  382. retries--
  383. }
  384. if backoff > max {
  385. backoff = max
  386. }
  387. // Randomize backoff delays so that if a cluster of requests start at
  388. // the same time, they won't operate in lockstep.
  389. backoff *= 1 + backoffJitter*(rand.Float64()*2-1)
  390. if backoff < 0 {
  391. return 0
  392. }
  393. return time.Duration(backoff)
  394. }
  395. // SupportPackageIsVersion1 is referenced from generated protocol buffer files
  396. // to assert that that code is compatible with this version of the grpc package.
  397. //
  398. // This constant may be renamed in the future if a change in the generated code
  399. // requires a synchronised update of grpc-go and protoc-gen-go. This constant
  400. // should not be referenced from any other code.
  401. const SupportPackageIsVersion1 = true