call.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. /*
  2. *
  3. * Copyright 2014, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. package grpc
  34. import (
  35. "bytes"
  36. "io"
  37. "time"
  38. "golang.org/x/net/context"
  39. "golang.org/x/net/trace"
  40. "google.golang.org/grpc/codes"
  41. "google.golang.org/grpc/transport"
  42. )
  43. // recvResponse receives and parses an RPC response.
  44. // On error, it returns the error and indicates whether the call should be retried.
  45. //
  46. // TODO(zhaoq): Check whether the received message sequence is valid.
  47. func recvResponse(dopts dialOptions, t transport.ClientTransport, c *callInfo, stream *transport.Stream, reply interface{}) error {
  48. // Try to acquire header metadata from the server if there is any.
  49. var err error
  50. c.headerMD, err = stream.Header()
  51. if err != nil {
  52. return err
  53. }
  54. p := &parser{r: stream}
  55. for {
  56. if err = recv(p, dopts.codec, stream, dopts.dc, reply); err != nil {
  57. if err == io.EOF {
  58. break
  59. }
  60. return err
  61. }
  62. }
  63. c.trailerMD = stream.Trailer()
  64. return nil
  65. }
  66. // sendRequest writes out various information of an RPC such as Context and Message.
  67. func sendRequest(ctx context.Context, codec Codec, compressor Compressor, callHdr *transport.CallHdr, t transport.ClientTransport, args interface{}, opts *transport.Options) (_ *transport.Stream, err error) {
  68. stream, err := t.NewStream(ctx, callHdr)
  69. if err != nil {
  70. return nil, err
  71. }
  72. defer func() {
  73. if err != nil {
  74. if _, ok := err.(transport.ConnectionError); !ok {
  75. t.CloseStream(stream, err)
  76. }
  77. }
  78. }()
  79. var cbuf *bytes.Buffer
  80. if compressor != nil {
  81. cbuf = new(bytes.Buffer)
  82. }
  83. outBuf, err := encode(codec, args, compressor, cbuf)
  84. if err != nil {
  85. return nil, transport.StreamErrorf(codes.Internal, "grpc: %v", err)
  86. }
  87. err = t.Write(stream, outBuf, opts)
  88. if err != nil {
  89. return nil, err
  90. }
  91. // Sent successfully.
  92. return stream, nil
  93. }
  94. // Invoke sends the RPC request on the wire and returns after response is received.
  95. // Invoke is called by generated code. Also users can call Invoke directly when it
  96. // is really needed in their use cases.
  97. func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (err error) {
  98. c := defaultCallInfo
  99. for _, o := range opts {
  100. if err := o.before(&c); err != nil {
  101. return toRPCErr(err)
  102. }
  103. }
  104. defer func() {
  105. for _, o := range opts {
  106. o.after(&c)
  107. }
  108. }()
  109. if EnableTracing {
  110. c.traceInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
  111. defer c.traceInfo.tr.Finish()
  112. c.traceInfo.firstLine.client = true
  113. if deadline, ok := ctx.Deadline(); ok {
  114. c.traceInfo.firstLine.deadline = deadline.Sub(time.Now())
  115. }
  116. c.traceInfo.tr.LazyLog(&c.traceInfo.firstLine, false)
  117. // TODO(dsymonds): Arrange for c.traceInfo.firstLine.remoteAddr to be set.
  118. defer func() {
  119. if err != nil {
  120. c.traceInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  121. c.traceInfo.tr.SetError()
  122. }
  123. }()
  124. }
  125. topts := &transport.Options{
  126. Last: true,
  127. Delay: false,
  128. }
  129. for {
  130. var (
  131. err error
  132. t transport.ClientTransport
  133. stream *transport.Stream
  134. // Record the put handler from Balancer.Get(...). It is called once the
  135. // RPC has completed or failed.
  136. put func()
  137. )
  138. // TODO(zhaoq): Need a formal spec of fail-fast.
  139. callHdr := &transport.CallHdr{
  140. Host: cc.authority,
  141. Method: method,
  142. }
  143. if cc.dopts.cp != nil {
  144. callHdr.SendCompress = cc.dopts.cp.Type()
  145. }
  146. gopts := BalancerGetOptions{
  147. BlockingWait: !c.failFast,
  148. }
  149. t, put, err = cc.getTransport(ctx, gopts)
  150. if err != nil {
  151. // TODO(zhaoq): Probably revisit the error handling.
  152. if _, ok := err.(*rpcError); ok {
  153. return err
  154. }
  155. if err == errConnClosing {
  156. if c.failFast {
  157. return Errorf(codes.Unavailable, "%v", errConnClosing)
  158. }
  159. continue
  160. }
  161. // All the other errors are treated as Internal errors.
  162. return Errorf(codes.Internal, "%v", err)
  163. }
  164. if c.traceInfo.tr != nil {
  165. c.traceInfo.tr.LazyLog(&payload{sent: true, msg: args}, true)
  166. }
  167. stream, err = sendRequest(ctx, cc.dopts.codec, cc.dopts.cp, callHdr, t, args, topts)
  168. if err != nil {
  169. if put != nil {
  170. put()
  171. put = nil
  172. }
  173. if _, ok := err.(transport.ConnectionError); ok {
  174. if c.failFast {
  175. return toRPCErr(err)
  176. }
  177. continue
  178. }
  179. return toRPCErr(err)
  180. }
  181. // Receive the response
  182. err = recvResponse(cc.dopts, t, &c, stream, reply)
  183. if err != nil {
  184. if put != nil {
  185. put()
  186. put = nil
  187. }
  188. if _, ok := err.(transport.ConnectionError); ok {
  189. if c.failFast {
  190. return toRPCErr(err)
  191. }
  192. continue
  193. }
  194. t.CloseStream(stream, err)
  195. return toRPCErr(err)
  196. }
  197. if c.traceInfo.tr != nil {
  198. c.traceInfo.tr.LazyLog(&payload{sent: false, msg: reply}, true)
  199. }
  200. t.CloseStream(stream, nil)
  201. if put != nil {
  202. put()
  203. put = nil
  204. }
  205. return Errorf(stream.StatusCode(), "%s", stream.StatusDesc())
  206. }
  207. }