call.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. "math"
  38. "time"
  39. "golang.org/x/net/context"
  40. "golang.org/x/net/trace"
  41. "google.golang.org/grpc/codes"
  42. "google.golang.org/grpc/transport"
  43. )
  44. // recvResponse receives and parses an RPC response.
  45. // On error, it returns the error and indicates whether the call should be retried.
  46. //
  47. // TODO(zhaoq): Check whether the received message sequence is valid.
  48. func recvResponse(dopts dialOptions, t transport.ClientTransport, c *callInfo, stream *transport.Stream, reply interface{}) (err error) {
  49. // Try to acquire header metadata from the server if there is any.
  50. defer func() {
  51. if err != nil {
  52. if _, ok := err.(transport.ConnectionError); !ok {
  53. t.CloseStream(stream, err)
  54. }
  55. }
  56. }()
  57. c.headerMD, err = stream.Header()
  58. if err != nil {
  59. return
  60. }
  61. p := &parser{r: stream}
  62. for {
  63. if err = recv(p, dopts.codec, stream, dopts.dc, reply, math.MaxInt32); err != nil {
  64. if err == io.EOF {
  65. break
  66. }
  67. return
  68. }
  69. }
  70. c.trailerMD = stream.Trailer()
  71. return nil
  72. }
  73. // sendRequest writes out various information of an RPC such as Context and Message.
  74. func sendRequest(ctx context.Context, codec Codec, compressor Compressor, callHdr *transport.CallHdr, t transport.ClientTransport, args interface{}, opts *transport.Options) (_ *transport.Stream, err error) {
  75. stream, err := t.NewStream(ctx, callHdr)
  76. if err != nil {
  77. return nil, err
  78. }
  79. defer func() {
  80. if err != nil {
  81. // If err is connection error, t will be closed, no need to close stream here.
  82. if _, ok := err.(transport.ConnectionError); !ok {
  83. t.CloseStream(stream, err)
  84. }
  85. }
  86. }()
  87. var cbuf *bytes.Buffer
  88. if compressor != nil {
  89. cbuf = new(bytes.Buffer)
  90. }
  91. outBuf, err := encode(codec, args, compressor, cbuf)
  92. if err != nil {
  93. return nil, Errorf(codes.Internal, "grpc: %v", err)
  94. }
  95. err = t.Write(stream, outBuf, opts)
  96. // t.NewStream(...) could lead to an early rejection of the RPC (e.g., the service/method
  97. // does not exist.) so that t.Write could get io.EOF from wait(...). Leave the following
  98. // recvResponse to get the final status.
  99. if err != nil && err != io.EOF {
  100. return nil, err
  101. }
  102. // Sent successfully.
  103. return stream, nil
  104. }
  105. // Invoke sends the RPC request on the wire and returns after response is received.
  106. // Invoke is called by generated code. Also users can call Invoke directly when it
  107. // is really needed in their use cases.
  108. func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error {
  109. if cc.dopts.unaryInt != nil {
  110. return cc.dopts.unaryInt(ctx, method, args, reply, cc, invoke, opts...)
  111. }
  112. return invoke(ctx, method, args, reply, cc, opts...)
  113. }
  114. func invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (err error) {
  115. c := defaultCallInfo
  116. for _, o := range opts {
  117. if err := o.before(&c); err != nil {
  118. return toRPCErr(err)
  119. }
  120. }
  121. defer func() {
  122. for _, o := range opts {
  123. o.after(&c)
  124. }
  125. }()
  126. if EnableTracing {
  127. c.traceInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
  128. defer c.traceInfo.tr.Finish()
  129. c.traceInfo.firstLine.client = true
  130. if deadline, ok := ctx.Deadline(); ok {
  131. c.traceInfo.firstLine.deadline = deadline.Sub(time.Now())
  132. }
  133. c.traceInfo.tr.LazyLog(&c.traceInfo.firstLine, false)
  134. // TODO(dsymonds): Arrange for c.traceInfo.firstLine.remoteAddr to be set.
  135. defer func() {
  136. if err != nil {
  137. c.traceInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  138. c.traceInfo.tr.SetError()
  139. }
  140. }()
  141. }
  142. topts := &transport.Options{
  143. Last: true,
  144. Delay: false,
  145. }
  146. for {
  147. var (
  148. err error
  149. t transport.ClientTransport
  150. stream *transport.Stream
  151. // Record the put handler from Balancer.Get(...). It is called once the
  152. // RPC has completed or failed.
  153. put func()
  154. )
  155. // TODO(zhaoq): Need a formal spec of fail-fast.
  156. callHdr := &transport.CallHdr{
  157. Host: cc.authority,
  158. Method: method,
  159. }
  160. if cc.dopts.cp != nil {
  161. callHdr.SendCompress = cc.dopts.cp.Type()
  162. }
  163. gopts := BalancerGetOptions{
  164. BlockingWait: !c.failFast,
  165. }
  166. t, put, err = cc.getTransport(ctx, gopts)
  167. if err != nil {
  168. // TODO(zhaoq): Probably revisit the error handling.
  169. if _, ok := err.(*rpcError); ok {
  170. return err
  171. }
  172. if err == errConnClosing || err == errConnUnavailable {
  173. if c.failFast {
  174. return Errorf(codes.Unavailable, "%v", err)
  175. }
  176. continue
  177. }
  178. // All the other errors are treated as Internal errors.
  179. return Errorf(codes.Internal, "%v", err)
  180. }
  181. if c.traceInfo.tr != nil {
  182. c.traceInfo.tr.LazyLog(&payload{sent: true, msg: args}, true)
  183. }
  184. stream, err = sendRequest(ctx, cc.dopts.codec, cc.dopts.cp, callHdr, t, args, topts)
  185. if err != nil {
  186. if put != nil {
  187. put()
  188. put = nil
  189. }
  190. // Retry a non-failfast RPC when
  191. // i) there is a connection error; or
  192. // ii) the server started to drain before this RPC was initiated.
  193. if _, ok := err.(transport.ConnectionError); ok || err == transport.ErrStreamDrain {
  194. if c.failFast {
  195. return toRPCErr(err)
  196. }
  197. continue
  198. }
  199. return toRPCErr(err)
  200. }
  201. err = recvResponse(cc.dopts, t, &c, stream, reply)
  202. if err != nil {
  203. if put != nil {
  204. put()
  205. put = nil
  206. }
  207. if _, ok := err.(transport.ConnectionError); ok || err == transport.ErrStreamDrain {
  208. if c.failFast {
  209. return toRPCErr(err)
  210. }
  211. continue
  212. }
  213. return toRPCErr(err)
  214. }
  215. if c.traceInfo.tr != nil {
  216. c.traceInfo.tr.LazyLog(&payload{sent: false, msg: reply}, true)
  217. }
  218. t.CloseStream(stream, nil)
  219. if put != nil {
  220. put()
  221. put = nil
  222. }
  223. return Errorf(stream.StatusCode(), "%s", stream.StatusDesc())
  224. }
  225. }