call.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. "io"
  22. "time"
  23. "golang.org/x/net/context"
  24. "golang.org/x/net/trace"
  25. "google.golang.org/grpc/codes"
  26. "google.golang.org/grpc/peer"
  27. "google.golang.org/grpc/stats"
  28. "google.golang.org/grpc/status"
  29. "google.golang.org/grpc/transport"
  30. )
  31. // recvResponse receives and parses an RPC response.
  32. // On error, it returns the error and indicates whether the call should be retried.
  33. //
  34. // TODO(zhaoq): Check whether the received message sequence is valid.
  35. // TODO ctx is used for stats collection and processing. It is the context passed from the application.
  36. func recvResponse(ctx context.Context, dopts dialOptions, t transport.ClientTransport, c *callInfo, stream *transport.Stream, reply interface{}) (err error) {
  37. // Try to acquire header metadata from the server if there is any.
  38. defer func() {
  39. if err != nil {
  40. if _, ok := err.(transport.ConnectionError); !ok {
  41. t.CloseStream(stream, err)
  42. }
  43. }
  44. }()
  45. c.headerMD, err = stream.Header()
  46. if err != nil {
  47. return
  48. }
  49. p := &parser{r: stream}
  50. var inPayload *stats.InPayload
  51. if dopts.copts.StatsHandler != nil {
  52. inPayload = &stats.InPayload{
  53. Client: true,
  54. }
  55. }
  56. for {
  57. if c.maxReceiveMessageSize == nil {
  58. return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)")
  59. }
  60. if err = recv(p, dopts.codec, stream, dopts.dc, reply, *c.maxReceiveMessageSize, inPayload); err != nil {
  61. if err == io.EOF {
  62. break
  63. }
  64. return
  65. }
  66. }
  67. if inPayload != nil && err == io.EOF && stream.Status().Code() == codes.OK {
  68. // TODO in the current implementation, inTrailer may be handled before inPayload in some cases.
  69. // Fix the order if necessary.
  70. dopts.copts.StatsHandler.HandleRPC(ctx, inPayload)
  71. }
  72. c.trailerMD = stream.Trailer()
  73. if peer, ok := peer.FromContext(stream.Context()); ok {
  74. c.peer = peer
  75. }
  76. return nil
  77. }
  78. // sendRequest writes out various information of an RPC such as Context and Message.
  79. func sendRequest(ctx context.Context, dopts dialOptions, compressor Compressor, c *callInfo, callHdr *transport.CallHdr, stream *transport.Stream, t transport.ClientTransport, args interface{}, opts *transport.Options) (err error) {
  80. defer func() {
  81. if err != nil {
  82. // If err is connection error, t will be closed, no need to close stream here.
  83. if _, ok := err.(transport.ConnectionError); !ok {
  84. t.CloseStream(stream, err)
  85. }
  86. }
  87. }()
  88. var (
  89. cbuf *bytes.Buffer
  90. outPayload *stats.OutPayload
  91. )
  92. if compressor != nil {
  93. cbuf = new(bytes.Buffer)
  94. }
  95. if dopts.copts.StatsHandler != nil {
  96. outPayload = &stats.OutPayload{
  97. Client: true,
  98. }
  99. }
  100. outBuf, err := encode(dopts.codec, args, compressor, cbuf, outPayload)
  101. if err != nil {
  102. return err
  103. }
  104. if c.maxSendMessageSize == nil {
  105. return Errorf(codes.Internal, "callInfo maxSendMessageSize field uninitialized(nil)")
  106. }
  107. if len(outBuf) > *c.maxSendMessageSize {
  108. return Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(outBuf), *c.maxSendMessageSize)
  109. }
  110. err = t.Write(stream, outBuf, opts)
  111. if err == nil && outPayload != nil {
  112. outPayload.SentTime = time.Now()
  113. dopts.copts.StatsHandler.HandleRPC(ctx, outPayload)
  114. }
  115. // t.NewStream(...) could lead to an early rejection of the RPC (e.g., the service/method
  116. // does not exist.) so that t.Write could get io.EOF from wait(...). Leave the following
  117. // recvResponse to get the final status.
  118. if err != nil && err != io.EOF {
  119. return err
  120. }
  121. // Sent successfully.
  122. return nil
  123. }
  124. // Invoke sends the RPC request on the wire and returns after response is received.
  125. // Invoke is called by generated code. Also users can call Invoke directly when it
  126. // is really needed in their use cases.
  127. func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error {
  128. if cc.dopts.unaryInt != nil {
  129. return cc.dopts.unaryInt(ctx, method, args, reply, cc, invoke, opts...)
  130. }
  131. return invoke(ctx, method, args, reply, cc, opts...)
  132. }
  133. func invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (e error) {
  134. c := defaultCallInfo
  135. mc := cc.GetMethodConfig(method)
  136. if mc.WaitForReady != nil {
  137. c.failFast = !*mc.WaitForReady
  138. }
  139. if mc.Timeout != nil && *mc.Timeout >= 0 {
  140. var cancel context.CancelFunc
  141. ctx, cancel = context.WithTimeout(ctx, *mc.Timeout)
  142. defer cancel()
  143. }
  144. opts = append(cc.dopts.callOptions, opts...)
  145. for _, o := range opts {
  146. if err := o.before(&c); err != nil {
  147. return toRPCErr(err)
  148. }
  149. }
  150. defer func() {
  151. for _, o := range opts {
  152. o.after(&c)
  153. }
  154. }()
  155. c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize)
  156. c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
  157. if EnableTracing {
  158. c.traceInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
  159. defer c.traceInfo.tr.Finish()
  160. c.traceInfo.firstLine.client = true
  161. if deadline, ok := ctx.Deadline(); ok {
  162. c.traceInfo.firstLine.deadline = deadline.Sub(time.Now())
  163. }
  164. c.traceInfo.tr.LazyLog(&c.traceInfo.firstLine, false)
  165. // TODO(dsymonds): Arrange for c.traceInfo.firstLine.remoteAddr to be set.
  166. defer func() {
  167. if e != nil {
  168. c.traceInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{e}}, true)
  169. c.traceInfo.tr.SetError()
  170. }
  171. }()
  172. }
  173. ctx = newContextWithRPCInfo(ctx)
  174. sh := cc.dopts.copts.StatsHandler
  175. if sh != nil {
  176. ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast})
  177. begin := &stats.Begin{
  178. Client: true,
  179. BeginTime: time.Now(),
  180. FailFast: c.failFast,
  181. }
  182. sh.HandleRPC(ctx, begin)
  183. defer func() {
  184. end := &stats.End{
  185. Client: true,
  186. EndTime: time.Now(),
  187. Error: e,
  188. }
  189. sh.HandleRPC(ctx, end)
  190. }()
  191. }
  192. topts := &transport.Options{
  193. Last: true,
  194. Delay: false,
  195. }
  196. for {
  197. var (
  198. err error
  199. t transport.ClientTransport
  200. stream *transport.Stream
  201. // Record the put handler from Balancer.Get(...). It is called once the
  202. // RPC has completed or failed.
  203. put func()
  204. )
  205. // TODO(zhaoq): Need a formal spec of fail-fast.
  206. callHdr := &transport.CallHdr{
  207. Host: cc.authority,
  208. Method: method,
  209. }
  210. if cc.dopts.cp != nil {
  211. callHdr.SendCompress = cc.dopts.cp.Type()
  212. }
  213. if c.creds != nil {
  214. callHdr.Creds = c.creds
  215. }
  216. gopts := BalancerGetOptions{
  217. BlockingWait: !c.failFast,
  218. }
  219. t, put, err = cc.getTransport(ctx, gopts)
  220. if err != nil {
  221. // TODO(zhaoq): Probably revisit the error handling.
  222. if _, ok := status.FromError(err); ok {
  223. return err
  224. }
  225. if err == errConnClosing || err == errConnUnavailable {
  226. if c.failFast {
  227. return Errorf(codes.Unavailable, "%v", err)
  228. }
  229. continue
  230. }
  231. // All the other errors are treated as Internal errors.
  232. return Errorf(codes.Internal, "%v", err)
  233. }
  234. if c.traceInfo.tr != nil {
  235. c.traceInfo.tr.LazyLog(&payload{sent: true, msg: args}, true)
  236. }
  237. stream, err = t.NewStream(ctx, callHdr)
  238. if err != nil {
  239. if put != nil {
  240. if _, ok := err.(transport.ConnectionError); ok {
  241. // If error is connection error, transport was sending data on wire,
  242. // and we are not sure if anything has been sent on wire.
  243. // If error is not connection error, we are sure nothing has been sent.
  244. updateRPCInfoInContext(ctx, rpcInfo{bytesSent: true, bytesReceived: false})
  245. }
  246. put()
  247. }
  248. if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
  249. continue
  250. }
  251. return toRPCErr(err)
  252. }
  253. err = sendRequest(ctx, cc.dopts, cc.dopts.cp, &c, callHdr, stream, t, args, topts)
  254. if err != nil {
  255. if put != nil {
  256. updateRPCInfoInContext(ctx, rpcInfo{
  257. bytesSent: stream.BytesSent(),
  258. bytesReceived: stream.BytesReceived(),
  259. })
  260. put()
  261. }
  262. // Retry a non-failfast RPC when
  263. // i) there is a connection error; or
  264. // ii) the server started to drain before this RPC was initiated.
  265. if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
  266. continue
  267. }
  268. return toRPCErr(err)
  269. }
  270. err = recvResponse(ctx, cc.dopts, t, &c, stream, reply)
  271. if err != nil {
  272. if put != nil {
  273. updateRPCInfoInContext(ctx, rpcInfo{
  274. bytesSent: stream.BytesSent(),
  275. bytesReceived: stream.BytesReceived(),
  276. })
  277. put()
  278. }
  279. if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
  280. continue
  281. }
  282. return toRPCErr(err)
  283. }
  284. if c.traceInfo.tr != nil {
  285. c.traceInfo.tr.LazyLog(&payload{sent: false, msg: reply}, true)
  286. }
  287. t.CloseStream(stream, nil)
  288. if put != nil {
  289. updateRPCInfoInContext(ctx, rpcInfo{
  290. bytesSent: stream.BytesSent(),
  291. bytesReceived: stream.BytesReceived(),
  292. })
  293. put()
  294. }
  295. return stream.Status().Err()
  296. }
  297. }