You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

758 lines
25 KiB

  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. return s.noHeaders, nil
  294. }
  295. // Trailer returns the cached trailer metedata. Note that if it is not called
  296. // after the entire stream is done, it could return an empty MD. Client
  297. // side only.
  298. // It can be safely read only after stream has ended that is either read
  299. // or write have returned io.EOF.
  300. func (s *Stream) Trailer() metadata.MD {
  301. c := s.trailer.Copy()
  302. return c
  303. }
  304. // ContentSubtype returns the content-subtype for a request. For example, a
  305. // content-subtype of "proto" will result in a content-type of
  306. // "application/grpc+proto". This will always be lowercase. See
  307. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  308. // more details.
  309. func (s *Stream) ContentSubtype() string {
  310. return s.contentSubtype
  311. }
  312. // Context returns the context of the stream.
  313. func (s *Stream) Context() context.Context {
  314. return s.ctx
  315. }
  316. // Method returns the method for the stream.
  317. func (s *Stream) Method() string {
  318. return s.method
  319. }
  320. // Status returns the status received from the server.
  321. // Status can be read safely only after the stream has ended,
  322. // that is, after Done() is closed.
  323. func (s *Stream) Status() *status.Status {
  324. return s.status
  325. }
  326. // SetHeader sets the header metadata. This can be called multiple times.
  327. // Server side only.
  328. // This should not be called in parallel to other data writes.
  329. func (s *Stream) SetHeader(md metadata.MD) error {
  330. if md.Len() == 0 {
  331. return nil
  332. }
  333. if s.isHeaderSent() || s.getState() == streamDone {
  334. return ErrIllegalHeaderWrite
  335. }
  336. s.hdrMu.Lock()
  337. s.header = metadata.Join(s.header, md)
  338. s.hdrMu.Unlock()
  339. return nil
  340. }
  341. // SendHeader sends the given header metadata. The given metadata is
  342. // combined with any metadata set by previous calls to SetHeader and
  343. // then written to the transport stream.
  344. func (s *Stream) SendHeader(md metadata.MD) error {
  345. return s.st.WriteHeader(s, md)
  346. }
  347. // SetTrailer sets the trailer metadata which will be sent with the RPC status
  348. // by the server. This can be called multiple times. Server side only.
  349. // This should not be called parallel to other data writes.
  350. func (s *Stream) SetTrailer(md metadata.MD) error {
  351. if md.Len() == 0 {
  352. return nil
  353. }
  354. if s.getState() == streamDone {
  355. return ErrIllegalHeaderWrite
  356. }
  357. s.hdrMu.Lock()
  358. s.trailer = metadata.Join(s.trailer, md)
  359. s.hdrMu.Unlock()
  360. return nil
  361. }
  362. func (s *Stream) write(m recvMsg) {
  363. s.buf.put(m)
  364. }
  365. // Read reads all p bytes from the wire for this stream.
  366. func (s *Stream) Read(p []byte) (n int, err error) {
  367. // Don't request a read if there was an error earlier
  368. if er := s.trReader.(*transportReader).er; er != nil {
  369. return 0, er
  370. }
  371. s.requestRead(len(p))
  372. return io.ReadFull(s.trReader, p)
  373. }
  374. // tranportReader reads all the data available for this Stream from the transport and
  375. // passes them into the decoder, which converts them into a gRPC message stream.
  376. // The error is io.EOF when the stream is done or another non-nil error if
  377. // the stream broke.
  378. type transportReader struct {
  379. reader io.Reader
  380. // The handler to control the window update procedure for both this
  381. // particular stream and the associated transport.
  382. windowHandler func(int)
  383. er error
  384. }
  385. func (t *transportReader) Read(p []byte) (n int, err error) {
  386. n, err = t.reader.Read(p)
  387. if err != nil {
  388. t.er = err
  389. return
  390. }
  391. t.windowHandler(n)
  392. return
  393. }
  394. // BytesReceived indicates whether any bytes have been received on this stream.
  395. func (s *Stream) BytesReceived() bool {
  396. return atomic.LoadUint32(&s.bytesReceived) == 1
  397. }
  398. // Unprocessed indicates whether the server did not process this stream --
  399. // i.e. it sent a refused stream or GOAWAY including this stream ID.
  400. func (s *Stream) Unprocessed() bool {
  401. return atomic.LoadUint32(&s.unprocessed) == 1
  402. }
  403. // GoString is implemented by Stream so context.String() won't
  404. // race when printing %#v.
  405. func (s *Stream) GoString() string {
  406. return fmt.Sprintf("<stream: %p, %v>", s, s.method)
  407. }
  408. // state of transport
  409. type transportState int
  410. const (
  411. reachable transportState = iota
  412. closing
  413. draining
  414. )
  415. // ServerConfig consists of all the configurations to establish a server transport.
  416. type ServerConfig struct {
  417. MaxStreams uint32
  418. AuthInfo credentials.AuthInfo
  419. InTapHandle tap.ServerInHandle
  420. StatsHandler stats.Handler
  421. KeepaliveParams keepalive.ServerParameters
  422. KeepalivePolicy keepalive.EnforcementPolicy
  423. InitialWindowSize int32
  424. InitialConnWindowSize int32
  425. WriteBufferSize int
  426. ReadBufferSize int
  427. ChannelzParentID int64
  428. MaxHeaderListSize *uint32
  429. }
  430. // NewServerTransport creates a ServerTransport with conn or non-nil error
  431. // if it fails.
  432. func NewServerTransport(protocol string, conn net.Conn, config *ServerConfig) (ServerTransport, error) {
  433. return newHTTP2Server(conn, config)
  434. }
  435. // ConnectOptions covers all relevant options for communicating with the server.
  436. type ConnectOptions struct {
  437. // UserAgent is the application user agent.
  438. UserAgent string
  439. // Dialer specifies how to dial a network address.
  440. Dialer func(context.Context, string) (net.Conn, error)
  441. // FailOnNonTempDialError specifies if gRPC fails on non-temporary dial errors.
  442. FailOnNonTempDialError bool
  443. // PerRPCCredentials stores the PerRPCCredentials required to issue RPCs.
  444. PerRPCCredentials []credentials.PerRPCCredentials
  445. // TransportCredentials stores the Authenticator required to setup a client
  446. // connection. Only one of TransportCredentials and CredsBundle is non-nil.
  447. TransportCredentials credentials.TransportCredentials
  448. // CredsBundle is the credentials bundle to be used. Only one of
  449. // TransportCredentials and CredsBundle is non-nil.
  450. CredsBundle credentials.Bundle
  451. // KeepaliveParams stores the keepalive parameters.
  452. KeepaliveParams keepalive.ClientParameters
  453. // StatsHandler stores the handler for stats.
  454. StatsHandler stats.Handler
  455. // InitialWindowSize sets the initial window size for a stream.
  456. InitialWindowSize int32
  457. // InitialConnWindowSize sets the initial window size for a connection.
  458. InitialConnWindowSize int32
  459. // WriteBufferSize sets the size of write buffer which in turn determines how much data can be batched before it's written on the wire.
  460. WriteBufferSize int
  461. // ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall.
  462. ReadBufferSize int
  463. // ChannelzParentID sets the addrConn id which initiate the creation of this client transport.
  464. ChannelzParentID int64
  465. // MaxHeaderListSize sets the max (uncompressed) size of header list that is prepared to be received.
  466. MaxHeaderListSize *uint32
  467. }
  468. // TargetInfo contains the information of the target such as network address and metadata.
  469. type TargetInfo struct {
  470. Addr string
  471. Metadata interface{}
  472. Authority string
  473. }
  474. // NewClientTransport establishes the transport with the required ConnectOptions
  475. // and returns it to the caller.
  476. func NewClientTransport(connectCtx, ctx context.Context, target TargetInfo, opts ConnectOptions, onPrefaceReceipt func(), onGoAway func(GoAwayReason), onClose func()) (ClientTransport, error) {
  477. return newHTTP2Client(connectCtx, ctx, target, opts, onPrefaceReceipt, onGoAway, onClose)
  478. }
  479. // Options provides additional hints and information for message
  480. // transmission.
  481. type Options struct {
  482. // Last indicates whether this write is the last piece for
  483. // this stream.
  484. Last bool
  485. }
  486. // CallHdr carries the information of a particular RPC.
  487. type CallHdr struct {
  488. // Host specifies the peer's host.
  489. Host string
  490. // Method specifies the operation to perform.
  491. Method string
  492. // SendCompress specifies the compression algorithm applied on
  493. // outbound message.
  494. SendCompress string
  495. // Creds specifies credentials.PerRPCCredentials for a call.
  496. Creds credentials.PerRPCCredentials
  497. // ContentSubtype specifies the content-subtype for a request. For example, a
  498. // content-subtype of "proto" will result in a content-type of
  499. // "application/grpc+proto". The value of ContentSubtype must be all
  500. // lowercase, otherwise the behavior is undefined. See
  501. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
  502. // for more details.
  503. ContentSubtype string
  504. PreviousAttempts int // value of grpc-previous-rpc-attempts header to set
  505. }
  506. // ClientTransport is the common interface for all gRPC client-side transport
  507. // implementations.
  508. type ClientTransport interface {
  509. // Close tears down this transport. Once it returns, the transport
  510. // should not be accessed any more. The caller must make sure this
  511. // is called only once.
  512. Close() error
  513. // GracefulClose starts to tear down the transport. It stops accepting
  514. // new RPCs and wait the completion of the pending RPCs.
  515. GracefulClose() error
  516. // Write sends the data for the given stream. A nil stream indicates
  517. // the write is to be performed on the transport as a whole.
  518. Write(s *Stream, hdr []byte, data []byte, opts *Options) error
  519. // NewStream creates a Stream for an RPC.
  520. NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error)
  521. // CloseStream clears the footprint of a stream when the stream is
  522. // not needed any more. The err indicates the error incurred when
  523. // CloseStream is called. Must be called when a stream is finished
  524. // unless the associated transport is closing.
  525. CloseStream(stream *Stream, err error)
  526. // Error returns a channel that is closed when some I/O error
  527. // happens. Typically the caller should have a goroutine to monitor
  528. // this in order to take action (e.g., close the current transport
  529. // and create a new one) in error case. It should not return nil
  530. // once the transport is initiated.
  531. Error() <-chan struct{}
  532. // GoAway returns a channel that is closed when ClientTransport
  533. // receives the draining signal from the server (e.g., GOAWAY frame in
  534. // HTTP/2).
  535. GoAway() <-chan struct{}
  536. // GetGoAwayReason returns the reason why GoAway frame was received.
  537. GetGoAwayReason() GoAwayReason
  538. // IncrMsgSent increments the number of message sent through this transport.
  539. IncrMsgSent()
  540. // IncrMsgRecv increments the number of message received through this transport.
  541. IncrMsgRecv()
  542. }
  543. // ServerTransport is the common interface for all gRPC server-side transport
  544. // implementations.
  545. //
  546. // Methods may be called concurrently from multiple goroutines, but
  547. // Write methods for a given Stream will be called serially.
  548. type ServerTransport interface {
  549. // HandleStreams receives incoming streams using the given handler.
  550. HandleStreams(func(*Stream), func(context.Context, string) context.Context)
  551. // WriteHeader sends the header metadata for the given stream.
  552. // WriteHeader may not be called on all streams.
  553. WriteHeader(s *Stream, md metadata.MD) error
  554. // Write sends the data for the given stream.
  555. // Write may not be called on all streams.
  556. Write(s *Stream, hdr []byte, data []byte, opts *Options) error
  557. // WriteStatus sends the status of a stream to the client. WriteStatus is
  558. // the final call made on a stream and always occurs.
  559. WriteStatus(s *Stream, st *status.Status) error
  560. // Close tears down the transport. Once it is called, the transport
  561. // should not be accessed any more. All the pending streams and their
  562. // handlers will be terminated asynchronously.
  563. Close() error
  564. // RemoteAddr returns the remote network address.
  565. RemoteAddr() net.Addr
  566. // Drain notifies the client this ServerTransport stops accepting new RPCs.
  567. Drain()
  568. // IncrMsgSent increments the number of message sent through this transport.
  569. IncrMsgSent()
  570. // IncrMsgRecv increments the number of message received through this transport.
  571. IncrMsgRecv()
  572. }
  573. // connectionErrorf creates an ConnectionError with the specified error description.
  574. func connectionErrorf(temp bool, e error, format string, a ...interface{}) ConnectionError {
  575. return ConnectionError{
  576. Desc: fmt.Sprintf(format, a...),
  577. temp: temp,
  578. err: e,
  579. }
  580. }
  581. // ConnectionError is an error that results in the termination of the
  582. // entire connection and the retry of all the active streams.
  583. type ConnectionError struct {
  584. Desc string
  585. temp bool
  586. err error
  587. }
  588. func (e ConnectionError) Error() string {
  589. return fmt.Sprintf("connection error: desc = %q", e.Desc)
  590. }
  591. // Temporary indicates if this connection error is temporary or fatal.
  592. func (e ConnectionError) Temporary() bool {
  593. return e.temp
  594. }
  595. // Origin returns the original error of this connection error.
  596. func (e ConnectionError) Origin() error {
  597. // Never return nil error here.
  598. // If the original error is nil, return itself.
  599. if e.err == nil {
  600. return e
  601. }
  602. return e.err
  603. }
  604. var (
  605. // ErrConnClosing indicates that the transport is closing.
  606. ErrConnClosing = connectionErrorf(true, nil, "transport is closing")
  607. // errStreamDrain indicates that the stream is rejected because the
  608. // connection is draining. This could be caused by goaway or balancer
  609. // removing the address.
  610. errStreamDrain = status.Error(codes.Unavailable, "the connection is draining")
  611. // errStreamDone is returned from write at the client side to indiacte application
  612. // layer of an error.
  613. errStreamDone = errors.New("the stream is done")
  614. // StatusGoAway indicates that the server sent a GOAWAY that included this
  615. // stream's ID in unprocessed RPCs.
  616. statusGoAway = status.New(codes.Unavailable, "the stream is rejected because server is draining the connection")
  617. )
  618. // GoAwayReason contains the reason for the GoAway frame received.
  619. type GoAwayReason uint8
  620. const (
  621. // GoAwayInvalid indicates that no GoAway frame is received.
  622. GoAwayInvalid GoAwayReason = 0
  623. // GoAwayNoReason is the default value when GoAway frame is received.
  624. GoAwayNoReason GoAwayReason = 1
  625. // GoAwayTooManyPings indicates that a GoAway frame with
  626. // ErrCodeEnhanceYourCalm was received and that the debug data said
  627. // "too_many_pings".
  628. GoAwayTooManyPings GoAwayReason = 2
  629. )
  630. // channelzData is used to store channelz related data for http2Client and http2Server.
  631. // These fields cannot be embedded in the original structs (e.g. http2Client), since to do atomic
  632. // operation on int64 variable on 32-bit machine, user is responsible to enforce memory alignment.
  633. // Here, by grouping those int64 fields inside a struct, we are enforcing the alignment.
  634. type channelzData struct {
  635. kpCount int64
  636. // The number of streams that have started, including already finished ones.
  637. streamsStarted int64
  638. // Client side: The number of streams that have ended successfully by receiving
  639. // EoS bit set frame from server.
  640. // Server side: The number of streams that have ended successfully by sending
  641. // frame with EoS bit set.
  642. streamsSucceeded int64
  643. streamsFailed int64
  644. // lastStreamCreatedTime stores the timestamp that the last stream gets created. It is of int64 type
  645. // instead of time.Time since it's more costly to atomically update time.Time variable than int64
  646. // variable. The same goes for lastMsgSentTime and lastMsgRecvTime.
  647. lastStreamCreatedTime int64
  648. msgSent int64
  649. msgRecv int64
  650. lastMsgSentTime int64
  651. lastMsgRecvTime int64
  652. }
  653. // ContextErr converts the error from context package into a status error.
  654. func ContextErr(err error) error {
  655. switch err {
  656. case context.DeadlineExceeded:
  657. return status.Error(codes.DeadlineExceeded, err.Error())
  658. case context.Canceled:
  659. return status.Error(codes.Canceled, err.Error())
  660. }
  661. return status.Errorf(codes.Internal, "Unexpected error from context packet: %v", err)
  662. }