rpc_util.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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
  256. // in bytes the client can receive.
  257. func MaxCallRecvMsgSize(bytes int) CallOption {
  258. return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: bytes}
  259. }
  260. // MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message
  261. // size in bytes the client can receive.
  262. // This is an EXPERIMENTAL API.
  263. type MaxRecvMsgSizeCallOption struct {
  264. MaxRecvMsgSize int
  265. }
  266. func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error {
  267. c.maxReceiveMessageSize = &o.MaxRecvMsgSize
  268. return nil
  269. }
  270. func (o MaxRecvMsgSizeCallOption) after(c *callInfo) {}
  271. // MaxCallSendMsgSize returns a CallOption which sets the maximum message size
  272. // in bytes the client can send.
  273. func MaxCallSendMsgSize(bytes int) CallOption {
  274. return MaxSendMsgSizeCallOption{MaxSendMsgSize: bytes}
  275. }
  276. // MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message
  277. // size in bytes the client can send.
  278. // This is an EXPERIMENTAL API.
  279. type MaxSendMsgSizeCallOption struct {
  280. MaxSendMsgSize int
  281. }
  282. func (o MaxSendMsgSizeCallOption) before(c *callInfo) error {
  283. c.maxSendMessageSize = &o.MaxSendMsgSize
  284. return nil
  285. }
  286. func (o MaxSendMsgSizeCallOption) after(c *callInfo) {}
  287. // PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials
  288. // for a call.
  289. func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption {
  290. return PerRPCCredsCallOption{Creds: creds}
  291. }
  292. // PerRPCCredsCallOption is a CallOption that indicates the per-RPC
  293. // credentials to use for the call.
  294. // This is an EXPERIMENTAL API.
  295. type PerRPCCredsCallOption struct {
  296. Creds credentials.PerRPCCredentials
  297. }
  298. func (o PerRPCCredsCallOption) before(c *callInfo) error {
  299. c.creds = o.Creds
  300. return nil
  301. }
  302. func (o PerRPCCredsCallOption) after(c *callInfo) {}
  303. // UseCompressor returns a CallOption which sets the compressor used when
  304. // sending the request. If WithCompressor is also set, UseCompressor has
  305. // higher priority.
  306. //
  307. // This API is EXPERIMENTAL.
  308. func UseCompressor(name string) CallOption {
  309. return CompressorCallOption{CompressorType: name}
  310. }
  311. // CompressorCallOption is a CallOption that indicates the compressor to use.
  312. // This is an EXPERIMENTAL API.
  313. type CompressorCallOption struct {
  314. CompressorType string
  315. }
  316. func (o CompressorCallOption) before(c *callInfo) error {
  317. c.compressorType = o.CompressorType
  318. return nil
  319. }
  320. func (o CompressorCallOption) after(c *callInfo) {}
  321. // CallContentSubtype returns a CallOption that will set the content-subtype
  322. // for a call. For example, if content-subtype is "json", the Content-Type over
  323. // the wire will be "application/grpc+json". The content-subtype is converted
  324. // to lowercase before being included in Content-Type. See Content-Type on
  325. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  326. // more details.
  327. //
  328. // If ForceCodec is not also used, the content-subtype will be used to look up
  329. // the Codec to use in the registry controlled by RegisterCodec. See the
  330. // documentation on RegisterCodec for details on registration. The lookup of
  331. // content-subtype is case-insensitive. If no such Codec is found, the call
  332. // will result in an error with code codes.Internal.
  333. //
  334. // If ForceCodec is also used, that Codec will be used for all request and
  335. // response messages, with the content-subtype set to the given contentSubtype
  336. // here for requests.
  337. func CallContentSubtype(contentSubtype string) CallOption {
  338. return ContentSubtypeCallOption{ContentSubtype: strings.ToLower(contentSubtype)}
  339. }
  340. // ContentSubtypeCallOption is a CallOption that indicates the content-subtype
  341. // used for marshaling messages.
  342. // This is an EXPERIMENTAL API.
  343. type ContentSubtypeCallOption struct {
  344. ContentSubtype string
  345. }
  346. func (o ContentSubtypeCallOption) before(c *callInfo) error {
  347. c.contentSubtype = o.ContentSubtype
  348. return nil
  349. }
  350. func (o ContentSubtypeCallOption) after(c *callInfo) {}
  351. // ForceCodec returns a CallOption that will set the given Codec to be
  352. // used for all request and response messages for a call. The result of calling
  353. // String() will be used as the content-subtype in a case-insensitive manner.
  354. //
  355. // See Content-Type on
  356. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  357. // more details. Also see the documentation on RegisterCodec and
  358. // CallContentSubtype for more details on the interaction between Codec and
  359. // content-subtype.
  360. //
  361. // This function is provided for advanced users; prefer to use only
  362. // CallContentSubtype to select a registered codec instead.
  363. //
  364. // This is an EXPERIMENTAL API.
  365. func ForceCodec(codec encoding.Codec) CallOption {
  366. return ForceCodecCallOption{Codec: codec}
  367. }
  368. // ForceCodecCallOption is a CallOption that indicates the codec used for
  369. // marshaling messages.
  370. //
  371. // This is an EXPERIMENTAL API.
  372. type ForceCodecCallOption struct {
  373. Codec encoding.Codec
  374. }
  375. func (o ForceCodecCallOption) before(c *callInfo) error {
  376. c.codec = o.Codec
  377. return nil
  378. }
  379. func (o ForceCodecCallOption) after(c *callInfo) {}
  380. // CallCustomCodec behaves like ForceCodec, but accepts a grpc.Codec instead of
  381. // an encoding.Codec.
  382. //
  383. // Deprecated: use ForceCodec instead.
  384. func CallCustomCodec(codec Codec) CallOption {
  385. return CustomCodecCallOption{Codec: codec}
  386. }
  387. // CustomCodecCallOption is a CallOption that indicates the codec used for
  388. // marshaling messages.
  389. //
  390. // This is an EXPERIMENTAL API.
  391. type CustomCodecCallOption struct {
  392. Codec Codec
  393. }
  394. func (o CustomCodecCallOption) before(c *callInfo) error {
  395. c.codec = o.Codec
  396. return nil
  397. }
  398. func (o CustomCodecCallOption) after(c *callInfo) {}
  399. // MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory
  400. // used for buffering this RPC's requests for retry purposes.
  401. //
  402. // This API is EXPERIMENTAL.
  403. func MaxRetryRPCBufferSize(bytes int) CallOption {
  404. return MaxRetryRPCBufferSizeCallOption{bytes}
  405. }
  406. // MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of
  407. // memory to be used for caching this RPC for retry purposes.
  408. // This is an EXPERIMENTAL API.
  409. type MaxRetryRPCBufferSizeCallOption struct {
  410. MaxRetryRPCBufferSize int
  411. }
  412. func (o MaxRetryRPCBufferSizeCallOption) before(c *callInfo) error {
  413. c.maxRetryRPCBufferSize = o.MaxRetryRPCBufferSize
  414. return nil
  415. }
  416. func (o MaxRetryRPCBufferSizeCallOption) after(c *callInfo) {}
  417. // The format of the payload: compressed or not?
  418. type payloadFormat uint8
  419. const (
  420. compressionNone payloadFormat = 0 // no compression
  421. compressionMade payloadFormat = 1 // compressed
  422. )
  423. // parser reads complete gRPC messages from the underlying reader.
  424. type parser struct {
  425. // r is the underlying reader.
  426. // See the comment on recvMsg for the permissible
  427. // error types.
  428. r io.Reader
  429. // The header of a gRPC message. Find more detail at
  430. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
  431. header [5]byte
  432. }
  433. // recvMsg reads a complete gRPC message from the stream.
  434. //
  435. // It returns the message and its payload (compression/encoding)
  436. // format. The caller owns the returned msg memory.
  437. //
  438. // If there is an error, possible values are:
  439. // * io.EOF, when no messages remain
  440. // * io.ErrUnexpectedEOF
  441. // * of type transport.ConnectionError
  442. // * an error from the status package
  443. // No other error values or types must be returned, which also means
  444. // that the underlying io.Reader must not return an incompatible
  445. // error.
  446. func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byte, err error) {
  447. if _, err := p.r.Read(p.header[:]); err != nil {
  448. return 0, nil, err
  449. }
  450. pf = payloadFormat(p.header[0])
  451. length := binary.BigEndian.Uint32(p.header[1:])
  452. if length == 0 {
  453. return pf, nil, nil
  454. }
  455. if int64(length) > int64(maxInt) {
  456. return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt)
  457. }
  458. if int(length) > maxReceiveMessageSize {
  459. return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize)
  460. }
  461. // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead
  462. // of making it for each message:
  463. msg = make([]byte, int(length))
  464. if _, err := p.r.Read(msg); err != nil {
  465. if err == io.EOF {
  466. err = io.ErrUnexpectedEOF
  467. }
  468. return 0, nil, err
  469. }
  470. return pf, msg, nil
  471. }
  472. // encode serializes msg and returns a buffer containing the message, or an
  473. // error if it is too large to be transmitted by grpc. If msg is nil, it
  474. // generates an empty message.
  475. func encode(c baseCodec, msg interface{}) ([]byte, error) {
  476. if msg == nil { // NOTE: typed nils will not be caught by this check
  477. return nil, nil
  478. }
  479. b, err := c.Marshal(msg)
  480. if err != nil {
  481. return nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error())
  482. }
  483. if uint(len(b)) > math.MaxUint32 {
  484. return nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b))
  485. }
  486. return b, nil
  487. }
  488. // compress returns the input bytes compressed by compressor or cp. If both
  489. // compressors are nil, returns nil.
  490. //
  491. // TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor.
  492. func compress(in []byte, cp Compressor, compressor encoding.Compressor) ([]byte, error) {
  493. if compressor == nil && cp == nil {
  494. return nil, nil
  495. }
  496. wrapErr := func(err error) error {
  497. return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error())
  498. }
  499. cbuf := &bytes.Buffer{}
  500. if compressor != nil {
  501. z, err := compressor.Compress(cbuf)
  502. if err != nil {
  503. return nil, wrapErr(err)
  504. }
  505. if _, err := z.Write(in); err != nil {
  506. return nil, wrapErr(err)
  507. }
  508. if err := z.Close(); err != nil {
  509. return nil, wrapErr(err)
  510. }
  511. } else {
  512. if err := cp.Do(cbuf, in); err != nil {
  513. return nil, wrapErr(err)
  514. }
  515. }
  516. return cbuf.Bytes(), nil
  517. }
  518. const (
  519. payloadLen = 1
  520. sizeLen = 4
  521. headerLen = payloadLen + sizeLen
  522. )
  523. // msgHeader returns a 5-byte header for the message being transmitted and the
  524. // payload, which is compData if non-nil or data otherwise.
  525. func msgHeader(data, compData []byte) (hdr []byte, payload []byte) {
  526. hdr = make([]byte, headerLen)
  527. if compData != nil {
  528. hdr[0] = byte(compressionMade)
  529. data = compData
  530. } else {
  531. hdr[0] = byte(compressionNone)
  532. }
  533. // Write length of payload into buf
  534. binary.BigEndian.PutUint32(hdr[payloadLen:], uint32(len(data)))
  535. return hdr, data
  536. }
  537. func outPayload(client bool, msg interface{}, data, payload []byte, t time.Time) *stats.OutPayload {
  538. return &stats.OutPayload{
  539. Client: client,
  540. Payload: msg,
  541. Data: data,
  542. Length: len(data),
  543. WireLength: len(payload) + headerLen,
  544. SentTime: t,
  545. }
  546. }
  547. func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool) *status.Status {
  548. switch pf {
  549. case compressionNone:
  550. case compressionMade:
  551. if recvCompress == "" || recvCompress == encoding.Identity {
  552. return status.New(codes.Internal, "grpc: compressed flag set with identity or empty encoding")
  553. }
  554. if !haveCompressor {
  555. return status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
  556. }
  557. default:
  558. return status.Newf(codes.Internal, "grpc: received unexpected payload format %d", pf)
  559. }
  560. return nil
  561. }
  562. type payloadInfo struct {
  563. wireLength int // The compressed length got from wire.
  564. uncompressedBytes []byte
  565. }
  566. func recvAndDecompress(p *parser, s *transport.Stream, dc Decompressor, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor) ([]byte, error) {
  567. pf, d, err := p.recvMsg(maxReceiveMessageSize)
  568. if err != nil {
  569. return nil, err
  570. }
  571. if payInfo != nil {
  572. payInfo.wireLength = len(d)
  573. }
  574. if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil); st != nil {
  575. return nil, st.Err()
  576. }
  577. var size int
  578. if pf == compressionMade {
  579. // To match legacy behavior, if the decompressor is set by WithDecompressor or RPCDecompressor,
  580. // use this decompressor as the default.
  581. if dc != nil {
  582. d, err = dc.Do(bytes.NewReader(d))
  583. size = len(d)
  584. } else {
  585. d, size, err = decompress(compressor, d, maxReceiveMessageSize)
  586. }
  587. if err != nil {
  588. return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
  589. }
  590. } else {
  591. size = len(d)
  592. }
  593. if size > maxReceiveMessageSize {
  594. // TODO: Revisit the error code. Currently keep it consistent with java
  595. // implementation.
  596. return nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", size, maxReceiveMessageSize)
  597. }
  598. return d, nil
  599. }
  600. // Using compressor, decompress d, returning data and size.
  601. // Optionally, if data will be over maxReceiveMessageSize, just return the size.
  602. func decompress(compressor encoding.Compressor, d []byte, maxReceiveMessageSize int) ([]byte, int, error) {
  603. dcReader, err := compressor.Decompress(bytes.NewReader(d))
  604. if err != nil {
  605. return nil, 0, err
  606. }
  607. if sizer, ok := compressor.(interface {
  608. DecompressedSize(compressedBytes []byte) int
  609. }); ok {
  610. if size := sizer.DecompressedSize(d); size >= 0 {
  611. if size > maxReceiveMessageSize {
  612. return nil, size, nil
  613. }
  614. // size is used as an estimate to size the buffer, but we
  615. // will read more data if available.
  616. // +MinRead so ReadFrom will not reallocate if size is correct.
  617. buf := bytes.NewBuffer(make([]byte, 0, size+bytes.MinRead))
  618. bytesRead, err := buf.ReadFrom(io.LimitReader(dcReader, int64(maxReceiveMessageSize)+1))
  619. return buf.Bytes(), int(bytesRead), err
  620. }
  621. }
  622. // Read from LimitReader with limit max+1. So if the underlying
  623. // reader is over limit, the result will be bigger than max.
  624. d, err = ioutil.ReadAll(io.LimitReader(dcReader, int64(maxReceiveMessageSize)+1))
  625. return d, len(d), err
  626. }
  627. // For the two compressor parameters, both should not be set, but if they are,
  628. // dc takes precedence over compressor.
  629. // TODO(dfawley): wrap the old compressor/decompressor using the new API?
  630. func recv(p *parser, c baseCodec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor) error {
  631. d, err := recvAndDecompress(p, s, dc, maxReceiveMessageSize, payInfo, compressor)
  632. if err != nil {
  633. return err
  634. }
  635. if err := c.Unmarshal(d, m); err != nil {
  636. return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err)
  637. }
  638. if payInfo != nil {
  639. payInfo.uncompressedBytes = d
  640. }
  641. return nil
  642. }
  643. // Information about RPC
  644. type rpcInfo struct {
  645. failfast bool
  646. preloaderInfo *compressorInfo
  647. }
  648. // Information about Preloader
  649. // Responsible for storing codec, and compressors
  650. // If stream (s) has context s.Context which stores rpcInfo that has non nil
  651. // pointers to codec, and compressors, then we can use preparedMsg for Async message prep
  652. // and reuse marshalled bytes
  653. type compressorInfo struct {
  654. codec baseCodec
  655. cp Compressor
  656. comp encoding.Compressor
  657. }
  658. type rpcInfoContextKey struct{}
  659. func newContextWithRPCInfo(ctx context.Context, failfast bool, codec baseCodec, cp Compressor, comp encoding.Compressor) context.Context {
  660. return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{
  661. failfast: failfast,
  662. preloaderInfo: &compressorInfo{
  663. codec: codec,
  664. cp: cp,
  665. comp: comp,
  666. },
  667. })
  668. }
  669. func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) {
  670. s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo)
  671. return
  672. }
  673. // Code returns the error code for err if it was produced by the rpc system.
  674. // Otherwise, it returns codes.Unknown.
  675. //
  676. // Deprecated: use status.Code instead.
  677. func Code(err error) codes.Code {
  678. return status.Code(err)
  679. }
  680. // ErrorDesc returns the error description of err if it was produced by the rpc system.
  681. // Otherwise, it returns err.Error() or empty string when err is nil.
  682. //
  683. // Deprecated: use status.Convert and Message method instead.
  684. func ErrorDesc(err error) string {
  685. return status.Convert(err).Message()
  686. }
  687. // Errorf returns an error containing an error code and a description;
  688. // Errorf returns nil if c is OK.
  689. //
  690. // Deprecated: use status.Errorf instead.
  691. func Errorf(c codes.Code, format string, a ...interface{}) error {
  692. return status.Errorf(c, format, a...)
  693. }
  694. // toRPCErr converts an error into an error from the status package.
  695. func toRPCErr(err error) error {
  696. if err == nil || err == io.EOF {
  697. return err
  698. }
  699. if err == io.ErrUnexpectedEOF {
  700. return status.Error(codes.Internal, err.Error())
  701. }
  702. if _, ok := status.FromError(err); ok {
  703. return err
  704. }
  705. switch e := err.(type) {
  706. case transport.ConnectionError:
  707. return status.Error(codes.Unavailable, e.Desc)
  708. default:
  709. switch err {
  710. case context.DeadlineExceeded:
  711. return status.Error(codes.DeadlineExceeded, err.Error())
  712. case context.Canceled:
  713. return status.Error(codes.Canceled, err.Error())
  714. }
  715. }
  716. return status.Error(codes.Unknown, err.Error())
  717. }
  718. // setCallInfoCodec should only be called after CallOptions have been applied.
  719. func setCallInfoCodec(c *callInfo) error {
  720. if c.codec != nil {
  721. // codec was already set by a CallOption; use it.
  722. return nil
  723. }
  724. if c.contentSubtype == "" {
  725. // No codec specified in CallOptions; use proto by default.
  726. c.codec = encoding.GetCodec(proto.Name)
  727. return nil
  728. }
  729. // c.contentSubtype is already lowercased in CallContentSubtype
  730. c.codec = encoding.GetCodec(c.contentSubtype)
  731. if c.codec == nil {
  732. return status.Errorf(codes.Internal, "no codec registered for content-subtype %s", c.contentSubtype)
  733. }
  734. return nil
  735. }
  736. // parseDialTarget returns the network and address to pass to dialer
  737. func parseDialTarget(target string) (net string, addr string) {
  738. net = "tcp"
  739. m1 := strings.Index(target, ":")
  740. m2 := strings.Index(target, ":/")
  741. // handle unix:addr which will fail with url.Parse
  742. if m1 >= 0 && m2 < 0 {
  743. if n := target[0:m1]; n == "unix" {
  744. net = n
  745. addr = target[m1+1:]
  746. return net, addr
  747. }
  748. }
  749. if m2 >= 0 {
  750. t, err := url.Parse(target)
  751. if err != nil {
  752. return net, target
  753. }
  754. scheme := t.Scheme
  755. addr = t.Path
  756. if scheme == "unix" {
  757. net = scheme
  758. if addr == "" {
  759. addr = t.Host
  760. }
  761. return net, addr
  762. }
  763. }
  764. return net, target
  765. }
  766. // channelzData is used to store channelz related data for ClientConn, addrConn and Server.
  767. // These fields cannot be embedded in the original structs (e.g. ClientConn), since to do atomic
  768. // operation on int64 variable on 32-bit machine, user is responsible to enforce memory alignment.
  769. // Here, by grouping those int64 fields inside a struct, we are enforcing the alignment.
  770. type channelzData struct {
  771. callsStarted int64
  772. callsFailed int64
  773. callsSucceeded int64
  774. // lastCallStartedTime stores the timestamp that last call starts. It is of int64 type instead of
  775. // time.Time since it's more costly to atomically update time.Time variable than int64 variable.
  776. lastCallStartedTime int64
  777. }
  778. // The SupportPackageIsVersion variables are referenced from generated protocol
  779. // buffer files to ensure compatibility with the gRPC version used. The latest
  780. // support package version is 6.
  781. //
  782. // Older versions are kept for compatibility. They may be removed if
  783. // compatibility cannot be maintained.
  784. //
  785. // These constants should not be referenced from any other code.
  786. const (
  787. SupportPackageIsVersion3 = true
  788. SupportPackageIsVersion4 = true
  789. SupportPackageIsVersion5 = true
  790. SupportPackageIsVersion6 = true
  791. )
  792. const grpcUA = "grpc-go/" + Version