rpc_util.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. "os"
  43. "github.com/golang/protobuf/proto"
  44. "golang.org/x/net/context"
  45. "google.golang.org/grpc/codes"
  46. "google.golang.org/grpc/metadata"
  47. "google.golang.org/grpc/transport"
  48. )
  49. // Codec defines the interface gRPC uses to encode and decode messages.
  50. type Codec interface {
  51. // Marshal returns the wire format of v.
  52. Marshal(v interface{}) ([]byte, error)
  53. // Unmarshal parses the wire format into v.
  54. Unmarshal(data []byte, v interface{}) error
  55. // String returns the name of the Codec implementation. The returned
  56. // string will be used as part of content type in transmission.
  57. String() string
  58. }
  59. // protoCodec is a Codec implemetation with protobuf. It is the default codec for gRPC.
  60. type protoCodec struct{}
  61. func (protoCodec) Marshal(v interface{}) ([]byte, error) {
  62. return proto.Marshal(v.(proto.Message))
  63. }
  64. func (protoCodec) Unmarshal(data []byte, v interface{}) error {
  65. return proto.Unmarshal(data, v.(proto.Message))
  66. }
  67. func (protoCodec) String() string {
  68. return "proto"
  69. }
  70. // Compressor defines the interface gRPC uses to compress a message.
  71. type Compressor interface {
  72. // Do compresses p into w.
  73. Do(w io.Writer, p []byte) error
  74. // Type returns the compression algorithm the Compressor uses.
  75. Type() string
  76. }
  77. // NewGZIPCompressor creates a Compressor based on GZIP.
  78. func NewGZIPCompressor() Compressor {
  79. return &gzipCompressor{}
  80. }
  81. type gzipCompressor struct {
  82. }
  83. func (c *gzipCompressor) Do(w io.Writer, p []byte) error {
  84. z := gzip.NewWriter(w)
  85. if _, err := z.Write(p); err != nil {
  86. return err
  87. }
  88. return z.Close()
  89. }
  90. func (c *gzipCompressor) Type() string {
  91. return "gzip"
  92. }
  93. // Decompressor defines the interface gRPC uses to decompress a message.
  94. type Decompressor interface {
  95. // Do reads the data from r and uncompress them.
  96. Do(r io.Reader) ([]byte, error)
  97. // Type returns the compression algorithm the Decompressor uses.
  98. Type() string
  99. }
  100. type gzipDecompressor struct {
  101. }
  102. // NewGZIPDecompressor creates a Decompressor based on GZIP.
  103. func NewGZIPDecompressor() Decompressor {
  104. return &gzipDecompressor{}
  105. }
  106. func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) {
  107. z, err := gzip.NewReader(r)
  108. if err != nil {
  109. return nil, err
  110. }
  111. defer z.Close()
  112. return ioutil.ReadAll(z)
  113. }
  114. func (d *gzipDecompressor) Type() string {
  115. return "gzip"
  116. }
  117. // callInfo contains all related configuration and information about an RPC.
  118. type callInfo struct {
  119. failFast bool
  120. headerMD metadata.MD
  121. trailerMD metadata.MD
  122. traceInfo traceInfo // in trace.go
  123. }
  124. // CallOption configures a Call before it starts or extracts information from
  125. // a Call after it completes.
  126. type CallOption interface {
  127. // before is called before the call is sent to any server. If before
  128. // returns a non-nil error, the RPC fails with that error.
  129. before(*callInfo) error
  130. // after is called after the call has completed. after cannot return an
  131. // error, so any failures should be reported via output parameters.
  132. after(*callInfo)
  133. }
  134. type beforeCall func(c *callInfo) error
  135. func (o beforeCall) before(c *callInfo) error { return o(c) }
  136. func (o beforeCall) after(c *callInfo) {}
  137. type afterCall func(c *callInfo)
  138. func (o afterCall) before(c *callInfo) error { return nil }
  139. func (o afterCall) after(c *callInfo) { o(c) }
  140. // Header returns a CallOptions that retrieves the header metadata
  141. // for a unary RPC.
  142. func Header(md *metadata.MD) CallOption {
  143. return afterCall(func(c *callInfo) {
  144. *md = c.headerMD
  145. })
  146. }
  147. // Trailer returns a CallOptions that retrieves the trailer metadata
  148. // for a unary RPC.
  149. func Trailer(md *metadata.MD) CallOption {
  150. return afterCall(func(c *callInfo) {
  151. *md = c.trailerMD
  152. })
  153. }
  154. // The format of the payload: compressed or not?
  155. type payloadFormat uint8
  156. const (
  157. compressionNone payloadFormat = iota // no compression
  158. compressionMade
  159. )
  160. // parser reads complelete gRPC messages from the underlying reader.
  161. type parser struct {
  162. // r is the underlying reader.
  163. // See the comment on recvMsg for the permissible
  164. // error types.
  165. r io.Reader
  166. // The header of a gRPC message. Find more detail
  167. // at http://www.grpc.io/docs/guides/wire.html.
  168. header [5]byte
  169. }
  170. // recvMsg reads a complete gRPC message from the stream.
  171. //
  172. // It returns the message and its payload (compression/encoding)
  173. // format. The caller owns the returned msg memory.
  174. //
  175. // If there is an error, possible values are:
  176. // * io.EOF, when no messages remain
  177. // * io.ErrUnexpectedEOF
  178. // * of type transport.ConnectionError
  179. // * of type transport.StreamError
  180. // No other error values or types must be returned, which also means
  181. // that the underlying io.Reader must not return an incompatible
  182. // error.
  183. func (p *parser) recvMsg() (pf payloadFormat, msg []byte, err error) {
  184. if _, err := io.ReadFull(p.r, p.header[:]); err != nil {
  185. return 0, nil, err
  186. }
  187. pf = payloadFormat(p.header[0])
  188. length := binary.BigEndian.Uint32(p.header[1:])
  189. if length == 0 {
  190. return pf, nil, nil
  191. }
  192. // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead
  193. // of making it for each message:
  194. msg = make([]byte, int(length))
  195. if _, err := io.ReadFull(p.r, msg); err != nil {
  196. if err == io.EOF {
  197. err = io.ErrUnexpectedEOF
  198. }
  199. return 0, nil, err
  200. }
  201. return pf, msg, nil
  202. }
  203. // encode serializes msg and prepends the message header. If msg is nil, it
  204. // generates the message header of 0 message length.
  205. func encode(c Codec, msg interface{}, cp Compressor, cbuf *bytes.Buffer) ([]byte, error) {
  206. var b []byte
  207. var length uint
  208. if msg != nil {
  209. var err error
  210. // TODO(zhaoq): optimize to reduce memory alloc and copying.
  211. b, err = c.Marshal(msg)
  212. if err != nil {
  213. return nil, err
  214. }
  215. if cp != nil {
  216. if err := cp.Do(cbuf, b); err != nil {
  217. return nil, err
  218. }
  219. b = cbuf.Bytes()
  220. }
  221. length = uint(len(b))
  222. }
  223. if length > math.MaxUint32 {
  224. return nil, Errorf(codes.InvalidArgument, "grpc: message too large (%d bytes)", length)
  225. }
  226. const (
  227. payloadLen = 1
  228. sizeLen = 4
  229. )
  230. var buf = make([]byte, payloadLen+sizeLen+len(b))
  231. // Write payload format
  232. if cp == nil {
  233. buf[0] = byte(compressionNone)
  234. } else {
  235. buf[0] = byte(compressionMade)
  236. }
  237. // Write length of b into buf
  238. binary.BigEndian.PutUint32(buf[1:], uint32(length))
  239. // Copy encoded msg to buf
  240. copy(buf[5:], b)
  241. return buf, nil
  242. }
  243. func checkRecvPayload(pf payloadFormat, recvCompress string, dc Decompressor) error {
  244. switch pf {
  245. case compressionNone:
  246. case compressionMade:
  247. if recvCompress == "" {
  248. return transport.StreamErrorf(codes.InvalidArgument, "grpc: invalid grpc-encoding %q with compression enabled", recvCompress)
  249. }
  250. if dc == nil || recvCompress != dc.Type() {
  251. return transport.StreamErrorf(codes.InvalidArgument, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
  252. }
  253. default:
  254. return transport.StreamErrorf(codes.InvalidArgument, "grpc: received unexpected payload format %d", pf)
  255. }
  256. return nil
  257. }
  258. func recv(p *parser, c Codec, s *transport.Stream, dc Decompressor, m interface{}) error {
  259. pf, d, err := p.recvMsg()
  260. if err != nil {
  261. return err
  262. }
  263. if err := checkRecvPayload(pf, s.RecvCompress(), dc); err != nil {
  264. return err
  265. }
  266. if pf == compressionMade {
  267. d, err = dc.Do(bytes.NewReader(d))
  268. if err != nil {
  269. return transport.StreamErrorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
  270. }
  271. }
  272. if err := c.Unmarshal(d, m); err != nil {
  273. return transport.StreamErrorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err)
  274. }
  275. return nil
  276. }
  277. // rpcError defines the status from an RPC.
  278. type rpcError struct {
  279. code codes.Code
  280. desc string
  281. }
  282. func (e rpcError) Error() string {
  283. return fmt.Sprintf("rpc error: code = %d desc = %s", e.code, e.desc)
  284. }
  285. // Code returns the error code for err if it was produced by the rpc system.
  286. // Otherwise, it returns codes.Unknown.
  287. func Code(err error) codes.Code {
  288. if err == nil {
  289. return codes.OK
  290. }
  291. if e, ok := err.(rpcError); ok {
  292. return e.code
  293. }
  294. return codes.Unknown
  295. }
  296. // ErrorDesc returns the error description of err if it was produced by the rpc system.
  297. // Otherwise, it returns err.Error() or empty string when err is nil.
  298. func ErrorDesc(err error) string {
  299. if err == nil {
  300. return ""
  301. }
  302. if e, ok := err.(rpcError); ok {
  303. return e.desc
  304. }
  305. return err.Error()
  306. }
  307. // Errorf returns an error containing an error code and a description;
  308. // Errorf returns nil if c is OK.
  309. func Errorf(c codes.Code, format string, a ...interface{}) error {
  310. if c == codes.OK {
  311. return nil
  312. }
  313. return rpcError{
  314. code: c,
  315. desc: fmt.Sprintf(format, a...),
  316. }
  317. }
  318. // toRPCErr converts an error into a rpcError.
  319. func toRPCErr(err error) error {
  320. switch e := err.(type) {
  321. case rpcError:
  322. return err
  323. case transport.StreamError:
  324. return rpcError{
  325. code: e.Code,
  326. desc: e.Desc,
  327. }
  328. case transport.ConnectionError:
  329. return rpcError{
  330. code: codes.Internal,
  331. desc: e.Desc,
  332. }
  333. }
  334. return Errorf(codes.Unknown, "%v", err)
  335. }
  336. // convertCode converts a standard Go error into its canonical code. Note that
  337. // this is only used to translate the error returned by the server applications.
  338. func convertCode(err error) codes.Code {
  339. switch err {
  340. case nil:
  341. return codes.OK
  342. case io.EOF:
  343. return codes.OutOfRange
  344. case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF:
  345. return codes.FailedPrecondition
  346. case os.ErrInvalid:
  347. return codes.InvalidArgument
  348. case context.Canceled:
  349. return codes.Canceled
  350. case context.DeadlineExceeded:
  351. return codes.DeadlineExceeded
  352. }
  353. switch {
  354. case os.IsExist(err):
  355. return codes.AlreadyExists
  356. case os.IsNotExist(err):
  357. return codes.NotFound
  358. case os.IsPermission(err):
  359. return codes.PermissionDenied
  360. }
  361. return codes.Unknown
  362. }
  363. // SupportPackageIsVersion2 is referenced from generated protocol buffer files
  364. // to assert that that code is compatible with this version of the grpc package.
  365. //
  366. // This constant may be renamed in the future if a change in the generated code
  367. // requires a synchronised update of grpc-go and protoc-gen-go. This constant
  368. // should not be referenced from any other code.
  369. const SupportPackageIsVersion2 = true