http2_client.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  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
  19. import (
  20. "bytes"
  21. "fmt"
  22. "io"
  23. "math"
  24. "net"
  25. "strings"
  26. "sync"
  27. "sync/atomic"
  28. "time"
  29. "golang.org/x/net/context"
  30. "golang.org/x/net/http2"
  31. "golang.org/x/net/http2/hpack"
  32. "google.golang.org/grpc/codes"
  33. "google.golang.org/grpc/credentials"
  34. "google.golang.org/grpc/keepalive"
  35. "google.golang.org/grpc/metadata"
  36. "google.golang.org/grpc/peer"
  37. "google.golang.org/grpc/stats"
  38. "google.golang.org/grpc/status"
  39. )
  40. // http2Client implements the ClientTransport interface with HTTP2.
  41. type http2Client struct {
  42. ctx context.Context
  43. cancel context.CancelFunc
  44. userAgent string
  45. md interface{}
  46. conn net.Conn // underlying communication channel
  47. remoteAddr net.Addr
  48. localAddr net.Addr
  49. authInfo credentials.AuthInfo // auth info about the connection
  50. nextID uint32 // the next stream ID to be used
  51. // goAway is closed to notify the upper layer (i.e., addrConn.transportMonitor)
  52. // that the server sent GoAway on this transport.
  53. goAway chan struct{}
  54. // awakenKeepalive is used to wake up keepalive when after it has gone dormant.
  55. awakenKeepalive chan struct{}
  56. framer *framer
  57. hBuf *bytes.Buffer // the buffer for HPACK encoding
  58. hEnc *hpack.Encoder // HPACK encoder
  59. // controlBuf delivers all the control related tasks (e.g., window
  60. // updates, reset streams, and various settings) to the controller.
  61. controlBuf *controlBuffer
  62. fc *inFlow
  63. // sendQuotaPool provides flow control to outbound message.
  64. sendQuotaPool *quotaPool
  65. // localSendQuota limits the amount of data that can be scheduled
  66. // for writing before it is actually written out.
  67. localSendQuota *quotaPool
  68. // streamsQuota limits the max number of concurrent streams.
  69. streamsQuota *quotaPool
  70. // The scheme used: https if TLS is on, http otherwise.
  71. scheme string
  72. isSecure bool
  73. creds []credentials.PerRPCCredentials
  74. // Boolean to keep track of reading activity on transport.
  75. // 1 is true and 0 is false.
  76. activity uint32 // Accessed atomically.
  77. kp keepalive.ClientParameters
  78. statsHandler stats.Handler
  79. initialWindowSize int32
  80. bdpEst *bdpEstimator
  81. outQuotaVersion uint32
  82. // onSuccess is a callback that client transport calls upon
  83. // receiving server preface to signal that a succefull HTTP2
  84. // connection was established.
  85. onSuccess func()
  86. mu sync.Mutex // guard the following variables
  87. state transportState // the state of underlying connection
  88. activeStreams map[uint32]*Stream
  89. // The max number of concurrent streams
  90. maxStreams int
  91. // the per-stream outbound flow control window size set by the peer.
  92. streamSendQuota uint32
  93. // prevGoAway ID records the Last-Stream-ID in the previous GOAway frame.
  94. prevGoAwayID uint32
  95. // goAwayReason records the http2.ErrCode and debug data received with the
  96. // GoAway frame.
  97. goAwayReason GoAwayReason
  98. }
  99. func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr string) (net.Conn, error) {
  100. if fn != nil {
  101. return fn(ctx, addr)
  102. }
  103. return dialContext(ctx, "tcp", addr)
  104. }
  105. func isTemporary(err error) bool {
  106. switch err {
  107. case io.EOF:
  108. // Connection closures may be resolved upon retry, and are thus
  109. // treated as temporary.
  110. return true
  111. case context.DeadlineExceeded:
  112. // In Go 1.7, context.DeadlineExceeded implements Timeout(), and this
  113. // special case is not needed. Until then, we need to keep this
  114. // clause.
  115. return true
  116. }
  117. switch err := err.(type) {
  118. case interface {
  119. Temporary() bool
  120. }:
  121. return err.Temporary()
  122. case interface {
  123. Timeout() bool
  124. }:
  125. // Timeouts may be resolved upon retry, and are thus treated as
  126. // temporary.
  127. return err.Timeout()
  128. }
  129. return false
  130. }
  131. // newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2
  132. // and starts to receive messages on it. Non-nil error returns if construction
  133. // fails.
  134. func newHTTP2Client(connectCtx, ctx context.Context, addr TargetInfo, opts ConnectOptions, onSuccess func()) (_ ClientTransport, err error) {
  135. scheme := "http"
  136. ctx, cancel := context.WithCancel(ctx)
  137. defer func() {
  138. if err != nil {
  139. cancel()
  140. }
  141. }()
  142. conn, err := dial(connectCtx, opts.Dialer, addr.Addr)
  143. if err != nil {
  144. if opts.FailOnNonTempDialError {
  145. return nil, connectionErrorf(isTemporary(err), err, "transport: error while dialing: %v", err)
  146. }
  147. return nil, connectionErrorf(true, err, "transport: Error while dialing %v", err)
  148. }
  149. // Any further errors will close the underlying connection
  150. defer func(conn net.Conn) {
  151. if err != nil {
  152. conn.Close()
  153. }
  154. }(conn)
  155. var (
  156. isSecure bool
  157. authInfo credentials.AuthInfo
  158. )
  159. if creds := opts.TransportCredentials; creds != nil {
  160. scheme = "https"
  161. conn, authInfo, err = creds.ClientHandshake(connectCtx, addr.Authority, conn)
  162. if err != nil {
  163. // Credentials handshake errors are typically considered permanent
  164. // to avoid retrying on e.g. bad certificates.
  165. temp := isTemporary(err)
  166. return nil, connectionErrorf(temp, err, "transport: authentication handshake failed: %v", err)
  167. }
  168. isSecure = true
  169. }
  170. kp := opts.KeepaliveParams
  171. // Validate keepalive parameters.
  172. if kp.Time == 0 {
  173. kp.Time = defaultClientKeepaliveTime
  174. }
  175. if kp.Timeout == 0 {
  176. kp.Timeout = defaultClientKeepaliveTimeout
  177. }
  178. dynamicWindow := true
  179. icwz := int32(initialWindowSize)
  180. if opts.InitialConnWindowSize >= defaultWindowSize {
  181. icwz = opts.InitialConnWindowSize
  182. dynamicWindow = false
  183. }
  184. var buf bytes.Buffer
  185. writeBufSize := defaultWriteBufSize
  186. if opts.WriteBufferSize > 0 {
  187. writeBufSize = opts.WriteBufferSize
  188. }
  189. readBufSize := defaultReadBufSize
  190. if opts.ReadBufferSize > 0 {
  191. readBufSize = opts.ReadBufferSize
  192. }
  193. t := &http2Client{
  194. ctx: ctx,
  195. cancel: cancel,
  196. userAgent: opts.UserAgent,
  197. md: addr.Metadata,
  198. conn: conn,
  199. remoteAddr: conn.RemoteAddr(),
  200. localAddr: conn.LocalAddr(),
  201. authInfo: authInfo,
  202. // The client initiated stream id is odd starting from 1.
  203. nextID: 1,
  204. goAway: make(chan struct{}),
  205. awakenKeepalive: make(chan struct{}, 1),
  206. hBuf: &buf,
  207. hEnc: hpack.NewEncoder(&buf),
  208. framer: newFramer(conn, writeBufSize, readBufSize),
  209. controlBuf: newControlBuffer(),
  210. fc: &inFlow{limit: uint32(icwz)},
  211. sendQuotaPool: newQuotaPool(defaultWindowSize),
  212. localSendQuota: newQuotaPool(defaultLocalSendQuota),
  213. scheme: scheme,
  214. state: reachable,
  215. activeStreams: make(map[uint32]*Stream),
  216. isSecure: isSecure,
  217. creds: opts.PerRPCCredentials,
  218. maxStreams: defaultMaxStreamsClient,
  219. streamsQuota: newQuotaPool(defaultMaxStreamsClient),
  220. streamSendQuota: defaultWindowSize,
  221. kp: kp,
  222. statsHandler: opts.StatsHandler,
  223. initialWindowSize: initialWindowSize,
  224. onSuccess: onSuccess,
  225. }
  226. if opts.InitialWindowSize >= defaultWindowSize {
  227. t.initialWindowSize = opts.InitialWindowSize
  228. dynamicWindow = false
  229. }
  230. if dynamicWindow {
  231. t.bdpEst = &bdpEstimator{
  232. bdp: initialWindowSize,
  233. updateFlowControl: t.updateFlowControl,
  234. }
  235. }
  236. // Make sure awakenKeepalive can't be written upon.
  237. // keepalive routine will make it writable, if need be.
  238. t.awakenKeepalive <- struct{}{}
  239. if t.statsHandler != nil {
  240. t.ctx = t.statsHandler.TagConn(t.ctx, &stats.ConnTagInfo{
  241. RemoteAddr: t.remoteAddr,
  242. LocalAddr: t.localAddr,
  243. })
  244. connBegin := &stats.ConnBegin{
  245. Client: true,
  246. }
  247. t.statsHandler.HandleConn(t.ctx, connBegin)
  248. }
  249. // Start the reader goroutine for incoming message. Each transport has
  250. // a dedicated goroutine which reads HTTP2 frame from network. Then it
  251. // dispatches the frame to the corresponding stream entity.
  252. go t.reader()
  253. // Send connection preface to server.
  254. n, err := t.conn.Write(clientPreface)
  255. if err != nil {
  256. t.Close()
  257. return nil, connectionErrorf(true, err, "transport: failed to write client preface: %v", err)
  258. }
  259. if n != len(clientPreface) {
  260. t.Close()
  261. return nil, connectionErrorf(true, err, "transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface))
  262. }
  263. if t.initialWindowSize != defaultWindowSize {
  264. err = t.framer.fr.WriteSettings(http2.Setting{
  265. ID: http2.SettingInitialWindowSize,
  266. Val: uint32(t.initialWindowSize),
  267. })
  268. } else {
  269. err = t.framer.fr.WriteSettings()
  270. }
  271. if err != nil {
  272. t.Close()
  273. return nil, connectionErrorf(true, err, "transport: failed to write initial settings frame: %v", err)
  274. }
  275. // Adjust the connection flow control window if needed.
  276. if delta := uint32(icwz - defaultWindowSize); delta > 0 {
  277. if err := t.framer.fr.WriteWindowUpdate(0, delta); err != nil {
  278. t.Close()
  279. return nil, connectionErrorf(true, err, "transport: failed to write window update: %v", err)
  280. }
  281. }
  282. t.framer.writer.Flush()
  283. go func() {
  284. loopyWriter(t.ctx, t.controlBuf, t.itemHandler)
  285. t.conn.Close()
  286. }()
  287. if t.kp.Time != infinity {
  288. go t.keepalive()
  289. }
  290. return t, nil
  291. }
  292. func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream {
  293. // TODO(zhaoq): Handle uint32 overflow of Stream.id.
  294. s := &Stream{
  295. id: t.nextID,
  296. done: make(chan struct{}),
  297. goAway: make(chan struct{}),
  298. method: callHdr.Method,
  299. sendCompress: callHdr.SendCompress,
  300. buf: newRecvBuffer(),
  301. fc: &inFlow{limit: uint32(t.initialWindowSize)},
  302. sendQuotaPool: newQuotaPool(int(t.streamSendQuota)),
  303. headerChan: make(chan struct{}),
  304. }
  305. t.nextID += 2
  306. s.requestRead = func(n int) {
  307. t.adjustWindow(s, uint32(n))
  308. }
  309. // The client side stream context should have exactly the same life cycle with the user provided context.
  310. // That means, s.ctx should be read-only. And s.ctx is done iff ctx is done.
  311. // So we use the original context here instead of creating a copy.
  312. s.ctx = ctx
  313. s.trReader = &transportReader{
  314. reader: &recvBufferReader{
  315. ctx: s.ctx,
  316. goAway: s.goAway,
  317. recv: s.buf,
  318. },
  319. windowHandler: func(n int) {
  320. t.updateWindow(s, uint32(n))
  321. },
  322. }
  323. s.waiters = waiters{
  324. ctx: s.ctx,
  325. tctx: t.ctx,
  326. done: s.done,
  327. goAway: s.goAway,
  328. }
  329. return s
  330. }
  331. // NewStream creates a stream and registers it into the transport as "active"
  332. // streams.
  333. func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) {
  334. pr := &peer.Peer{
  335. Addr: t.remoteAddr,
  336. }
  337. // Attach Auth info if there is any.
  338. if t.authInfo != nil {
  339. pr.AuthInfo = t.authInfo
  340. }
  341. ctx = peer.NewContext(ctx, pr)
  342. var (
  343. authData = make(map[string]string)
  344. audience string
  345. )
  346. // Create an audience string only if needed.
  347. if len(t.creds) > 0 || callHdr.Creds != nil {
  348. // Construct URI required to get auth request metadata.
  349. // Omit port if it is the default one.
  350. host := strings.TrimSuffix(callHdr.Host, ":443")
  351. pos := strings.LastIndex(callHdr.Method, "/")
  352. if pos == -1 {
  353. pos = len(callHdr.Method)
  354. }
  355. audience = "https://" + host + callHdr.Method[:pos]
  356. }
  357. for _, c := range t.creds {
  358. data, err := c.GetRequestMetadata(ctx, audience)
  359. if err != nil {
  360. return nil, streamErrorf(codes.Internal, "transport: %v", err)
  361. }
  362. for k, v := range data {
  363. // Capital header names are illegal in HTTP/2.
  364. k = strings.ToLower(k)
  365. authData[k] = v
  366. }
  367. }
  368. callAuthData := map[string]string{}
  369. // Check if credentials.PerRPCCredentials were provided via call options.
  370. // Note: if these credentials are provided both via dial options and call
  371. // options, then both sets of credentials will be applied.
  372. if callCreds := callHdr.Creds; callCreds != nil {
  373. if !t.isSecure && callCreds.RequireTransportSecurity() {
  374. return nil, streamErrorf(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure connection")
  375. }
  376. data, err := callCreds.GetRequestMetadata(ctx, audience)
  377. if err != nil {
  378. return nil, streamErrorf(codes.Internal, "transport: %v", err)
  379. }
  380. for k, v := range data {
  381. // Capital header names are illegal in HTTP/2
  382. k = strings.ToLower(k)
  383. callAuthData[k] = v
  384. }
  385. }
  386. t.mu.Lock()
  387. if t.activeStreams == nil {
  388. t.mu.Unlock()
  389. return nil, ErrConnClosing
  390. }
  391. if t.state == draining {
  392. t.mu.Unlock()
  393. return nil, errStreamDrain
  394. }
  395. if t.state != reachable {
  396. t.mu.Unlock()
  397. return nil, ErrConnClosing
  398. }
  399. t.mu.Unlock()
  400. // Get a quota of 1 from streamsQuota.
  401. if _, _, err := t.streamsQuota.get(1, waiters{ctx: ctx, tctx: t.ctx}); err != nil {
  402. return nil, err
  403. }
  404. // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields
  405. // first and create a slice of that exact size.
  406. // Make the slice of certain predictable size to reduce allocations made by append.
  407. hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te
  408. hfLen += len(authData) + len(callAuthData)
  409. headerFields := make([]hpack.HeaderField, 0, hfLen)
  410. headerFields = append(headerFields, hpack.HeaderField{Name: ":method", Value: "POST"})
  411. headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme})
  412. headerFields = append(headerFields, hpack.HeaderField{Name: ":path", Value: callHdr.Method})
  413. headerFields = append(headerFields, hpack.HeaderField{Name: ":authority", Value: callHdr.Host})
  414. headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: "application/grpc"})
  415. headerFields = append(headerFields, hpack.HeaderField{Name: "user-agent", Value: t.userAgent})
  416. headerFields = append(headerFields, hpack.HeaderField{Name: "te", Value: "trailers"})
  417. if callHdr.SendCompress != "" {
  418. headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress})
  419. }
  420. if dl, ok := ctx.Deadline(); ok {
  421. // Send out timeout regardless its value. The server can detect timeout context by itself.
  422. // TODO(mmukhi): Perhaps this field should be updated when actually writing out to the wire.
  423. timeout := dl.Sub(time.Now())
  424. headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-timeout", Value: encodeTimeout(timeout)})
  425. }
  426. for k, v := range authData {
  427. headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
  428. }
  429. for k, v := range callAuthData {
  430. headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
  431. }
  432. if b := stats.OutgoingTags(ctx); b != nil {
  433. headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-tags-bin", Value: encodeBinHeader(b)})
  434. }
  435. if b := stats.OutgoingTrace(ctx); b != nil {
  436. headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-trace-bin", Value: encodeBinHeader(b)})
  437. }
  438. if md, ok := metadata.FromOutgoingContext(ctx); ok {
  439. for k, vv := range md {
  440. // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set.
  441. if isReservedHeader(k) {
  442. continue
  443. }
  444. for _, v := range vv {
  445. headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
  446. }
  447. }
  448. }
  449. if md, ok := t.md.(*metadata.MD); ok {
  450. for k, vv := range *md {
  451. if isReservedHeader(k) {
  452. continue
  453. }
  454. for _, v := range vv {
  455. headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
  456. }
  457. }
  458. }
  459. t.mu.Lock()
  460. if t.state == draining {
  461. t.mu.Unlock()
  462. t.streamsQuota.add(1)
  463. return nil, errStreamDrain
  464. }
  465. if t.state != reachable {
  466. t.mu.Unlock()
  467. return nil, ErrConnClosing
  468. }
  469. s := t.newStream(ctx, callHdr)
  470. t.activeStreams[s.id] = s
  471. // If the number of active streams change from 0 to 1, then check if keepalive
  472. // has gone dormant. If so, wake it up.
  473. if len(t.activeStreams) == 1 {
  474. select {
  475. case t.awakenKeepalive <- struct{}{}:
  476. t.controlBuf.put(&ping{data: [8]byte{}})
  477. // Fill the awakenKeepalive channel again as this channel must be
  478. // kept non-writable except at the point that the keepalive()
  479. // goroutine is waiting either to be awaken or shutdown.
  480. t.awakenKeepalive <- struct{}{}
  481. default:
  482. }
  483. }
  484. t.controlBuf.put(&headerFrame{
  485. streamID: s.id,
  486. hf: headerFields,
  487. endStream: false,
  488. })
  489. t.mu.Unlock()
  490. if t.statsHandler != nil {
  491. outHeader := &stats.OutHeader{
  492. Client: true,
  493. FullMethod: callHdr.Method,
  494. RemoteAddr: t.remoteAddr,
  495. LocalAddr: t.localAddr,
  496. Compression: callHdr.SendCompress,
  497. }
  498. t.statsHandler.HandleRPC(s.ctx, outHeader)
  499. }
  500. return s, nil
  501. }
  502. // CloseStream clears the footprint of a stream when the stream is not needed any more.
  503. // This must not be executed in reader's goroutine.
  504. func (t *http2Client) CloseStream(s *Stream, err error) {
  505. t.mu.Lock()
  506. if t.activeStreams == nil {
  507. t.mu.Unlock()
  508. return
  509. }
  510. if err != nil {
  511. // notify in-flight streams, before the deletion
  512. s.write(recvMsg{err: err})
  513. }
  514. delete(t.activeStreams, s.id)
  515. if t.state == draining && len(t.activeStreams) == 0 {
  516. // The transport is draining and s is the last live stream on t.
  517. t.mu.Unlock()
  518. t.Close()
  519. return
  520. }
  521. t.mu.Unlock()
  522. // rstStream is true in case the stream is being closed at the client-side
  523. // and the server needs to be intimated about it by sending a RST_STREAM
  524. // frame.
  525. // To make sure this frame is written to the wire before the headers of the
  526. // next stream waiting for streamsQuota, we add to streamsQuota pool only
  527. // after having acquired the writableChan to send RST_STREAM out (look at
  528. // the controller() routine).
  529. var rstStream bool
  530. var rstError http2.ErrCode
  531. defer func() {
  532. // In case, the client doesn't have to send RST_STREAM to server
  533. // we can safely add back to streamsQuota pool now.
  534. if !rstStream {
  535. t.streamsQuota.add(1)
  536. return
  537. }
  538. t.controlBuf.put(&resetStream{s.id, rstError})
  539. }()
  540. s.mu.Lock()
  541. rstStream = s.rstStream
  542. rstError = s.rstError
  543. if s.state == streamDone {
  544. s.mu.Unlock()
  545. return
  546. }
  547. if !s.headerDone {
  548. close(s.headerChan)
  549. s.headerDone = true
  550. }
  551. s.state = streamDone
  552. s.mu.Unlock()
  553. if _, ok := err.(StreamError); ok {
  554. rstStream = true
  555. rstError = http2.ErrCodeCancel
  556. }
  557. }
  558. // Close kicks off the shutdown process of the transport. This should be called
  559. // only once on a transport. Once it is called, the transport should not be
  560. // accessed any more.
  561. func (t *http2Client) Close() error {
  562. t.mu.Lock()
  563. if t.state == closing {
  564. t.mu.Unlock()
  565. return nil
  566. }
  567. t.state = closing
  568. t.mu.Unlock()
  569. t.cancel()
  570. err := t.conn.Close()
  571. t.mu.Lock()
  572. streams := t.activeStreams
  573. t.activeStreams = nil
  574. t.mu.Unlock()
  575. // Notify all active streams.
  576. for _, s := range streams {
  577. s.mu.Lock()
  578. if !s.headerDone {
  579. close(s.headerChan)
  580. s.headerDone = true
  581. }
  582. s.mu.Unlock()
  583. s.write(recvMsg{err: ErrConnClosing})
  584. }
  585. if t.statsHandler != nil {
  586. connEnd := &stats.ConnEnd{
  587. Client: true,
  588. }
  589. t.statsHandler.HandleConn(t.ctx, connEnd)
  590. }
  591. return err
  592. }
  593. // GracefulClose sets the state to draining, which prevents new streams from
  594. // being created and causes the transport to be closed when the last active
  595. // stream is closed. If there are no active streams, the transport is closed
  596. // immediately. This does nothing if the transport is already draining or
  597. // closing.
  598. func (t *http2Client) GracefulClose() error {
  599. t.mu.Lock()
  600. switch t.state {
  601. case closing, draining:
  602. t.mu.Unlock()
  603. return nil
  604. }
  605. t.state = draining
  606. active := len(t.activeStreams)
  607. t.mu.Unlock()
  608. if active == 0 {
  609. return t.Close()
  610. }
  611. return nil
  612. }
  613. // Write formats the data into HTTP2 data frame(s) and sends it out. The caller
  614. // should proceed only if Write returns nil.
  615. func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error {
  616. select {
  617. case <-s.ctx.Done():
  618. return ContextErr(s.ctx.Err())
  619. case <-s.done:
  620. return io.EOF
  621. case <-t.ctx.Done():
  622. return ErrConnClosing
  623. default:
  624. }
  625. if hdr == nil && data == nil && opts.Last {
  626. // stream.CloseSend uses this to send an empty frame with endStream=True
  627. t.controlBuf.put(&dataFrame{streamID: s.id, endStream: true, f: func() {}})
  628. return nil
  629. }
  630. // Add data to header frame so that we can equally distribute data across frames.
  631. emptyLen := http2MaxFrameLen - len(hdr)
  632. if emptyLen > len(data) {
  633. emptyLen = len(data)
  634. }
  635. hdr = append(hdr, data[:emptyLen]...)
  636. data = data[emptyLen:]
  637. var (
  638. streamQuota int
  639. streamQuotaVer uint32
  640. err error
  641. )
  642. for idx, r := range [][]byte{hdr, data} {
  643. for len(r) > 0 {
  644. size := http2MaxFrameLen
  645. if size > len(r) {
  646. size = len(r)
  647. }
  648. if streamQuota == 0 { // Used up all the locally cached stream quota.
  649. // Get all the stream quota there is.
  650. streamQuota, streamQuotaVer, err = s.sendQuotaPool.get(math.MaxInt32, s.waiters)
  651. if err != nil {
  652. return err
  653. }
  654. }
  655. if size > streamQuota {
  656. size = streamQuota
  657. }
  658. // Get size worth quota from transport.
  659. tq, _, err := t.sendQuotaPool.get(size, s.waiters)
  660. if err != nil {
  661. return err
  662. }
  663. if tq < size {
  664. size = tq
  665. }
  666. ltq, _, err := t.localSendQuota.get(size, s.waiters)
  667. if err != nil {
  668. return err
  669. }
  670. // even if ltq is smaller than size we don't adjust size since
  671. // ltq is only a soft limit.
  672. streamQuota -= size
  673. p := r[:size]
  674. var endStream bool
  675. // See if this is the last frame to be written.
  676. if opts.Last {
  677. if len(r)-size == 0 { // No more data in r after this iteration.
  678. if idx == 0 { // We're writing data header.
  679. if len(data) == 0 { // There's no data to follow.
  680. endStream = true
  681. }
  682. } else { // We're writing data.
  683. endStream = true
  684. }
  685. }
  686. }
  687. success := func() {
  688. ltq := ltq
  689. t.controlBuf.put(&dataFrame{streamID: s.id, endStream: endStream, d: p, f: func() { t.localSendQuota.add(ltq) }})
  690. r = r[size:]
  691. }
  692. failure := func() { // The stream quota version must have changed.
  693. // Our streamQuota cache is invalidated now, so give it back.
  694. s.sendQuotaPool.lockedAdd(streamQuota + size)
  695. }
  696. if !s.sendQuotaPool.compareAndExecute(streamQuotaVer, success, failure) {
  697. // Couldn't send this chunk out.
  698. t.sendQuotaPool.add(size)
  699. t.localSendQuota.add(ltq)
  700. streamQuota = 0
  701. }
  702. }
  703. }
  704. if streamQuota > 0 { // Add the left over quota back to stream.
  705. s.sendQuotaPool.add(streamQuota)
  706. }
  707. if !opts.Last {
  708. return nil
  709. }
  710. s.mu.Lock()
  711. if s.state != streamDone {
  712. s.state = streamWriteDone
  713. }
  714. s.mu.Unlock()
  715. return nil
  716. }
  717. func (t *http2Client) getStream(f http2.Frame) (*Stream, bool) {
  718. t.mu.Lock()
  719. defer t.mu.Unlock()
  720. s, ok := t.activeStreams[f.Header().StreamID]
  721. return s, ok
  722. }
  723. // adjustWindow sends out extra window update over the initial window size
  724. // of stream if the application is requesting data larger in size than
  725. // the window.
  726. func (t *http2Client) adjustWindow(s *Stream, n uint32) {
  727. s.mu.Lock()
  728. defer s.mu.Unlock()
  729. if s.state == streamDone {
  730. return
  731. }
  732. if w := s.fc.maybeAdjust(n); w > 0 {
  733. // Piggyback connection's window update along.
  734. if cw := t.fc.resetPendingUpdate(); cw > 0 {
  735. t.controlBuf.put(&windowUpdate{0, cw})
  736. }
  737. t.controlBuf.put(&windowUpdate{s.id, w})
  738. }
  739. }
  740. // updateWindow adjusts the inbound quota for the stream and the transport.
  741. // Window updates will deliver to the controller for sending when
  742. // the cumulative quota exceeds the corresponding threshold.
  743. func (t *http2Client) updateWindow(s *Stream, n uint32) {
  744. s.mu.Lock()
  745. defer s.mu.Unlock()
  746. if s.state == streamDone {
  747. return
  748. }
  749. if w := s.fc.onRead(n); w > 0 {
  750. if cw := t.fc.resetPendingUpdate(); cw > 0 {
  751. t.controlBuf.put(&windowUpdate{0, cw})
  752. }
  753. t.controlBuf.put(&windowUpdate{s.id, w})
  754. }
  755. }
  756. // updateFlowControl updates the incoming flow control windows
  757. // for the transport and the stream based on the current bdp
  758. // estimation.
  759. func (t *http2Client) updateFlowControl(n uint32) {
  760. t.mu.Lock()
  761. for _, s := range t.activeStreams {
  762. s.fc.newLimit(n)
  763. }
  764. t.initialWindowSize = int32(n)
  765. t.mu.Unlock()
  766. t.controlBuf.put(&windowUpdate{0, t.fc.newLimit(n)})
  767. t.controlBuf.put(&settings{
  768. ss: []http2.Setting{
  769. {
  770. ID: http2.SettingInitialWindowSize,
  771. Val: uint32(n),
  772. },
  773. },
  774. })
  775. }
  776. func (t *http2Client) handleData(f *http2.DataFrame) {
  777. size := f.Header().Length
  778. var sendBDPPing bool
  779. if t.bdpEst != nil {
  780. sendBDPPing = t.bdpEst.add(uint32(size))
  781. }
  782. // Decouple connection's flow control from application's read.
  783. // An update on connection's flow control should not depend on
  784. // whether user application has read the data or not. Such a
  785. // restriction is already imposed on the stream's flow control,
  786. // and therefore the sender will be blocked anyways.
  787. // Decoupling the connection flow control will prevent other
  788. // active(fast) streams from starving in presence of slow or
  789. // inactive streams.
  790. //
  791. // Furthermore, if a bdpPing is being sent out we can piggyback
  792. // connection's window update for the bytes we just received.
  793. if sendBDPPing {
  794. if size != 0 { // Could've been an empty data frame.
  795. t.controlBuf.put(&windowUpdate{0, uint32(size)})
  796. }
  797. t.controlBuf.put(bdpPing)
  798. } else {
  799. if err := t.fc.onData(uint32(size)); err != nil {
  800. t.Close()
  801. return
  802. }
  803. if w := t.fc.onRead(uint32(size)); w > 0 {
  804. t.controlBuf.put(&windowUpdate{0, w})
  805. }
  806. }
  807. // Select the right stream to dispatch.
  808. s, ok := t.getStream(f)
  809. if !ok {
  810. return
  811. }
  812. if size > 0 {
  813. s.mu.Lock()
  814. if s.state == streamDone {
  815. s.mu.Unlock()
  816. return
  817. }
  818. if err := s.fc.onData(uint32(size)); err != nil {
  819. s.rstStream = true
  820. s.rstError = http2.ErrCodeFlowControl
  821. s.finish(status.New(codes.Internal, err.Error()))
  822. s.mu.Unlock()
  823. s.write(recvMsg{err: io.EOF})
  824. return
  825. }
  826. if f.Header().Flags.Has(http2.FlagDataPadded) {
  827. if w := s.fc.onRead(uint32(size) - uint32(len(f.Data()))); w > 0 {
  828. t.controlBuf.put(&windowUpdate{s.id, w})
  829. }
  830. }
  831. s.mu.Unlock()
  832. // TODO(bradfitz, zhaoq): A copy is required here because there is no
  833. // guarantee f.Data() is consumed before the arrival of next frame.
  834. // Can this copy be eliminated?
  835. if len(f.Data()) > 0 {
  836. data := make([]byte, len(f.Data()))
  837. copy(data, f.Data())
  838. s.write(recvMsg{data: data})
  839. }
  840. }
  841. // The server has closed the stream without sending trailers. Record that
  842. // the read direction is closed, and set the status appropriately.
  843. if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) {
  844. s.mu.Lock()
  845. if s.state == streamDone {
  846. s.mu.Unlock()
  847. return
  848. }
  849. s.finish(status.New(codes.Internal, "server closed the stream without sending trailers"))
  850. s.mu.Unlock()
  851. s.write(recvMsg{err: io.EOF})
  852. }
  853. }
  854. func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) {
  855. s, ok := t.getStream(f)
  856. if !ok {
  857. return
  858. }
  859. s.mu.Lock()
  860. if s.state == streamDone {
  861. s.mu.Unlock()
  862. return
  863. }
  864. if !s.headerDone {
  865. close(s.headerChan)
  866. s.headerDone = true
  867. }
  868. code := http2.ErrCode(f.ErrCode)
  869. if code == http2.ErrCodeRefusedStream {
  870. // The stream was unprocessed by the server.
  871. s.unprocessed = true
  872. }
  873. statusCode, ok := http2ErrConvTab[code]
  874. if !ok {
  875. warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode)
  876. statusCode = codes.Unknown
  877. }
  878. s.finish(status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %v", f.ErrCode))
  879. s.mu.Unlock()
  880. s.write(recvMsg{err: io.EOF})
  881. }
  882. func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) {
  883. if f.IsAck() {
  884. return
  885. }
  886. var rs []http2.Setting
  887. var ps []http2.Setting
  888. isMaxConcurrentStreamsMissing := true
  889. f.ForeachSetting(func(s http2.Setting) error {
  890. if s.ID == http2.SettingMaxConcurrentStreams {
  891. isMaxConcurrentStreamsMissing = false
  892. }
  893. if t.isRestrictive(s) {
  894. rs = append(rs, s)
  895. } else {
  896. ps = append(ps, s)
  897. }
  898. return nil
  899. })
  900. if isFirst && isMaxConcurrentStreamsMissing {
  901. // This means server is imposing no limits on
  902. // maximum number of concurrent streams initiated by client.
  903. // So we must remove our self-imposed limit.
  904. ps = append(ps, http2.Setting{
  905. ID: http2.SettingMaxConcurrentStreams,
  906. Val: math.MaxUint32,
  907. })
  908. }
  909. t.applySettings(rs)
  910. t.controlBuf.put(&settingsAck{})
  911. t.applySettings(ps)
  912. }
  913. func (t *http2Client) isRestrictive(s http2.Setting) bool {
  914. switch s.ID {
  915. case http2.SettingMaxConcurrentStreams:
  916. return int(s.Val) < t.maxStreams
  917. case http2.SettingInitialWindowSize:
  918. // Note: we don't acquire a lock here to read streamSendQuota
  919. // because the same goroutine updates it later.
  920. return s.Val < t.streamSendQuota
  921. }
  922. return false
  923. }
  924. func (t *http2Client) handlePing(f *http2.PingFrame) {
  925. if f.IsAck() {
  926. // Maybe it's a BDP ping.
  927. if t.bdpEst != nil {
  928. t.bdpEst.calculate(f.Data)
  929. }
  930. return
  931. }
  932. pingAck := &ping{ack: true}
  933. copy(pingAck.data[:], f.Data[:])
  934. t.controlBuf.put(pingAck)
  935. }
  936. func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) {
  937. t.mu.Lock()
  938. if t.state != reachable && t.state != draining {
  939. t.mu.Unlock()
  940. return
  941. }
  942. if f.ErrCode == http2.ErrCodeEnhanceYourCalm {
  943. infof("Client received GoAway with http2.ErrCodeEnhanceYourCalm.")
  944. }
  945. id := f.LastStreamID
  946. if id > 0 && id%2 != 1 {
  947. t.mu.Unlock()
  948. t.Close()
  949. return
  950. }
  951. // A client can receive multiple GoAways from the server (see
  952. // https://github.com/grpc/grpc-go/issues/1387). The idea is that the first
  953. // GoAway will be sent with an ID of MaxInt32 and the second GoAway will be
  954. // sent after an RTT delay with the ID of the last stream the server will
  955. // process.
  956. //
  957. // Therefore, when we get the first GoAway we don't necessarily close any
  958. // streams. While in case of second GoAway we close all streams created after
  959. // the GoAwayId. This way streams that were in-flight while the GoAway from
  960. // server was being sent don't get killed.
  961. select {
  962. case <-t.goAway: // t.goAway has been closed (i.e.,multiple GoAways).
  963. // If there are multiple GoAways the first one should always have an ID greater than the following ones.
  964. if id > t.prevGoAwayID {
  965. t.mu.Unlock()
  966. t.Close()
  967. return
  968. }
  969. default:
  970. t.setGoAwayReason(f)
  971. close(t.goAway)
  972. t.state = draining
  973. }
  974. // All streams with IDs greater than the GoAwayId
  975. // and smaller than the previous GoAway ID should be killed.
  976. upperLimit := t.prevGoAwayID
  977. if upperLimit == 0 { // This is the first GoAway Frame.
  978. upperLimit = math.MaxUint32 // Kill all streams after the GoAway ID.
  979. }
  980. for streamID, stream := range t.activeStreams {
  981. if streamID > id && streamID <= upperLimit {
  982. // The stream was unprocessed by the server.
  983. stream.mu.Lock()
  984. stream.unprocessed = true
  985. stream.finish(statusGoAway)
  986. stream.mu.Unlock()
  987. close(stream.goAway)
  988. }
  989. }
  990. t.prevGoAwayID = id
  991. active := len(t.activeStreams)
  992. t.mu.Unlock()
  993. if active == 0 {
  994. t.Close()
  995. }
  996. }
  997. // setGoAwayReason sets the value of t.goAwayReason based
  998. // on the GoAway frame received.
  999. // It expects a lock on transport's mutext to be held by
  1000. // the caller.
  1001. func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) {
  1002. t.goAwayReason = GoAwayNoReason
  1003. switch f.ErrCode {
  1004. case http2.ErrCodeEnhanceYourCalm:
  1005. if string(f.DebugData()) == "too_many_pings" {
  1006. t.goAwayReason = GoAwayTooManyPings
  1007. }
  1008. }
  1009. }
  1010. func (t *http2Client) GetGoAwayReason() GoAwayReason {
  1011. t.mu.Lock()
  1012. defer t.mu.Unlock()
  1013. return t.goAwayReason
  1014. }
  1015. func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) {
  1016. id := f.Header().StreamID
  1017. incr := f.Increment
  1018. if id == 0 {
  1019. t.sendQuotaPool.add(int(incr))
  1020. return
  1021. }
  1022. if s, ok := t.getStream(f); ok {
  1023. s.sendQuotaPool.add(int(incr))
  1024. }
  1025. }
  1026. // operateHeaders takes action on the decoded headers.
  1027. func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) {
  1028. s, ok := t.getStream(frame)
  1029. if !ok {
  1030. return
  1031. }
  1032. s.mu.Lock()
  1033. s.bytesReceived = true
  1034. s.mu.Unlock()
  1035. var state decodeState
  1036. if err := state.decodeResponseHeader(frame); err != nil {
  1037. s.mu.Lock()
  1038. if !s.headerDone {
  1039. close(s.headerChan)
  1040. s.headerDone = true
  1041. }
  1042. s.mu.Unlock()
  1043. s.write(recvMsg{err: err})
  1044. // Something wrong. Stops reading even when there is remaining.
  1045. return
  1046. }
  1047. endStream := frame.StreamEnded()
  1048. var isHeader bool
  1049. defer func() {
  1050. if t.statsHandler != nil {
  1051. if isHeader {
  1052. inHeader := &stats.InHeader{
  1053. Client: true,
  1054. WireLength: int(frame.Header().Length),
  1055. }
  1056. t.statsHandler.HandleRPC(s.ctx, inHeader)
  1057. } else {
  1058. inTrailer := &stats.InTrailer{
  1059. Client: true,
  1060. WireLength: int(frame.Header().Length),
  1061. }
  1062. t.statsHandler.HandleRPC(s.ctx, inTrailer)
  1063. }
  1064. }
  1065. }()
  1066. s.mu.Lock()
  1067. if !s.headerDone {
  1068. // Headers frame is not actually a trailers-only frame.
  1069. if !endStream {
  1070. s.recvCompress = state.encoding
  1071. if len(state.mdata) > 0 {
  1072. s.header = state.mdata
  1073. }
  1074. }
  1075. close(s.headerChan)
  1076. s.headerDone = true
  1077. isHeader = true
  1078. }
  1079. if !endStream || s.state == streamDone {
  1080. s.mu.Unlock()
  1081. return
  1082. }
  1083. if len(state.mdata) > 0 {
  1084. s.trailer = state.mdata
  1085. }
  1086. s.finish(state.status())
  1087. s.mu.Unlock()
  1088. s.write(recvMsg{err: io.EOF})
  1089. }
  1090. func handleMalformedHTTP2(s *Stream, err error) {
  1091. s.mu.Lock()
  1092. if !s.headerDone {
  1093. close(s.headerChan)
  1094. s.headerDone = true
  1095. }
  1096. s.mu.Unlock()
  1097. s.write(recvMsg{err: err})
  1098. }
  1099. // reader runs as a separate goroutine in charge of reading data from network
  1100. // connection.
  1101. //
  1102. // TODO(zhaoq): currently one reader per transport. Investigate whether this is
  1103. // optimal.
  1104. // TODO(zhaoq): Check the validity of the incoming frame sequence.
  1105. func (t *http2Client) reader() {
  1106. // Check the validity of server preface.
  1107. frame, err := t.framer.fr.ReadFrame()
  1108. if err != nil {
  1109. t.Close()
  1110. return
  1111. }
  1112. atomic.CompareAndSwapUint32(&t.activity, 0, 1)
  1113. sf, ok := frame.(*http2.SettingsFrame)
  1114. if !ok {
  1115. t.Close()
  1116. return
  1117. }
  1118. t.onSuccess()
  1119. t.handleSettings(sf, true)
  1120. // loop to keep reading incoming messages on this transport.
  1121. for {
  1122. frame, err := t.framer.fr.ReadFrame()
  1123. atomic.CompareAndSwapUint32(&t.activity, 0, 1)
  1124. if err != nil {
  1125. // Abort an active stream if the http2.Framer returns a
  1126. // http2.StreamError. This can happen only if the server's response
  1127. // is malformed http2.
  1128. if se, ok := err.(http2.StreamError); ok {
  1129. t.mu.Lock()
  1130. s := t.activeStreams[se.StreamID]
  1131. t.mu.Unlock()
  1132. if s != nil {
  1133. // use error detail to provide better err message
  1134. handleMalformedHTTP2(s, streamErrorf(http2ErrConvTab[se.Code], "%v", t.framer.fr.ErrorDetail()))
  1135. }
  1136. continue
  1137. } else {
  1138. // Transport error.
  1139. t.Close()
  1140. return
  1141. }
  1142. }
  1143. switch frame := frame.(type) {
  1144. case *http2.MetaHeadersFrame:
  1145. t.operateHeaders(frame)
  1146. case *http2.DataFrame:
  1147. t.handleData(frame)
  1148. case *http2.RSTStreamFrame:
  1149. t.handleRSTStream(frame)
  1150. case *http2.SettingsFrame:
  1151. t.handleSettings(frame, false)
  1152. case *http2.PingFrame:
  1153. t.handlePing(frame)
  1154. case *http2.GoAwayFrame:
  1155. t.handleGoAway(frame)
  1156. case *http2.WindowUpdateFrame:
  1157. t.handleWindowUpdate(frame)
  1158. default:
  1159. errorf("transport: http2Client.reader got unhandled frame type %v.", frame)
  1160. }
  1161. }
  1162. }
  1163. func (t *http2Client) applySettings(ss []http2.Setting) {
  1164. for _, s := range ss {
  1165. switch s.ID {
  1166. case http2.SettingMaxConcurrentStreams:
  1167. // TODO(zhaoq): This is a hack to avoid significant refactoring of the
  1168. // code to deal with the unrealistic int32 overflow. Probably will try
  1169. // to find a better way to handle this later.
  1170. if s.Val > math.MaxInt32 {
  1171. s.Val = math.MaxInt32
  1172. }
  1173. ms := t.maxStreams
  1174. t.maxStreams = int(s.Val)
  1175. t.streamsQuota.add(int(s.Val) - ms)
  1176. case http2.SettingInitialWindowSize:
  1177. t.mu.Lock()
  1178. for _, stream := range t.activeStreams {
  1179. // Adjust the sending quota for each stream.
  1180. stream.sendQuotaPool.addAndUpdate(int(s.Val) - int(t.streamSendQuota))
  1181. }
  1182. t.streamSendQuota = s.Val
  1183. t.mu.Unlock()
  1184. }
  1185. }
  1186. }
  1187. // TODO(mmukhi): A lot of this code(and code in other places in the tranpsort layer)
  1188. // is duplicated between the client and the server.
  1189. // The transport layer needs to be refactored to take care of this.
  1190. func (t *http2Client) itemHandler(i item) (err error) {
  1191. defer func() {
  1192. if err != nil {
  1193. errorf(" error in itemHandler: %v", err)
  1194. }
  1195. }()
  1196. switch i := i.(type) {
  1197. case *dataFrame:
  1198. if err := t.framer.fr.WriteData(i.streamID, i.endStream, i.d); err != nil {
  1199. return err
  1200. }
  1201. i.f()
  1202. return nil
  1203. case *headerFrame:
  1204. t.hBuf.Reset()
  1205. for _, f := range i.hf {
  1206. t.hEnc.WriteField(f)
  1207. }
  1208. endHeaders := false
  1209. first := true
  1210. for !endHeaders {
  1211. size := t.hBuf.Len()
  1212. if size > http2MaxFrameLen {
  1213. size = http2MaxFrameLen
  1214. } else {
  1215. endHeaders = true
  1216. }
  1217. if first {
  1218. first = false
  1219. err = t.framer.fr.WriteHeaders(http2.HeadersFrameParam{
  1220. StreamID: i.streamID,
  1221. BlockFragment: t.hBuf.Next(size),
  1222. EndStream: i.endStream,
  1223. EndHeaders: endHeaders,
  1224. })
  1225. } else {
  1226. err = t.framer.fr.WriteContinuation(
  1227. i.streamID,
  1228. endHeaders,
  1229. t.hBuf.Next(size),
  1230. )
  1231. }
  1232. if err != nil {
  1233. return err
  1234. }
  1235. }
  1236. return nil
  1237. case *windowUpdate:
  1238. return t.framer.fr.WriteWindowUpdate(i.streamID, i.increment)
  1239. case *settings:
  1240. return t.framer.fr.WriteSettings(i.ss...)
  1241. case *settingsAck:
  1242. return t.framer.fr.WriteSettingsAck()
  1243. case *resetStream:
  1244. // If the server needs to be to intimated about stream closing,
  1245. // then we need to make sure the RST_STREAM frame is written to
  1246. // the wire before the headers of the next stream waiting on
  1247. // streamQuota. We ensure this by adding to the streamsQuota pool
  1248. // only after having acquired the writableChan to send RST_STREAM.
  1249. err := t.framer.fr.WriteRSTStream(i.streamID, i.code)
  1250. t.streamsQuota.add(1)
  1251. return err
  1252. case *flushIO:
  1253. return t.framer.writer.Flush()
  1254. case *ping:
  1255. if !i.ack {
  1256. t.bdpEst.timesnap(i.data)
  1257. }
  1258. return t.framer.fr.WritePing(i.ack, i.data)
  1259. default:
  1260. errorf("transport: http2Client.controller got unexpected item type %v", i)
  1261. return fmt.Errorf("transport: http2Client.controller got unexpected item type %v", i)
  1262. }
  1263. }
  1264. // keepalive running in a separate goroutune makes sure the connection is alive by sending pings.
  1265. func (t *http2Client) keepalive() {
  1266. p := &ping{data: [8]byte{}}
  1267. timer := time.NewTimer(t.kp.Time)
  1268. for {
  1269. select {
  1270. case <-timer.C:
  1271. if atomic.CompareAndSwapUint32(&t.activity, 1, 0) {
  1272. timer.Reset(t.kp.Time)
  1273. continue
  1274. }
  1275. // Check if keepalive should go dormant.
  1276. t.mu.Lock()
  1277. if len(t.activeStreams) < 1 && !t.kp.PermitWithoutStream {
  1278. // Make awakenKeepalive writable.
  1279. <-t.awakenKeepalive
  1280. t.mu.Unlock()
  1281. select {
  1282. case <-t.awakenKeepalive:
  1283. // If the control gets here a ping has been sent
  1284. // need to reset the timer with keepalive.Timeout.
  1285. case <-t.ctx.Done():
  1286. return
  1287. }
  1288. } else {
  1289. t.mu.Unlock()
  1290. // Send ping.
  1291. t.controlBuf.put(p)
  1292. }
  1293. // By the time control gets here a ping has been sent one way or the other.
  1294. timer.Reset(t.kp.Timeout)
  1295. select {
  1296. case <-timer.C:
  1297. if atomic.CompareAndSwapUint32(&t.activity, 1, 0) {
  1298. timer.Reset(t.kp.Time)
  1299. continue
  1300. }
  1301. t.Close()
  1302. return
  1303. case <-t.ctx.Done():
  1304. if !timer.Stop() {
  1305. <-timer.C
  1306. }
  1307. return
  1308. }
  1309. case <-t.ctx.Done():
  1310. if !timer.Stop() {
  1311. <-timer.C
  1312. }
  1313. return
  1314. }
  1315. }
  1316. }
  1317. func (t *http2Client) Error() <-chan struct{} {
  1318. return t.ctx.Done()
  1319. }
  1320. func (t *http2Client) GoAway() <-chan struct{} {
  1321. return t.goAway
  1322. }