transport.go 24 KB

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