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.
 
 
 

844 line
25 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. "context"
  23. "encoding/binary"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "math"
  28. "net/url"
  29. "strings"
  30. "sync"
  31. "time"
  32. "google.golang.org/grpc/codes"
  33. "google.golang.org/grpc/credentials"
  34. "google.golang.org/grpc/encoding"
  35. "google.golang.org/grpc/encoding/proto"
  36. "google.golang.org/grpc/internal/transport"
  37. "google.golang.org/grpc/metadata"
  38. "google.golang.org/grpc/peer"
  39. "google.golang.org/grpc/stats"
  40. "google.golang.org/grpc/status"
  41. )
  42. // Compressor defines the interface gRPC uses to compress a message.
  43. //
  44. // Deprecated: use package encoding.
  45. type Compressor interface {
  46. // Do compresses p into w.
  47. Do(w io.Writer, p []byte) error
  48. // Type returns the compression algorithm the Compressor uses.
  49. Type() string
  50. }
  51. type gzipCompressor struct {
  52. pool sync.Pool
  53. }
  54. // NewGZIPCompressor creates a Compressor based on GZIP.
  55. //
  56. // Deprecated: use package encoding/gzip.
  57. func NewGZIPCompressor() Compressor {
  58. c, _ := NewGZIPCompressorWithLevel(gzip.DefaultCompression)
  59. return c
  60. }
  61. // NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead
  62. // of assuming DefaultCompression.
  63. //
  64. // The error returned will be nil if the level is valid.
  65. //
  66. // Deprecated: use package encoding/gzip.
  67. func NewGZIPCompressorWithLevel(level int) (Compressor, error) {
  68. if level < gzip.DefaultCompression || level > gzip.BestCompression {
  69. return nil, fmt.Errorf("grpc: invalid compression level: %d", level)
  70. }
  71. return &gzipCompressor{
  72. pool: sync.Pool{
  73. New: func() interface{} {
  74. w, err := gzip.NewWriterLevel(ioutil.Discard, level)
  75. if err != nil {
  76. panic(err)
  77. }
  78. return w
  79. },
  80. },
  81. }, nil
  82. }
  83. func (c *gzipCompressor) Do(w io.Writer, p []byte) error {
  84. z := c.pool.Get().(*gzip.Writer)
  85. defer c.pool.Put(z)
  86. z.Reset(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. //
  97. // Deprecated: use package encoding.
  98. type Decompressor interface {
  99. // Do reads the data from r and uncompress them.
  100. Do(r io.Reader) ([]byte, error)
  101. // Type returns the compression algorithm the Decompressor uses.
  102. Type() string
  103. }
  104. type gzipDecompressor struct {
  105. pool sync.Pool
  106. }
  107. // NewGZIPDecompressor creates a Decompressor based on GZIP.
  108. //
  109. // Deprecated: use package encoding/gzip.
  110. func NewGZIPDecompressor() Decompressor {
  111. return &gzipDecompressor{}
  112. }
  113. func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) {
  114. var z *gzip.Reader
  115. switch maybeZ := d.pool.Get().(type) {
  116. case nil:
  117. newZ, err := gzip.NewReader(r)
  118. if err != nil {
  119. return nil, err
  120. }
  121. z = newZ
  122. case *gzip.Reader:
  123. z = maybeZ
  124. if err := z.Reset(r); err != nil {
  125. d.pool.Put(z)
  126. return nil, err
  127. }
  128. }
  129. defer func() {
  130. z.Close()
  131. d.pool.Put(z)
  132. }()
  133. return ioutil.ReadAll(z)
  134. }
  135. func (d *gzipDecompressor) Type() string {
  136. return "gzip"
  137. }
  138. // callInfo contains all related configuration and information about an RPC.
  139. type callInfo struct {
  140. compressorType string
  141. failFast bool
  142. stream ClientStream
  143. maxReceiveMessageSize *int
  144. maxSendMessageSize *int
  145. creds credentials.PerRPCCredentials
  146. contentSubtype string
  147. codec baseCodec
  148. maxRetryRPCBufferSize int
  149. }
  150. func defaultCallInfo() *callInfo {
  151. return &callInfo{
  152. failFast: true,
  153. maxRetryRPCBufferSize: 256 * 1024, // 256KB
  154. }
  155. }
  156. // CallOption configures a Call before it starts or extracts information from
  157. // a Call after it completes.
  158. type CallOption interface {
  159. // before is called before the call is sent to any server. If before
  160. // returns a non-nil error, the RPC fails with that error.
  161. before(*callInfo) error
  162. // after is called after the call has completed. after cannot return an
  163. // error, so any failures should be reported via output parameters.
  164. after(*callInfo)
  165. }
  166. // EmptyCallOption does not alter the Call configuration.
  167. // It can be embedded in another structure to carry satellite data for use
  168. // by interceptors.
  169. type EmptyCallOption struct{}
  170. func (EmptyCallOption) before(*callInfo) error { return nil }
  171. func (EmptyCallOption) after(*callInfo) {}
  172. // Header returns a CallOptions that retrieves the header metadata
  173. // for a unary RPC.
  174. func Header(md *metadata.MD) CallOption {
  175. return HeaderCallOption{HeaderAddr: md}
  176. }
  177. // HeaderCallOption is a CallOption for collecting response header metadata.
  178. // The metadata field will be populated *after* the RPC completes.
  179. // This is an EXPERIMENTAL API.
  180. type HeaderCallOption struct {
  181. HeaderAddr *metadata.MD
  182. }
  183. func (o HeaderCallOption) before(c *callInfo) error { return nil }
  184. func (o HeaderCallOption) after(c *callInfo) {
  185. if c.stream != nil {
  186. *o.HeaderAddr, _ = c.stream.Header()
  187. }
  188. }
  189. // Trailer returns a CallOptions that retrieves the trailer metadata
  190. // for a unary RPC.
  191. func Trailer(md *metadata.MD) CallOption {
  192. return TrailerCallOption{TrailerAddr: md}
  193. }
  194. // TrailerCallOption is a CallOption for collecting response trailer metadata.
  195. // The metadata field will be populated *after* the RPC completes.
  196. // This is an EXPERIMENTAL API.
  197. type TrailerCallOption struct {
  198. TrailerAddr *metadata.MD
  199. }
  200. func (o TrailerCallOption) before(c *callInfo) error { return nil }
  201. func (o TrailerCallOption) after(c *callInfo) {
  202. if c.stream != nil {
  203. *o.TrailerAddr = c.stream.Trailer()
  204. }
  205. }
  206. // Peer returns a CallOption that retrieves peer information for a unary RPC.
  207. // The peer field will be populated *after* the RPC completes.
  208. func Peer(p *peer.Peer) CallOption {
  209. return PeerCallOption{PeerAddr: p}
  210. }
  211. // PeerCallOption is a CallOption for collecting the identity of the remote
  212. // peer. The peer field will be populated *after* the RPC completes.
  213. // This is an EXPERIMENTAL API.
  214. type PeerCallOption struct {
  215. PeerAddr *peer.Peer
  216. }
  217. func (o PeerCallOption) before(c *callInfo) error { return nil }
  218. func (o PeerCallOption) after(c *callInfo) {
  219. if c.stream != nil {
  220. if x, ok := peer.FromContext(c.stream.Context()); ok {
  221. *o.PeerAddr = *x
  222. }
  223. }
  224. }
  225. // WaitForReady configures the action to take when an RPC is attempted on broken
  226. // connections or unreachable servers. If waitForReady is false, the RPC will fail
  227. // immediately. Otherwise, the RPC client will block the call until a
  228. // connection is available (or the call is canceled or times out) and will
  229. // retry the call if it fails due to a transient error. gRPC will not retry if
  230. // data was written to the wire unless the server indicates it did not process
  231. // the data. Please refer to
  232. // https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md.
  233. //
  234. // By default, RPCs don't "wait for ready".
  235. func WaitForReady(waitForReady bool) CallOption {
  236. return FailFastCallOption{FailFast: !waitForReady}
  237. }
  238. // FailFast is the opposite of WaitForReady.
  239. //
  240. // Deprecated: use WaitForReady.
  241. func FailFast(failFast bool) CallOption {
  242. return FailFastCallOption{FailFast: failFast}
  243. }
  244. // FailFastCallOption is a CallOption for indicating whether an RPC should fail
  245. // fast or not.
  246. // This is an EXPERIMENTAL API.
  247. type FailFastCallOption struct {
  248. FailFast bool
  249. }
  250. func (o FailFastCallOption) before(c *callInfo) error {
  251. c.failFast = o.FailFast
  252. return nil
  253. }
  254. func (o FailFastCallOption) after(c *callInfo) {}
  255. // MaxCallRecvMsgSize returns a CallOption which sets the maximum message size the client can receive.
  256. func MaxCallRecvMsgSize(s int) CallOption {
  257. return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: s}
  258. }
  259. // MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message
  260. // size the client can receive.
  261. // This is an EXPERIMENTAL API.
  262. type MaxRecvMsgSizeCallOption struct {
  263. MaxRecvMsgSize int
  264. }
  265. func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error {
  266. c.maxReceiveMessageSize = &o.MaxRecvMsgSize
  267. return nil
  268. }
  269. func (o MaxRecvMsgSizeCallOption) after(c *callInfo) {}
  270. // MaxCallSendMsgSize returns a CallOption which sets the maximum message size the client can send.
  271. func MaxCallSendMsgSize(s int) CallOption {
  272. return MaxSendMsgSizeCallOption{MaxSendMsgSize: s}
  273. }
  274. // MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message
  275. // size the client can send.
  276. // This is an EXPERIMENTAL API.
  277. type MaxSendMsgSizeCallOption struct {
  278. MaxSendMsgSize int
  279. }
  280. func (o MaxSendMsgSizeCallOption) before(c *callInfo) error {
  281. c.maxSendMessageSize = &o.MaxSendMsgSize
  282. return nil
  283. }
  284. func (o MaxSendMsgSizeCallOption) after(c *callInfo) {}
  285. // PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials
  286. // for a call.
  287. func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption {
  288. return PerRPCCredsCallOption{Creds: creds}
  289. }
  290. // PerRPCCredsCallOption is a CallOption that indicates the per-RPC
  291. // credentials to use for the call.
  292. // This is an EXPERIMENTAL API.
  293. type PerRPCCredsCallOption struct {
  294. Creds credentials.PerRPCCredentials
  295. }
  296. func (o PerRPCCredsCallOption) before(c *callInfo) error {
  297. c.creds = o.Creds
  298. return nil
  299. }
  300. func (o PerRPCCredsCallOption) after(c *callInfo) {}
  301. // UseCompressor returns a CallOption which sets the compressor used when
  302. // sending the request. If WithCompressor is also set, UseCompressor has
  303. // higher priority.
  304. //
  305. // This API is EXPERIMENTAL.
  306. func UseCompressor(name string) CallOption {
  307. return CompressorCallOption{CompressorType: name}
  308. }
  309. // CompressorCallOption is a CallOption that indicates the compressor to use.
  310. // This is an EXPERIMENTAL API.
  311. type CompressorCallOption struct {
  312. CompressorType string
  313. }
  314. func (o CompressorCallOption) before(c *callInfo) error {
  315. c.compressorType = o.CompressorType
  316. return nil
  317. }
  318. func (o CompressorCallOption) after(c *callInfo) {}
  319. // CallContentSubtype returns a CallOption that will set the content-subtype
  320. // for a call. For example, if content-subtype is "json", the Content-Type over
  321. // the wire will be "application/grpc+json". The content-subtype is converted
  322. // to lowercase before being included in Content-Type. See Content-Type on
  323. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  324. // more details.
  325. //
  326. // If ForceCodec is not also used, the content-subtype will be used to look up
  327. // the Codec to use in the registry controlled by RegisterCodec. See the
  328. // documentation on RegisterCodec for details on registration. The lookup of
  329. // content-subtype is case-insensitive. If no such Codec is found, the call
  330. // will result in an error with code codes.Internal.
  331. //
  332. // If ForceCodec is also used, that Codec will be used for all request and
  333. // response messages, with the content-subtype set to the given contentSubtype
  334. // here for requests.
  335. func CallContentSubtype(contentSubtype string) CallOption {
  336. return ContentSubtypeCallOption{ContentSubtype: strings.ToLower(contentSubtype)}
  337. }
  338. // ContentSubtypeCallOption is a CallOption that indicates the content-subtype
  339. // used for marshaling messages.
  340. // This is an EXPERIMENTAL API.
  341. type ContentSubtypeCallOption struct {
  342. ContentSubtype string
  343. }
  344. func (o ContentSubtypeCallOption) before(c *callInfo) error {
  345. c.contentSubtype = o.ContentSubtype
  346. return nil
  347. }
  348. func (o ContentSubtypeCallOption) after(c *callInfo) {}
  349. // ForceCodec returns a CallOption that will set the given Codec to be
  350. // used for all request and response messages for a call. The result of calling
  351. // String() will be used as the content-subtype in a case-insensitive manner.
  352. //
  353. // See Content-Type on
  354. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  355. // more details. Also see the documentation on RegisterCodec and
  356. // CallContentSubtype for more details on the interaction between Codec and
  357. // content-subtype.
  358. //
  359. // This function is provided for advanced users; prefer to use only
  360. // CallContentSubtype to select a registered codec instead.
  361. //
  362. // This is an EXPERIMENTAL API.
  363. func ForceCodec(codec encoding.Codec) CallOption {
  364. return ForceCodecCallOption{Codec: codec}
  365. }
  366. // ForceCodecCallOption is a CallOption that indicates the codec used for
  367. // marshaling messages.
  368. //
  369. // This is an EXPERIMENTAL API.
  370. type ForceCodecCallOption struct {
  371. Codec encoding.Codec
  372. }
  373. func (o ForceCodecCallOption) before(c *callInfo) error {
  374. c.codec = o.Codec
  375. return nil
  376. }
  377. func (o ForceCodecCallOption) after(c *callInfo) {}
  378. // CallCustomCodec behaves like ForceCodec, but accepts a grpc.Codec instead of
  379. // an encoding.Codec.
  380. //
  381. // Deprecated: use ForceCodec instead.
  382. func CallCustomCodec(codec Codec) CallOption {
  383. return CustomCodecCallOption{Codec: codec}
  384. }
  385. // CustomCodecCallOption is a CallOption that indicates the codec used for
  386. // marshaling messages.
  387. //
  388. // This is an EXPERIMENTAL API.
  389. type CustomCodecCallOption struct {
  390. Codec Codec
  391. }
  392. func (o CustomCodecCallOption) before(c *callInfo) error {
  393. c.codec = o.Codec
  394. return nil
  395. }
  396. func (o CustomCodecCallOption) after(c *callInfo) {}
  397. // MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory
  398. // used for buffering this RPC's requests for retry purposes.
  399. //
  400. // This API is EXPERIMENTAL.
  401. func MaxRetryRPCBufferSize(bytes int) CallOption {
  402. return MaxRetryRPCBufferSizeCallOption{bytes}
  403. }
  404. // MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of
  405. // memory to be used for caching this RPC for retry purposes.
  406. // This is an EXPERIMENTAL API.
  407. type MaxRetryRPCBufferSizeCallOption struct {
  408. MaxRetryRPCBufferSize int
  409. }
  410. func (o MaxRetryRPCBufferSizeCallOption) before(c *callInfo) error {
  411. c.maxRetryRPCBufferSize = o.MaxRetryRPCBufferSize
  412. return nil
  413. }
  414. func (o MaxRetryRPCBufferSizeCallOption) after(c *callInfo) {}
  415. // The format of the payload: compressed or not?
  416. type payloadFormat uint8
  417. const (
  418. compressionNone payloadFormat = 0 // no compression
  419. compressionMade payloadFormat = 1 // compressed
  420. )
  421. // parser reads complete gRPC messages from the underlying reader.
  422. type parser struct {
  423. // r is the underlying reader.
  424. // See the comment on recvMsg for the permissible
  425. // error types.
  426. r io.Reader
  427. // The header of a gRPC message. Find more detail at
  428. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
  429. header [5]byte
  430. }
  431. // recvMsg reads a complete gRPC message from the stream.
  432. //
  433. // It returns the message and its payload (compression/encoding)
  434. // format. The caller owns the returned msg memory.
  435. //
  436. // If there is an error, possible values are:
  437. // * io.EOF, when no messages remain
  438. // * io.ErrUnexpectedEOF
  439. // * of type transport.ConnectionError
  440. // * an error from the status package
  441. // No other error values or types must be returned, which also means
  442. // that the underlying io.Reader must not return an incompatible
  443. // error.
  444. func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byte, err error) {
  445. if _, err := p.r.Read(p.header[:]); err != nil {
  446. return 0, nil, err
  447. }
  448. pf = payloadFormat(p.header[0])
  449. length := binary.BigEndian.Uint32(p.header[1:])
  450. if length == 0 {
  451. return pf, nil, nil
  452. }
  453. if int64(length) > int64(maxInt) {
  454. return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt)
  455. }
  456. if int(length) > maxReceiveMessageSize {
  457. return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize)
  458. }
  459. // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead
  460. // of making it for each message:
  461. msg = make([]byte, int(length))
  462. if _, err := p.r.Read(msg); err != nil {
  463. if err == io.EOF {
  464. err = io.ErrUnexpectedEOF
  465. }
  466. return 0, nil, err
  467. }
  468. return pf, msg, nil
  469. }
  470. // encode serializes msg and returns a buffer containing the message, or an
  471. // error if it is too large to be transmitted by grpc. If msg is nil, it
  472. // generates an empty message.
  473. func encode(c baseCodec, msg interface{}) ([]byte, error) {
  474. if msg == nil { // NOTE: typed nils will not be caught by this check
  475. return nil, nil
  476. }
  477. b, err := c.Marshal(msg)
  478. if err != nil {
  479. return nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error())
  480. }
  481. if uint(len(b)) > math.MaxUint32 {
  482. return nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b))
  483. }
  484. return b, nil
  485. }
  486. // compress returns the input bytes compressed by compressor or cp. If both
  487. // compressors are nil, returns nil.
  488. //
  489. // TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor.
  490. func compress(in []byte, cp Compressor, compressor encoding.Compressor) ([]byte, error) {
  491. if compressor == nil && cp == nil {
  492. return nil, nil
  493. }
  494. wrapErr := func(err error) error {
  495. return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error())
  496. }
  497. cbuf := &bytes.Buffer{}
  498. if compressor != nil {
  499. z, err := compressor.Compress(cbuf)
  500. if err != nil {
  501. return nil, wrapErr(err)
  502. }
  503. if _, err := z.Write(in); err != nil {
  504. return nil, wrapErr(err)
  505. }
  506. if err := z.Close(); err != nil {
  507. return nil, wrapErr(err)
  508. }
  509. } else {
  510. if err := cp.Do(cbuf, in); err != nil {
  511. return nil, wrapErr(err)
  512. }
  513. }
  514. return cbuf.Bytes(), nil
  515. }
  516. const (
  517. payloadLen = 1
  518. sizeLen = 4
  519. headerLen = payloadLen + sizeLen
  520. )
  521. // msgHeader returns a 5-byte header for the message being transmitted and the
  522. // payload, which is compData if non-nil or data otherwise.
  523. func msgHeader(data, compData []byte) (hdr []byte, payload []byte) {
  524. hdr = make([]byte, headerLen)
  525. if compData != nil {
  526. hdr[0] = byte(compressionMade)
  527. data = compData
  528. } else {
  529. hdr[0] = byte(compressionNone)
  530. }
  531. // Write length of payload into buf
  532. binary.BigEndian.PutUint32(hdr[payloadLen:], uint32(len(data)))
  533. return hdr, data
  534. }
  535. func outPayload(client bool, msg interface{}, data, payload []byte, t time.Time) *stats.OutPayload {
  536. return &stats.OutPayload{
  537. Client: client,
  538. Payload: msg,
  539. Data: data,
  540. Length: len(data),
  541. WireLength: len(payload) + headerLen,
  542. SentTime: t,
  543. }
  544. }
  545. func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool) *status.Status {
  546. switch pf {
  547. case compressionNone:
  548. case compressionMade:
  549. if recvCompress == "" || recvCompress == encoding.Identity {
  550. return status.New(codes.Internal, "grpc: compressed flag set with identity or empty encoding")
  551. }
  552. if !haveCompressor {
  553. return status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
  554. }
  555. default:
  556. return status.Newf(codes.Internal, "grpc: received unexpected payload format %d", pf)
  557. }
  558. return nil
  559. }
  560. type payloadInfo struct {
  561. wireLength int // The compressed length got from wire.
  562. uncompressedBytes []byte
  563. }
  564. func recvAndDecompress(p *parser, s *transport.Stream, dc Decompressor, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor) ([]byte, error) {
  565. pf, d, err := p.recvMsg(maxReceiveMessageSize)
  566. if err != nil {
  567. return nil, err
  568. }
  569. if payInfo != nil {
  570. payInfo.wireLength = len(d)
  571. }
  572. if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil); st != nil {
  573. return nil, st.Err()
  574. }
  575. if pf == compressionMade {
  576. // To match legacy behavior, if the decompressor is set by WithDecompressor or RPCDecompressor,
  577. // use this decompressor as the default.
  578. if dc != nil {
  579. d, err = dc.Do(bytes.NewReader(d))
  580. if err != nil {
  581. return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
  582. }
  583. } else {
  584. dcReader, err := compressor.Decompress(bytes.NewReader(d))
  585. if err != nil {
  586. return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
  587. }
  588. // Read from LimitReader with limit max+1. So if the underlying
  589. // reader is over limit, the result will be bigger than max.
  590. d, err = ioutil.ReadAll(io.LimitReader(dcReader, int64(maxReceiveMessageSize)+1))
  591. if err != nil {
  592. return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
  593. }
  594. }
  595. }
  596. if len(d) > maxReceiveMessageSize {
  597. // TODO: Revisit the error code. Currently keep it consistent with java
  598. // implementation.
  599. return nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(d), maxReceiveMessageSize)
  600. }
  601. return d, nil
  602. }
  603. // For the two compressor parameters, both should not be set, but if they are,
  604. // dc takes precedence over compressor.
  605. // TODO(dfawley): wrap the old compressor/decompressor using the new API?
  606. func recv(p *parser, c baseCodec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor) error {
  607. d, err := recvAndDecompress(p, s, dc, maxReceiveMessageSize, payInfo, compressor)
  608. if err != nil {
  609. return err
  610. }
  611. if err := c.Unmarshal(d, m); err != nil {
  612. return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err)
  613. }
  614. if payInfo != nil {
  615. payInfo.uncompressedBytes = d
  616. }
  617. return nil
  618. }
  619. type rpcInfo struct {
  620. failfast bool
  621. }
  622. type rpcInfoContextKey struct{}
  623. func newContextWithRPCInfo(ctx context.Context, failfast bool) context.Context {
  624. return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{failfast: failfast})
  625. }
  626. func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) {
  627. s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo)
  628. return
  629. }
  630. // Code returns the error code for err if it was produced by the rpc system.
  631. // Otherwise, it returns codes.Unknown.
  632. //
  633. // Deprecated: use status.Code instead.
  634. func Code(err error) codes.Code {
  635. return status.Code(err)
  636. }
  637. // ErrorDesc returns the error description of err if it was produced by the rpc system.
  638. // Otherwise, it returns err.Error() or empty string when err is nil.
  639. //
  640. // Deprecated: use status.Convert and Message method instead.
  641. func ErrorDesc(err error) string {
  642. return status.Convert(err).Message()
  643. }
  644. // Errorf returns an error containing an error code and a description;
  645. // Errorf returns nil if c is OK.
  646. //
  647. // Deprecated: use status.Errorf instead.
  648. func Errorf(c codes.Code, format string, a ...interface{}) error {
  649. return status.Errorf(c, format, a...)
  650. }
  651. // toRPCErr converts an error into an error from the status package.
  652. func toRPCErr(err error) error {
  653. if err == nil || err == io.EOF {
  654. return err
  655. }
  656. if err == io.ErrUnexpectedEOF {
  657. return status.Error(codes.Internal, err.Error())
  658. }
  659. if _, ok := status.FromError(err); ok {
  660. return err
  661. }
  662. switch e := err.(type) {
  663. case transport.ConnectionError:
  664. return status.Error(codes.Unavailable, e.Desc)
  665. default:
  666. switch err {
  667. case context.DeadlineExceeded:
  668. return status.Error(codes.DeadlineExceeded, err.Error())
  669. case context.Canceled:
  670. return status.Error(codes.Canceled, err.Error())
  671. }
  672. }
  673. return status.Error(codes.Unknown, err.Error())
  674. }
  675. // setCallInfoCodec should only be called after CallOptions have been applied.
  676. func setCallInfoCodec(c *callInfo) error {
  677. if c.codec != nil {
  678. // codec was already set by a CallOption; use it.
  679. return nil
  680. }
  681. if c.contentSubtype == "" {
  682. // No codec specified in CallOptions; use proto by default.
  683. c.codec = encoding.GetCodec(proto.Name)
  684. return nil
  685. }
  686. // c.contentSubtype is already lowercased in CallContentSubtype
  687. c.codec = encoding.GetCodec(c.contentSubtype)
  688. if c.codec == nil {
  689. return status.Errorf(codes.Internal, "no codec registered for content-subtype %s", c.contentSubtype)
  690. }
  691. return nil
  692. }
  693. // parseDialTarget returns the network and address to pass to dialer
  694. func parseDialTarget(target string) (net string, addr string) {
  695. net = "tcp"
  696. m1 := strings.Index(target, ":")
  697. m2 := strings.Index(target, ":/")
  698. // handle unix:addr which will fail with url.Parse
  699. if m1 >= 0 && m2 < 0 {
  700. if n := target[0:m1]; n == "unix" {
  701. net = n
  702. addr = target[m1+1:]
  703. return net, addr
  704. }
  705. }
  706. if m2 >= 0 {
  707. t, err := url.Parse(target)
  708. if err != nil {
  709. return net, target
  710. }
  711. scheme := t.Scheme
  712. addr = t.Path
  713. if scheme == "unix" {
  714. net = scheme
  715. if addr == "" {
  716. addr = t.Host
  717. }
  718. return net, addr
  719. }
  720. }
  721. return net, target
  722. }
  723. // channelzData is used to store channelz related data for ClientConn, addrConn and Server.
  724. // These fields cannot be embedded in the original structs (e.g. ClientConn), since to do atomic
  725. // operation on int64 variable on 32-bit machine, user is responsible to enforce memory alignment.
  726. // Here, by grouping those int64 fields inside a struct, we are enforcing the alignment.
  727. type channelzData struct {
  728. callsStarted int64
  729. callsFailed int64
  730. callsSucceeded int64
  731. // lastCallStartedTime stores the timestamp that last call starts. It is of int64 type instead of
  732. // time.Time since it's more costly to atomically update time.Time variable than int64 variable.
  733. lastCallStartedTime int64
  734. }
  735. // The SupportPackageIsVersion variables are referenced from generated protocol
  736. // buffer files to ensure compatibility with the gRPC version used. The latest
  737. // support package version is 5.
  738. //
  739. // Older versions are kept for compatibility. They may be removed if
  740. // compatibility cannot be maintained.
  741. //
  742. // These constants should not be referenced from any other code.
  743. const (
  744. SupportPackageIsVersion3 = true
  745. SupportPackageIsVersion4 = true
  746. SupportPackageIsVersion5 = true
  747. )
  748. const grpcUA = "grpc-go/" + Version