Debian Codegraph @

vendor/google.golang.org/grpc/transport/transport.go

raw
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
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"
22
23 import (
24 stdctx "context"
25 "fmt"
26 "io"
27 "net"
28 "sync"
29 "time"
30
31 "golang.org/x/net/context"
32 "golang.org/x/net/http2"
33 "google.golang.org/grpc/codes"
34 "google.golang.org/grpc/credentials"
35 "google.golang.org/grpc/keepalive"
36 "google.golang.org/grpc/metadata"
37 "google.golang.org/grpc/stats"
38 "google.golang.org/grpc/status"
39 "google.golang.org/grpc/tap"
40 )
41
42 // recvMsg represents the received msg from the transport. All transport
43 // protocol specific info has been removed.
44 type recvMsg struct {
45 data []byte
46 // nil: received some data
47 // io.EOF: stream is completed. data is nil.
48 // other non-nil error: transport failure. data is nil.
49 err error
50 }
51
52 // recvBuffer is an unbounded channel of recvMsg structs.
53 // Note recvBuffer differs from controlBuffer only in that recvBuffer
54 // holds a channel of only recvMsg structs instead of objects implementing "item" interface.
55 // recvBuffer is written to much more often than
56 // controlBuffer and using strict recvMsg structs helps avoid allocation in "recvBuffer.put"
57 type recvBuffer struct {
58 c chan recvMsg
59 mu sync.Mutex
60 backlog []recvMsg
61 }
62
63 func newRecvBuffer() *recvBuffer {
64 b := &recvBuffer{
65 c: make(chan recvMsg, 1),
66 }
67 return b
68 }
69
70 func (b *recvBuffer) put(r recvMsg) {
71 b.mu.Lock()
72 if len(b.backlog) == 0 {
73 select {
74 case b.c <- r:
75 b.mu.Unlock()
76 return
77 default:
78 }
79 }
80 b.backlog = append(b.backlog, r)
81 b.mu.Unlock()
82 }
83
84 func (b *recvBuffer) load() {
85 b.mu.Lock()
86 if len(b.backlog) > 0 {
87 select {
88 case b.c <- b.backlog[0]:
89 b.backlog[0] = recvMsg{}
90 b.backlog = b.backlog[1:]
91 default:
92 }
93 }
94 b.mu.Unlock()
95 }
96
97 // get returns the channel that receives a recvMsg in the buffer.
98 //
99 // Upon receipt of a recvMsg, the caller should call load to send another
100 // recvMsg onto the channel if there is any.
101 func (b *recvBuffer) get() <-chan recvMsg {
102 return b.c
103 }
104
105 // recvBufferReader implements io.Reader interface to read the data from
106 // recvBuffer.
107 type recvBufferReader struct {
108 ctx context.Context
109 goAway chan struct{}
110 recv *recvBuffer
111 last []byte // Stores the remaining data in the previous calls.
112 err error
113 }
114
115 // Read reads the next len(p) bytes from last. If last is drained, it tries to
116 // read additional data from recv. It blocks if there no additional data available
117 // in recv. If Read returns any non-nil error, it will continue to return that error.
118 func (r *recvBufferReader) Read(p []byte) (n int, err error) {
119 if r.err != nil {
120 return 0, r.err
121 }
122 n, r.err = r.read(p)
123 return n, r.err
124 }
125
126 func (r *recvBufferReader) read(p []byte) (n int, err error) {
127 if r.last != nil && len(r.last) > 0 {
128 // Read remaining data left in last call.
129 copied := copy(p, r.last)
130 r.last = r.last[copied:]
131 return copied, nil
132 }
133 select {
134 case <-r.ctx.Done():
135 return 0, ContextErr(r.ctx.Err())
136 case <-r.goAway:
137 return 0, ErrStreamDrain
138 case m := <-r.recv.get():
139 r.recv.load()
140 if m.err != nil {
141 return 0, m.err
142 }
143 copied := copy(p, m.data)
144 r.last = m.data[copied:]
145 return copied, nil
146 }
147 }
148
149 // All items in an out of a controlBuffer should be the same type.
150 type item interface {
151 item()
152 }
153
154 // controlBuffer is an unbounded channel of item.
155 type controlBuffer struct {
156 c chan item
157 mu sync.Mutex
158 backlog []item
159 }
160
161 func newControlBuffer() *controlBuffer {
162 b := &controlBuffer{
163 c: make(chan item, 1),
164 }
165 return b
166 }
167
168 func (b *controlBuffer) put(r item) {
169 b.mu.Lock()
170 if len(b.backlog) == 0 {
171 select {
172 case b.c <- r:
173 b.mu.Unlock()
174 return
175 default:
176 }
177 }
178 b.backlog = append(b.backlog, r)
179 b.mu.Unlock()
180 }
181
182 func (b *controlBuffer) load() {
183 b.mu.Lock()
184 if len(b.backlog) > 0 {
185 select {
186 case b.c <- b.backlog[0]:
187 b.backlog[0] = nil
188 b.backlog = b.backlog[1:]
189 default:
190 }
191 }
192 b.mu.Unlock()
193 }
194
195 // get returns the channel that receives an item in the buffer.
196 //
197 // Upon receipt of an item, the caller should call load to send another
198 // item onto the channel if there is any.
199 func (b *controlBuffer) get() <-chan item {
200 return b.c
201 }
202
203 type streamState uint8
204
205 const (
206 streamActive streamState = iota
207 streamWriteDone // EndStream sent
208 streamReadDone // EndStream received
209 streamDone // the entire stream is finished.
210 )
211
212 // Stream represents an RPC in the transport layer.
213 type Stream struct {
214 id uint32
215 // nil for client side Stream.
216 st ServerTransport
217 // ctx is the associated context of the stream.
218 ctx context.Context
219 // cancel is always nil for client side Stream.
220 cancel context.CancelFunc
221 // done is closed when the final status arrives.
222 done chan struct{}
223 // goAway is closed when the server sent GoAways signal before this stream was initiated.
224 goAway chan struct{}
225 // method records the associated RPC method of the stream.
226 method string
227 recvCompress string
228 sendCompress string
229 buf *recvBuffer
230 trReader io.Reader
231 fc *inFlow
232 recvQuota uint32
233
234 // TODO: Remote this unused variable.
235 // The accumulated inbound quota pending for window update.
236 updateQuota uint32
237
238 // Callback to state application's intentions to read data. This
239 // is used to adjust flow control, if need be.
240 requestRead func(int)
241
242 sendQuotaPool *quotaPool
243 localSendQuota *quotaPool
244 // Close headerChan to indicate the end of reception of header metadata.
245 headerChan chan struct{}
246 // header caches the received header metadata.
247 header metadata.MD
248 // The key-value map of trailer metadata.
249 trailer metadata.MD
250
251 mu sync.RWMutex // guard the following
252 // headerOK becomes true from the first header is about to send.
253 headerOk bool
254 state streamState
255 // true iff headerChan is closed. Used to avoid closing headerChan
256 // multiple times.
257 headerDone bool
258 // the status error received from the server.
259 status *status.Status
260 // rstStream indicates whether a RST_STREAM frame needs to be sent
261 // to the server to signify that this stream is closing.
262 rstStream bool
263 // rstError is the error that needs to be sent along with the RST_STREAM frame.
264 rstError http2.ErrCode
265 // bytesSent and bytesReceived indicates whether any bytes have been sent or
266 // received on this stream.
267 bytesSent bool
268 bytesReceived bool
269 }
270
271 // RecvCompress returns the compression algorithm applied to the inbound
272 // message. It is empty string if there is no compression applied.
273 func (s *Stream) RecvCompress() string {
274 return s.recvCompress
275 }
276
277 // SetSendCompress sets the compression algorithm to the stream.
278 func (s *Stream) SetSendCompress(str string) {
279 s.sendCompress = str
280 }
281
282 // Done returns a chanel which is closed when it receives the final status
283 // from the server.
284 func (s *Stream) Done() <-chan struct{} {
285 return s.done
286 }
287
288 // GoAway returns a channel which is closed when the server sent GoAways signal
289 // before this stream was initiated.
290 func (s *Stream) GoAway() <-chan struct{} {
291 return s.goAway
292 }
293
294 // Header acquires the key-value pairs of header metadata once it
295 // is available. It blocks until i) the metadata is ready or ii) there is no
296 // header metadata or iii) the stream is canceled/expired.
297 func (s *Stream) Header() (metadata.MD, error) {
298 var err error
299 select {
300 case <-s.ctx.Done():
301 err = ContextErr(s.ctx.Err())
302 case <-s.goAway:
303 err = ErrStreamDrain
304 case <-s.headerChan:
305 return s.header.Copy(), nil
306 }
307 // Even if the stream is closed, header is returned if available.
308 select {
309 case <-s.headerChan:
310 return s.header.Copy(), nil
311 default:
312 }
313 return nil, err
314 }
315
316 // Trailer returns the cached trailer metedata. Note that if it is not called
317 // after the entire stream is done, it could return an empty MD. Client
318 // side only.
319 func (s *Stream) Trailer() metadata.MD {
320 s.mu.RLock()
321 c := s.trailer.Copy()
322 s.mu.RUnlock()
323 return c
324 }
325
326 // ServerTransport returns the underlying ServerTransport for the stream.
327 // The client side stream always returns nil.
328 func (s *Stream) ServerTransport() ServerTransport {
329 return s.st
330 }
331
332 // Context returns the context of the stream.
333 func (s *Stream) Context() context.Context {
334 return s.ctx
335 }
336
337 // Method returns the method for the stream.
338 func (s *Stream) Method() string {
339 return s.method
340 }
341
342 // Status returns the status received from the server.
343 func (s *Stream) Status() *status.Status {
344 return s.status
345 }
346
347 // SetHeader sets the header metadata. This can be called multiple times.
348 // Server side only.
349 func (s *Stream) SetHeader(md metadata.MD) error {
350 s.mu.Lock()
351 if s.headerOk || s.state == streamDone {
352 s.mu.Unlock()
353 return ErrIllegalHeaderWrite
354 }
355 if md.Len() == 0 {
356 s.mu.Unlock()
357 return nil
358 }
359 s.header = metadata.Join(s.header, md)
360 s.mu.Unlock()
361 return nil
362 }
363
364 // SetTrailer sets the trailer metadata which will be sent with the RPC status
365 // by the server. This can be called multiple times. Server side only.
366 func (s *Stream) SetTrailer(md metadata.MD) error {
367 if md.Len() == 0 {
368 return nil
369 }
370 s.mu.Lock()
371 s.trailer = metadata.Join(s.trailer, md)
372 s.mu.Unlock()
373 return nil
374 }
375
376 func (s *Stream) write(m recvMsg) {
377 s.buf.put(m)
378 }
379
380 // Read reads all p bytes from the wire for this stream.
381 func (s *Stream) Read(p []byte) (n int, err error) {
382 // Don't request a read if there was an error earlier
383 if er := s.trReader.(*transportReader).er; er != nil {
384 return 0, er
385 }
386 s.requestRead(len(p))
387 return io.ReadFull(s.trReader, p)
388 }
389
390 // tranportReader reads all the data available for this Stream from the transport and
391 // passes them into the decoder, which converts them into a gRPC message stream.
392 // The error is io.EOF when the stream is done or another non-nil error if
393 // the stream broke.
394 type transportReader struct {
395 reader io.Reader
396 // The handler to control the window update procedure for both this
397 // particular stream and the associated transport.
398 windowHandler func(int)
399 er error
400 }
401
402 func (t *transportReader) Read(p []byte) (n int, err error) {
403 n, err = t.reader.Read(p)
404 if err != nil {
405 t.er = err
406 return
407 }
408 t.windowHandler(n)
409 return
410 }
411
412 // finish sets the stream's state and status, and closes the done channel.
413 // s.mu must be held by the caller. st must always be non-nil.
414 func (s *Stream) finish(st *status.Status) {
415 s.status = st
416 s.state = streamDone
417 close(s.done)
418 }
419
420 // BytesSent indicates whether any bytes have been sent on this stream.
421 func (s *Stream) BytesSent() bool {
422 s.mu.Lock()
423 bs := s.bytesSent
424 s.mu.Unlock()
425 return bs
426 }
427
428 // BytesReceived indicates whether any bytes have been received on this stream.
429 func (s *Stream) BytesReceived() bool {
430 s.mu.Lock()
431 br := s.bytesReceived
432 s.mu.Unlock()
433 return br
434 }
435
436 // GoString is implemented by Stream so context.String() won't
437 // race when printing %#v.
438 func (s *Stream) GoString() string {
439 return fmt.Sprintf("<stream: %p, %v>", s, s.method)
440 }
441
442 // The key to save transport.Stream in the context.
443 type streamKey struct{}
444
445 // newContextWithStream creates a new context from ctx and attaches stream
446 // to it.
447 func newContextWithStream(ctx context.Context, stream *Stream) context.Context {
448 return context.WithValue(ctx, streamKey{}, stream)
449 }
450
451 // StreamFromContext returns the stream saved in ctx.
452 func StreamFromContext(ctx context.Context) (s *Stream, ok bool) {
453 s, ok = ctx.Value(streamKey{}).(*Stream)
454 return
455 }
456
457 // state of transport
458 type transportState int
459
460 const (
461 reachable transportState = iota
462 closing
463 draining
464 )
465
466 // ServerConfig consists of all the configurations to establish a server transport.
467 type ServerConfig struct {
468 MaxStreams uint32
469 AuthInfo credentials.AuthInfo
470 InTapHandle tap.ServerInHandle
471 StatsHandler stats.Handler
472 KeepaliveParams keepalive.ServerParameters
473 KeepalivePolicy keepalive.EnforcementPolicy
474 InitialWindowSize int32
475 InitialConnWindowSize int32
476 WriteBufferSize int
477 ReadBufferSize int
478 }
479
480 // NewServerTransport creates a ServerTransport with conn or non-nil error
481 // if it fails.
482 func NewServerTransport(protocol string, conn net.Conn, config *ServerConfig) (ServerTransport, error) {
483 return newHTTP2Server(conn, config)
484 }
485
486 // ConnectOptions covers all relevant options for communicating with the server.
487 type ConnectOptions struct {
488 // UserAgent is the application user agent.
489 UserAgent string
490 // Authority is the :authority pseudo-header to use. This field has no effect if
491 // TransportCredentials is set.
492 Authority string
493 // Dialer specifies how to dial a network address.
494 Dialer func(context.Context, string) (net.Conn, error)
495 // FailOnNonTempDialError specifies if gRPC fails on non-temporary dial errors.
496 FailOnNonTempDialError bool
497 // PerRPCCredentials stores the PerRPCCredentials required to issue RPCs.
498 PerRPCCredentials []credentials.PerRPCCredentials
499 // TransportCredentials stores the Authenticator required to setup a client connection.
500 TransportCredentials credentials.TransportCredentials
501 // KeepaliveParams stores the keepalive parameters.
502 KeepaliveParams keepalive.ClientParameters
503 // StatsHandler stores the handler for stats.
504 StatsHandler stats.Handler
505 // InitialWindowSize sets the initial window size for a stream.
506 InitialWindowSize int32
507 // InitialConnWindowSize sets the initial window size for a connection.
508 InitialConnWindowSize int32
509 // 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 WriteBufferSize int
511 // ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall.
512 ReadBufferSize int
513 }
514
515 // TargetInfo contains the information of the target such as network address and metadata.
516 type TargetInfo struct {
517 Addr string
518 Metadata interface{}
519 }
520
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)
525 }
526
527 // Options provides additional hints and information for message
528 // transmission.
529 type Options struct {
530 // Last indicates whether this write is the last piece for
531 // this stream.
532 Last bool
533
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.
537 Delay bool
538 }
539
540 // CallHdr carries the information of a particular RPC.
541 type CallHdr struct {
542 // Host specifies the peer's host.
543 Host string
544
545 // Method specifies the operation to perform.
546 Method string
547
548 // RecvCompress specifies the compression algorithm applied on
549 // inbound messages.
550 RecvCompress string
551
552 // SendCompress specifies the compression algorithm applied on
553 // outbound message.
554 SendCompress string
555
556 // Creds specifies credentials.PerRPCCredentials for a call.
557 Creds credentials.PerRPCCredentials
558
559 // Flush indicates whether a new stream command should be sent
560 // to the peer without waiting for the first data. This is
561 // only a hint.
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.
565 Flush bool
566 }
567
568 // ClientTransport is the common interface for all gRPC client-side transport
569 // implementations.
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.
574 Close() error
575
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
579
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
583
584 // NewStream creates a Stream for an RPC.
585 NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error)
586
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)
592
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{}
599
600 // GoAway returns a channel that is closed when ClientTransport
601 // receives the draining signal from the server (e.g., GOAWAY frame in
602 // HTTP/2).
603 GoAway() <-chan struct{}
604
605 // GetGoAwayReason returns the reason why GoAway frame was received.
606 GetGoAwayReason() GoAwayReason
607 }
608
609 // ServerTransport is the common interface for all gRPC server-side transport
610 // implementations.
611 //
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)
617
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
621
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
625
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
629
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.
633 Close() error
634
635 // RemoteAddr returns the remote network address.
636 RemoteAddr() net.Addr
637
638 // Drain notifies the client this ServerTransport stops accepting new RPCs.
639 Drain()
640 }
641
642 // streamErrorf creates an StreamError with the specified error code and description.
643 func streamErrorf(c codes.Code, format string, a ...interface{}) StreamError {
644 return StreamError{
645 Code: c,
646 Desc: fmt.Sprintf(format, a...),
647 }
648 }
649
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...),
654 temp: temp,
655 err: e,
656 }
657 }
658
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 {
662 Desc string
663 temp bool
664 err error
665 }
666
667 func (e ConnectionError) Error() string {
668 return fmt.Sprintf("connection error: desc = %q", e.Desc)
669 }
670
671 // Temporary indicates if this connection error is temporary or fatal.
672 func (e ConnectionError) Temporary() bool {
673 return e.temp
674 }
675
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.
680 if e.err == nil {
681 return e
682 }
683 return e.err
684 }
685
686 var (
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")
692 )
693
694 // TODO: See if we can replace StreamError with status package errors.
695
696 // StreamError is an error that only affects one stream within a connection.
697 type StreamError struct {
698 Code codes.Code
699 Desc string
700 }
701
702 func (e StreamError) Error() string {
703 return fmt.Sprintf("stream error: code = %s desc = %q", e.Code, e.Desc)
704 }
705
706 // wait blocks until it can receive from one of the provided contexts or channels
707 func wait(ctx, tctx context.Context, done, goAway <-chan struct{}, proceed <-chan int) (int, error) {
708 select {
709 case <-ctx.Done():
710 return 0, ContextErr(ctx.Err())
711 case <-done:
712 return 0, io.EOF
713 case <-goAway:
714 return 0, ErrStreamDrain
715 case <-tctx.Done():
716 return 0, ErrConnClosing
717 case i := <-proceed:
718 return i, nil
719 }
720 }
721
722 // ContextErr converts the error from context package into a StreamError.
723 func ContextErr(err error) StreamError {
724 switch err {
725 case context.DeadlineExceeded, stdctx.DeadlineExceeded:
726 return streamErrorf(codes.DeadlineExceeded, "%v", err)
727 case context.Canceled, stdctx.Canceled:
728 return streamErrorf(codes.Canceled, "%v", err)
729 }
730 return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err)
731 }
732
733 // GoAwayReason contains the reason for the GoAway frame received.
734 type GoAwayReason uint8
735
736 const (
737 // Invalid indicates that no GoAway frame is received.
738 Invalid GoAwayReason = 0
739 // NoReason is the default value when GoAway frame is received.
740 NoReason GoAwayReason = 1
741 // TooManyPings indicates that a GoAway frame with ErrCodeEnhanceYourCalm
742 // was received and that the debug data said "too_many_pings".
743 TooManyPings GoAwayReason = 2
744 )
745
746 // loopyWriter is run in a separate go routine. It is the single code path that will
747 // write data on wire.
748 func loopyWriter(ctx context.Context, cbuf *controlBuffer, handler func(item) error) {
749 for {
750 select {
751 case i := <-cbuf.get():
752 cbuf.load()
753 if err := handler(i); err != nil {
754 return
755 }
756 case <-ctx.Done():
757 return
758 }
759 hasData:
760 for {
761 select {
762 case i := <-cbuf.get():
763 cbuf.load()
764 if err := handler(i); err != nil {
765 return
766 }
767 case <-ctx.Done():
768 return
769 default:
770 if err := handler(&flushIO{}); err != nil {
771 return
772 }
773 break hasData
774 }
775 }
776 }
777 }