blob: e18935653c16c3d03fcb75cdfe82880fd04a1231 [file] [log] [blame]
Prince Pereirac1c21d62021-04-22 08:38:15 +00001/*
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
19package transport
20
21import (
22 "context"
23 "fmt"
24 "io"
25 "math"
26 "net"
27 "strconv"
28 "strings"
29 "sync"
30 "sync/atomic"
31 "time"
32
33 "golang.org/x/net/http2"
34 "golang.org/x/net/http2/hpack"
35
36 "google.golang.org/grpc/codes"
37 "google.golang.org/grpc/credentials"
38 "google.golang.org/grpc/internal"
39 "google.golang.org/grpc/internal/channelz"
40 "google.golang.org/grpc/internal/syscall"
41 "google.golang.org/grpc/keepalive"
42 "google.golang.org/grpc/metadata"
43 "google.golang.org/grpc/peer"
44 "google.golang.org/grpc/stats"
45 "google.golang.org/grpc/status"
46)
47
48// clientConnectionCounter counts the number of connections a client has
49// initiated (equal to the number of http2Clients created). Must be accessed
50// atomically.
51var clientConnectionCounter uint64
52
53// http2Client implements the ClientTransport interface with HTTP2.
54type http2Client struct {
55 lastRead int64 // Keep this field 64-bit aligned. Accessed atomically.
56 ctx context.Context
57 cancel context.CancelFunc
58 ctxDone <-chan struct{} // Cache the ctx.Done() chan.
59 userAgent string
60 md interface{}
61 conn net.Conn // underlying communication channel
62 loopy *loopyWriter
63 remoteAddr net.Addr
64 localAddr net.Addr
65 authInfo credentials.AuthInfo // auth info about the connection
66
67 readerDone chan struct{} // sync point to enable testing.
68 writerDone chan struct{} // sync point to enable testing.
69 // goAway is closed to notify the upper layer (i.e., addrConn.transportMonitor)
70 // that the server sent GoAway on this transport.
71 goAway chan struct{}
72
73 framer *framer
74 // controlBuf delivers all the control related tasks (e.g., window
75 // updates, reset streams, and various settings) to the controller.
76 controlBuf *controlBuffer
77 fc *trInFlow
78 // The scheme used: https if TLS is on, http otherwise.
79 scheme string
80
81 isSecure bool
82
83 perRPCCreds []credentials.PerRPCCredentials
84
85 kp keepalive.ClientParameters
86 keepaliveEnabled bool
87
88 statsHandler stats.Handler
89
90 initialWindowSize int32
91
92 // configured by peer through SETTINGS_MAX_HEADER_LIST_SIZE
93 maxSendHeaderListSize *uint32
94
95 bdpEst *bdpEstimator
96 // onPrefaceReceipt is a callback that client transport calls upon
97 // receiving server preface to signal that a succefull HTTP2
98 // connection was established.
99 onPrefaceReceipt func()
100
101 maxConcurrentStreams uint32
102 streamQuota int64
103 streamsQuotaAvailable chan struct{}
104 waitingStreams uint32
105 nextID uint32
106
107 mu sync.Mutex // guard the following variables
108 state transportState
109 activeStreams map[uint32]*Stream
110 // prevGoAway ID records the Last-Stream-ID in the previous GOAway frame.
111 prevGoAwayID uint32
112 // goAwayReason records the http2.ErrCode and debug data received with the
113 // GoAway frame.
114 goAwayReason GoAwayReason
115 // A condition variable used to signal when the keepalive goroutine should
116 // go dormant. The condition for dormancy is based on the number of active
117 // streams and the `PermitWithoutStream` keepalive client parameter. And
118 // since the number of active streams is guarded by the above mutex, we use
119 // the same for this condition variable as well.
120 kpDormancyCond *sync.Cond
121 // A boolean to track whether the keepalive goroutine is dormant or not.
122 // This is checked before attempting to signal the above condition
123 // variable.
124 kpDormant bool
125
126 // Fields below are for channelz metric collection.
127 channelzID int64 // channelz unique identification number
128 czData *channelzData
129
130 onGoAway func(GoAwayReason)
131 onClose func()
132
133 bufferPool *bufferPool
134
135 connectionID uint64
136}
137
138func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr string) (net.Conn, error) {
139 if fn != nil {
140 return fn(ctx, addr)
141 }
142 return (&net.Dialer{}).DialContext(ctx, "tcp", addr)
143}
144
145func isTemporary(err error) bool {
146 switch err := err.(type) {
147 case interface {
148 Temporary() bool
149 }:
150 return err.Temporary()
151 case interface {
152 Timeout() bool
153 }:
154 // Timeouts may be resolved upon retry, and are thus treated as
155 // temporary.
156 return err.Timeout()
157 }
158 return true
159}
160
161// newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2
162// and starts to receive messages on it. Non-nil error returns if construction
163// fails.
164func newHTTP2Client(connectCtx, ctx context.Context, addr TargetInfo, opts ConnectOptions, onPrefaceReceipt func(), onGoAway func(GoAwayReason), onClose func()) (_ *http2Client, err error) {
165 scheme := "http"
166 ctx, cancel := context.WithCancel(ctx)
167 defer func() {
168 if err != nil {
169 cancel()
170 }
171 }()
172
173 conn, err := dial(connectCtx, opts.Dialer, addr.Addr)
174 if err != nil {
175 if opts.FailOnNonTempDialError {
176 return nil, connectionErrorf(isTemporary(err), err, "transport: error while dialing: %v", err)
177 }
178 return nil, connectionErrorf(true, err, "transport: Error while dialing %v", err)
179 }
180 // Any further errors will close the underlying connection
181 defer func(conn net.Conn) {
182 if err != nil {
183 conn.Close()
184 }
185 }(conn)
186 kp := opts.KeepaliveParams
187 // Validate keepalive parameters.
188 if kp.Time == 0 {
189 kp.Time = defaultClientKeepaliveTime
190 }
191 if kp.Timeout == 0 {
192 kp.Timeout = defaultClientKeepaliveTimeout
193 }
194 keepaliveEnabled := false
195 if kp.Time != infinity {
196 if err = syscall.SetTCPUserTimeout(conn, kp.Timeout); err != nil {
197 return nil, connectionErrorf(false, err, "transport: failed to set TCP_USER_TIMEOUT: %v", err)
198 }
199 keepaliveEnabled = true
200 }
201 var (
202 isSecure bool
203 authInfo credentials.AuthInfo
204 )
205 transportCreds := opts.TransportCredentials
206 perRPCCreds := opts.PerRPCCredentials
207
208 if b := opts.CredsBundle; b != nil {
209 if t := b.TransportCredentials(); t != nil {
210 transportCreds = t
211 }
212 if t := b.PerRPCCredentials(); t != nil {
213 perRPCCreds = append(perRPCCreds, t)
214 }
215 }
216 if transportCreds != nil {
217 scheme = "https"
218 conn, authInfo, err = transportCreds.ClientHandshake(connectCtx, addr.Authority, conn)
219 if err != nil {
220 return nil, connectionErrorf(isTemporary(err), err, "transport: authentication handshake failed: %v", err)
221 }
222 isSecure = true
223 }
224 dynamicWindow := true
225 icwz := int32(initialWindowSize)
226 if opts.InitialConnWindowSize >= defaultWindowSize {
227 icwz = opts.InitialConnWindowSize
228 dynamicWindow = false
229 }
230 writeBufSize := opts.WriteBufferSize
231 readBufSize := opts.ReadBufferSize
232 maxHeaderListSize := defaultClientMaxHeaderListSize
233 if opts.MaxHeaderListSize != nil {
234 maxHeaderListSize = *opts.MaxHeaderListSize
235 }
236 t := &http2Client{
237 ctx: ctx,
238 ctxDone: ctx.Done(), // Cache Done chan.
239 cancel: cancel,
240 userAgent: opts.UserAgent,
241 md: addr.Metadata,
242 conn: conn,
243 remoteAddr: conn.RemoteAddr(),
244 localAddr: conn.LocalAddr(),
245 authInfo: authInfo,
246 readerDone: make(chan struct{}),
247 writerDone: make(chan struct{}),
248 goAway: make(chan struct{}),
249 framer: newFramer(conn, writeBufSize, readBufSize, maxHeaderListSize),
250 fc: &trInFlow{limit: uint32(icwz)},
251 scheme: scheme,
252 activeStreams: make(map[uint32]*Stream),
253 isSecure: isSecure,
254 perRPCCreds: perRPCCreds,
255 kp: kp,
256 statsHandler: opts.StatsHandler,
257 initialWindowSize: initialWindowSize,
258 onPrefaceReceipt: onPrefaceReceipt,
259 nextID: 1,
260 maxConcurrentStreams: defaultMaxStreamsClient,
261 streamQuota: defaultMaxStreamsClient,
262 streamsQuotaAvailable: make(chan struct{}, 1),
263 czData: new(channelzData),
264 onGoAway: onGoAway,
265 onClose: onClose,
266 keepaliveEnabled: keepaliveEnabled,
267 bufferPool: newBufferPool(),
268 }
269 t.controlBuf = newControlBuffer(t.ctxDone)
270 if opts.InitialWindowSize >= defaultWindowSize {
271 t.initialWindowSize = opts.InitialWindowSize
272 dynamicWindow = false
273 }
274 if dynamicWindow {
275 t.bdpEst = &bdpEstimator{
276 bdp: initialWindowSize,
277 updateFlowControl: t.updateFlowControl,
278 }
279 }
280 if t.statsHandler != nil {
281 t.ctx = t.statsHandler.TagConn(t.ctx, &stats.ConnTagInfo{
282 RemoteAddr: t.remoteAddr,
283 LocalAddr: t.localAddr,
284 })
285 connBegin := &stats.ConnBegin{
286 Client: true,
287 }
288 t.statsHandler.HandleConn(t.ctx, connBegin)
289 }
290 if channelz.IsOn() {
291 t.channelzID = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, fmt.Sprintf("%s -> %s", t.localAddr, t.remoteAddr))
292 }
293 if t.keepaliveEnabled {
294 t.kpDormancyCond = sync.NewCond(&t.mu)
295 go t.keepalive()
296 }
297 // Start the reader goroutine for incoming message. Each transport has
298 // a dedicated goroutine which reads HTTP2 frame from network. Then it
299 // dispatches the frame to the corresponding stream entity.
300 go t.reader()
301
302 // Send connection preface to server.
303 n, err := t.conn.Write(clientPreface)
304 if err != nil {
305 t.Close()
306 return nil, connectionErrorf(true, err, "transport: failed to write client preface: %v", err)
307 }
308 if n != len(clientPreface) {
309 t.Close()
310 return nil, connectionErrorf(true, err, "transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface))
311 }
312 var ss []http2.Setting
313
314 if t.initialWindowSize != defaultWindowSize {
315 ss = append(ss, http2.Setting{
316 ID: http2.SettingInitialWindowSize,
317 Val: uint32(t.initialWindowSize),
318 })
319 }
320 if opts.MaxHeaderListSize != nil {
321 ss = append(ss, http2.Setting{
322 ID: http2.SettingMaxHeaderListSize,
323 Val: *opts.MaxHeaderListSize,
324 })
325 }
326 err = t.framer.fr.WriteSettings(ss...)
327 if err != nil {
328 t.Close()
329 return nil, connectionErrorf(true, err, "transport: failed to write initial settings frame: %v", err)
330 }
331 // Adjust the connection flow control window if needed.
332 if delta := uint32(icwz - defaultWindowSize); delta > 0 {
333 if err := t.framer.fr.WriteWindowUpdate(0, delta); err != nil {
334 t.Close()
335 return nil, connectionErrorf(true, err, "transport: failed to write window update: %v", err)
336 }
337 }
338
339 t.connectionID = atomic.AddUint64(&clientConnectionCounter, 1)
340
341 if err := t.framer.writer.Flush(); err != nil {
342 return nil, err
343 }
344 go func() {
345 t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst)
346 err := t.loopy.run()
347 if err != nil {
348 errorf("transport: loopyWriter.run returning. Err: %v", err)
349 }
350 // If it's a connection error, let reader goroutine handle it
351 // since there might be data in the buffers.
352 if _, ok := err.(net.Error); !ok {
353 t.conn.Close()
354 }
355 close(t.writerDone)
356 }()
357 return t, nil
358}
359
360func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream {
361 // TODO(zhaoq): Handle uint32 overflow of Stream.id.
362 s := &Stream{
363 ct: t,
364 done: make(chan struct{}),
365 method: callHdr.Method,
366 sendCompress: callHdr.SendCompress,
367 buf: newRecvBuffer(),
368 headerChan: make(chan struct{}),
369 contentSubtype: callHdr.ContentSubtype,
370 }
371 s.wq = newWriteQuota(defaultWriteQuota, s.done)
372 s.requestRead = func(n int) {
373 t.adjustWindow(s, uint32(n))
374 }
375 // The client side stream context should have exactly the same life cycle with the user provided context.
376 // That means, s.ctx should be read-only. And s.ctx is done iff ctx is done.
377 // So we use the original context here instead of creating a copy.
378 s.ctx = ctx
379 s.trReader = &transportReader{
380 reader: &recvBufferReader{
381 ctx: s.ctx,
382 ctxDone: s.ctx.Done(),
383 recv: s.buf,
384 closeStream: func(err error) {
385 t.CloseStream(s, err)
386 },
387 freeBuffer: t.bufferPool.put,
388 },
389 windowHandler: func(n int) {
390 t.updateWindow(s, uint32(n))
391 },
392 }
393 return s
394}
395
396func (t *http2Client) getPeer() *peer.Peer {
397 return &peer.Peer{
398 Addr: t.remoteAddr,
399 AuthInfo: t.authInfo,
400 }
401}
402
403func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) ([]hpack.HeaderField, error) {
404 aud := t.createAudience(callHdr)
405 ri := credentials.RequestInfo{
406 Method: callHdr.Method,
407 }
408 ctxWithRequestInfo := internal.NewRequestInfoContext.(func(context.Context, credentials.RequestInfo) context.Context)(ctx, ri)
409 authData, err := t.getTrAuthData(ctxWithRequestInfo, aud)
410 if err != nil {
411 return nil, err
412 }
413 callAuthData, err := t.getCallAuthData(ctxWithRequestInfo, aud, callHdr)
414 if err != nil {
415 return nil, err
416 }
417 // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields
418 // first and create a slice of that exact size.
419 // Make the slice of certain predictable size to reduce allocations made by append.
420 hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te
421 hfLen += len(authData) + len(callAuthData)
422 headerFields := make([]hpack.HeaderField, 0, hfLen)
423 headerFields = append(headerFields, hpack.HeaderField{Name: ":method", Value: "POST"})
424 headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme})
425 headerFields = append(headerFields, hpack.HeaderField{Name: ":path", Value: callHdr.Method})
426 headerFields = append(headerFields, hpack.HeaderField{Name: ":authority", Value: callHdr.Host})
427 headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(callHdr.ContentSubtype)})
428 headerFields = append(headerFields, hpack.HeaderField{Name: "user-agent", Value: t.userAgent})
429 headerFields = append(headerFields, hpack.HeaderField{Name: "te", Value: "trailers"})
430 if callHdr.PreviousAttempts > 0 {
431 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-previous-rpc-attempts", Value: strconv.Itoa(callHdr.PreviousAttempts)})
432 }
433
434 if callHdr.SendCompress != "" {
435 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress})
436 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-accept-encoding", Value: callHdr.SendCompress})
437 }
438 if dl, ok := ctx.Deadline(); ok {
439 // Send out timeout regardless its value. The server can detect timeout context by itself.
440 // TODO(mmukhi): Perhaps this field should be updated when actually writing out to the wire.
441 timeout := time.Until(dl)
442 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-timeout", Value: encodeTimeout(timeout)})
443 }
444 for k, v := range authData {
445 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
446 }
447 for k, v := range callAuthData {
448 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
449 }
450 if b := stats.OutgoingTags(ctx); b != nil {
451 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-tags-bin", Value: encodeBinHeader(b)})
452 }
453 if b := stats.OutgoingTrace(ctx); b != nil {
454 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-trace-bin", Value: encodeBinHeader(b)})
455 }
456
457 if md, added, ok := metadata.FromOutgoingContextRaw(ctx); ok {
458 var k string
459 for k, vv := range md {
460 // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set.
461 if isReservedHeader(k) {
462 continue
463 }
464 for _, v := range vv {
465 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
466 }
467 }
468 for _, vv := range added {
469 for i, v := range vv {
470 if i%2 == 0 {
471 k = v
472 continue
473 }
474 // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set.
475 if isReservedHeader(k) {
476 continue
477 }
478 headerFields = append(headerFields, hpack.HeaderField{Name: strings.ToLower(k), Value: encodeMetadataHeader(k, v)})
479 }
480 }
481 }
482 if md, ok := t.md.(*metadata.MD); ok {
483 for k, vv := range *md {
484 if isReservedHeader(k) {
485 continue
486 }
487 for _, v := range vv {
488 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
489 }
490 }
491 }
492 return headerFields, nil
493}
494
495func (t *http2Client) createAudience(callHdr *CallHdr) string {
496 // Create an audience string only if needed.
497 if len(t.perRPCCreds) == 0 && callHdr.Creds == nil {
498 return ""
499 }
500 // Construct URI required to get auth request metadata.
501 // Omit port if it is the default one.
502 host := strings.TrimSuffix(callHdr.Host, ":443")
503 pos := strings.LastIndex(callHdr.Method, "/")
504 if pos == -1 {
505 pos = len(callHdr.Method)
506 }
507 return "https://" + host + callHdr.Method[:pos]
508}
509
510func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[string]string, error) {
511 if len(t.perRPCCreds) == 0 {
512 return nil, nil
513 }
514 authData := map[string]string{}
515 for _, c := range t.perRPCCreds {
516 data, err := c.GetRequestMetadata(ctx, audience)
517 if err != nil {
518 if _, ok := status.FromError(err); ok {
519 return nil, err
520 }
521
522 return nil, status.Errorf(codes.Unauthenticated, "transport: %v", err)
523 }
524 for k, v := range data {
525 // Capital header names are illegal in HTTP/2.
526 k = strings.ToLower(k)
527 authData[k] = v
528 }
529 }
530 return authData, nil
531}
532
533func (t *http2Client) getCallAuthData(ctx context.Context, audience string, callHdr *CallHdr) (map[string]string, error) {
534 var callAuthData map[string]string
535 // Check if credentials.PerRPCCredentials were provided via call options.
536 // Note: if these credentials are provided both via dial options and call
537 // options, then both sets of credentials will be applied.
538 if callCreds := callHdr.Creds; callCreds != nil {
539 if !t.isSecure && callCreds.RequireTransportSecurity() {
540 return nil, status.Error(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure connection")
541 }
542 data, err := callCreds.GetRequestMetadata(ctx, audience)
543 if err != nil {
544 return nil, status.Errorf(codes.Internal, "transport: %v", err)
545 }
546 callAuthData = make(map[string]string, len(data))
547 for k, v := range data {
548 // Capital header names are illegal in HTTP/2
549 k = strings.ToLower(k)
550 callAuthData[k] = v
551 }
552 }
553 return callAuthData, nil
554}
555
556// NewStream creates a stream and registers it into the transport as "active"
557// streams.
558func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) {
559 ctx = peer.NewContext(ctx, t.getPeer())
560 headerFields, err := t.createHeaderFields(ctx, callHdr)
561 if err != nil {
562 return nil, err
563 }
564 s := t.newStream(ctx, callHdr)
565 cleanup := func(err error) {
566 if s.swapState(streamDone) == streamDone {
567 // If it was already done, return.
568 return
569 }
570 // The stream was unprocessed by the server.
571 atomic.StoreUint32(&s.unprocessed, 1)
572 s.write(recvMsg{err: err})
573 close(s.done)
574 // If headerChan isn't closed, then close it.
575 if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
576 close(s.headerChan)
577 }
578 }
579 hdr := &headerFrame{
580 hf: headerFields,
581 endStream: false,
582 initStream: func(id uint32) error {
583 t.mu.Lock()
584 if state := t.state; state != reachable {
585 t.mu.Unlock()
586 // Do a quick cleanup.
587 err := error(errStreamDrain)
588 if state == closing {
589 err = ErrConnClosing
590 }
591 cleanup(err)
592 return err
593 }
594 t.activeStreams[id] = s
595 if channelz.IsOn() {
596 atomic.AddInt64(&t.czData.streamsStarted, 1)
597 atomic.StoreInt64(&t.czData.lastStreamCreatedTime, time.Now().UnixNano())
598 }
599 // If the keepalive goroutine has gone dormant, wake it up.
600 if t.kpDormant {
601 t.kpDormancyCond.Signal()
602 }
603 t.mu.Unlock()
604 return nil
605 },
606 onOrphaned: cleanup,
607 wq: s.wq,
608 }
609 firstTry := true
610 var ch chan struct{}
611 checkForStreamQuota := func(it interface{}) bool {
612 if t.streamQuota <= 0 { // Can go negative if server decreases it.
613 if firstTry {
614 t.waitingStreams++
615 }
616 ch = t.streamsQuotaAvailable
617 return false
618 }
619 if !firstTry {
620 t.waitingStreams--
621 }
622 t.streamQuota--
623 h := it.(*headerFrame)
624 h.streamID = t.nextID
625 t.nextID += 2
626 s.id = h.streamID
627 s.fc = &inFlow{limit: uint32(t.initialWindowSize)}
628 if t.streamQuota > 0 && t.waitingStreams > 0 {
629 select {
630 case t.streamsQuotaAvailable <- struct{}{}:
631 default:
632 }
633 }
634 return true
635 }
636 var hdrListSizeErr error
637 checkForHeaderListSize := func(it interface{}) bool {
638 if t.maxSendHeaderListSize == nil {
639 return true
640 }
641 hdrFrame := it.(*headerFrame)
642 var sz int64
643 for _, f := range hdrFrame.hf {
644 if sz += int64(f.Size()); sz > int64(*t.maxSendHeaderListSize) {
645 hdrListSizeErr = status.Errorf(codes.Internal, "header list size to send violates the maximum size (%d bytes) set by server", *t.maxSendHeaderListSize)
646 return false
647 }
648 }
649 return true
650 }
651 for {
652 success, err := t.controlBuf.executeAndPut(func(it interface{}) bool {
653 if !checkForStreamQuota(it) {
654 return false
655 }
656 if !checkForHeaderListSize(it) {
657 return false
658 }
659 return true
660 }, hdr)
661 if err != nil {
662 return nil, err
663 }
664 if success {
665 break
666 }
667 if hdrListSizeErr != nil {
668 return nil, hdrListSizeErr
669 }
670 firstTry = false
671 select {
672 case <-ch:
673 case <-s.ctx.Done():
674 return nil, ContextErr(s.ctx.Err())
675 case <-t.goAway:
676 return nil, errStreamDrain
677 case <-t.ctx.Done():
678 return nil, ErrConnClosing
679 }
680 }
681 if t.statsHandler != nil {
682 header, _, _ := metadata.FromOutgoingContextRaw(ctx)
683 outHeader := &stats.OutHeader{
684 Client: true,
685 FullMethod: callHdr.Method,
686 RemoteAddr: t.remoteAddr,
687 LocalAddr: t.localAddr,
688 Compression: callHdr.SendCompress,
689 Header: header.Copy(),
690 }
691 t.statsHandler.HandleRPC(s.ctx, outHeader)
692 }
693 return s, nil
694}
695
696// CloseStream clears the footprint of a stream when the stream is not needed any more.
697// This must not be executed in reader's goroutine.
698func (t *http2Client) CloseStream(s *Stream, err error) {
699 var (
700 rst bool
701 rstCode http2.ErrCode
702 )
703 if err != nil {
704 rst = true
705 rstCode = http2.ErrCodeCancel
706 }
707 t.closeStream(s, err, rst, rstCode, status.Convert(err), nil, false)
708}
709
710func (t *http2Client) closeStream(s *Stream, err error, rst bool, rstCode http2.ErrCode, st *status.Status, mdata map[string][]string, eosReceived bool) {
711 // Set stream status to done.
712 if s.swapState(streamDone) == streamDone {
713 // If it was already done, return. If multiple closeStream calls
714 // happen simultaneously, wait for the first to finish.
715 <-s.done
716 return
717 }
718 // status and trailers can be updated here without any synchronization because the stream goroutine will
719 // only read it after it sees an io.EOF error from read or write and we'll write those errors
720 // only after updating this.
721 s.status = st
722 if len(mdata) > 0 {
723 s.trailer = mdata
724 }
725 if err != nil {
726 // This will unblock reads eventually.
727 s.write(recvMsg{err: err})
728 }
729 // If headerChan isn't closed, then close it.
730 if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
731 s.noHeaders = true
732 close(s.headerChan)
733 }
734 cleanup := &cleanupStream{
735 streamID: s.id,
736 onWrite: func() {
737 t.mu.Lock()
738 if t.activeStreams != nil {
739 delete(t.activeStreams, s.id)
740 }
741 t.mu.Unlock()
742 if channelz.IsOn() {
743 if eosReceived {
744 atomic.AddInt64(&t.czData.streamsSucceeded, 1)
745 } else {
746 atomic.AddInt64(&t.czData.streamsFailed, 1)
747 }
748 }
749 },
750 rst: rst,
751 rstCode: rstCode,
752 }
753 addBackStreamQuota := func(interface{}) bool {
754 t.streamQuota++
755 if t.streamQuota > 0 && t.waitingStreams > 0 {
756 select {
757 case t.streamsQuotaAvailable <- struct{}{}:
758 default:
759 }
760 }
761 return true
762 }
763 t.controlBuf.executeAndPut(addBackStreamQuota, cleanup)
764 // This will unblock write.
765 close(s.done)
766}
767
768// Close kicks off the shutdown process of the transport. This should be called
769// only once on a transport. Once it is called, the transport should not be
770// accessed any more.
771//
772// This method blocks until the addrConn that initiated this transport is
773// re-connected. This happens because t.onClose() begins reconnect logic at the
774// addrConn level and blocks until the addrConn is successfully connected.
775func (t *http2Client) Close() error {
776 t.mu.Lock()
777 // Make sure we only Close once.
778 if t.state == closing {
779 t.mu.Unlock()
780 return nil
781 }
782 // Call t.onClose before setting the state to closing to prevent the client
783 // from attempting to create new streams ASAP.
784 t.onClose()
785 t.state = closing
786 streams := t.activeStreams
787 t.activeStreams = nil
788 if t.kpDormant {
789 // If the keepalive goroutine is blocked on this condition variable, we
790 // should unblock it so that the goroutine eventually exits.
791 t.kpDormancyCond.Signal()
792 }
793 t.mu.Unlock()
794 t.controlBuf.finish()
795 t.cancel()
796 err := t.conn.Close()
797 if channelz.IsOn() {
798 channelz.RemoveEntry(t.channelzID)
799 }
800 // Notify all active streams.
801 for _, s := range streams {
802 t.closeStream(s, ErrConnClosing, false, http2.ErrCodeNo, status.New(codes.Unavailable, ErrConnClosing.Desc), nil, false)
803 }
804 if t.statsHandler != nil {
805 connEnd := &stats.ConnEnd{
806 Client: true,
807 }
808 t.statsHandler.HandleConn(t.ctx, connEnd)
809 }
810 return err
811}
812
813// GracefulClose sets the state to draining, which prevents new streams from
814// being created and causes the transport to be closed when the last active
815// stream is closed. If there are no active streams, the transport is closed
816// immediately. This does nothing if the transport is already draining or
817// closing.
818func (t *http2Client) GracefulClose() {
819 t.mu.Lock()
820 // Make sure we move to draining only from active.
821 if t.state == draining || t.state == closing {
822 t.mu.Unlock()
823 return
824 }
825 t.state = draining
826 active := len(t.activeStreams)
827 t.mu.Unlock()
828 if active == 0 {
829 t.Close()
830 return
831 }
832 t.controlBuf.put(&incomingGoAway{})
833}
834
835// Write formats the data into HTTP2 data frame(s) and sends it out. The caller
836// should proceed only if Write returns nil.
837func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error {
838 if opts.Last {
839 // If it's the last message, update stream state.
840 if !s.compareAndSwapState(streamActive, streamWriteDone) {
841 return errStreamDone
842 }
843 } else if s.getState() != streamActive {
844 return errStreamDone
845 }
846 df := &dataFrame{
847 streamID: s.id,
848 endStream: opts.Last,
849 }
850 if hdr != nil || data != nil { // If it's not an empty data frame.
851 // Add some data to grpc message header so that we can equally
852 // distribute bytes across frames.
853 emptyLen := http2MaxFrameLen - len(hdr)
854 if emptyLen > len(data) {
855 emptyLen = len(data)
856 }
857 hdr = append(hdr, data[:emptyLen]...)
858 data = data[emptyLen:]
859 df.h, df.d = hdr, data
860 // TODO(mmukhi): The above logic in this if can be moved to loopyWriter's data handler.
861 if err := s.wq.get(int32(len(hdr) + len(data))); err != nil {
862 return err
863 }
864 }
865 return t.controlBuf.put(df)
866}
867
868func (t *http2Client) getStream(f http2.Frame) *Stream {
869 t.mu.Lock()
870 s := t.activeStreams[f.Header().StreamID]
871 t.mu.Unlock()
872 return s
873}
874
875// adjustWindow sends out extra window update over the initial window size
876// of stream if the application is requesting data larger in size than
877// the window.
878func (t *http2Client) adjustWindow(s *Stream, n uint32) {
879 if w := s.fc.maybeAdjust(n); w > 0 {
880 t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w})
881 }
882}
883
884// updateWindow adjusts the inbound quota for the stream.
885// Window updates will be sent out when the cumulative quota
886// exceeds the corresponding threshold.
887func (t *http2Client) updateWindow(s *Stream, n uint32) {
888 if w := s.fc.onRead(n); w > 0 {
889 t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w})
890 }
891}
892
893// updateFlowControl updates the incoming flow control windows
894// for the transport and the stream based on the current bdp
895// estimation.
896func (t *http2Client) updateFlowControl(n uint32) {
897 t.mu.Lock()
898 for _, s := range t.activeStreams {
899 s.fc.newLimit(n)
900 }
901 t.mu.Unlock()
902 updateIWS := func(interface{}) bool {
903 t.initialWindowSize = int32(n)
904 return true
905 }
906 t.controlBuf.executeAndPut(updateIWS, &outgoingWindowUpdate{streamID: 0, increment: t.fc.newLimit(n)})
907 t.controlBuf.put(&outgoingSettings{
908 ss: []http2.Setting{
909 {
910 ID: http2.SettingInitialWindowSize,
911 Val: n,
912 },
913 },
914 })
915}
916
917func (t *http2Client) handleData(f *http2.DataFrame) {
918 size := f.Header().Length
919 var sendBDPPing bool
920 if t.bdpEst != nil {
921 sendBDPPing = t.bdpEst.add(size)
922 }
923 // Decouple connection's flow control from application's read.
924 // An update on connection's flow control should not depend on
925 // whether user application has read the data or not. Such a
926 // restriction is already imposed on the stream's flow control,
927 // and therefore the sender will be blocked anyways.
928 // Decoupling the connection flow control will prevent other
929 // active(fast) streams from starving in presence of slow or
930 // inactive streams.
931 //
932 if w := t.fc.onData(size); w > 0 {
933 t.controlBuf.put(&outgoingWindowUpdate{
934 streamID: 0,
935 increment: w,
936 })
937 }
938 if sendBDPPing {
939 // Avoid excessive ping detection (e.g. in an L7 proxy)
940 // by sending a window update prior to the BDP ping.
941
942 if w := t.fc.reset(); w > 0 {
943 t.controlBuf.put(&outgoingWindowUpdate{
944 streamID: 0,
945 increment: w,
946 })
947 }
948
949 t.controlBuf.put(bdpPing)
950 }
951 // Select the right stream to dispatch.
952 s := t.getStream(f)
953 if s == nil {
954 return
955 }
956 if size > 0 {
957 if err := s.fc.onData(size); err != nil {
958 t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false)
959 return
960 }
961 if f.Header().Flags.Has(http2.FlagDataPadded) {
962 if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 {
963 t.controlBuf.put(&outgoingWindowUpdate{s.id, w})
964 }
965 }
966 // TODO(bradfitz, zhaoq): A copy is required here because there is no
967 // guarantee f.Data() is consumed before the arrival of next frame.
968 // Can this copy be eliminated?
969 if len(f.Data()) > 0 {
970 buffer := t.bufferPool.get()
971 buffer.Reset()
972 buffer.Write(f.Data())
973 s.write(recvMsg{buffer: buffer})
974 }
975 }
976 // The server has closed the stream without sending trailers. Record that
977 // the read direction is closed, and set the status appropriately.
978 if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) {
979 t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.New(codes.Internal, "server closed the stream without sending trailers"), nil, true)
980 }
981}
982
983func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) {
984 s := t.getStream(f)
985 if s == nil {
986 return
987 }
988 if f.ErrCode == http2.ErrCodeRefusedStream {
989 // The stream was unprocessed by the server.
990 atomic.StoreUint32(&s.unprocessed, 1)
991 }
992 statusCode, ok := http2ErrConvTab[f.ErrCode]
993 if !ok {
994 warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode)
995 statusCode = codes.Unknown
996 }
997 if statusCode == codes.Canceled {
998 if d, ok := s.ctx.Deadline(); ok && !d.After(time.Now()) {
999 // Our deadline was already exceeded, and that was likely the cause
1000 // of this cancelation. Alter the status code accordingly.
1001 statusCode = codes.DeadlineExceeded
1002 }
1003 }
1004 t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %v", f.ErrCode), nil, false)
1005}
1006
1007func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) {
1008 if f.IsAck() {
1009 return
1010 }
1011 var maxStreams *uint32
1012 var ss []http2.Setting
1013 var updateFuncs []func()
1014 f.ForeachSetting(func(s http2.Setting) error {
1015 switch s.ID {
1016 case http2.SettingMaxConcurrentStreams:
1017 maxStreams = new(uint32)
1018 *maxStreams = s.Val
1019 case http2.SettingMaxHeaderListSize:
1020 updateFuncs = append(updateFuncs, func() {
1021 t.maxSendHeaderListSize = new(uint32)
1022 *t.maxSendHeaderListSize = s.Val
1023 })
1024 default:
1025 ss = append(ss, s)
1026 }
1027 return nil
1028 })
1029 if isFirst && maxStreams == nil {
1030 maxStreams = new(uint32)
1031 *maxStreams = math.MaxUint32
1032 }
1033 sf := &incomingSettings{
1034 ss: ss,
1035 }
1036 if maxStreams != nil {
1037 updateStreamQuota := func() {
1038 delta := int64(*maxStreams) - int64(t.maxConcurrentStreams)
1039 t.maxConcurrentStreams = *maxStreams
1040 t.streamQuota += delta
1041 if delta > 0 && t.waitingStreams > 0 {
1042 close(t.streamsQuotaAvailable) // wake all of them up.
1043 t.streamsQuotaAvailable = make(chan struct{}, 1)
1044 }
1045 }
1046 updateFuncs = append(updateFuncs, updateStreamQuota)
1047 }
1048 t.controlBuf.executeAndPut(func(interface{}) bool {
1049 for _, f := range updateFuncs {
1050 f()
1051 }
1052 return true
1053 }, sf)
1054}
1055
1056func (t *http2Client) handlePing(f *http2.PingFrame) {
1057 if f.IsAck() {
1058 // Maybe it's a BDP ping.
1059 if t.bdpEst != nil {
1060 t.bdpEst.calculate(f.Data)
1061 }
1062 return
1063 }
1064 pingAck := &ping{ack: true}
1065 copy(pingAck.data[:], f.Data[:])
1066 t.controlBuf.put(pingAck)
1067}
1068
1069func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) {
1070 t.mu.Lock()
1071 if t.state == closing {
1072 t.mu.Unlock()
1073 return
1074 }
1075 if f.ErrCode == http2.ErrCodeEnhanceYourCalm {
1076 infof("Client received GoAway with http2.ErrCodeEnhanceYourCalm.")
1077 }
1078 id := f.LastStreamID
1079 if id > 0 && id%2 != 1 {
1080 t.mu.Unlock()
1081 t.Close()
1082 return
1083 }
1084 // A client can receive multiple GoAways from the server (see
1085 // https://github.com/grpc/grpc-go/issues/1387). The idea is that the first
1086 // GoAway will be sent with an ID of MaxInt32 and the second GoAway will be
1087 // sent after an RTT delay with the ID of the last stream the server will
1088 // process.
1089 //
1090 // Therefore, when we get the first GoAway we don't necessarily close any
1091 // streams. While in case of second GoAway we close all streams created after
1092 // the GoAwayId. This way streams that were in-flight while the GoAway from
1093 // server was being sent don't get killed.
1094 select {
1095 case <-t.goAway: // t.goAway has been closed (i.e.,multiple GoAways).
1096 // If there are multiple GoAways the first one should always have an ID greater than the following ones.
1097 if id > t.prevGoAwayID {
1098 t.mu.Unlock()
1099 t.Close()
1100 return
1101 }
1102 default:
1103 t.setGoAwayReason(f)
1104 close(t.goAway)
1105 t.controlBuf.put(&incomingGoAway{})
1106 // Notify the clientconn about the GOAWAY before we set the state to
1107 // draining, to allow the client to stop attempting to create streams
1108 // before disallowing new streams on this connection.
1109 t.onGoAway(t.goAwayReason)
1110 t.state = draining
1111 }
1112 // All streams with IDs greater than the GoAwayId
1113 // and smaller than the previous GoAway ID should be killed.
1114 upperLimit := t.prevGoAwayID
1115 if upperLimit == 0 { // This is the first GoAway Frame.
1116 upperLimit = math.MaxUint32 // Kill all streams after the GoAway ID.
1117 }
1118 for streamID, stream := range t.activeStreams {
1119 if streamID > id && streamID <= upperLimit {
1120 // The stream was unprocessed by the server.
1121 atomic.StoreUint32(&stream.unprocessed, 1)
1122 t.closeStream(stream, errStreamDrain, false, http2.ErrCodeNo, statusGoAway, nil, false)
1123 }
1124 }
1125 t.prevGoAwayID = id
1126 active := len(t.activeStreams)
1127 t.mu.Unlock()
1128 if active == 0 {
1129 t.Close()
1130 }
1131}
1132
1133// setGoAwayReason sets the value of t.goAwayReason based
1134// on the GoAway frame received.
1135// It expects a lock on transport's mutext to be held by
1136// the caller.
1137func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) {
1138 t.goAwayReason = GoAwayNoReason
1139 switch f.ErrCode {
1140 case http2.ErrCodeEnhanceYourCalm:
1141 if string(f.DebugData()) == "too_many_pings" {
1142 t.goAwayReason = GoAwayTooManyPings
1143 }
1144 }
1145}
1146
1147func (t *http2Client) GetGoAwayReason() GoAwayReason {
1148 t.mu.Lock()
1149 defer t.mu.Unlock()
1150 return t.goAwayReason
1151}
1152
1153func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) {
1154 t.controlBuf.put(&incomingWindowUpdate{
1155 streamID: f.Header().StreamID,
1156 increment: f.Increment,
1157 })
1158}
1159
1160// operateHeaders takes action on the decoded headers.
1161func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) {
1162 s := t.getStream(frame)
1163 if s == nil {
1164 return
1165 }
1166 endStream := frame.StreamEnded()
1167 atomic.StoreUint32(&s.bytesReceived, 1)
1168 initialHeader := atomic.LoadUint32(&s.headerChanClosed) == 0
1169
1170 if !initialHeader && !endStream {
1171 // As specified by gRPC over HTTP2, a HEADERS frame (and associated CONTINUATION frames) can only appear at the start or end of a stream. Therefore, second HEADERS frame must have EOS bit set.
1172 st := status.New(codes.Internal, "a HEADERS frame cannot appear in the middle of a stream")
1173 t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, false)
1174 return
1175 }
1176
1177 state := &decodeState{}
1178 // Initialize isGRPC value to be !initialHeader, since if a gRPC Response-Headers has already been received, then it means that the peer is speaking gRPC and we are in gRPC mode.
1179 state.data.isGRPC = !initialHeader
1180 if err := state.decodeHeader(frame); err != nil {
1181 t.closeStream(s, err, true, http2.ErrCodeProtocol, status.Convert(err), nil, endStream)
1182 return
1183 }
1184
1185 isHeader := false
1186 defer func() {
1187 if t.statsHandler != nil {
1188 if isHeader {
1189 inHeader := &stats.InHeader{
1190 Client: true,
1191 WireLength: int(frame.Header().Length),
1192 Header: s.header.Copy(),
1193 }
1194 t.statsHandler.HandleRPC(s.ctx, inHeader)
1195 } else {
1196 inTrailer := &stats.InTrailer{
1197 Client: true,
1198 WireLength: int(frame.Header().Length),
1199 Trailer: s.trailer.Copy(),
1200 }
1201 t.statsHandler.HandleRPC(s.ctx, inTrailer)
1202 }
1203 }
1204 }()
1205
1206 // If headerChan hasn't been closed yet
1207 if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
1208 s.headerValid = true
1209 if !endStream {
1210 // HEADERS frame block carries a Response-Headers.
1211 isHeader = true
1212 // These values can be set without any synchronization because
1213 // stream goroutine will read it only after seeing a closed
1214 // headerChan which we'll close after setting this.
1215 s.recvCompress = state.data.encoding
1216 if len(state.data.mdata) > 0 {
1217 s.header = state.data.mdata
1218 }
1219 } else {
1220 // HEADERS frame block carries a Trailers-Only.
1221 s.noHeaders = true
1222 }
1223 close(s.headerChan)
1224 }
1225
1226 if !endStream {
1227 return
1228 }
1229
1230 // if client received END_STREAM from server while stream was still active, send RST_STREAM
1231 rst := s.getState() == streamActive
1232 t.closeStream(s, io.EOF, rst, http2.ErrCodeNo, state.status(), state.data.mdata, true)
1233}
1234
1235// reader runs as a separate goroutine in charge of reading data from network
1236// connection.
1237//
1238// TODO(zhaoq): currently one reader per transport. Investigate whether this is
1239// optimal.
1240// TODO(zhaoq): Check the validity of the incoming frame sequence.
1241func (t *http2Client) reader() {
1242 defer close(t.readerDone)
1243 // Check the validity of server preface.
1244 frame, err := t.framer.fr.ReadFrame()
1245 if err != nil {
1246 t.Close() // this kicks off resetTransport, so must be last before return
1247 return
1248 }
1249 t.conn.SetReadDeadline(time.Time{}) // reset deadline once we get the settings frame (we didn't time out, yay!)
1250 if t.keepaliveEnabled {
1251 atomic.StoreInt64(&t.lastRead, time.Now().UnixNano())
1252 }
1253 sf, ok := frame.(*http2.SettingsFrame)
1254 if !ok {
1255 t.Close() // this kicks off resetTransport, so must be last before return
1256 return
1257 }
1258 t.onPrefaceReceipt()
1259 t.handleSettings(sf, true)
1260
1261 // loop to keep reading incoming messages on this transport.
1262 for {
1263 t.controlBuf.throttle()
1264 frame, err := t.framer.fr.ReadFrame()
1265 if t.keepaliveEnabled {
1266 atomic.StoreInt64(&t.lastRead, time.Now().UnixNano())
1267 }
1268 if err != nil {
1269 // Abort an active stream if the http2.Framer returns a
1270 // http2.StreamError. This can happen only if the server's response
1271 // is malformed http2.
1272 if se, ok := err.(http2.StreamError); ok {
1273 t.mu.Lock()
1274 s := t.activeStreams[se.StreamID]
1275 t.mu.Unlock()
1276 if s != nil {
1277 // use error detail to provide better err message
1278 code := http2ErrConvTab[se.Code]
1279 msg := t.framer.fr.ErrorDetail().Error()
1280 t.closeStream(s, status.Error(code, msg), true, http2.ErrCodeProtocol, status.New(code, msg), nil, false)
1281 }
1282 continue
1283 } else {
1284 // Transport error.
1285 t.Close()
1286 return
1287 }
1288 }
1289 switch frame := frame.(type) {
1290 case *http2.MetaHeadersFrame:
1291 t.operateHeaders(frame)
1292 case *http2.DataFrame:
1293 t.handleData(frame)
1294 case *http2.RSTStreamFrame:
1295 t.handleRSTStream(frame)
1296 case *http2.SettingsFrame:
1297 t.handleSettings(frame, false)
1298 case *http2.PingFrame:
1299 t.handlePing(frame)
1300 case *http2.GoAwayFrame:
1301 t.handleGoAway(frame)
1302 case *http2.WindowUpdateFrame:
1303 t.handleWindowUpdate(frame)
1304 default:
1305 errorf("transport: http2Client.reader got unhandled frame type %v.", frame)
1306 }
1307 }
1308}
1309
1310func minTime(a, b time.Duration) time.Duration {
1311 if a < b {
1312 return a
1313 }
1314 return b
1315}
1316
1317// keepalive running in a separate goroutune makes sure the connection is alive by sending pings.
1318func (t *http2Client) keepalive() {
1319 p := &ping{data: [8]byte{}}
1320 // True iff a ping has been sent, and no data has been received since then.
1321 outstandingPing := false
1322 // Amount of time remaining before which we should receive an ACK for the
1323 // last sent ping.
1324 timeoutLeft := time.Duration(0)
1325 // Records the last value of t.lastRead before we go block on the timer.
1326 // This is required to check for read activity since then.
1327 prevNano := time.Now().UnixNano()
1328 timer := time.NewTimer(t.kp.Time)
1329 for {
1330 select {
1331 case <-timer.C:
1332 lastRead := atomic.LoadInt64(&t.lastRead)
1333 if lastRead > prevNano {
1334 // There has been read activity since the last time we were here.
1335 outstandingPing = false
1336 // Next timer should fire at kp.Time seconds from lastRead time.
1337 timer.Reset(time.Duration(lastRead) + t.kp.Time - time.Duration(time.Now().UnixNano()))
1338 prevNano = lastRead
1339 continue
1340 }
1341 if outstandingPing && timeoutLeft <= 0 {
1342 t.Close()
1343 return
1344 }
1345 t.mu.Lock()
1346 if t.state == closing {
1347 // If the transport is closing, we should exit from the
1348 // keepalive goroutine here. If not, we could have a race
1349 // between the call to Signal() from Close() and the call to
1350 // Wait() here, whereby the keepalive goroutine ends up
1351 // blocking on the condition variable which will never be
1352 // signalled again.
1353 t.mu.Unlock()
1354 return
1355 }
1356 if len(t.activeStreams) < 1 && !t.kp.PermitWithoutStream {
1357 // If a ping was sent out previously (because there were active
1358 // streams at that point) which wasn't acked and its timeout
1359 // hadn't fired, but we got here and are about to go dormant,
1360 // we should make sure that we unconditionally send a ping once
1361 // we awaken.
1362 outstandingPing = false
1363 t.kpDormant = true
1364 t.kpDormancyCond.Wait()
1365 }
1366 t.kpDormant = false
1367 t.mu.Unlock()
1368
1369 // We get here either because we were dormant and a new stream was
1370 // created which unblocked the Wait() call, or because the
1371 // keepalive timer expired. In both cases, we need to send a ping.
1372 if !outstandingPing {
1373 if channelz.IsOn() {
1374 atomic.AddInt64(&t.czData.kpCount, 1)
1375 }
1376 t.controlBuf.put(p)
1377 timeoutLeft = t.kp.Timeout
1378 outstandingPing = true
1379 }
1380 // The amount of time to sleep here is the minimum of kp.Time and
1381 // timeoutLeft. This will ensure that we wait only for kp.Time
1382 // before sending out the next ping (for cases where the ping is
1383 // acked).
1384 sleepDuration := minTime(t.kp.Time, timeoutLeft)
1385 timeoutLeft -= sleepDuration
1386 timer.Reset(sleepDuration)
1387 case <-t.ctx.Done():
1388 if !timer.Stop() {
1389 <-timer.C
1390 }
1391 return
1392 }
1393 }
1394}
1395
1396func (t *http2Client) Error() <-chan struct{} {
1397 return t.ctx.Done()
1398}
1399
1400func (t *http2Client) GoAway() <-chan struct{} {
1401 return t.goAway
1402}
1403
1404func (t *http2Client) ChannelzMetric() *channelz.SocketInternalMetric {
1405 s := channelz.SocketInternalMetric{
1406 StreamsStarted: atomic.LoadInt64(&t.czData.streamsStarted),
1407 StreamsSucceeded: atomic.LoadInt64(&t.czData.streamsSucceeded),
1408 StreamsFailed: atomic.LoadInt64(&t.czData.streamsFailed),
1409 MessagesSent: atomic.LoadInt64(&t.czData.msgSent),
1410 MessagesReceived: atomic.LoadInt64(&t.czData.msgRecv),
1411 KeepAlivesSent: atomic.LoadInt64(&t.czData.kpCount),
1412 LastLocalStreamCreatedTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastStreamCreatedTime)),
1413 LastMessageSentTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastMsgSentTime)),
1414 LastMessageReceivedTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastMsgRecvTime)),
1415 LocalFlowControlWindow: int64(t.fc.getSize()),
1416 SocketOptions: channelz.GetSocketOption(t.conn),
1417 LocalAddr: t.localAddr,
1418 RemoteAddr: t.remoteAddr,
1419 // RemoteName :
1420 }
1421 if au, ok := t.authInfo.(credentials.ChannelzSecurityInfo); ok {
1422 s.Security = au.GetSecurityValue()
1423 }
1424 s.RemoteFlowControlWindow = t.getOutFlowWindow()
1425 return &s
1426}
1427
1428func (t *http2Client) RemoteAddr() net.Addr { return t.remoteAddr }
1429
1430func (t *http2Client) IncrMsgSent() {
1431 atomic.AddInt64(&t.czData.msgSent, 1)
1432 atomic.StoreInt64(&t.czData.lastMsgSentTime, time.Now().UnixNano())
1433}
1434
1435func (t *http2Client) IncrMsgRecv() {
1436 atomic.AddInt64(&t.czData.msgRecv, 1)
1437 atomic.StoreInt64(&t.czData.lastMsgRecvTime, time.Now().UnixNano())
1438}
1439
1440func (t *http2Client) getOutFlowWindow() int64 {
1441 resp := make(chan uint32, 1)
1442 timer := time.NewTimer(time.Second)
1443 defer timer.Stop()
1444 t.controlBuf.put(&outFlowControlSizeRequest{resp})
1445 select {
1446 case sz := <-resp:
1447 return int64(sz)
1448 case <-t.ctxDone:
1449 return -1
1450 case <-timer.C:
1451 return -2
1452 }
1453}