rpc_util.go 17 KB

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