rpc_util.go 27 KB

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