rpc_util.go 21 KB

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