transport.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. "errors"
  41. "fmt"
  42. "io"
  43. "net"
  44. "sync"
  45. "time"
  46. "golang.org/x/net/context"
  47. "golang.org/x/net/trace"
  48. "google.golang.org/grpc/codes"
  49. "google.golang.org/grpc/credentials"
  50. "google.golang.org/grpc/metadata"
  51. )
  52. // recvMsg represents the received msg from the transport. All transport
  53. // protocol specific info has been removed.
  54. type recvMsg struct {
  55. data []byte
  56. // nil: received some data
  57. // io.EOF: stream is completed. data is nil.
  58. // other non-nil error: transport failure. data is nil.
  59. err error
  60. }
  61. func (*recvMsg) item() {}
  62. // All items in an out of a recvBuffer should be the same type.
  63. type item interface {
  64. item()
  65. }
  66. // recvBuffer is an unbounded channel of item.
  67. type recvBuffer struct {
  68. c chan item
  69. mu sync.Mutex
  70. backlog []item
  71. }
  72. func newRecvBuffer() *recvBuffer {
  73. b := &recvBuffer{
  74. c: make(chan item, 1),
  75. }
  76. return b
  77. }
  78. func (b *recvBuffer) put(r item) {
  79. b.mu.Lock()
  80. defer b.mu.Unlock()
  81. if len(b.backlog) == 0 {
  82. select {
  83. case b.c <- r:
  84. return
  85. default:
  86. }
  87. }
  88. b.backlog = append(b.backlog, r)
  89. }
  90. func (b *recvBuffer) load() {
  91. b.mu.Lock()
  92. defer b.mu.Unlock()
  93. if len(b.backlog) > 0 {
  94. select {
  95. case b.c <- b.backlog[0]:
  96. b.backlog = b.backlog[1:]
  97. default:
  98. }
  99. }
  100. }
  101. // get returns the channel that receives an item in the buffer.
  102. //
  103. // Upon receipt of an item, the caller should call load to send another
  104. // item onto the channel if there is any.
  105. func (b *recvBuffer) get() <-chan item {
  106. return b.c
  107. }
  108. // recvBufferReader implements io.Reader interface to read the data from
  109. // recvBuffer.
  110. type recvBufferReader struct {
  111. ctx context.Context
  112. recv *recvBuffer
  113. last *bytes.Reader // Stores the remaining data in the previous calls.
  114. err error
  115. }
  116. // Read reads the next len(p) bytes from last. If last is drained, it tries to
  117. // read additional data from recv. It blocks if there no additional data available
  118. // in recv. If Read returns any non-nil error, it will continue to return that error.
  119. func (r *recvBufferReader) Read(p []byte) (n int, err error) {
  120. if r.err != nil {
  121. return 0, r.err
  122. }
  123. defer func() { r.err = err }()
  124. if r.last != nil && r.last.Len() > 0 {
  125. // Read remaining data left in last call.
  126. return r.last.Read(p)
  127. }
  128. select {
  129. case <-r.ctx.Done():
  130. return 0, ContextErr(r.ctx.Err())
  131. case i := <-r.recv.get():
  132. r.recv.load()
  133. m := i.(*recvMsg)
  134. if m.err != nil {
  135. return 0, m.err
  136. }
  137. r.last = bytes.NewReader(m.data)
  138. return r.last.Read(p)
  139. }
  140. }
  141. type streamState uint8
  142. const (
  143. streamActive streamState = iota
  144. streamWriteDone // EndStream sent
  145. streamReadDone // EndStream received
  146. streamDone // sendDone and recvDone or RSTStreamFrame is sent or received.
  147. )
  148. // Stream represents an RPC in the transport layer.
  149. type Stream struct {
  150. id uint32
  151. // nil for client side Stream.
  152. st ServerTransport
  153. // ctx is the associated context of the stream.
  154. ctx context.Context
  155. cancel context.CancelFunc
  156. // method records the associated RPC method of the stream.
  157. method string
  158. recvCompress string
  159. sendCompress string
  160. buf *recvBuffer
  161. dec io.Reader
  162. fc *inFlow
  163. recvQuota uint32
  164. // The accumulated inbound quota pending for window update.
  165. updateQuota uint32
  166. // The handler to control the window update procedure for both this
  167. // particular stream and the associated transport.
  168. windowHandler func(int)
  169. sendQuotaPool *quotaPool
  170. // Close headerChan to indicate the end of reception of header metadata.
  171. headerChan chan struct{}
  172. // header caches the received header metadata.
  173. header metadata.MD
  174. // The key-value map of trailer metadata.
  175. trailer metadata.MD
  176. mu sync.RWMutex // guard the following
  177. // headerOK becomes true from the first header is about to send.
  178. headerOk bool
  179. state streamState
  180. // true iff headerChan is closed. Used to avoid closing headerChan
  181. // multiple times.
  182. headerDone bool
  183. // the status received from the server.
  184. statusCode codes.Code
  185. statusDesc string
  186. }
  187. // RecvCompress returns the compression algorithm applied to the inbound
  188. // message. It is empty string if there is no compression applied.
  189. func (s *Stream) RecvCompress() string {
  190. return s.recvCompress
  191. }
  192. // SetSendCompress sets the compression algorithm to the stream.
  193. func (s *Stream) SetSendCompress(str string) {
  194. s.sendCompress = str
  195. }
  196. // Header acquires the key-value pairs of header metadata once it
  197. // is available. It blocks until i) the metadata is ready or ii) there is no
  198. // header metadata or iii) the stream is cancelled/expired.
  199. func (s *Stream) Header() (metadata.MD, error) {
  200. select {
  201. case <-s.ctx.Done():
  202. return nil, ContextErr(s.ctx.Err())
  203. case <-s.headerChan:
  204. return s.header.Copy(), nil
  205. }
  206. }
  207. // Trailer returns the cached trailer metedata. Note that if it is not called
  208. // after the entire stream is done, it could return an empty MD. Client
  209. // side only.
  210. func (s *Stream) Trailer() metadata.MD {
  211. s.mu.RLock()
  212. defer s.mu.RUnlock()
  213. return s.trailer.Copy()
  214. }
  215. // ServerTransport returns the underlying ServerTransport for the stream.
  216. // The client side stream always returns nil.
  217. func (s *Stream) ServerTransport() ServerTransport {
  218. return s.st
  219. }
  220. // Context returns the context of the stream.
  221. func (s *Stream) Context() context.Context {
  222. return s.ctx
  223. }
  224. // TraceContext recreates the context of s with a trace.Trace.
  225. func (s *Stream) TraceContext(tr trace.Trace) {
  226. s.ctx = trace.NewContext(s.ctx, tr)
  227. }
  228. // Method returns the method for the stream.
  229. func (s *Stream) Method() string {
  230. return s.method
  231. }
  232. // StatusCode returns statusCode received from the server.
  233. func (s *Stream) StatusCode() codes.Code {
  234. return s.statusCode
  235. }
  236. // StatusDesc returns statusDesc received from the server.
  237. func (s *Stream) StatusDesc() string {
  238. return s.statusDesc
  239. }
  240. // ErrIllegalTrailerSet indicates that the trailer has already been set or it
  241. // is too late to do so.
  242. var ErrIllegalTrailerSet = errors.New("transport: trailer has been set")
  243. // SetTrailer sets the trailer metadata which will be sent with the RPC status
  244. // by the server. This can only be called at most once. Server side only.
  245. func (s *Stream) SetTrailer(md metadata.MD) error {
  246. s.mu.Lock()
  247. defer s.mu.Unlock()
  248. if s.trailer != nil {
  249. return ErrIllegalTrailerSet
  250. }
  251. s.trailer = md.Copy()
  252. return nil
  253. }
  254. func (s *Stream) write(m recvMsg) {
  255. s.buf.put(&m)
  256. }
  257. // Read reads all the data available for this Stream from the transport and
  258. // passes them into the decoder, which converts them into a gRPC message stream.
  259. // The error is io.EOF when the stream is done or another non-nil error if
  260. // the stream broke.
  261. func (s *Stream) Read(p []byte) (n int, err error) {
  262. n, err = s.dec.Read(p)
  263. if err != nil {
  264. return
  265. }
  266. s.windowHandler(n)
  267. return
  268. }
  269. // The key to save transport.Stream in the context.
  270. type streamKey struct{}
  271. // newContextWithStream creates a new context from ctx and attaches stream
  272. // to it.
  273. func newContextWithStream(ctx context.Context, stream *Stream) context.Context {
  274. return context.WithValue(ctx, streamKey{}, stream)
  275. }
  276. // StreamFromContext returns the stream saved in ctx.
  277. func StreamFromContext(ctx context.Context) (s *Stream, ok bool) {
  278. s, ok = ctx.Value(streamKey{}).(*Stream)
  279. return
  280. }
  281. // state of transport
  282. type transportState int
  283. const (
  284. reachable transportState = iota
  285. unreachable
  286. closing
  287. )
  288. // NewServerTransport creates a ServerTransport with conn or non-nil error
  289. // if it fails.
  290. func NewServerTransport(protocol string, conn net.Conn, maxStreams uint32, authInfo credentials.AuthInfo) (ServerTransport, error) {
  291. return newHTTP2Server(conn, maxStreams, authInfo)
  292. }
  293. // ConnectOptions covers all relevant options for dialing a server.
  294. type ConnectOptions struct {
  295. // UserAgent is the application user agent.
  296. UserAgent string
  297. // Dialer specifies how to dial a network address.
  298. Dialer func(string, time.Duration) (net.Conn, error)
  299. // AuthOptions stores the credentials required to setup a client connection and/or issue RPCs.
  300. AuthOptions []credentials.Credentials
  301. // Timeout specifies the timeout for dialing a client connection.
  302. Timeout time.Duration
  303. }
  304. // NewClientTransport establishes the transport with the required ConnectOptions
  305. // and returns it to the caller.
  306. func NewClientTransport(target string, opts *ConnectOptions) (ClientTransport, error) {
  307. return newHTTP2Client(target, opts)
  308. }
  309. // Options provides additional hints and information for message
  310. // transmission.
  311. type Options struct {
  312. // Last indicates whether this write is the last piece for
  313. // this stream.
  314. Last bool
  315. // Delay is a hint to the transport implementation for whether
  316. // the data could be buffered for a batching write. The
  317. // Transport implementation may ignore the hint.
  318. Delay bool
  319. }
  320. // CallHdr carries the information of a particular RPC.
  321. type CallHdr struct {
  322. // Host specifies the peer's host.
  323. Host string
  324. // Method specifies the operation to perform.
  325. Method string
  326. // RecvCompress specifies the compression algorithm applied on
  327. // inbound messages.
  328. RecvCompress string
  329. // SendCompress specifies the compression algorithm applied on
  330. // outbound message.
  331. SendCompress string
  332. // Flush indicates whether a new stream command should be sent
  333. // to the peer without waiting for the first data. This is
  334. // only a hint. The transport may modify the flush decision
  335. // for performance purposes.
  336. Flush bool
  337. }
  338. // ClientTransport is the common interface for all gRPC client-side transport
  339. // implementations.
  340. type ClientTransport interface {
  341. // Close tears down this transport. Once it returns, the transport
  342. // should not be accessed any more. The caller must make sure this
  343. // is called only once.
  344. Close() error
  345. // Write sends the data for the given stream. A nil stream indicates
  346. // the write is to be performed on the transport as a whole.
  347. Write(s *Stream, data []byte, opts *Options) error
  348. // NewStream creates a Stream for an RPC.
  349. NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error)
  350. // CloseStream clears the footprint of a stream when the stream is
  351. // not needed any more. The err indicates the error incurred when
  352. // CloseStream is called. Must be called when a stream is finished
  353. // unless the associated transport is closing.
  354. CloseStream(stream *Stream, err error)
  355. // Error returns a channel that is closed when some I/O error
  356. // happens. Typically the caller should have a goroutine to monitor
  357. // this in order to take action (e.g., close the current transport
  358. // and create a new one) in error case. It should not return nil
  359. // once the transport is initiated.
  360. Error() <-chan struct{}
  361. }
  362. // ServerTransport is the common interface for all gRPC server-side transport
  363. // implementations.
  364. //
  365. // Methods may be called concurrently from multiple goroutines, but
  366. // Write methods for a given Stream will be called serially.
  367. type ServerTransport interface {
  368. // HandleStreams receives incoming streams using the given handler.
  369. HandleStreams(func(*Stream))
  370. // WriteHeader sends the header metadata for the given stream.
  371. // WriteHeader may not be called on all streams.
  372. WriteHeader(s *Stream, md metadata.MD) error
  373. // Write sends the data for the given stream.
  374. // Write may not be called on all streams.
  375. Write(s *Stream, data []byte, opts *Options) error
  376. // WriteStatus sends the status of a stream to the client.
  377. // WriteStatus is the final call made on a stream and always
  378. // occurs.
  379. WriteStatus(s *Stream, statusCode codes.Code, statusDesc string) error
  380. // Close tears down the transport. Once it is called, the transport
  381. // should not be accessed any more. All the pending streams and their
  382. // handlers will be terminated asynchronously.
  383. Close() error
  384. // RemoteAddr returns the remote network address.
  385. RemoteAddr() net.Addr
  386. }
  387. // StreamErrorf creates an StreamError with the specified error code and description.
  388. func StreamErrorf(c codes.Code, format string, a ...interface{}) StreamError {
  389. return StreamError{
  390. Code: c,
  391. Desc: fmt.Sprintf(format, a...),
  392. }
  393. }
  394. // ConnectionErrorf creates an ConnectionError with the specified error description.
  395. func ConnectionErrorf(format string, a ...interface{}) ConnectionError {
  396. return ConnectionError{
  397. Desc: fmt.Sprintf(format, a...),
  398. }
  399. }
  400. // ConnectionError is an error that results in the termination of the
  401. // entire connection and the retry of all the active streams.
  402. type ConnectionError struct {
  403. Desc string
  404. }
  405. func (e ConnectionError) Error() string {
  406. return fmt.Sprintf("connection error: desc = %q", e.Desc)
  407. }
  408. // Define some common ConnectionErrors.
  409. var ErrConnClosing = ConnectionError{Desc: "transport is closing"}
  410. // StreamError is an error that only affects one stream within a connection.
  411. type StreamError struct {
  412. Code codes.Code
  413. Desc string
  414. }
  415. func (e StreamError) Error() string {
  416. return fmt.Sprintf("stream error: code = %d desc = %q", e.Code, e.Desc)
  417. }
  418. // ContextErr converts the error from context package into a StreamError.
  419. func ContextErr(err error) StreamError {
  420. switch err {
  421. case context.DeadlineExceeded:
  422. return StreamErrorf(codes.DeadlineExceeded, "%v", err)
  423. case context.Canceled:
  424. return StreamErrorf(codes.Canceled, "%v", err)
  425. }
  426. panic(fmt.Sprintf("Unexpected error from context packet: %v", err))
  427. }
  428. // wait blocks until it can receive from ctx.Done, closing, or proceed.
  429. // If it receives from ctx.Done, it returns 0, the StreamError for ctx.Err.
  430. // If it receives from closing, it returns 0, ErrConnClosing.
  431. // If it receives from proceed, it returns the received integer, nil.
  432. func wait(ctx context.Context, closing <-chan struct{}, proceed <-chan int) (int, error) {
  433. select {
  434. case <-ctx.Done():
  435. return 0, ContextErr(ctx.Err())
  436. case <-closing:
  437. return 0, ErrConnClosing
  438. case i := <-proceed:
  439. return i, nil
  440. }
  441. }