3 * Copyright 2014 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
26 "golang.org/x/net/context"
27 "golang.org/x/net/trace"
28 "google.golang.org/grpc/balancer"
29 "google.golang.org/grpc/codes"
30 "google.golang.org/grpc/peer"
31 "google.golang.org/grpc/stats"
32 "google.golang.org/grpc/status"
33 "google.golang.org/grpc/transport"
36 // recvResponse receives and parses an RPC response.
37 // On error, it returns the error and indicates whether the call should be retried.
39 // TODO(zhaoq): Check whether the received message sequence is valid.
40 // TODO ctx is used for stats collection and processing. It is the context passed from the application.
41 func recvResponse(ctx context.Context, dopts dialOptions, t transport.ClientTransport, c *callInfo, stream *transport.Stream, reply interface{}) (err error) {
42 // Try to acquire header metadata from the server if there is any.
45 if _, ok := err.(transport.ConnectionError); !ok {
46 t.CloseStream(stream, err)
50 c.headerMD, err = stream.Header()
54 p := &parser{r: stream}
55 var inPayload *stats.InPayload
56 if dopts.copts.StatsHandler != nil {
57 inPayload = &stats.InPayload{
62 if c.maxReceiveMessageSize == nil {
63 return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)")
65 if err = recv(p, dopts.codec, stream, dopts.dc, reply, *c.maxReceiveMessageSize, inPayload); err != nil {
72 if inPayload != nil && err == io.EOF && stream.Status().Code() == codes.OK {
73 // TODO in the current implementation, inTrailer may be handled before inPayload in some cases.
74 // Fix the order if necessary.
75 dopts.copts.StatsHandler.HandleRPC(ctx, inPayload)
77 c.trailerMD = stream.Trailer()
81 // sendRequest writes out various information of an RPC such as Context and Message.
82 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) {
85 // If err is connection error, t will be closed, no need to close stream here.
86 if _, ok := err.(transport.ConnectionError); !ok {
87 t.CloseStream(stream, err)
93 outPayload *stats.OutPayload
95 if compressor != nil {
96 cbuf = new(bytes.Buffer)
98 if dopts.copts.StatsHandler != nil {
99 outPayload = &stats.OutPayload{
103 hdr, data, err := encode(dopts.codec, args, compressor, cbuf, outPayload)
107 if c.maxSendMessageSize == nil {
108 return Errorf(codes.Internal, "callInfo maxSendMessageSize field uninitialized(nil)")
110 if len(data) > *c.maxSendMessageSize {
111 return Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(data), *c.maxSendMessageSize)
113 err = t.Write(stream, hdr, data, opts)
114 if err == nil && outPayload != nil {
115 outPayload.SentTime = time.Now()
116 dopts.copts.StatsHandler.HandleRPC(ctx, outPayload)
118 // t.NewStream(...) could lead to an early rejection of the RPC (e.g., the service/method
119 // does not exist.) so that t.Write could get io.EOF from wait(...). Leave the following
120 // recvResponse to get the final status.
121 if err != nil && err != io.EOF {
124 // Sent successfully.
128 // Invoke sends the RPC request on the wire and returns after response is
129 // received. This is typically called by generated code.
130 func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) error {
131 if cc.dopts.unaryInt != nil {
132 return cc.dopts.unaryInt(ctx, method, args, reply, cc, invoke, opts...)
134 return invoke(ctx, method, args, reply, cc, opts...)
137 // Invoke sends the RPC request on the wire and returns after response is
138 // received. This is typically called by generated code.
140 // DEPRECATED: Use ClientConn.Invoke instead.
141 func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error {
142 return cc.Invoke(ctx, method, args, reply, opts...)
145 func invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (e error) {
146 c := defaultCallInfo()
147 mc := cc.GetMethodConfig(method)
148 if mc.WaitForReady != nil {
149 c.failFast = !*mc.WaitForReady
152 if mc.Timeout != nil && *mc.Timeout >= 0 {
153 var cancel context.CancelFunc
154 ctx, cancel = context.WithTimeout(ctx, *mc.Timeout)
158 opts = append(cc.dopts.callOptions, opts...)
159 for _, o := range opts {
160 if err := o.before(c); err != nil {
165 for _, o := range opts {
170 c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize)
171 c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
174 c.traceInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
175 defer c.traceInfo.tr.Finish()
176 c.traceInfo.firstLine.client = true
177 if deadline, ok := ctx.Deadline(); ok {
178 c.traceInfo.firstLine.deadline = deadline.Sub(time.Now())
180 c.traceInfo.tr.LazyLog(&c.traceInfo.firstLine, false)
181 // TODO(dsymonds): Arrange for c.traceInfo.firstLine.remoteAddr to be set.
184 c.traceInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{e}}, true)
185 c.traceInfo.tr.SetError()
189 ctx = newContextWithRPCInfo(ctx, c.failFast)
190 sh := cc.dopts.copts.StatsHandler
192 ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast})
193 begin := &stats.Begin{
195 BeginTime: time.Now(),
196 FailFast: c.failFast,
198 sh.HandleRPC(ctx, begin)
205 sh.HandleRPC(ctx, end)
208 topts := &transport.Options{
215 t transport.ClientTransport
216 stream *transport.Stream
217 // Record the done handler from Balancer.Get(...). It is called once the
218 // RPC has completed or failed.
219 done func(balancer.DoneInfo)
221 // TODO(zhaoq): Need a formal spec of fail-fast.
222 callHdr := &transport.CallHdr{
226 if cc.dopts.cp != nil {
227 callHdr.SendCompress = cc.dopts.cp.Type()
230 callHdr.Creds = c.creds
233 t, done, err = cc.getTransport(ctx, c.failFast)
235 // TODO(zhaoq): Probably revisit the error handling.
236 if _, ok := status.FromError(err); ok {
239 if err == errConnClosing || err == errConnUnavailable {
241 return Errorf(codes.Unavailable, "%v", err)
245 // All the other errors are treated as Internal errors.
246 return Errorf(codes.Internal, "%v", err)
248 if c.traceInfo.tr != nil {
249 c.traceInfo.tr.LazyLog(&payload{sent: true, msg: args}, true)
251 stream, err = t.NewStream(ctx, callHdr)
254 if _, ok := err.(transport.ConnectionError); ok {
255 // If error is connection error, transport was sending data on wire,
256 // and we are not sure if anything has been sent on wire.
257 // If error is not connection error, we are sure nothing has been sent.
258 updateRPCInfoInContext(ctx, rpcInfo{bytesSent: true, bytesReceived: false})
260 done(balancer.DoneInfo{Err: err})
262 if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
267 if peer, ok := peer.FromContext(stream.Context()); ok {
270 err = sendRequest(ctx, cc.dopts, cc.dopts.cp, c, callHdr, stream, t, args, topts)
273 updateRPCInfoInContext(ctx, rpcInfo{
274 bytesSent: stream.BytesSent(),
275 bytesReceived: stream.BytesReceived(),
277 done(balancer.DoneInfo{Err: err})
279 // Retry a non-failfast RPC when
280 // i) there is a connection error; or
281 // ii) the server started to drain before this RPC was initiated.
282 if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
287 err = recvResponse(ctx, cc.dopts, t, c, stream, reply)
290 updateRPCInfoInContext(ctx, rpcInfo{
291 bytesSent: stream.BytesSent(),
292 bytesReceived: stream.BytesReceived(),
294 done(balancer.DoneInfo{Err: err})
296 if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
301 if c.traceInfo.tr != nil {
302 c.traceInfo.tr.LazyLog(&payload{sent: false, msg: reply}, true)
304 t.CloseStream(stream, nil)
306 updateRPCInfoInContext(ctx, rpcInfo{
307 bytesSent: stream.BytesSent(),
308 bytesReceived: stream.BytesReceived(),
310 done(balancer.DoneInfo{Err: err})
312 return stream.Status().Err()