transport.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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. // Package transport defines and implements message oriented communication
  19. // channel to complete various transactions (e.g., an RPC). It is meant for
  20. // grpc-internal usage and is not intended to be imported directly by users.
  21. package transport
  22. import (
  23. "bytes"
  24. "context"
  25. "errors"
  26. "fmt"
  27. "io"
  28. "net"
  29. "sync"
  30. "sync/atomic"
  31. "google.golang.org/grpc/codes"
  32. "google.golang.org/grpc/credentials"
  33. "google.golang.org/grpc/keepalive"
  34. "google.golang.org/grpc/metadata"
  35. "google.golang.org/grpc/resolver"
  36. "google.golang.org/grpc/stats"
  37. "google.golang.org/grpc/status"
  38. "google.golang.org/grpc/tap"
  39. )
  40. const logLevel = 2
  41. type bufferPool struct {
  42. pool sync.Pool
  43. }
  44. func newBufferPool() *bufferPool {
  45. return &bufferPool{
  46. pool: sync.Pool{
  47. New: func() interface{} {
  48. return new(bytes.Buffer)
  49. },
  50. },
  51. }
  52. }
  53. func (p *bufferPool) get() *bytes.Buffer {
  54. return p.pool.Get().(*bytes.Buffer)
  55. }
  56. func (p *bufferPool) put(b *bytes.Buffer) {
  57. p.pool.Put(b)
  58. }
  59. // recvMsg represents the received msg from the transport. All transport
  60. // protocol specific info has been removed.
  61. type recvMsg struct {
  62. buffer *bytes.Buffer
  63. // nil: received some data
  64. // io.EOF: stream is completed. data is nil.
  65. // other non-nil error: transport failure. data is nil.
  66. err error
  67. }
  68. // recvBuffer is an unbounded channel of recvMsg structs.
  69. //
  70. // Note: recvBuffer differs from buffer.Unbounded only in the fact that it
  71. // holds a channel of recvMsg structs instead of objects implementing "item"
  72. // interface. recvBuffer is written to much more often and using strict recvMsg
  73. // structs helps avoid allocation in "recvBuffer.put"
  74. type recvBuffer struct {
  75. c chan recvMsg
  76. mu sync.Mutex
  77. backlog []recvMsg
  78. err error
  79. }
  80. func newRecvBuffer() *recvBuffer {
  81. b := &recvBuffer{
  82. c: make(chan recvMsg, 1),
  83. }
  84. return b
  85. }
  86. func (b *recvBuffer) put(r recvMsg) {
  87. b.mu.Lock()
  88. if b.err != nil {
  89. b.mu.Unlock()
  90. // An error had occurred earlier, don't accept more
  91. // data or errors.
  92. return
  93. }
  94. b.err = r.err
  95. if len(b.backlog) == 0 {
  96. select {
  97. case b.c <- r:
  98. b.mu.Unlock()
  99. return
  100. default:
  101. }
  102. }
  103. b.backlog = append(b.backlog, r)
  104. b.mu.Unlock()
  105. }
  106. func (b *recvBuffer) load() {
  107. b.mu.Lock()
  108. if len(b.backlog) > 0 {
  109. select {
  110. case b.c <- b.backlog[0]:
  111. b.backlog[0] = recvMsg{}
  112. b.backlog = b.backlog[1:]
  113. default:
  114. }
  115. }
  116. b.mu.Unlock()
  117. }
  118. // get returns the channel that receives a recvMsg in the buffer.
  119. //
  120. // Upon receipt of a recvMsg, the caller should call load to send another
  121. // recvMsg onto the channel if there is any.
  122. func (b *recvBuffer) get() <-chan recvMsg {
  123. return b.c
  124. }
  125. // recvBufferReader implements io.Reader interface to read the data from
  126. // recvBuffer.
  127. type recvBufferReader struct {
  128. closeStream func(error) // Closes the client transport stream with the given error and nil trailer metadata.
  129. ctx context.Context
  130. ctxDone <-chan struct{} // cache of ctx.Done() (for performance).
  131. recv *recvBuffer
  132. last *bytes.Buffer // Stores the remaining data in the previous calls.
  133. err error
  134. freeBuffer func(*bytes.Buffer)
  135. }
  136. // Read reads the next len(p) bytes from last. If last is drained, it tries to
  137. // read additional data from recv. It blocks if there no additional data available
  138. // in recv. If Read returns any non-nil error, it will continue to return that error.
  139. func (r *recvBufferReader) Read(p []byte) (n int, err error) {
  140. if r.err != nil {
  141. return 0, r.err
  142. }
  143. if r.last != nil {
  144. // Read remaining data left in last call.
  145. copied, _ := r.last.Read(p)
  146. if r.last.Len() == 0 {
  147. r.freeBuffer(r.last)
  148. r.last = nil
  149. }
  150. return copied, nil
  151. }
  152. if r.closeStream != nil {
  153. n, r.err = r.readClient(p)
  154. } else {
  155. n, r.err = r.read(p)
  156. }
  157. return n, r.err
  158. }
  159. func (r *recvBufferReader) read(p []byte) (n int, err error) {
  160. select {
  161. case <-r.ctxDone:
  162. return 0, ContextErr(r.ctx.Err())
  163. case m := <-r.recv.get():
  164. return r.readAdditional(m, p)
  165. }
  166. }
  167. func (r *recvBufferReader) readClient(p []byte) (n int, err error) {
  168. // If the context is canceled, then closes the stream with nil metadata.
  169. // closeStream writes its error parameter to r.recv as a recvMsg.
  170. // r.readAdditional acts on that message and returns the necessary error.
  171. select {
  172. case <-r.ctxDone:
  173. // Note that this adds the ctx error to the end of recv buffer, and
  174. // reads from the head. This will delay the error until recv buffer is
  175. // empty, thus will delay ctx cancellation in Recv().
  176. //
  177. // It's done this way to fix a race between ctx cancel and trailer. The
  178. // race was, stream.Recv() may return ctx error if ctxDone wins the
  179. // race, but stream.Trailer() may return a non-nil md because the stream
  180. // was not marked as done when trailer is received. This closeStream
  181. // call will mark stream as done, thus fix the race.
  182. //
  183. // TODO: delaying ctx error seems like a unnecessary side effect. What
  184. // we really want is to mark the stream as done, and return ctx error
  185. // faster.
  186. r.closeStream(ContextErr(r.ctx.Err()))
  187. m := <-r.recv.get()
  188. return r.readAdditional(m, p)
  189. case m := <-r.recv.get():
  190. return r.readAdditional(m, p)
  191. }
  192. }
  193. func (r *recvBufferReader) readAdditional(m recvMsg, p []byte) (n int, err error) {
  194. r.recv.load()
  195. if m.err != nil {
  196. return 0, m.err
  197. }
  198. copied, _ := m.buffer.Read(p)
  199. if m.buffer.Len() == 0 {
  200. r.freeBuffer(m.buffer)
  201. r.last = nil
  202. } else {
  203. r.last = m.buffer
  204. }
  205. return copied, nil
  206. }
  207. type streamState uint32
  208. const (
  209. streamActive streamState = iota
  210. streamWriteDone // EndStream sent
  211. streamReadDone // EndStream received
  212. streamDone // the entire stream is finished.
  213. )
  214. // Stream represents an RPC in the transport layer.
  215. type Stream struct {
  216. id uint32
  217. st ServerTransport // nil for client side Stream
  218. ct *http2Client // nil for server side Stream
  219. ctx context.Context // the associated context of the stream
  220. cancel context.CancelFunc // always nil for client side Stream
  221. done chan struct{} // closed at the end of stream to unblock writers. On the client side.
  222. ctxDone <-chan struct{} // same as done chan but for server side. Cache of ctx.Done() (for performance)
  223. method string // the associated RPC method of the stream
  224. recvCompress string
  225. sendCompress string
  226. buf *recvBuffer
  227. trReader io.Reader
  228. fc *inFlow
  229. wq *writeQuota
  230. // Callback to state application's intentions to read data. This
  231. // is used to adjust flow control, if needed.
  232. requestRead func(int)
  233. headerChan chan struct{} // closed to indicate the end of header metadata.
  234. headerChanClosed uint32 // set when headerChan is closed. Used to avoid closing headerChan multiple times.
  235. // headerValid indicates whether a valid header was received. Only
  236. // meaningful after headerChan is closed (always call waitOnHeader() before
  237. // reading its value). Not valid on server side.
  238. headerValid bool
  239. // hdrMu protects header and trailer metadata on the server-side.
  240. hdrMu sync.Mutex
  241. // On client side, header keeps the received header metadata.
  242. //
  243. // On server side, header keeps the header set by SetHeader(). The complete
  244. // header will merged into this after t.WriteHeader() is called.
  245. header metadata.MD
  246. trailer metadata.MD // the key-value map of trailer metadata.
  247. noHeaders bool // set if the client never received headers (set only after the stream is done).
  248. // On the server-side, headerSent is atomically set to 1 when the headers are sent out.
  249. headerSent uint32
  250. state streamState
  251. // On client-side it is the status error received from the server.
  252. // On server-side it is unused.
  253. status *status.Status
  254. bytesReceived uint32 // indicates whether any bytes have been received on this stream
  255. unprocessed uint32 // set if the server sends a refused stream or GOAWAY including this stream
  256. // contentSubtype is the content-subtype for requests.
  257. // this must be lowercase or the behavior is undefined.
  258. contentSubtype string
  259. }
  260. // isHeaderSent is only valid on the server-side.
  261. func (s *Stream) isHeaderSent() bool {
  262. return atomic.LoadUint32(&s.headerSent) == 1
  263. }
  264. // updateHeaderSent updates headerSent and returns true
  265. // if it was alreay set. It is valid only on server-side.
  266. func (s *Stream) updateHeaderSent() bool {
  267. return atomic.SwapUint32(&s.headerSent, 1) == 1
  268. }
  269. func (s *Stream) swapState(st streamState) streamState {
  270. return streamState(atomic.SwapUint32((*uint32)(&s.state), uint32(st)))
  271. }
  272. func (s *Stream) compareAndSwapState(oldState, newState streamState) bool {
  273. return atomic.CompareAndSwapUint32((*uint32)(&s.state), uint32(oldState), uint32(newState))
  274. }
  275. func (s *Stream) getState() streamState {
  276. return streamState(atomic.LoadUint32((*uint32)(&s.state)))
  277. }
  278. func (s *Stream) waitOnHeader() {
  279. if s.headerChan == nil {
  280. // On the server headerChan is always nil since a stream originates
  281. // only after having received headers.
  282. return
  283. }
  284. select {
  285. case <-s.ctx.Done():
  286. // Close the stream to prevent headers/trailers from changing after
  287. // this function returns.
  288. s.ct.CloseStream(s, ContextErr(s.ctx.Err()))
  289. // headerChan could possibly not be closed yet if closeStream raced
  290. // with operateHeaders; wait until it is closed explicitly here.
  291. <-s.headerChan
  292. case <-s.headerChan:
  293. }
  294. }
  295. // RecvCompress returns the compression algorithm applied to the inbound
  296. // message. It is empty string if there is no compression applied.
  297. func (s *Stream) RecvCompress() string {
  298. s.waitOnHeader()
  299. return s.recvCompress
  300. }
  301. // SetSendCompress sets the compression algorithm to the stream.
  302. func (s *Stream) SetSendCompress(str string) {
  303. s.sendCompress = str
  304. }
  305. // Done returns a channel which is closed when it receives the final status
  306. // from the server.
  307. func (s *Stream) Done() <-chan struct{} {
  308. return s.done
  309. }
  310. // Header returns the header metadata of the stream.
  311. //
  312. // On client side, it acquires the key-value pairs of header metadata once it is
  313. // available. It blocks until i) the metadata is ready or ii) there is no header
  314. // metadata or iii) the stream is canceled/expired.
  315. //
  316. // On server side, it returns the out header after t.WriteHeader is called. It
  317. // does not block and must not be called until after WriteHeader.
  318. func (s *Stream) Header() (metadata.MD, error) {
  319. if s.headerChan == nil {
  320. // On server side, return the header in stream. It will be the out
  321. // header after t.WriteHeader is called.
  322. return s.header.Copy(), nil
  323. }
  324. s.waitOnHeader()
  325. if !s.headerValid {
  326. return nil, s.status.Err()
  327. }
  328. return s.header.Copy(), nil
  329. }
  330. // TrailersOnly blocks until a header or trailers-only frame is received and
  331. // then returns true if the stream was trailers-only. If the stream ends
  332. // before headers are received, returns true, nil. Client-side only.
  333. func (s *Stream) TrailersOnly() bool {
  334. s.waitOnHeader()
  335. return s.noHeaders
  336. }
  337. // Trailer returns the cached trailer metedata. Note that if it is not called
  338. // after the entire stream is done, it could return an empty MD. Client
  339. // side only.
  340. // It can be safely read only after stream has ended that is either read
  341. // or write have returned io.EOF.
  342. func (s *Stream) Trailer() metadata.MD {
  343. c := s.trailer.Copy()
  344. return c
  345. }
  346. // ContentSubtype returns the content-subtype for a request. For example, a
  347. // content-subtype of "proto" will result in a content-type of
  348. // "application/grpc+proto". This will always be lowercase. See
  349. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  350. // more details.
  351. func (s *Stream) ContentSubtype() string {
  352. return s.contentSubtype
  353. }
  354. // Context returns the context of the stream.
  355. func (s *Stream) Context() context.Context {
  356. return s.ctx
  357. }
  358. // Method returns the method for the stream.
  359. func (s *Stream) Method() string {
  360. return s.method
  361. }
  362. // Status returns the status received from the server.
  363. // Status can be read safely only after the stream has ended,
  364. // that is, after Done() is closed.
  365. func (s *Stream) Status() *status.Status {
  366. return s.status
  367. }
  368. // SetHeader sets the header metadata. This can be called multiple times.
  369. // Server side only.
  370. // This should not be called in parallel to other data writes.
  371. func (s *Stream) SetHeader(md metadata.MD) error {
  372. if md.Len() == 0 {
  373. return nil
  374. }
  375. if s.isHeaderSent() || s.getState() == streamDone {
  376. return ErrIllegalHeaderWrite
  377. }
  378. s.hdrMu.Lock()
  379. s.header = metadata.Join(s.header, md)
  380. s.hdrMu.Unlock()
  381. return nil
  382. }
  383. // SendHeader sends the given header metadata. The given metadata is
  384. // combined with any metadata set by previous calls to SetHeader and
  385. // then written to the transport stream.
  386. func (s *Stream) SendHeader(md metadata.MD) error {
  387. return s.st.WriteHeader(s, md)
  388. }
  389. // SetTrailer sets the trailer metadata which will be sent with the RPC status
  390. // by the server. This can be called multiple times. Server side only.
  391. // This should not be called parallel to other data writes.
  392. func (s *Stream) SetTrailer(md metadata.MD) error {
  393. if md.Len() == 0 {
  394. return nil
  395. }
  396. if s.getState() == streamDone {
  397. return ErrIllegalHeaderWrite
  398. }
  399. s.hdrMu.Lock()
  400. s.trailer = metadata.Join(s.trailer, md)
  401. s.hdrMu.Unlock()
  402. return nil
  403. }
  404. func (s *Stream) write(m recvMsg) {
  405. s.buf.put(m)
  406. }
  407. // Read reads all p bytes from the wire for this stream.
  408. func (s *Stream) Read(p []byte) (n int, err error) {
  409. // Don't request a read if there was an error earlier
  410. if er := s.trReader.(*transportReader).er; er != nil {
  411. return 0, er
  412. }
  413. s.requestRead(len(p))
  414. return io.ReadFull(s.trReader, p)
  415. }
  416. // tranportReader reads all the data available for this Stream from the transport and
  417. // passes them into the decoder, which converts them into a gRPC message stream.
  418. // The error is io.EOF when the stream is done or another non-nil error if
  419. // the stream broke.
  420. type transportReader struct {
  421. reader io.Reader
  422. // The handler to control the window update procedure for both this
  423. // particular stream and the associated transport.
  424. windowHandler func(int)
  425. er error
  426. }
  427. func (t *transportReader) Read(p []byte) (n int, err error) {
  428. n, err = t.reader.Read(p)
  429. if err != nil {
  430. t.er = err
  431. return
  432. }
  433. t.windowHandler(n)
  434. return
  435. }
  436. // BytesReceived indicates whether any bytes have been received on this stream.
  437. func (s *Stream) BytesReceived() bool {
  438. return atomic.LoadUint32(&s.bytesReceived) == 1
  439. }
  440. // Unprocessed indicates whether the server did not process this stream --
  441. // i.e. it sent a refused stream or GOAWAY including this stream ID.
  442. func (s *Stream) Unprocessed() bool {
  443. return atomic.LoadUint32(&s.unprocessed) == 1
  444. }
  445. // GoString is implemented by Stream so context.String() won't
  446. // race when printing %#v.
  447. func (s *Stream) GoString() string {
  448. return fmt.Sprintf("<stream: %p, %v>", s, s.method)
  449. }
  450. // state of transport
  451. type transportState int
  452. const (
  453. reachable transportState = iota
  454. closing
  455. draining
  456. )
  457. // ServerConfig consists of all the configurations to establish a server transport.
  458. type ServerConfig struct {
  459. MaxStreams uint32
  460. AuthInfo credentials.AuthInfo
  461. InTapHandle tap.ServerInHandle
  462. StatsHandler stats.Handler
  463. KeepaliveParams keepalive.ServerParameters
  464. KeepalivePolicy keepalive.EnforcementPolicy
  465. InitialWindowSize int32
  466. InitialConnWindowSize int32
  467. WriteBufferSize int
  468. ReadBufferSize int
  469. ChannelzParentID int64
  470. MaxHeaderListSize *uint32
  471. HeaderTableSize *uint32
  472. }
  473. // NewServerTransport creates a ServerTransport with conn or non-nil error
  474. // if it fails.
  475. func NewServerTransport(protocol string, conn net.Conn, config *ServerConfig) (ServerTransport, error) {
  476. return newHTTP2Server(conn, config)
  477. }
  478. // ConnectOptions covers all relevant options for communicating with the server.
  479. type ConnectOptions struct {
  480. // UserAgent is the application user agent.
  481. UserAgent string
  482. // Dialer specifies how to dial a network address.
  483. Dialer func(context.Context, string) (net.Conn, error)
  484. // FailOnNonTempDialError specifies if gRPC fails on non-temporary dial errors.
  485. FailOnNonTempDialError bool
  486. // PerRPCCredentials stores the PerRPCCredentials required to issue RPCs.
  487. PerRPCCredentials []credentials.PerRPCCredentials
  488. // TransportCredentials stores the Authenticator required to setup a client
  489. // connection. Only one of TransportCredentials and CredsBundle is non-nil.
  490. TransportCredentials credentials.TransportCredentials
  491. // CredsBundle is the credentials bundle to be used. Only one of
  492. // TransportCredentials and CredsBundle is non-nil.
  493. CredsBundle credentials.Bundle
  494. // KeepaliveParams stores the keepalive parameters.
  495. KeepaliveParams keepalive.ClientParameters
  496. // StatsHandler stores the handler for stats.
  497. StatsHandler stats.Handler
  498. // InitialWindowSize sets the initial window size for a stream.
  499. InitialWindowSize int32
  500. // InitialConnWindowSize sets the initial window size for a connection.
  501. InitialConnWindowSize int32
  502. // WriteBufferSize sets the size of write buffer which in turn determines how much data can be batched before it's written on the wire.
  503. WriteBufferSize int
  504. // ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall.
  505. ReadBufferSize int
  506. // ChannelzParentID sets the addrConn id which initiate the creation of this client transport.
  507. ChannelzParentID int64
  508. // MaxHeaderListSize sets the max (uncompressed) size of header list that is prepared to be received.
  509. MaxHeaderListSize *uint32
  510. }
  511. // NewClientTransport establishes the transport with the required ConnectOptions
  512. // and returns it to the caller.
  513. func NewClientTransport(connectCtx, ctx context.Context, addr resolver.Address, opts ConnectOptions, onPrefaceReceipt func(), onGoAway func(GoAwayReason), onClose func()) (ClientTransport, error) {
  514. return newHTTP2Client(connectCtx, ctx, addr, opts, onPrefaceReceipt, onGoAway, onClose)
  515. }
  516. // Options provides additional hints and information for message
  517. // transmission.
  518. type Options struct {
  519. // Last indicates whether this write is the last piece for
  520. // this stream.
  521. Last bool
  522. }
  523. // CallHdr carries the information of a particular RPC.
  524. type CallHdr struct {
  525. // Host specifies the peer's host.
  526. Host string
  527. // Method specifies the operation to perform.
  528. Method string
  529. // SendCompress specifies the compression algorithm applied on
  530. // outbound message.
  531. SendCompress string
  532. // Creds specifies credentials.PerRPCCredentials for a call.
  533. Creds credentials.PerRPCCredentials
  534. // ContentSubtype specifies the content-subtype for a request. For example, a
  535. // content-subtype of "proto" will result in a content-type of
  536. // "application/grpc+proto". The value of ContentSubtype must be all
  537. // lowercase, otherwise the behavior is undefined. See
  538. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
  539. // for more details.
  540. ContentSubtype string
  541. PreviousAttempts int // value of grpc-previous-rpc-attempts header to set
  542. }
  543. // ClientTransport is the common interface for all gRPC client-side transport
  544. // implementations.
  545. type ClientTransport interface {
  546. // Close tears down this transport. Once it returns, the transport
  547. // should not be accessed any more. The caller must make sure this
  548. // is called only once.
  549. Close() error
  550. // GracefulClose starts to tear down the transport: the transport will stop
  551. // accepting new RPCs and NewStream will return error. Once all streams are
  552. // finished, the transport will close.
  553. //
  554. // It does not block.
  555. GracefulClose()
  556. // Write sends the data for the given stream. A nil stream indicates
  557. // the write is to be performed on the transport as a whole.
  558. Write(s *Stream, hdr []byte, data []byte, opts *Options) error
  559. // NewStream creates a Stream for an RPC.
  560. NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error)
  561. // CloseStream clears the footprint of a stream when the stream is
  562. // not needed any more. The err indicates the error incurred when
  563. // CloseStream is called. Must be called when a stream is finished
  564. // unless the associated transport is closing.
  565. CloseStream(stream *Stream, err error)
  566. // Error returns a channel that is closed when some I/O error
  567. // happens. Typically the caller should have a goroutine to monitor
  568. // this in order to take action (e.g., close the current transport
  569. // and create a new one) in error case. It should not return nil
  570. // once the transport is initiated.
  571. Error() <-chan struct{}
  572. // GoAway returns a channel that is closed when ClientTransport
  573. // receives the draining signal from the server (e.g., GOAWAY frame in
  574. // HTTP/2).
  575. GoAway() <-chan struct{}
  576. // GetGoAwayReason returns the reason why GoAway frame was received.
  577. GetGoAwayReason() GoAwayReason
  578. // RemoteAddr returns the remote network address.
  579. RemoteAddr() net.Addr
  580. // IncrMsgSent increments the number of message sent through this transport.
  581. IncrMsgSent()
  582. // IncrMsgRecv increments the number of message received through this transport.
  583. IncrMsgRecv()
  584. }
  585. // ServerTransport is the common interface for all gRPC server-side transport
  586. // implementations.
  587. //
  588. // Methods may be called concurrently from multiple goroutines, but
  589. // Write methods for a given Stream will be called serially.
  590. type ServerTransport interface {
  591. // HandleStreams receives incoming streams using the given handler.
  592. HandleStreams(func(*Stream), func(context.Context, string) context.Context)
  593. // WriteHeader sends the header metadata for the given stream.
  594. // WriteHeader may not be called on all streams.
  595. WriteHeader(s *Stream, md metadata.MD) error
  596. // Write sends the data for the given stream.
  597. // Write may not be called on all streams.
  598. Write(s *Stream, hdr []byte, data []byte, opts *Options) error
  599. // WriteStatus sends the status of a stream to the client. WriteStatus is
  600. // the final call made on a stream and always occurs.
  601. WriteStatus(s *Stream, st *status.Status) error
  602. // Close tears down the transport. Once it is called, the transport
  603. // should not be accessed any more. All the pending streams and their
  604. // handlers will be terminated asynchronously.
  605. Close() error
  606. // RemoteAddr returns the remote network address.
  607. RemoteAddr() net.Addr
  608. // Drain notifies the client this ServerTransport stops accepting new RPCs.
  609. Drain()
  610. // IncrMsgSent increments the number of message sent through this transport.
  611. IncrMsgSent()
  612. // IncrMsgRecv increments the number of message received through this transport.
  613. IncrMsgRecv()
  614. }
  615. // connectionErrorf creates an ConnectionError with the specified error description.
  616. func connectionErrorf(temp bool, e error, format string, a ...interface{}) ConnectionError {
  617. return ConnectionError{
  618. Desc: fmt.Sprintf(format, a...),
  619. temp: temp,
  620. err: e,
  621. }
  622. }
  623. // ConnectionError is an error that results in the termination of the
  624. // entire connection and the retry of all the active streams.
  625. type ConnectionError struct {
  626. Desc string
  627. temp bool
  628. err error
  629. }
  630. func (e ConnectionError) Error() string {
  631. return fmt.Sprintf("connection error: desc = %q", e.Desc)
  632. }
  633. // Temporary indicates if this connection error is temporary or fatal.
  634. func (e ConnectionError) Temporary() bool {
  635. return e.temp
  636. }
  637. // Origin returns the original error of this connection error.
  638. func (e ConnectionError) Origin() error {
  639. // Never return nil error here.
  640. // If the original error is nil, return itself.
  641. if e.err == nil {
  642. return e
  643. }
  644. return e.err
  645. }
  646. var (
  647. // ErrConnClosing indicates that the transport is closing.
  648. ErrConnClosing = connectionErrorf(true, nil, "transport is closing")
  649. // errStreamDrain indicates that the stream is rejected because the
  650. // connection is draining. This could be caused by goaway or balancer
  651. // removing the address.
  652. errStreamDrain = status.Error(codes.Unavailable, "the connection is draining")
  653. // errStreamDone is returned from write at the client side to indiacte application
  654. // layer of an error.
  655. errStreamDone = errors.New("the stream is done")
  656. // StatusGoAway indicates that the server sent a GOAWAY that included this
  657. // stream's ID in unprocessed RPCs.
  658. statusGoAway = status.New(codes.Unavailable, "the stream is rejected because server is draining the connection")
  659. )
  660. // GoAwayReason contains the reason for the GoAway frame received.
  661. type GoAwayReason uint8
  662. const (
  663. // GoAwayInvalid indicates that no GoAway frame is received.
  664. GoAwayInvalid GoAwayReason = 0
  665. // GoAwayNoReason is the default value when GoAway frame is received.
  666. GoAwayNoReason GoAwayReason = 1
  667. // GoAwayTooManyPings indicates that a GoAway frame with
  668. // ErrCodeEnhanceYourCalm was received and that the debug data said
  669. // "too_many_pings".
  670. GoAwayTooManyPings GoAwayReason = 2
  671. )
  672. // channelzData is used to store channelz related data for http2Client and http2Server.
  673. // These fields cannot be embedded in the original structs (e.g. http2Client), since to do atomic
  674. // operation on int64 variable on 32-bit machine, user is responsible to enforce memory alignment.
  675. // Here, by grouping those int64 fields inside a struct, we are enforcing the alignment.
  676. type channelzData struct {
  677. kpCount int64
  678. // The number of streams that have started, including already finished ones.
  679. streamsStarted int64
  680. // Client side: The number of streams that have ended successfully by receiving
  681. // EoS bit set frame from server.
  682. // Server side: The number of streams that have ended successfully by sending
  683. // frame with EoS bit set.
  684. streamsSucceeded int64
  685. streamsFailed int64
  686. // lastStreamCreatedTime stores the timestamp that the last stream gets created. It is of int64 type
  687. // instead of time.Time since it's more costly to atomically update time.Time variable than int64
  688. // variable. The same goes for lastMsgSentTime and lastMsgRecvTime.
  689. lastStreamCreatedTime int64
  690. msgSent int64
  691. msgRecv int64
  692. lastMsgSentTime int64
  693. lastMsgRecvTime int64
  694. }
  695. // ContextErr converts the error from context package into a status error.
  696. func ContextErr(err error) error {
  697. switch err {
  698. case context.DeadlineExceeded:
  699. return status.Error(codes.DeadlineExceeded, err.Error())
  700. case context.Canceled:
  701. return status.Error(codes.Canceled, err.Error())
  702. }
  703. return status.Errorf(codes.Internal, "Unexpected error from context packet: %v", err)
  704. }