rpc_util.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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. // Information about RPC
  620. type rpcInfo struct {
  621. failfast bool
  622. preloaderInfo *compressorInfo
  623. }
  624. // Information about Preloader
  625. // Responsible for storing codec, and compressors
  626. // If stream (s) has context s.Context which stores rpcInfo that has non nil
  627. // pointers to codec, and compressors, then we can use preparedMsg for Async message prep
  628. // and reuse marshalled bytes
  629. type compressorInfo struct {
  630. codec baseCodec
  631. cp Compressor
  632. comp encoding.Compressor
  633. }
  634. type rpcInfoContextKey struct{}
  635. func newContextWithRPCInfo(ctx context.Context, failfast bool, codec baseCodec, cp Compressor, comp encoding.Compressor) context.Context {
  636. return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{
  637. failfast: failfast,
  638. preloaderInfo: &compressorInfo{
  639. codec: codec,
  640. cp: cp,
  641. comp: comp,
  642. },
  643. })
  644. }
  645. func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) {
  646. s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo)
  647. return
  648. }
  649. // Code returns the error code for err if it was produced by the rpc system.
  650. // Otherwise, it returns codes.Unknown.
  651. //
  652. // Deprecated: use status.Code instead.
  653. func Code(err error) codes.Code {
  654. return status.Code(err)
  655. }
  656. // ErrorDesc returns the error description of err if it was produced by the rpc system.
  657. // Otherwise, it returns err.Error() or empty string when err is nil.
  658. //
  659. // Deprecated: use status.Convert and Message method instead.
  660. func ErrorDesc(err error) string {
  661. return status.Convert(err).Message()
  662. }
  663. // Errorf returns an error containing an error code and a description;
  664. // Errorf returns nil if c is OK.
  665. //
  666. // Deprecated: use status.Errorf instead.
  667. func Errorf(c codes.Code, format string, a ...interface{}) error {
  668. return status.Errorf(c, format, a...)
  669. }
  670. // toRPCErr converts an error into an error from the status package.
  671. func toRPCErr(err error) error {
  672. if err == nil || err == io.EOF {
  673. return err
  674. }
  675. if err == io.ErrUnexpectedEOF {
  676. return status.Error(codes.Internal, err.Error())
  677. }
  678. if _, ok := status.FromError(err); ok {
  679. return err
  680. }
  681. switch e := err.(type) {
  682. case transport.ConnectionError:
  683. return status.Error(codes.Unavailable, e.Desc)
  684. default:
  685. switch err {
  686. case context.DeadlineExceeded:
  687. return status.Error(codes.DeadlineExceeded, err.Error())
  688. case context.Canceled:
  689. return status.Error(codes.Canceled, err.Error())
  690. }
  691. }
  692. return status.Error(codes.Unknown, err.Error())
  693. }
  694. // setCallInfoCodec should only be called after CallOptions have been applied.
  695. func setCallInfoCodec(c *callInfo) error {
  696. if c.codec != nil {
  697. // codec was already set by a CallOption; use it.
  698. return nil
  699. }
  700. if c.contentSubtype == "" {
  701. // No codec specified in CallOptions; use proto by default.
  702. c.codec = encoding.GetCodec(proto.Name)
  703. return nil
  704. }
  705. // c.contentSubtype is already lowercased in CallContentSubtype
  706. c.codec = encoding.GetCodec(c.contentSubtype)
  707. if c.codec == nil {
  708. return status.Errorf(codes.Internal, "no codec registered for content-subtype %s", c.contentSubtype)
  709. }
  710. return nil
  711. }
  712. // parseDialTarget returns the network and address to pass to dialer
  713. func parseDialTarget(target string) (net string, addr string) {
  714. net = "tcp"
  715. m1 := strings.Index(target, ":")
  716. m2 := strings.Index(target, ":/")
  717. // handle unix:addr which will fail with url.Parse
  718. if m1 >= 0 && m2 < 0 {
  719. if n := target[0:m1]; n == "unix" {
  720. net = n
  721. addr = target[m1+1:]
  722. return net, addr
  723. }
  724. }
  725. if m2 >= 0 {
  726. t, err := url.Parse(target)
  727. if err != nil {
  728. return net, target
  729. }
  730. scheme := t.Scheme
  731. addr = t.Path
  732. if scheme == "unix" {
  733. net = scheme
  734. if addr == "" {
  735. addr = t.Host
  736. }
  737. return net, addr
  738. }
  739. }
  740. return net, target
  741. }
  742. // channelzData is used to store channelz related data for ClientConn, addrConn and Server.
  743. // These fields cannot be embedded in the original structs (e.g. ClientConn), since to do atomic
  744. // operation on int64 variable on 32-bit machine, user is responsible to enforce memory alignment.
  745. // Here, by grouping those int64 fields inside a struct, we are enforcing the alignment.
  746. type channelzData struct {
  747. callsStarted int64
  748. callsFailed int64
  749. callsSucceeded int64
  750. // lastCallStartedTime stores the timestamp that last call starts. It is of int64 type instead of
  751. // time.Time since it's more costly to atomically update time.Time variable than int64 variable.
  752. lastCallStartedTime int64
  753. }
  754. // The SupportPackageIsVersion variables are referenced from generated protocol
  755. // buffer files to ensure compatibility with the gRPC version used. The latest
  756. // support package version is 5.
  757. //
  758. // Older versions are kept for compatibility. They may be removed if
  759. // compatibility cannot be maintained.
  760. //
  761. // These constants should not be referenced from any other code.
  762. const (
  763. SupportPackageIsVersion3 = true
  764. SupportPackageIsVersion4 = true
  765. SupportPackageIsVersion5 = true
  766. )
  767. const grpcUA = "grpc-go/" + Version