transport.go 25 KB

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