rpc_util.go 22 KB

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