transport.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /*
  2. *
  3. * Copyright 2014, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. /*
  34. Package transport defines and implements message oriented communication channel
  35. to complete various transactions (e.g., an RPC).
  36. */
  37. package transport // import "google.golang.org/grpc/transport"
  38. import (
  39. "bytes"
  40. "fmt"
  41. "io"
  42. "net"
  43. "sync"
  44. "golang.org/x/net/context"
  45. "golang.org/x/net/trace"
  46. "google.golang.org/grpc/codes"
  47. "google.golang.org/grpc/credentials"
  48. "google.golang.org/grpc/metadata"
  49. )
  50. // recvMsg represents the received msg from the transport. All transport
  51. // protocol specific info has been removed.
  52. type recvMsg struct {
  53. data []byte
  54. // nil: received some data
  55. // io.EOF: stream is completed. data is nil.
  56. // other non-nil error: transport failure. data is nil.
  57. err error
  58. }
  59. func (*recvMsg) item() {}
  60. // All items in an out of a recvBuffer should be the same type.
  61. type item interface {
  62. item()
  63. }
  64. // recvBuffer is an unbounded channel of item.
  65. type recvBuffer struct {
  66. c chan item
  67. mu sync.Mutex
  68. backlog []item
  69. }
  70. func newRecvBuffer() *recvBuffer {
  71. b := &recvBuffer{
  72. c: make(chan item, 1),
  73. }
  74. return b
  75. }
  76. func (b *recvBuffer) put(r item) {
  77. b.mu.Lock()
  78. defer b.mu.Unlock()
  79. if len(b.backlog) == 0 {
  80. select {
  81. case b.c <- r:
  82. return
  83. default:
  84. }
  85. }
  86. b.backlog = append(b.backlog, r)
  87. }
  88. func (b *recvBuffer) load() {
  89. b.mu.Lock()
  90. defer b.mu.Unlock()
  91. if len(b.backlog) > 0 {
  92. select {
  93. case b.c <- b.backlog[0]:
  94. b.backlog = b.backlog[1:]
  95. default:
  96. }
  97. }
  98. }
  99. // get returns the channel that receives an item in the buffer.
  100. //
  101. // Upon receipt of an item, the caller should call load to send another
  102. // item onto the channel if there is any.
  103. func (b *recvBuffer) get() <-chan item {
  104. return b.c
  105. }
  106. // recvBufferReader implements io.Reader interface to read the data from
  107. // recvBuffer.
  108. type recvBufferReader struct {
  109. ctx context.Context
  110. goAway chan struct{}
  111. recv *recvBuffer
  112. last *bytes.Reader // Stores the remaining data in the previous calls.
  113. err error
  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. defer func() { r.err = err }()
  123. if r.last != nil && r.last.Len() > 0 {
  124. // Read remaining data left in last call.
  125. return r.last.Read(p)
  126. }
  127. select {
  128. case <-r.ctx.Done():
  129. return 0, ContextErr(r.ctx.Err())
  130. case <-r.goAway:
  131. return 0, ErrStreamDrain
  132. case i := <-r.recv.get():
  133. r.recv.load()
  134. m := i.(*recvMsg)
  135. if m.err != nil {
  136. return 0, m.err
  137. }
  138. r.last = bytes.NewReader(m.data)
  139. return r.last.Read(p)
  140. }
  141. }
  142. type streamState uint8
  143. const (
  144. streamActive streamState = iota
  145. streamWriteDone // EndStream sent
  146. streamReadDone // EndStream received
  147. streamDone // the entire stream is finished.
  148. )
  149. // Stream represents an RPC in the transport layer.
  150. type Stream struct {
  151. id uint32
  152. // nil for client side Stream.
  153. st ServerTransport
  154. // ctx is the associated context of the stream.
  155. ctx context.Context
  156. // cancel is always nil for client side Stream.
  157. cancel context.CancelFunc
  158. // done is closed when the final status arrives.
  159. done chan struct{}
  160. // goAway is closed when the server sent GoAways signal before this stream was initiated.
  161. goAway chan struct{}
  162. // method records the associated RPC method of the stream.
  163. method string
  164. recvCompress string
  165. sendCompress string
  166. buf *recvBuffer
  167. dec io.Reader
  168. fc *inFlow
  169. recvQuota uint32
  170. // The accumulated inbound quota pending for window update.
  171. updateQuota uint32
  172. // The handler to control the window update procedure for both this
  173. // particular stream and the associated transport.
  174. windowHandler func(int)
  175. sendQuotaPool *quotaPool
  176. // Close headerChan to indicate the end of reception of header metadata.
  177. headerChan chan struct{}
  178. // header caches the received header metadata.
  179. header metadata.MD
  180. // The key-value map of trailer metadata.
  181. trailer metadata.MD
  182. mu sync.RWMutex // guard the following
  183. // headerOK becomes true from the first header is about to send.
  184. headerOk bool
  185. state streamState
  186. // true iff headerChan is closed. Used to avoid closing headerChan
  187. // multiple times.
  188. headerDone bool
  189. // the status received from the server.
  190. statusCode codes.Code
  191. statusDesc string
  192. }
  193. // RecvCompress returns the compression algorithm applied to the inbound
  194. // message. It is empty string if there is no compression applied.
  195. func (s *Stream) RecvCompress() string {
  196. return s.recvCompress
  197. }
  198. // SetSendCompress sets the compression algorithm to the stream.
  199. func (s *Stream) SetSendCompress(str string) {
  200. s.sendCompress = str
  201. }
  202. // Done returns a chanel which is closed when it receives the final status
  203. // from the server.
  204. func (s *Stream) Done() <-chan struct{} {
  205. return s.done
  206. }
  207. // GoAway returns a channel which is closed when the server sent GoAways signal
  208. // before this stream was initiated.
  209. func (s *Stream) GoAway() <-chan struct{} {
  210. return s.goAway
  211. }
  212. // Header acquires the key-value pairs of header metadata once it
  213. // is available. It blocks until i) the metadata is ready or ii) there is no
  214. // header metadata or iii) the stream is cancelled/expired.
  215. func (s *Stream) Header() (metadata.MD, error) {
  216. select {
  217. case <-s.ctx.Done():
  218. return nil, ContextErr(s.ctx.Err())
  219. case <-s.goAway:
  220. return nil, ErrStreamDrain
  221. case <-s.headerChan:
  222. return s.header.Copy(), nil
  223. }
  224. }
  225. // Trailer returns the cached trailer metedata. Note that if it is not called
  226. // after the entire stream is done, it could return an empty MD. Client
  227. // side only.
  228. func (s *Stream) Trailer() metadata.MD {
  229. s.mu.RLock()
  230. defer s.mu.RUnlock()
  231. return s.trailer.Copy()
  232. }
  233. // ServerTransport returns the underlying ServerTransport for the stream.
  234. // The client side stream always returns nil.
  235. func (s *Stream) ServerTransport() ServerTransport {
  236. return s.st
  237. }
  238. // Context returns the context of the stream.
  239. func (s *Stream) Context() context.Context {
  240. return s.ctx
  241. }
  242. // TraceContext recreates the context of s with a trace.Trace.
  243. func (s *Stream) TraceContext(tr trace.Trace) {
  244. s.ctx = trace.NewContext(s.ctx, tr)
  245. }
  246. // Method returns the method for the stream.
  247. func (s *Stream) Method() string {
  248. return s.method
  249. }
  250. // StatusCode returns statusCode received from the server.
  251. func (s *Stream) StatusCode() codes.Code {
  252. return s.statusCode
  253. }
  254. // StatusDesc returns statusDesc received from the server.
  255. func (s *Stream) StatusDesc() string {
  256. return s.statusDesc
  257. }
  258. // SetHeader sets the header metadata. This can be called multiple times.
  259. // Server side only.
  260. func (s *Stream) SetHeader(md metadata.MD) error {
  261. s.mu.Lock()
  262. defer s.mu.Unlock()
  263. if s.headerOk || s.state == streamDone {
  264. return ErrIllegalHeaderWrite
  265. }
  266. if md.Len() == 0 {
  267. return nil
  268. }
  269. s.header = metadata.Join(s.header, md)
  270. return nil
  271. }
  272. // SetTrailer sets the trailer metadata which will be sent with the RPC status
  273. // by the server. This can be called multiple times. Server side only.
  274. func (s *Stream) SetTrailer(md metadata.MD) error {
  275. if md.Len() == 0 {
  276. return nil
  277. }
  278. s.mu.Lock()
  279. defer s.mu.Unlock()
  280. s.trailer = metadata.Join(s.trailer, md)
  281. return nil
  282. }
  283. func (s *Stream) write(m recvMsg) {
  284. s.buf.put(&m)
  285. }
  286. // Read reads all the data available for this Stream from the transport and
  287. // passes them into the decoder, which converts them into a gRPC message stream.
  288. // The error is io.EOF when the stream is done or another non-nil error if
  289. // the stream broke.
  290. func (s *Stream) Read(p []byte) (n int, err error) {
  291. n, err = s.dec.Read(p)
  292. if err != nil {
  293. return
  294. }
  295. s.windowHandler(n)
  296. return
  297. }
  298. // The key to save transport.Stream in the context.
  299. type streamKey struct{}
  300. // newContextWithStream creates a new context from ctx and attaches stream
  301. // to it.
  302. func newContextWithStream(ctx context.Context, stream *Stream) context.Context {
  303. return context.WithValue(ctx, streamKey{}, stream)
  304. }
  305. // StreamFromContext returns the stream saved in ctx.
  306. func StreamFromContext(ctx context.Context) (s *Stream, ok bool) {
  307. s, ok = ctx.Value(streamKey{}).(*Stream)
  308. return
  309. }
  310. // state of transport
  311. type transportState int
  312. const (
  313. reachable transportState = iota
  314. unreachable
  315. closing
  316. draining
  317. )
  318. // NewServerTransport creates a ServerTransport with conn or non-nil error
  319. // if it fails.
  320. func NewServerTransport(protocol string, conn net.Conn, maxStreams uint32, authInfo credentials.AuthInfo) (ServerTransport, error) {
  321. return newHTTP2Server(conn, maxStreams, authInfo)
  322. }
  323. // ConnectOptions covers all relevant options for communicating with the server.
  324. type ConnectOptions struct {
  325. // UserAgent is the application user agent.
  326. UserAgent string
  327. // Dialer specifies how to dial a network address.
  328. Dialer func(context.Context, string) (net.Conn, error)
  329. // PerRPCCredentials stores the PerRPCCredentials required to issue RPCs.
  330. PerRPCCredentials []credentials.PerRPCCredentials
  331. // TransportCredentials stores the Authenticator required to setup a client connection.
  332. TransportCredentials credentials.TransportCredentials
  333. }
  334. // TargetInfo contains the information of the target such as network address and metadata.
  335. type TargetInfo struct {
  336. Addr string
  337. Metadata interface{}
  338. }
  339. // NewClientTransport establishes the transport with the required ConnectOptions
  340. // and returns it to the caller.
  341. func NewClientTransport(ctx context.Context, target TargetInfo, opts ConnectOptions) (ClientTransport, error) {
  342. return newHTTP2Client(ctx, target, opts)
  343. }
  344. // Options provides additional hints and information for message
  345. // transmission.
  346. type Options struct {
  347. // Last indicates whether this write is the last piece for
  348. // this stream.
  349. Last bool
  350. // Delay is a hint to the transport implementation for whether
  351. // the data could be buffered for a batching write. The
  352. // Transport implementation may ignore the hint.
  353. Delay bool
  354. }
  355. // CallHdr carries the information of a particular RPC.
  356. type CallHdr struct {
  357. // Host specifies the peer's host.
  358. Host string
  359. // Method specifies the operation to perform.
  360. Method string
  361. // RecvCompress specifies the compression algorithm applied on
  362. // inbound messages.
  363. RecvCompress string
  364. // SendCompress specifies the compression algorithm applied on
  365. // outbound message.
  366. SendCompress string
  367. // Flush indicates whether a new stream command should be sent
  368. // to the peer without waiting for the first data. This is
  369. // only a hint. The transport may modify the flush decision
  370. // for performance purposes.
  371. Flush bool
  372. }
  373. // ClientTransport is the common interface for all gRPC client-side transport
  374. // implementations.
  375. type ClientTransport interface {
  376. // Close tears down this transport. Once it returns, the transport
  377. // should not be accessed any more. The caller must make sure this
  378. // is called only once.
  379. Close() error
  380. // GracefulClose starts to tear down the transport. It stops accepting
  381. // new RPCs and wait the completion of the pending RPCs.
  382. GracefulClose() error
  383. // Write sends the data for the given stream. A nil stream indicates
  384. // the write is to be performed on the transport as a whole.
  385. Write(s *Stream, data []byte, opts *Options) error
  386. // NewStream creates a Stream for an RPC.
  387. NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error)
  388. // CloseStream clears the footprint of a stream when the stream is
  389. // not needed any more. The err indicates the error incurred when
  390. // CloseStream is called. Must be called when a stream is finished
  391. // unless the associated transport is closing.
  392. CloseStream(stream *Stream, err error)
  393. // Error returns a channel that is closed when some I/O error
  394. // happens. Typically the caller should have a goroutine to monitor
  395. // this in order to take action (e.g., close the current transport
  396. // and create a new one) in error case. It should not return nil
  397. // once the transport is initiated.
  398. Error() <-chan struct{}
  399. // GoAway returns a channel that is closed when ClientTranspor
  400. // receives the draining signal from the server (e.g., GOAWAY frame in
  401. // HTTP/2).
  402. GoAway() <-chan struct{}
  403. }
  404. // ServerTransport is the common interface for all gRPC server-side transport
  405. // implementations.
  406. //
  407. // Methods may be called concurrently from multiple goroutines, but
  408. // Write methods for a given Stream will be called serially.
  409. type ServerTransport interface {
  410. // HandleStreams receives incoming streams using the given handler.
  411. HandleStreams(func(*Stream))
  412. // WriteHeader sends the header metadata for the given stream.
  413. // WriteHeader may not be called on all streams.
  414. WriteHeader(s *Stream, md metadata.MD) error
  415. // Write sends the data for the given stream.
  416. // Write may not be called on all streams.
  417. Write(s *Stream, data []byte, opts *Options) error
  418. // WriteStatus sends the status of a stream to the client.
  419. // WriteStatus is the final call made on a stream and always
  420. // occurs.
  421. WriteStatus(s *Stream, statusCode codes.Code, statusDesc string) error
  422. // Close tears down the transport. Once it is called, the transport
  423. // should not be accessed any more. All the pending streams and their
  424. // handlers will be terminated asynchronously.
  425. Close() error
  426. // RemoteAddr returns the remote network address.
  427. RemoteAddr() net.Addr
  428. // Drain notifies the client this ServerTransport stops accepting new RPCs.
  429. Drain()
  430. }
  431. // streamErrorf creates an StreamError with the specified error code and description.
  432. func streamErrorf(c codes.Code, format string, a ...interface{}) StreamError {
  433. return StreamError{
  434. Code: c,
  435. Desc: fmt.Sprintf(format, a...),
  436. }
  437. }
  438. // connectionErrorf creates an ConnectionError with the specified error description.
  439. func connectionErrorf(temp bool, e error, format string, a ...interface{}) ConnectionError {
  440. return ConnectionError{
  441. Desc: fmt.Sprintf(format, a...),
  442. temp: temp,
  443. err: e,
  444. }
  445. }
  446. // ConnectionError is an error that results in the termination of the
  447. // entire connection and the retry of all the active streams.
  448. type ConnectionError struct {
  449. Desc string
  450. temp bool
  451. err error
  452. }
  453. func (e ConnectionError) Error() string {
  454. return fmt.Sprintf("connection error: desc = %q", e.Desc)
  455. }
  456. // Temporary indicates if this connection error is temporary or fatal.
  457. func (e ConnectionError) Temporary() bool {
  458. return e.temp
  459. }
  460. // Origin returns the original error of this connection error.
  461. func (e ConnectionError) Origin() error {
  462. // Never return nil error here.
  463. // If the original error is nil, return itself.
  464. if e.err == nil {
  465. return e
  466. }
  467. return e.err
  468. }
  469. var (
  470. // ErrConnClosing indicates that the transport is closing.
  471. ErrConnClosing = connectionErrorf(true, nil, "transport is closing")
  472. // ErrStreamDrain indicates that the stream is rejected by the server because
  473. // the server stops accepting new RPCs.
  474. ErrStreamDrain = streamErrorf(codes.Unavailable, "the server stops accepting new RPCs")
  475. )
  476. // StreamError is an error that only affects one stream within a connection.
  477. type StreamError struct {
  478. Code codes.Code
  479. Desc string
  480. }
  481. func (e StreamError) Error() string {
  482. return fmt.Sprintf("stream error: code = %d desc = %q", e.Code, e.Desc)
  483. }
  484. // ContextErr converts the error from context package into a StreamError.
  485. func ContextErr(err error) StreamError {
  486. switch err {
  487. case context.DeadlineExceeded:
  488. return streamErrorf(codes.DeadlineExceeded, "%v", err)
  489. case context.Canceled:
  490. return streamErrorf(codes.Canceled, "%v", err)
  491. }
  492. panic(fmt.Sprintf("Unexpected error from context packet: %v", err))
  493. }
  494. // wait blocks until it can receive from ctx.Done, closing, or proceed.
  495. // If it receives from ctx.Done, it returns 0, the StreamError for ctx.Err.
  496. // If it receives from done, it returns 0, io.EOF if ctx is not done; otherwise
  497. // it return the StreamError for ctx.Err.
  498. // If it receives from goAway, it returns 0, ErrStreamDrain.
  499. // If it receives from closing, it returns 0, ErrConnClosing.
  500. // If it receives from proceed, it returns the received integer, nil.
  501. func wait(ctx context.Context, done, goAway, closing <-chan struct{}, proceed <-chan int) (int, error) {
  502. select {
  503. case <-ctx.Done():
  504. return 0, ContextErr(ctx.Err())
  505. case <-done:
  506. // User cancellation has precedence.
  507. select {
  508. case <-ctx.Done():
  509. return 0, ContextErr(ctx.Err())
  510. default:
  511. }
  512. return 0, io.EOF
  513. case <-goAway:
  514. return 0, ErrStreamDrain
  515. case <-closing:
  516. return 0, ErrConnClosing
  517. case i := <-proceed:
  518. return i, nil
  519. }
  520. }