rpc_util.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. "encoding/binary"
  23. "io"
  24. "io/ioutil"
  25. "math"
  26. "sync"
  27. "time"
  28. "golang.org/x/net/context"
  29. "google.golang.org/grpc/codes"
  30. "google.golang.org/grpc/credentials"
  31. "google.golang.org/grpc/metadata"
  32. "google.golang.org/grpc/peer"
  33. "google.golang.org/grpc/stats"
  34. "google.golang.org/grpc/status"
  35. "google.golang.org/grpc/transport"
  36. )
  37. // Compressor defines the interface gRPC uses to compress a message.
  38. type Compressor interface {
  39. // Do compresses p into w.
  40. Do(w io.Writer, p []byte) error
  41. // Type returns the compression algorithm the Compressor uses.
  42. Type() string
  43. }
  44. type gzipCompressor struct {
  45. pool sync.Pool
  46. }
  47. // NewGZIPCompressor creates a Compressor based on GZIP.
  48. func NewGZIPCompressor() Compressor {
  49. return &gzipCompressor{
  50. pool: sync.Pool{
  51. New: func() interface{} {
  52. return gzip.NewWriter(ioutil.Discard)
  53. },
  54. },
  55. }
  56. }
  57. func (c *gzipCompressor) Do(w io.Writer, p []byte) error {
  58. z := c.pool.Get().(*gzip.Writer)
  59. defer c.pool.Put(z)
  60. z.Reset(w)
  61. if _, err := z.Write(p); err != nil {
  62. return err
  63. }
  64. return z.Close()
  65. }
  66. func (c *gzipCompressor) Type() string {
  67. return "gzip"
  68. }
  69. // Decompressor defines the interface gRPC uses to decompress a message.
  70. type Decompressor interface {
  71. // Do reads the data from r and uncompress them.
  72. Do(r io.Reader) ([]byte, error)
  73. // Type returns the compression algorithm the Decompressor uses.
  74. Type() string
  75. }
  76. type gzipDecompressor struct {
  77. pool sync.Pool
  78. }
  79. // NewGZIPDecompressor creates a Decompressor based on GZIP.
  80. func NewGZIPDecompressor() Decompressor {
  81. return &gzipDecompressor{}
  82. }
  83. func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) {
  84. var z *gzip.Reader
  85. switch maybeZ := d.pool.Get().(type) {
  86. case nil:
  87. newZ, err := gzip.NewReader(r)
  88. if err != nil {
  89. return nil, err
  90. }
  91. z = newZ
  92. case *gzip.Reader:
  93. z = maybeZ
  94. if err := z.Reset(r); err != nil {
  95. d.pool.Put(z)
  96. return nil, err
  97. }
  98. }
  99. defer func() {
  100. z.Close()
  101. d.pool.Put(z)
  102. }()
  103. return ioutil.ReadAll(z)
  104. }
  105. func (d *gzipDecompressor) Type() string {
  106. return "gzip"
  107. }
  108. // callInfo contains all related configuration and information about an RPC.
  109. type callInfo struct {
  110. failFast bool
  111. headerMD metadata.MD
  112. trailerMD metadata.MD
  113. peer *peer.Peer
  114. traceInfo traceInfo // in trace.go
  115. maxReceiveMessageSize *int
  116. maxSendMessageSize *int
  117. creds credentials.PerRPCCredentials
  118. }
  119. var defaultCallInfo = callInfo{failFast: true}
  120. // CallOption configures a Call before it starts or extracts information from
  121. // a Call after it completes.
  122. type CallOption interface {
  123. // before is called before the call is sent to any server. If before
  124. // returns a non-nil error, the RPC fails with that error.
  125. before(*callInfo) error
  126. // after is called after the call has completed. after cannot return an
  127. // error, so any failures should be reported via output parameters.
  128. after(*callInfo)
  129. }
  130. // EmptyCallOption does not alter the Call configuration.
  131. // It can be embedded in another structure to carry satellite data for use
  132. // by interceptors.
  133. type EmptyCallOption struct{}
  134. func (EmptyCallOption) before(*callInfo) error { return nil }
  135. func (EmptyCallOption) after(*callInfo) {}
  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. // Peer returns a CallOption that retrieves peer information for a
  157. // unary RPC.
  158. func Peer(peer *peer.Peer) CallOption {
  159. return afterCall(func(c *callInfo) {
  160. if c.peer != nil {
  161. *peer = *c.peer
  162. }
  163. })
  164. }
  165. // FailFast configures the action to take when an RPC is attempted on broken
  166. // connections or unreachable servers. If failfast is true, the RPC will fail
  167. // immediately. Otherwise, the RPC client will block the call until a
  168. // connection is available (or the call is canceled or times out) and will retry
  169. // the call if it fails due to a transient error. Please refer to
  170. // https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md.
  171. // Note: failFast is default to true.
  172. func FailFast(failFast bool) CallOption {
  173. return beforeCall(func(c *callInfo) error {
  174. c.failFast = failFast
  175. return nil
  176. })
  177. }
  178. // MaxCallRecvMsgSize returns a CallOption which sets the maximum message size the client can receive.
  179. func MaxCallRecvMsgSize(s int) CallOption {
  180. return beforeCall(func(o *callInfo) error {
  181. o.maxReceiveMessageSize = &s
  182. return nil
  183. })
  184. }
  185. // MaxCallSendMsgSize returns a CallOption which sets the maximum message size the client can send.
  186. func MaxCallSendMsgSize(s int) CallOption {
  187. return beforeCall(func(o *callInfo) error {
  188. o.maxSendMessageSize = &s
  189. return nil
  190. })
  191. }
  192. // PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials
  193. // for a call.
  194. func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption {
  195. return beforeCall(func(c *callInfo) error {
  196. c.creds = creds
  197. return nil
  198. })
  199. }
  200. // The format of the payload: compressed or not?
  201. type payloadFormat uint8
  202. const (
  203. compressionNone payloadFormat = iota // no compression
  204. compressionMade
  205. )
  206. // parser reads complete gRPC messages from the underlying reader.
  207. type parser struct {
  208. // r is the underlying reader.
  209. // See the comment on recvMsg for the permissible
  210. // error types.
  211. r io.Reader
  212. // The header of a gRPC message. Find more detail
  213. // at https://grpc.io/docs/guides/wire.html.
  214. header [5]byte
  215. }
  216. // recvMsg reads a complete gRPC message from the stream.
  217. //
  218. // It returns the message and its payload (compression/encoding)
  219. // format. The caller owns the returned msg memory.
  220. //
  221. // If there is an error, possible values are:
  222. // * io.EOF, when no messages remain
  223. // * io.ErrUnexpectedEOF
  224. // * of type transport.ConnectionError
  225. // * of type transport.StreamError
  226. // No other error values or types must be returned, which also means
  227. // that the underlying io.Reader must not return an incompatible
  228. // error.
  229. func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byte, err error) {
  230. if _, err := p.r.Read(p.header[:]); err != nil {
  231. return 0, nil, err
  232. }
  233. pf = payloadFormat(p.header[0])
  234. length := binary.BigEndian.Uint32(p.header[1:])
  235. if length == 0 {
  236. return pf, nil, nil
  237. }
  238. if length > uint32(maxReceiveMessageSize) {
  239. return 0, nil, Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize)
  240. }
  241. // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead
  242. // of making it for each message:
  243. msg = make([]byte, int(length))
  244. if _, err := p.r.Read(msg); err != nil {
  245. if err == io.EOF {
  246. err = io.ErrUnexpectedEOF
  247. }
  248. return 0, nil, err
  249. }
  250. return pf, msg, nil
  251. }
  252. // encode serializes msg and returns a buffer of message header and a buffer of msg.
  253. // If msg is nil, it generates the message header and an empty msg buffer.
  254. func encode(c Codec, msg interface{}, cp Compressor, cbuf *bytes.Buffer, outPayload *stats.OutPayload) ([]byte, []byte, error) {
  255. var b []byte
  256. const (
  257. payloadLen = 1
  258. sizeLen = 4
  259. )
  260. if msg != nil {
  261. var err error
  262. b, err = c.Marshal(msg)
  263. if err != nil {
  264. return nil, nil, Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error())
  265. }
  266. if outPayload != nil {
  267. outPayload.Payload = msg
  268. // TODO truncate large payload.
  269. outPayload.Data = b
  270. outPayload.Length = len(b)
  271. }
  272. if cp != nil {
  273. if err := cp.Do(cbuf, b); err != nil {
  274. return nil, nil, Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error())
  275. }
  276. b = cbuf.Bytes()
  277. }
  278. }
  279. if uint(len(b)) > math.MaxUint32 {
  280. return nil, nil, Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b))
  281. }
  282. bufHeader := make([]byte, payloadLen+sizeLen)
  283. if cp == nil {
  284. bufHeader[0] = byte(compressionNone)
  285. } else {
  286. bufHeader[0] = byte(compressionMade)
  287. }
  288. // Write length of b into buf
  289. binary.BigEndian.PutUint32(bufHeader[payloadLen:], uint32(len(b)))
  290. if outPayload != nil {
  291. outPayload.WireLength = payloadLen + sizeLen + len(b)
  292. }
  293. return bufHeader, b, nil
  294. }
  295. func checkRecvPayload(pf payloadFormat, recvCompress string, dc Decompressor) error {
  296. switch pf {
  297. case compressionNone:
  298. case compressionMade:
  299. if dc == nil || recvCompress != dc.Type() {
  300. return Errorf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
  301. }
  302. default:
  303. return Errorf(codes.Internal, "grpc: received unexpected payload format %d", pf)
  304. }
  305. return nil
  306. }
  307. func recv(p *parser, c Codec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, inPayload *stats.InPayload) error {
  308. pf, d, err := p.recvMsg(maxReceiveMessageSize)
  309. if err != nil {
  310. return err
  311. }
  312. if inPayload != nil {
  313. inPayload.WireLength = len(d)
  314. }
  315. if err := checkRecvPayload(pf, s.RecvCompress(), dc); err != nil {
  316. return err
  317. }
  318. if pf == compressionMade {
  319. d, err = dc.Do(bytes.NewReader(d))
  320. if err != nil {
  321. return Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
  322. }
  323. }
  324. if len(d) > maxReceiveMessageSize {
  325. // TODO: Revisit the error code. Currently keep it consistent with java
  326. // implementation.
  327. return Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(d), maxReceiveMessageSize)
  328. }
  329. if err := c.Unmarshal(d, m); err != nil {
  330. return Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err)
  331. }
  332. if inPayload != nil {
  333. inPayload.RecvTime = time.Now()
  334. inPayload.Payload = m
  335. // TODO truncate large payload.
  336. inPayload.Data = d
  337. inPayload.Length = len(d)
  338. }
  339. return nil
  340. }
  341. type rpcInfo struct {
  342. bytesSent bool
  343. bytesReceived bool
  344. }
  345. type rpcInfoContextKey struct{}
  346. func newContextWithRPCInfo(ctx context.Context) context.Context {
  347. return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{})
  348. }
  349. func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) {
  350. s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo)
  351. return
  352. }
  353. func updateRPCInfoInContext(ctx context.Context, s rpcInfo) {
  354. if ss, ok := rpcInfoFromContext(ctx); ok {
  355. *ss = s
  356. }
  357. return
  358. }
  359. // Code returns the error code for err if it was produced by the rpc system.
  360. // Otherwise, it returns codes.Unknown.
  361. //
  362. // Deprecated; use status.FromError and Code method instead.
  363. func Code(err error) codes.Code {
  364. if s, ok := status.FromError(err); ok {
  365. return s.Code()
  366. }
  367. return codes.Unknown
  368. }
  369. // ErrorDesc returns the error description of err if it was produced by the rpc system.
  370. // Otherwise, it returns err.Error() or empty string when err is nil.
  371. //
  372. // Deprecated; use status.FromError and Message method instead.
  373. func ErrorDesc(err error) string {
  374. if s, ok := status.FromError(err); ok {
  375. return s.Message()
  376. }
  377. return err.Error()
  378. }
  379. // Errorf returns an error containing an error code and a description;
  380. // Errorf returns nil if c is OK.
  381. //
  382. // Deprecated; use status.Errorf instead.
  383. func Errorf(c codes.Code, format string, a ...interface{}) error {
  384. return status.Errorf(c, format, a...)
  385. }
  386. // MethodConfig defines the configuration recommended by the service providers for a
  387. // particular method.
  388. // This is EXPERIMENTAL and subject to change.
  389. type MethodConfig struct {
  390. // WaitForReady indicates whether RPCs sent to this method should wait until
  391. // the connection is ready by default (!failfast). The value specified via the
  392. // gRPC client API will override the value set here.
  393. WaitForReady *bool
  394. // Timeout is the default timeout for RPCs sent to this method. The actual
  395. // deadline used will be the minimum of the value specified here and the value
  396. // set by the application via the gRPC client API. If either one is not set,
  397. // then the other will be used. If neither is set, then the RPC has no deadline.
  398. Timeout *time.Duration
  399. // MaxReqSize is the maximum allowed payload size for an individual request in a
  400. // stream (client->server) in bytes. The size which is measured is the serialized
  401. // payload after per-message compression (but before stream compression) in bytes.
  402. // The actual value used is the minumum of the value specified here and the value set
  403. // by the application via the gRPC client API. If either one is not set, then the other
  404. // will be used. If neither is set, then the built-in default is used.
  405. MaxReqSize *int
  406. // MaxRespSize is the maximum allowed payload size for an individual response in a
  407. // stream (server->client) in bytes.
  408. MaxRespSize *int
  409. }
  410. // ServiceConfig is provided by the service provider and contains parameters for how
  411. // clients that connect to the service should behave.
  412. // This is EXPERIMENTAL and subject to change.
  413. type ServiceConfig struct {
  414. // LB is the load balancer the service providers recommends. The balancer specified
  415. // via grpc.WithBalancer will override this.
  416. LB Balancer
  417. // Methods contains a map for the methods in this service.
  418. // If there is an exact match for a method (i.e. /service/method) in the map, use the corresponding MethodConfig.
  419. // If there's no exact match, look for the default config for the service (/service/) and use the corresponding MethodConfig if it exists.
  420. // Otherwise, the method has no MethodConfig to use.
  421. Methods map[string]MethodConfig
  422. }
  423. func min(a, b *int) *int {
  424. if *a < *b {
  425. return a
  426. }
  427. return b
  428. }
  429. func getMaxSize(mcMax, doptMax *int, defaultVal int) *int {
  430. if mcMax == nil && doptMax == nil {
  431. return &defaultVal
  432. }
  433. if mcMax != nil && doptMax != nil {
  434. return min(mcMax, doptMax)
  435. }
  436. if mcMax != nil {
  437. return mcMax
  438. }
  439. return doptMax
  440. }
  441. // SupportPackageIsVersion3 is referenced from generated protocol buffer files.
  442. // The latest support package version is 4.
  443. // SupportPackageIsVersion3 is kept for compability. It will be removed in the
  444. // next support package version update.
  445. const SupportPackageIsVersion3 = true
  446. // SupportPackageIsVersion4 is referenced from generated protocol buffer files
  447. // to assert that that code is compatible with this version of the grpc package.
  448. //
  449. // This constant may be renamed in the future if a change in the generated code
  450. // requires a synchronised update of grpc-go and protoc-gen-go. This constant
  451. // should not be referenced from any other code.
  452. const SupportPackageIsVersion4 = true
  453. // Version is the current grpc version.
  454. const Version = "1.6.0"
  455. const grpcUA = "grpc-go/" + Version