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.
19 // Package transport defines and implements message oriented communication
20 // channel to complete various transactions (e.g., an RPC).
21 package transport // import "google.golang.org/grpc/transport"
30 "golang.org/x/net/context"
31 "golang.org/x/net/http2"
32 "google.golang.org/grpc/codes"
33 "google.golang.org/grpc/credentials"
34 "google.golang.org/grpc/keepalive"
35 "google.golang.org/grpc/metadata"
36 "google.golang.org/grpc/stats"
37 "google.golang.org/grpc/status"
38 "google.golang.org/grpc/tap"
41 // recvMsg represents the received msg from the transport. All transport
42 // protocol specific info has been removed.
45 // nil: received some data
46 // io.EOF: stream is completed. data is nil.
47 // other non-nil error: transport failure. data is nil.
51 // recvBuffer is an unbounded channel of recvMsg structs.
52 // Note recvBuffer differs from controlBuffer only in that recvBuffer
53 // holds a channel of only recvMsg structs instead of objects implementing "item" interface.
54 // recvBuffer is written to much more often than
55 // controlBuffer and using strict recvMsg structs helps avoid allocation in "recvBuffer.put"
56 type recvBuffer struct {
62 func newRecvBuffer() *recvBuffer {
64 c: make(chan recvMsg, 1),
69 func (b *recvBuffer) put(r recvMsg) {
71 if len(b.backlog) == 0 {
79 b.backlog = append(b.backlog, r)
83 func (b *recvBuffer) load() {
85 if len(b.backlog) > 0 {
87 case b.c <- b.backlog[0]:
88 b.backlog[0] = recvMsg{}
89 b.backlog = b.backlog[1:]
96 // get returns the channel that receives a recvMsg in the buffer.
98 // Upon receipt of a recvMsg, the caller should call load to send another
99 // recvMsg onto the channel if there is any.
100 func (b *recvBuffer) get() <-chan recvMsg {
104 // recvBufferReader implements io.Reader interface to read the data from
106 type recvBufferReader struct {
110 last []byte // Stores the remaining data in the previous calls.
114 // Read reads the next len(p) bytes from last. If last is drained, it tries to
115 // read additional data from recv. It blocks if there no additional data available
116 // in recv. If Read returns any non-nil error, it will continue to return that error.
117 func (r *recvBufferReader) Read(p []byte) (n int, err error) {
125 func (r *recvBufferReader) read(p []byte) (n int, err error) {
126 if r.last != nil && len(r.last) > 0 {
127 // Read remaining data left in last call.
128 copied := copy(p, r.last)
129 r.last = r.last[copied:]
134 return 0, ContextErr(r.ctx.Err())
136 return 0, ErrStreamDrain
137 case m := <-r.recv.get():
142 copied := copy(p, m.data)
143 r.last = m.data[copied:]
148 // All items in an out of a controlBuffer should be the same type.
149 type item interface {
153 // controlBuffer is an unbounded channel of item.
154 type controlBuffer struct {
160 func newControlBuffer() *controlBuffer {
162 c: make(chan item, 1),
167 func (b *controlBuffer) put(r item) {
169 if len(b.backlog) == 0 {
177 b.backlog = append(b.backlog, r)
181 func (b *controlBuffer) load() {
183 if len(b.backlog) > 0 {
185 case b.c <- b.backlog[0]:
187 b.backlog = b.backlog[1:]
194 // get returns the channel that receives an item in the buffer.
196 // Upon receipt of an item, the caller should call load to send another
197 // item onto the channel if there is any.
198 func (b *controlBuffer) get() <-chan item {
202 type streamState uint8
205 streamActive streamState = iota
206 streamWriteDone // EndStream sent
207 streamReadDone // EndStream received
208 streamDone // the entire stream is finished.
211 // Stream represents an RPC in the transport layer.
214 // nil for client side Stream.
216 // ctx is the associated context of the stream.
218 // cancel is always nil for client side Stream.
219 cancel context.CancelFunc
220 // done is closed when the final status arrives.
222 // goAway is closed when the server sent GoAways signal before this stream was initiated.
224 // method records the associated RPC method of the stream.
233 // TODO: Remote this unused variable.
234 // The accumulated inbound quota pending for window update.
237 // Callback to state application's intentions to read data. This
238 // is used to adjust flow control, if need be.
239 requestRead func(int)
241 sendQuotaPool *quotaPool
242 localSendQuota *quotaPool
243 // Close headerChan to indicate the end of reception of header metadata.
244 headerChan chan struct{}
245 // header caches the received header metadata.
247 // The key-value map of trailer metadata.
250 mu sync.RWMutex // guard the following
251 // headerOK becomes true from the first header is about to send.
254 // true iff headerChan is closed. Used to avoid closing headerChan
257 // the status error received from the server.
258 status *status.Status
259 // rstStream indicates whether a RST_STREAM frame needs to be sent
260 // to the server to signify that this stream is closing.
262 // rstError is the error that needs to be sent along with the RST_STREAM frame.
263 rstError http2.ErrCode
264 // bytesSent and bytesReceived indicates whether any bytes have been sent or
265 // received on this stream.
270 // RecvCompress returns the compression algorithm applied to the inbound
271 // message. It is empty string if there is no compression applied.
272 func (s *Stream) RecvCompress() string {
273 return s.recvCompress
276 // SetSendCompress sets the compression algorithm to the stream.
277 func (s *Stream) SetSendCompress(str string) {
281 // Done returns a chanel which is closed when it receives the final status
283 func (s *Stream) Done() <-chan struct{} {
287 // GoAway returns a channel which is closed when the server sent GoAways signal
288 // before this stream was initiated.
289 func (s *Stream) GoAway() <-chan struct{} {
293 // Header acquires the key-value pairs of header metadata once it
294 // is available. It blocks until i) the metadata is ready or ii) there is no
295 // header metadata or iii) the stream is canceled/expired.
296 func (s *Stream) Header() (metadata.MD, error) {
300 err = ContextErr(s.ctx.Err())
304 return s.header.Copy(), nil
306 // Even if the stream is closed, header is returned if available.
309 return s.header.Copy(), nil
315 // Trailer returns the cached trailer metedata. Note that if it is not called
316 // after the entire stream is done, it could return an empty MD. Client
318 func (s *Stream) Trailer() metadata.MD {
320 c := s.trailer.Copy()
325 // ServerTransport returns the underlying ServerTransport for the stream.
326 // The client side stream always returns nil.
327 func (s *Stream) ServerTransport() ServerTransport {
331 // Context returns the context of the stream.
332 func (s *Stream) Context() context.Context {
336 // Method returns the method for the stream.
337 func (s *Stream) Method() string {
341 // Status returns the status received from the server.
342 func (s *Stream) Status() *status.Status {
346 // SetHeader sets the header metadata. This can be called multiple times.
348 func (s *Stream) SetHeader(md metadata.MD) error {
350 if s.headerOk || s.state == streamDone {
352 return ErrIllegalHeaderWrite
358 s.header = metadata.Join(s.header, md)
363 // SetTrailer sets the trailer metadata which will be sent with the RPC status
364 // by the server. This can be called multiple times. Server side only.
365 func (s *Stream) SetTrailer(md metadata.MD) error {
370 s.trailer = metadata.Join(s.trailer, md)
375 func (s *Stream) write(m recvMsg) {
379 // Read reads all p bytes from the wire for this stream.
380 func (s *Stream) Read(p []byte) (n int, err error) {
381 // Don't request a read if there was an error earlier
382 if er := s.trReader.(*transportReader).er; er != nil {
385 s.requestRead(len(p))
386 return io.ReadFull(s.trReader, p)
389 // tranportReader reads all the data available for this Stream from the transport and
390 // passes them into the decoder, which converts them into a gRPC message stream.
391 // The error is io.EOF when the stream is done or another non-nil error if
393 type transportReader struct {
395 // The handler to control the window update procedure for both this
396 // particular stream and the associated transport.
397 windowHandler func(int)
401 func (t *transportReader) Read(p []byte) (n int, err error) {
402 n, err = t.reader.Read(p)
411 // finish sets the stream's state and status, and closes the done channel.
412 // s.mu must be held by the caller. st must always be non-nil.
413 func (s *Stream) finish(st *status.Status) {
419 // BytesSent indicates whether any bytes have been sent on this stream.
420 func (s *Stream) BytesSent() bool {
427 // BytesReceived indicates whether any bytes have been received on this stream.
428 func (s *Stream) BytesReceived() bool {
430 br := s.bytesReceived
435 // GoString is implemented by Stream so context.String() won't
436 // race when printing %#v.
437 func (s *Stream) GoString() string {
438 return fmt.Sprintf("<stream: %p, %v>", s, s.method)
441 // The key to save transport.Stream in the context.
442 type streamKey struct{}
444 // newContextWithStream creates a new context from ctx and attaches stream
446 func newContextWithStream(ctx context.Context, stream *Stream) context.Context {
447 return context.WithValue(ctx, streamKey{}, stream)
450 // StreamFromContext returns the stream saved in ctx.
451 func StreamFromContext(ctx context.Context) (s *Stream, ok bool) {
452 s, ok = ctx.Value(streamKey{}).(*Stream)
456 // state of transport
457 type transportState int
460 reachable transportState = iota
465 // ServerConfig consists of all the configurations to establish a server transport.
466 type ServerConfig struct {
468 AuthInfo credentials.AuthInfo
469 InTapHandle tap.ServerInHandle
470 StatsHandler stats.Handler
471 KeepaliveParams keepalive.ServerParameters
472 KeepalivePolicy keepalive.EnforcementPolicy
473 InitialWindowSize int32
474 InitialConnWindowSize int32
479 // NewServerTransport creates a ServerTransport with conn or non-nil error
481 func NewServerTransport(protocol string, conn net.Conn, config *ServerConfig) (ServerTransport, error) {
482 return newHTTP2Server(conn, config)
485 // ConnectOptions covers all relevant options for communicating with the server.
486 type ConnectOptions struct {
487 // UserAgent is the application user agent.
489 // Authority is the :authority pseudo-header to use. This field has no effect if
490 // TransportCredentials is set.
492 // Dialer specifies how to dial a network address.
493 Dialer func(context.Context, string) (net.Conn, error)
494 // FailOnNonTempDialError specifies if gRPC fails on non-temporary dial errors.
495 FailOnNonTempDialError bool
496 // PerRPCCredentials stores the PerRPCCredentials required to issue RPCs.
497 PerRPCCredentials []credentials.PerRPCCredentials
498 // TransportCredentials stores the Authenticator required to setup a client connection.
499 TransportCredentials credentials.TransportCredentials
500 // KeepaliveParams stores the keepalive parameters.
501 KeepaliveParams keepalive.ClientParameters
502 // StatsHandler stores the handler for stats.
503 StatsHandler stats.Handler
504 // InitialWindowSize sets the initial window size for a stream.
505 InitialWindowSize int32
506 // InitialConnWindowSize sets the initial window size for a connection.
507 InitialConnWindowSize int32
508 // WriteBufferSize sets the size of write buffer which in turn determines how much data can be batched before it's written on the wire.
510 // ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall.
514 // TargetInfo contains the information of the target such as network address and metadata.
515 type TargetInfo struct {
521 // NewClientTransport establishes the transport with the required ConnectOptions
522 // and returns it to the caller.
523 func NewClientTransport(ctx context.Context, target TargetInfo, opts ConnectOptions, timeout time.Duration) (ClientTransport, error) {
524 return newHTTP2Client(ctx, target, opts, timeout)
527 // Options provides additional hints and information for message
529 type Options struct {
530 // Last indicates whether this write is the last piece for
534 // Delay is a hint to the transport implementation for whether
535 // the data could be buffered for a batching write. The
536 // transport implementation may ignore the hint.
540 // CallHdr carries the information of a particular RPC.
541 type CallHdr struct {
542 // Host specifies the peer's host.
545 // Method specifies the operation to perform.
548 // RecvCompress specifies the compression algorithm applied on
552 // SendCompress specifies the compression algorithm applied on
556 // Creds specifies credentials.PerRPCCredentials for a call.
557 Creds credentials.PerRPCCredentials
559 // Flush indicates whether a new stream command should be sent
560 // to the peer without waiting for the first data. This is
562 // If it's true, the transport may modify the flush decision
563 // for performance purposes.
564 // If it's false, new stream will never be flushed.
568 // ClientTransport is the common interface for all gRPC client-side transport
570 type ClientTransport interface {
571 // Close tears down this transport. Once it returns, the transport
572 // should not be accessed any more. The caller must make sure this
573 // is called only once.
576 // GracefulClose starts to tear down the transport. It stops accepting
577 // new RPCs and wait the completion of the pending RPCs.
578 GracefulClose() error
580 // Write sends the data for the given stream. A nil stream indicates
581 // the write is to be performed on the transport as a whole.
582 Write(s *Stream, hdr []byte, data []byte, opts *Options) error
584 // NewStream creates a Stream for an RPC.
585 NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error)
587 // CloseStream clears the footprint of a stream when the stream is
588 // not needed any more. The err indicates the error incurred when
589 // CloseStream is called. Must be called when a stream is finished
590 // unless the associated transport is closing.
591 CloseStream(stream *Stream, err error)
593 // Error returns a channel that is closed when some I/O error
594 // happens. Typically the caller should have a goroutine to monitor
595 // this in order to take action (e.g., close the current transport
596 // and create a new one) in error case. It should not return nil
597 // once the transport is initiated.
598 Error() <-chan struct{}
600 // GoAway returns a channel that is closed when ClientTransport
601 // receives the draining signal from the server (e.g., GOAWAY frame in
603 GoAway() <-chan struct{}
605 // GetGoAwayReason returns the reason why GoAway frame was received.
606 GetGoAwayReason() GoAwayReason
609 // ServerTransport is the common interface for all gRPC server-side transport
612 // Methods may be called concurrently from multiple goroutines, but
613 // Write methods for a given Stream will be called serially.
614 type ServerTransport interface {
615 // HandleStreams receives incoming streams using the given handler.
616 HandleStreams(func(*Stream), func(context.Context, string) context.Context)
618 // WriteHeader sends the header metadata for the given stream.
619 // WriteHeader may not be called on all streams.
620 WriteHeader(s *Stream, md metadata.MD) error
622 // Write sends the data for the given stream.
623 // Write may not be called on all streams.
624 Write(s *Stream, hdr []byte, data []byte, opts *Options) error
626 // WriteStatus sends the status of a stream to the client. WriteStatus is
627 // the final call made on a stream and always occurs.
628 WriteStatus(s *Stream, st *status.Status) error
630 // Close tears down the transport. Once it is called, the transport
631 // should not be accessed any more. All the pending streams and their
632 // handlers will be terminated asynchronously.
635 // RemoteAddr returns the remote network address.
636 RemoteAddr() net.Addr
638 // Drain notifies the client this ServerTransport stops accepting new RPCs.
642 // streamErrorf creates an StreamError with the specified error code and description.
643 func streamErrorf(c codes.Code, format string, a ...interface{}) StreamError {
646 Desc: fmt.Sprintf(format, a...),
650 // connectionErrorf creates an ConnectionError with the specified error description.
651 func connectionErrorf(temp bool, e error, format string, a ...interface{}) ConnectionError {
652 return ConnectionError{
653 Desc: fmt.Sprintf(format, a...),
659 // ConnectionError is an error that results in the termination of the
660 // entire connection and the retry of all the active streams.
661 type ConnectionError struct {
667 func (e ConnectionError) Error() string {
668 return fmt.Sprintf("connection error: desc = %q", e.Desc)
671 // Temporary indicates if this connection error is temporary or fatal.
672 func (e ConnectionError) Temporary() bool {
676 // Origin returns the original error of this connection error.
677 func (e ConnectionError) Origin() error {
678 // Never return nil error here.
679 // If the original error is nil, return itself.
687 // ErrConnClosing indicates that the transport is closing.
688 ErrConnClosing = connectionErrorf(true, nil, "transport is closing")
689 // ErrStreamDrain indicates that the stream is rejected by the server because
690 // the server stops accepting new RPCs.
691 ErrStreamDrain = streamErrorf(codes.Unavailable, "the server stops accepting new RPCs")
694 // TODO: See if we can replace StreamError with status package errors.
696 // StreamError is an error that only affects one stream within a connection.
697 type StreamError struct {
702 func (e StreamError) Error() string {
703 return fmt.Sprintf("stream error: code = %s desc = %q", e.Code, e.Desc)
706 // wait blocks until it can receive from one of the provided contexts or
707 // channels. ctx is the context of the RPC, tctx is the context of the
708 // transport, done is a channel closed to indicate the end of the RPC, goAway
709 // is a channel closed to indicate a GOAWAY was received, and proceed is a
710 // quota channel, whose received value is returned from this function if none
711 // of the other signals occur first.
712 func wait(ctx, tctx context.Context, done, goAway <-chan struct{}, proceed <-chan int) (int, error) {
715 return 0, ContextErr(ctx.Err())
719 return 0, ErrStreamDrain
721 return 0, ErrConnClosing
727 // GoAwayReason contains the reason for the GoAway frame received.
728 type GoAwayReason uint8
731 // Invalid indicates that no GoAway frame is received.
732 Invalid GoAwayReason = 0
733 // NoReason is the default value when GoAway frame is received.
734 NoReason GoAwayReason = 1
735 // TooManyPings indicates that a GoAway frame with ErrCodeEnhanceYourCalm
736 // was received and that the debug data said "too_many_pings".
737 TooManyPings GoAwayReason = 2
740 // loopyWriter is run in a separate go routine. It is the single code path that will
741 // write data on wire.
742 func loopyWriter(ctx context.Context, cbuf *controlBuffer, handler func(item) error) {
745 case i := <-cbuf.get():
747 if err := handler(i); err != nil {
756 case i := <-cbuf.get():
758 if err := handler(i); err != nil {
764 if err := handler(&flushIO{}); err != nil {