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. return nil
  74. }
  75. // sendRequest writes out various information of an RPC such as Context and Message.
  76. 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) {
  77. defer func() {
  78. if err != nil {
  79. // If err is connection error, t will be closed, no need to close stream here.
  80. if _, ok := err.(transport.ConnectionError); !ok {
  81. t.CloseStream(stream, err)
  82. }
  83. }
  84. }()
  85. var (
  86. cbuf *bytes.Buffer
  87. outPayload *stats.OutPayload
  88. )
  89. if compressor != nil {
  90. cbuf = new(bytes.Buffer)
  91. }
  92. if dopts.copts.StatsHandler != nil {
  93. outPayload = &stats.OutPayload{
  94. Client: true,
  95. }
  96. }
  97. hdr, data, err := encode(dopts.codec, args, compressor, cbuf, outPayload)
  98. if err != nil {
  99. return err
  100. }
  101. if c.maxSendMessageSize == nil {
  102. return Errorf(codes.Internal, "callInfo maxSendMessageSize field uninitialized(nil)")
  103. }
  104. if len(data) > *c.maxSendMessageSize {
  105. return Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(data), *c.maxSendMessageSize)
  106. }
  107. err = t.Write(stream, hdr, data, opts)
  108. if err == nil && outPayload != nil {
  109. outPayload.SentTime = time.Now()
  110. dopts.copts.StatsHandler.HandleRPC(ctx, outPayload)
  111. }
  112. // t.NewStream(...) could lead to an early rejection of the RPC (e.g., the service/method
  113. // does not exist.) so that t.Write could get io.EOF from wait(...). Leave the following
  114. // recvResponse to get the final status.
  115. if err != nil && err != io.EOF {
  116. return err
  117. }
  118. // Sent successfully.
  119. return nil
  120. }
  121. // Invoke sends the RPC request on the wire and returns after response is received.
  122. // Invoke is called by generated code. Also users can call Invoke directly when it
  123. // is really needed in their use cases.
  124. func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error {
  125. if cc.dopts.unaryInt != nil {
  126. return cc.dopts.unaryInt(ctx, method, args, reply, cc, invoke, opts...)
  127. }
  128. return invoke(ctx, method, args, reply, cc, opts...)
  129. }
  130. func invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (e error) {
  131. c := defaultCallInfo
  132. mc := cc.GetMethodConfig(method)
  133. if mc.WaitForReady != nil {
  134. c.failFast = !*mc.WaitForReady
  135. }
  136. if mc.Timeout != nil && *mc.Timeout >= 0 {
  137. var cancel context.CancelFunc
  138. ctx, cancel = context.WithTimeout(ctx, *mc.Timeout)
  139. defer cancel()
  140. }
  141. opts = append(cc.dopts.callOptions, opts...)
  142. for _, o := range opts {
  143. if err := o.before(&c); err != nil {
  144. return toRPCErr(err)
  145. }
  146. }
  147. defer func() {
  148. for _, o := range opts {
  149. o.after(&c)
  150. }
  151. }()
  152. c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize)
  153. c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
  154. if EnableTracing {
  155. c.traceInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
  156. defer c.traceInfo.tr.Finish()
  157. c.traceInfo.firstLine.client = true
  158. if deadline, ok := ctx.Deadline(); ok {
  159. c.traceInfo.firstLine.deadline = deadline.Sub(time.Now())
  160. }
  161. c.traceInfo.tr.LazyLog(&c.traceInfo.firstLine, false)
  162. // TODO(dsymonds): Arrange for c.traceInfo.firstLine.remoteAddr to be set.
  163. defer func() {
  164. if e != nil {
  165. c.traceInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{e}}, true)
  166. c.traceInfo.tr.SetError()
  167. }
  168. }()
  169. }
  170. ctx = newContextWithRPCInfo(ctx)
  171. sh := cc.dopts.copts.StatsHandler
  172. if sh != nil {
  173. ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast})
  174. begin := &stats.Begin{
  175. Client: true,
  176. BeginTime: time.Now(),
  177. FailFast: c.failFast,
  178. }
  179. sh.HandleRPC(ctx, begin)
  180. defer func() {
  181. end := &stats.End{
  182. Client: true,
  183. EndTime: time.Now(),
  184. Error: e,
  185. }
  186. sh.HandleRPC(ctx, end)
  187. }()
  188. }
  189. topts := &transport.Options{
  190. Last: true,
  191. Delay: false,
  192. }
  193. for {
  194. var (
  195. err error
  196. t transport.ClientTransport
  197. stream *transport.Stream
  198. // Record the put handler from Balancer.Get(...). It is called once the
  199. // RPC has completed or failed.
  200. put func()
  201. )
  202. // TODO(zhaoq): Need a formal spec of fail-fast.
  203. callHdr := &transport.CallHdr{
  204. Host: cc.authority,
  205. Method: method,
  206. }
  207. if cc.dopts.cp != nil {
  208. callHdr.SendCompress = cc.dopts.cp.Type()
  209. }
  210. if c.creds != nil {
  211. callHdr.Creds = c.creds
  212. }
  213. gopts := BalancerGetOptions{
  214. BlockingWait: !c.failFast,
  215. }
  216. t, put, err = cc.getTransport(ctx, gopts)
  217. if err != nil {
  218. // TODO(zhaoq): Probably revisit the error handling.
  219. if _, ok := status.FromError(err); ok {
  220. return err
  221. }
  222. if err == errConnClosing || err == errConnUnavailable {
  223. if c.failFast {
  224. return Errorf(codes.Unavailable, "%v", err)
  225. }
  226. continue
  227. }
  228. // All the other errors are treated as Internal errors.
  229. return Errorf(codes.Internal, "%v", err)
  230. }
  231. if c.traceInfo.tr != nil {
  232. c.traceInfo.tr.LazyLog(&payload{sent: true, msg: args}, true)
  233. }
  234. stream, err = t.NewStream(ctx, callHdr)
  235. if err != nil {
  236. if put != nil {
  237. if _, ok := err.(transport.ConnectionError); ok {
  238. // If error is connection error, transport was sending data on wire,
  239. // and we are not sure if anything has been sent on wire.
  240. // If error is not connection error, we are sure nothing has been sent.
  241. updateRPCInfoInContext(ctx, rpcInfo{bytesSent: true, bytesReceived: false})
  242. }
  243. put()
  244. }
  245. if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
  246. continue
  247. }
  248. return toRPCErr(err)
  249. }
  250. if peer, ok := peer.FromContext(stream.Context()); ok {
  251. c.peer = peer
  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. }