grpc-go/stream.go

642 строки
18 KiB
Go
Исходник Обычный вид История

2015-02-06 04:14:05 +03:00
/*
*
* Copyright 2014, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package grpc
2015-02-06 04:14:05 +03:00
import (
2016-01-23 05:21:41 +03:00
"bytes"
"errors"
2015-02-06 04:14:05 +03:00
"io"
"sync"
2015-06-18 05:30:57 +03:00
"time"
2015-02-06 04:14:05 +03:00
"golang.org/x/net/context"
2015-06-18 05:30:57 +03:00
"golang.org/x/net/trace"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/stats"
"google.golang.org/grpc/status"
"google.golang.org/grpc/transport"
2015-02-06 04:14:05 +03:00
)
2016-04-19 02:18:34 +03:00
// StreamHandler defines the handler called by gRPC server to complete the
// execution of a streaming RPC.
type StreamHandler func(srv interface{}, stream ServerStream) error
// StreamDesc represents a streaming RPC service's method specification.
type StreamDesc struct {
StreamName string
2016-04-19 02:18:34 +03:00
Handler StreamHandler
// At least one of these is true.
ServerStreams bool
ClientStreams bool
}
2015-02-06 04:14:05 +03:00
// Stream defines the common interface a client or server stream has to satisfy.
type Stream interface {
// Context returns the context for this stream.
Context() context.Context
// SendMsg blocks until it sends m, the stream is done or the stream
2015-02-14 03:43:51 +03:00
// breaks.
// On error, it aborts the stream and returns an RPC status on client
// side. On server side, it simply returns the error to the caller.
// SendMsg is called by generated code. Also Users can call SendMsg
// directly when it is really needed in their use cases.
SendMsg(m interface{}) error
// RecvMsg blocks until it receives a message or the stream is
2015-02-14 03:43:51 +03:00
// done. On client side, it returns io.EOF when the stream is done. On
2016-02-12 07:19:47 +03:00
// any other error, it aborts the stream and returns an RPC status. On
2015-02-14 03:43:51 +03:00
// server side, it simply returns the error to the caller.
RecvMsg(m interface{}) error
2015-02-06 04:14:05 +03:00
}
2016-06-07 14:01:07 +03:00
// ClientStream defines the interface a client stream has to satisfy.
2015-02-06 04:14:05 +03:00
type ClientStream interface {
2016-04-30 00:58:02 +03:00
// Header returns the header metadata received from the server if there
2015-02-06 04:14:05 +03:00
// is any. It blocks if the metadata is not ready to read.
Header() (metadata.MD, error)
// Trailer returns the trailer metadata from the server, if there is any.
// It must only be called after stream.CloseAndRecv has returned, or
// stream.Recv has returned a non-nil error (including io.EOF).
2015-02-06 04:14:05 +03:00
Trailer() metadata.MD
2015-02-14 03:43:51 +03:00
// CloseSend closes the send direction of the stream. It closes the stream
// when non-nil error is met.
2015-02-06 04:14:05 +03:00
CloseSend() error
Stream
}
// NewClientStream creates a new Stream for the client side. This is called
// by generated code.
2016-11-02 02:57:54 +03:00
func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
2016-08-26 23:50:38 +03:00
if cc.dopts.streamInt != nil {
return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...)
}
return newClientStream(ctx, desc, cc, method, opts...)
}
func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
2015-09-25 23:21:25 +03:00
var (
t transport.ClientTransport
s *transport.Stream
put func()
cancel context.CancelFunc
2015-09-25 23:21:25 +03:00
)
c := defaultCallInfo
2017-04-22 02:18:59 +03:00
mc := cc.GetMethodConfig(method)
if mc.WaitForReady != nil {
c.failFast = !*mc.WaitForReady
}
2017-04-22 02:18:59 +03:00
if mc.Timeout != nil && *mc.Timeout >= 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, *mc.Timeout)
defer cancel()
}
2017-04-22 02:18:59 +03:00
maxSendMessageSize := getMaxSize(mc.MaxReqSize, cc.dopts.maxSendMessageSize, defaultClientMaxSendMessageSize)
maxReceiveMessageSize := getMaxSize(mc.MaxRespSize, cc.dopts.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
for _, o := range opts {
if err := o.before(&c); err != nil {
return nil, toRPCErr(err)
}
}
2015-02-06 04:14:05 +03:00
callHdr := &transport.CallHdr{
2016-11-08 00:17:59 +03:00
Host: cc.authority,
Method: method,
Flush: desc.ServerStreams && desc.ClientStreams,
2015-02-06 04:14:05 +03:00
}
if cc.dopts.cp != nil {
callHdr.SendCompress = cc.dopts.cp.Type()
2016-01-23 05:21:41 +03:00
}
var trInfo traceInfo
if EnableTracing {
trInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
trInfo.firstLine.client = true
2015-06-18 21:45:40 +03:00
if deadline, ok := ctx.Deadline(); ok {
trInfo.firstLine.deadline = deadline.Sub(time.Now())
2015-06-18 21:45:40 +03:00
}
trInfo.tr.LazyLog(&trInfo.firstLine, false)
ctx = trace.NewContext(ctx, trInfo.tr)
defer func() {
if err != nil {
// Need to call tr.finish() if error is returned.
// Because tr will not be returned to caller.
trInfo.tr.LazyPrintf("RPC: [%v]", err)
trInfo.tr.SetError()
trInfo.tr.Finish()
}
}()
2015-06-18 21:45:40 +03:00
}
sh := cc.dopts.copts.StatsHandler
if sh != nil {
ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method})
2016-11-08 00:17:59 +03:00
begin := &stats.Begin{
Client: true,
BeginTime: time.Now(),
FailFast: c.failFast,
}
sh.HandleRPC(ctx, begin)
2016-11-08 00:17:59 +03:00
}
defer func() {
if err != nil && sh != nil {
2016-11-08 00:17:59 +03:00
// Only handle end stats if err != nil.
end := &stats.End{
Client: true,
Error: err,
}
sh.HandleRPC(ctx, end)
2016-11-08 00:17:59 +03:00
}
}()
gopts := BalancerGetOptions{
BlockingWait: !c.failFast,
}
for {
t, put, err = cc.getTransport(ctx, gopts)
if err != nil {
// TODO(zhaoq): Probably revisit the error handling.
if _, ok := status.FromError(err); ok {
return nil, err
}
2016-08-17 00:16:42 +03:00
if err == errConnClosing || err == errConnUnavailable {
if c.failFast {
2016-08-17 00:16:42 +03:00
return nil, Errorf(codes.Unavailable, "%v", err)
}
continue
}
// All the other errors are treated as Internal errors.
return nil, Errorf(codes.Internal, "%v", err)
}
s, err = t.NewStream(ctx, callHdr)
if err != nil {
if put != nil {
put()
put = nil
}
2016-07-29 02:45:48 +03:00
if _, ok := err.(transport.ConnectionError); ok || err == transport.ErrStreamDrain {
if c.failFast {
return nil, toRPCErr(err)
}
continue
}
return nil, toRPCErr(err)
}
break
}
cs := &clientStream{
opts: opts,
c: c,
desc: desc,
codec: cc.dopts.codec,
cp: cc.dopts.cp,
dc: cc.dopts.dc,
maxReceiveMessageSize: maxReceiveMessageSize,
maxSendMessageSize: maxSendMessageSize,
cancel: cancel,
put: put,
t: t,
s: s,
p: &parser{r: s},
tracing: EnableTracing,
trInfo: trInfo,
statsCtx: ctx,
statsHandler: cc.dopts.copts.StatsHandler,
}
if cc.dopts.cp != nil {
cs.cbuf = new(bytes.Buffer)
}
2016-07-16 01:06:00 +03:00
// Listen on ctx.Done() to detect cancellation and s.Done() to detect normal termination
// when there is no pending I/O operations on this stream.
go func() {
select {
2016-07-22 02:19:34 +03:00
case <-t.Error():
// Incur transport error, simply exit.
case <-cc.ctx.Done():
cs.finish(ErrClientConnClosing)
cs.closeTransportStream(ErrClientConnClosing)
case <-s.Done():
2016-07-16 01:43:42 +03:00
// TODO: The trace of the RPC is terminated here when there is no pending
// I/O, which is probably not the optimal solution.
cs.finish(s.Status().Err())
cs.closeTransportStream(nil)
2016-07-21 04:48:49 +03:00
case <-s.GoAway():
cs.finish(errConnDrain)
cs.closeTransportStream(errConnDrain)
case <-s.Context().Done():
err := s.Context().Err()
cs.finish(err)
cs.closeTransportStream(transport.ContextErr(err))
}
}()
2015-06-18 21:45:40 +03:00
return cs, nil
2015-02-06 04:14:05 +03:00
}
// clientStream implements a client side Stream.
type clientStream struct {
opts []CallOption
c callInfo
t transport.ClientTransport
s *transport.Stream
p *parser
desc *StreamDesc
codec Codec
cp Compressor
cbuf *bytes.Buffer
dc Decompressor
maxReceiveMessageSize int
maxSendMessageSize int
cancel context.CancelFunc
tracing bool // set to EnableTracing when the clientStream is created.
mu sync.Mutex
put func()
closed bool
finished bool
2015-10-06 03:49:53 +03:00
// trInfo.tr is set when the clientStream is created (if EnableTracing is true),
// and is set to nil when the clientStream's finish method is called.
2015-10-06 03:49:53 +03:00
trInfo traceInfo
2016-11-08 04:35:30 +03:00
// statsCtx keeps the user context for stats handling.
// All stats collection should use the statsCtx (instead of the stream context)
// so that all the generated stats for a particular RPC can be associated in the processing phase.
statsCtx context.Context
statsHandler stats.Handler
2015-02-06 04:14:05 +03:00
}
func (cs *clientStream) Context() context.Context {
return cs.s.Context()
}
func (cs *clientStream) Header() (metadata.MD, error) {
m, err := cs.s.Header()
if err != nil {
if _, ok := err.(transport.ConnectionError); !ok {
cs.closeTransportStream(err)
}
}
return m, err
2015-02-06 04:14:05 +03:00
}
func (cs *clientStream) Trailer() metadata.MD {
return cs.s.Trailer()
}
func (cs *clientStream) SendMsg(m interface{}) (err error) {
if cs.tracing {
cs.mu.Lock()
2015-10-06 03:49:53 +03:00
if cs.trInfo.tr != nil {
cs.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
}
cs.mu.Unlock()
}
2016-11-08 21:31:02 +03:00
// TODO Investigate how to signal the stats handling party.
// generate error stats if err != nil && err != io.EOF?
2015-02-06 04:14:05 +03:00
defer func() {
if err != nil {
cs.finish(err)
}
if err == nil {
return
}
if err == io.EOF {
// Specialize the process for server streaming. SendMesg is only called
// once when creating the stream object. io.EOF needs to be skipped when
// the rpc is early finished (before the stream object is created.).
// TODO: It is probably better to move this into the generated code.
if !cs.desc.ClientStreams && cs.desc.ServerStreams {
err = nil
}
2015-02-06 04:14:05 +03:00
return
}
if _, ok := err.(transport.ConnectionError); !ok {
cs.closeTransportStream(err)
2015-02-06 04:14:05 +03:00
}
err = toRPCErr(err)
}()
var outPayload *stats.OutPayload
if cs.statsHandler != nil {
outPayload = &stats.OutPayload{
2016-11-03 01:45:22 +03:00
Client: true,
2016-11-02 02:57:54 +03:00
}
}
out, err := encode(cs.codec, m, cs.cp, cs.cbuf, outPayload)
defer func() {
if cs.cbuf != nil {
cs.cbuf.Reset()
}
}()
2015-02-06 04:14:05 +03:00
if err != nil {
return Errorf(codes.Internal, "grpc: %v", err)
2015-02-06 04:14:05 +03:00
}
if len(out) > cs.maxSendMessageSize {
return Errorf(codes.ResourceExhausted, "Sent message larger than max (%d vs. %d)", len(out), cs.maxSendMessageSize)
}
2016-11-02 02:57:54 +03:00
err = cs.t.Write(cs.s, out, &transport.Options{Last: false})
2016-11-08 00:17:59 +03:00
if err == nil && outPayload != nil {
outPayload.SentTime = time.Now()
cs.statsHandler.HandleRPC(cs.statsCtx, outPayload)
2016-11-02 02:57:54 +03:00
}
return err
2015-02-06 04:14:05 +03:00
}
func (cs *clientStream) RecvMsg(m interface{}) (err error) {
2016-11-05 02:02:19 +03:00
var inPayload *stats.InPayload
if cs.statsHandler != nil {
2016-11-05 02:02:19 +03:00
inPayload = &stats.InPayload{
2016-11-03 01:45:22 +03:00
Client: true,
2016-11-02 02:57:54 +03:00
}
}
err = recv(cs.p, cs.codec, cs.s, cs.dc, m, cs.maxReceiveMessageSize, inPayload)
2015-06-18 21:45:40 +03:00
defer func() {
// err != nil indicates the termination of the stream.
if err != nil {
cs.finish(err)
2015-06-18 21:45:40 +03:00
}
}()
2015-02-06 04:14:05 +03:00
if err == nil {
2015-07-25 01:39:25 +03:00
if cs.tracing {
cs.mu.Lock()
2015-10-06 03:49:53 +03:00
if cs.trInfo.tr != nil {
cs.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
2015-07-25 01:39:25 +03:00
}
cs.mu.Unlock()
}
2016-11-05 02:02:19 +03:00
if inPayload != nil {
cs.statsHandler.HandleRPC(cs.statsCtx, inPayload)
2016-11-02 02:57:54 +03:00
}
if !cs.desc.ClientStreams || cs.desc.ServerStreams {
return
}
// Special handling for client streaming rpc.
2016-11-05 02:02:19 +03:00
// This recv expects EOF or errors, so we don't collect inPayload.
err = recv(cs.p, cs.codec, cs.s, cs.dc, m, cs.maxReceiveMessageSize, nil)
cs.closeTransportStream(err)
if err == nil {
return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
}
if err == io.EOF {
if se := cs.s.Status().Err(); se != nil {
return se
}
cs.finish(err)
return nil
}
return toRPCErr(err)
2015-02-06 04:14:05 +03:00
}
if _, ok := err.(transport.ConnectionError); !ok {
cs.closeTransportStream(err)
}
2015-02-06 04:14:05 +03:00
if err == io.EOF {
if statusErr := cs.s.Status().Err(); statusErr != nil {
return statusErr
2015-02-06 04:14:05 +03:00
}
// Returns io.EOF to indicate the end of the stream.
return
2015-02-06 04:14:05 +03:00
}
return toRPCErr(err)
}
func (cs *clientStream) CloseSend() (err error) {
err = cs.t.Write(cs.s, nil, &transport.Options{Last: true})
defer func() {
if err != nil {
cs.finish(err)
}
}()
2015-02-06 04:14:05 +03:00
if err == nil || err == io.EOF {
2016-07-15 03:12:11 +03:00
return nil
}
2015-02-06 04:14:05 +03:00
if _, ok := err.(transport.ConnectionError); !ok {
cs.closeTransportStream(err)
2015-02-06 04:14:05 +03:00
}
err = toRPCErr(err)
return
}
func (cs *clientStream) closeTransportStream(err error) {
cs.mu.Lock()
if cs.closed {
cs.mu.Unlock()
return
}
cs.closed = true
cs.mu.Unlock()
cs.t.CloseStream(cs.s, err)
}
func (cs *clientStream) finish(err error) {
cs.mu.Lock()
defer cs.mu.Unlock()
if cs.finished {
return
}
cs.finished = true
defer func() {
if cs.cancel != nil {
cs.cancel()
}
}()
for _, o := range cs.opts {
o.after(&cs.c)
}
2016-05-07 01:47:09 +03:00
if cs.put != nil {
cs.put()
cs.put = nil
}
if cs.statsHandler != nil {
end := &stats.End{
Client: true,
EndTime: time.Now(),
}
if err != io.EOF {
// end.Error is nil if the RPC finished successfully.
end.Error = toRPCErr(err)
}
cs.statsHandler.HandleRPC(cs.statsCtx, end)
}
if !cs.tracing {
return
}
2015-10-06 03:49:53 +03:00
if cs.trInfo.tr != nil {
if err == nil || err == io.EOF {
2015-10-06 03:49:53 +03:00
cs.trInfo.tr.LazyPrintf("RPC: [OK]")
} else {
2015-10-06 03:49:53 +03:00
cs.trInfo.tr.LazyPrintf("RPC: [%v]", err)
cs.trInfo.tr.SetError()
}
2015-10-06 03:49:53 +03:00
cs.trInfo.tr.Finish()
cs.trInfo.tr = nil
}
}
2015-02-06 04:14:05 +03:00
// ServerStream defines the interface a server stream has to satisfy.
type ServerStream interface {
// SetHeader sets the header metadata. It may be called multiple times.
// When call multiple times, all the provided metadata will be merged.
// All the metadata will be sent out when one of the following happens:
// - ServerStream.SendHeader() is called;
// - The first response is sent out;
// - An RPC status is sent out (error or success).
SetHeader(metadata.MD) error
// SendHeader sends the header metadata.
// The provided md and headers set by SetHeader() will be sent.
// It fails if called multiple times.
2015-02-06 04:14:05 +03:00
SendHeader(metadata.MD) error
2016-08-26 01:17:50 +03:00
// SetTrailer sets the trailer metadata which will be sent with the RPC status.
// When called more than once, all the provided metadata will be merged.
2015-02-06 04:14:05 +03:00
SetTrailer(metadata.MD)
Stream
}
// serverStream implements a server side Stream.
type serverStream struct {
2017-04-06 01:08:25 +03:00
t transport.ServerTransport
s *transport.Stream
p *parser
codec Codec
cp Compressor
dc Decompressor
cbuf *bytes.Buffer
maxReceiveMessageSize int
maxSendMessageSize int
2017-04-06 01:08:25 +03:00
trInfo *traceInfo
statsHandler stats.Handler
2015-10-06 03:49:53 +03:00
mu sync.Mutex // protects trInfo.tr after the service handler runs.
2015-02-06 04:14:05 +03:00
}
func (ss *serverStream) Context() context.Context {
2015-10-02 03:24:39 +03:00
return ss.s.Context()
2015-02-06 04:14:05 +03:00
}
func (ss *serverStream) SetHeader(md metadata.MD) error {
if md.Len() == 0 {
return nil
}
return ss.s.SetHeader(md)
}
2015-02-06 04:14:05 +03:00
func (ss *serverStream) SendHeader(md metadata.MD) error {
return ss.t.WriteHeader(ss.s, md)
}
func (ss *serverStream) SetTrailer(md metadata.MD) {
if md.Len() == 0 {
return
}
ss.s.SetTrailer(md)
return
}
2015-07-29 01:27:46 +03:00
func (ss *serverStream) SendMsg(m interface{}) (err error) {
defer func() {
2015-10-06 03:49:53 +03:00
if ss.trInfo != nil {
2015-07-29 01:27:46 +03:00
ss.mu.Lock()
2015-10-06 03:49:53 +03:00
if ss.trInfo.tr != nil {
if err == nil {
ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
} else {
ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
ss.trInfo.tr.SetError()
}
2015-07-29 01:27:46 +03:00
}
ss.mu.Unlock()
2015-07-28 00:33:17 +03:00
}
2015-07-29 01:27:46 +03:00
}()
var outPayload *stats.OutPayload
if ss.statsHandler != nil {
outPayload = &stats.OutPayload{}
}
out, err := encode(ss.codec, m, ss.cp, ss.cbuf, outPayload)
defer func() {
if ss.cbuf != nil {
ss.cbuf.Reset()
}
}()
2015-02-06 04:14:05 +03:00
if err != nil {
err = Errorf(codes.Internal, "grpc: %v", err)
2015-02-06 04:14:05 +03:00
return err
}
if len(out) > ss.maxSendMessageSize {
return Errorf(codes.ResourceExhausted, "Sent message larger than max (%d vs. %d)", len(out), ss.maxSendMessageSize)
}
if err := ss.t.Write(ss.s, out, &transport.Options{Last: false}); err != nil {
return toRPCErr(err)
}
if outPayload != nil {
2016-11-08 00:17:59 +03:00
outPayload.SentTime = time.Now()
ss.statsHandler.HandleRPC(ss.s.Context(), outPayload)
}
return nil
2015-02-06 04:14:05 +03:00
}
2015-07-29 01:27:46 +03:00
func (ss *serverStream) RecvMsg(m interface{}) (err error) {
2015-07-28 00:33:17 +03:00
defer func() {
2015-10-06 03:49:53 +03:00
if ss.trInfo != nil {
2015-07-28 00:33:17 +03:00
ss.mu.Lock()
2015-10-06 03:49:53 +03:00
if ss.trInfo.tr != nil {
if err == nil {
ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
} else if err != io.EOF {
ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
ss.trInfo.tr.SetError()
}
2015-07-28 00:33:17 +03:00
}
ss.mu.Unlock()
}
}()
2016-11-05 02:02:19 +03:00
var inPayload *stats.InPayload
if ss.statsHandler != nil {
2016-11-05 02:02:19 +03:00
inPayload = &stats.InPayload{}
}
if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, inPayload); err != nil {
if err == io.EOF {
return err
}
if err == io.ErrUnexpectedEOF {
err = Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
}
return toRPCErr(err)
}
2016-11-05 02:02:19 +03:00
if inPayload != nil {
ss.statsHandler.HandleRPC(ss.s.Context(), inPayload)
}
return nil
2015-02-06 04:14:05 +03:00
}