transport.go 23 KB

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