blob: b1b82ec956eb0a4f1d52635499076615ef70d19f [file] [log] [blame]
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +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
Dinesh Belwalkar396b6522020-02-06 22:11:53 +000048// 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
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +000053// http2Client implements the ClientTransport interface with HTTP2.
54type http2Client struct {
Dinesh Belwalkar396b6522020-02-06 22:11:53 +000055 lastRead int64 // Keep this field 64-bit aligned. Accessed atomically.
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +000056 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
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000134
135 connectionID uint64
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000136}
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
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000339 t.connectionID = atomic.AddUint64(&clientConnectionCounter, 1)
340
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000341 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{
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000406 Method: callHdr.Method,
407 AuthInfo: t.authInfo,
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000408 }
409 ctxWithRequestInfo := internal.NewRequestInfoContext.(func(context.Context, credentials.RequestInfo) context.Context)(ctx, ri)
410 authData, err := t.getTrAuthData(ctxWithRequestInfo, aud)
411 if err != nil {
412 return nil, err
413 }
414 callAuthData, err := t.getCallAuthData(ctxWithRequestInfo, aud, callHdr)
415 if err != nil {
416 return nil, err
417 }
418 // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields
419 // first and create a slice of that exact size.
420 // Make the slice of certain predictable size to reduce allocations made by append.
421 hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te
422 hfLen += len(authData) + len(callAuthData)
423 headerFields := make([]hpack.HeaderField, 0, hfLen)
424 headerFields = append(headerFields, hpack.HeaderField{Name: ":method", Value: "POST"})
425 headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme})
426 headerFields = append(headerFields, hpack.HeaderField{Name: ":path", Value: callHdr.Method})
427 headerFields = append(headerFields, hpack.HeaderField{Name: ":authority", Value: callHdr.Host})
428 headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(callHdr.ContentSubtype)})
429 headerFields = append(headerFields, hpack.HeaderField{Name: "user-agent", Value: t.userAgent})
430 headerFields = append(headerFields, hpack.HeaderField{Name: "te", Value: "trailers"})
431 if callHdr.PreviousAttempts > 0 {
432 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-previous-rpc-attempts", Value: strconv.Itoa(callHdr.PreviousAttempts)})
433 }
434
435 if callHdr.SendCompress != "" {
436 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress})
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000437 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-accept-encoding", Value: callHdr.SendCompress})
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000438 }
439 if dl, ok := ctx.Deadline(); ok {
440 // Send out timeout regardless its value. The server can detect timeout context by itself.
441 // TODO(mmukhi): Perhaps this field should be updated when actually writing out to the wire.
442 timeout := time.Until(dl)
443 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-timeout", Value: encodeTimeout(timeout)})
444 }
445 for k, v := range authData {
446 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
447 }
448 for k, v := range callAuthData {
449 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
450 }
451 if b := stats.OutgoingTags(ctx); b != nil {
452 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-tags-bin", Value: encodeBinHeader(b)})
453 }
454 if b := stats.OutgoingTrace(ctx); b != nil {
455 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-trace-bin", Value: encodeBinHeader(b)})
456 }
457
458 if md, added, ok := metadata.FromOutgoingContextRaw(ctx); ok {
459 var k string
460 for k, vv := range md {
461 // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set.
462 if isReservedHeader(k) {
463 continue
464 }
465 for _, v := range vv {
466 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
467 }
468 }
469 for _, vv := range added {
470 for i, v := range vv {
471 if i%2 == 0 {
472 k = v
473 continue
474 }
475 // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set.
476 if isReservedHeader(k) {
477 continue
478 }
479 headerFields = append(headerFields, hpack.HeaderField{Name: strings.ToLower(k), Value: encodeMetadataHeader(k, v)})
480 }
481 }
482 }
483 if md, ok := t.md.(*metadata.MD); ok {
484 for k, vv := range *md {
485 if isReservedHeader(k) {
486 continue
487 }
488 for _, v := range vv {
489 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
490 }
491 }
492 }
493 return headerFields, nil
494}
495
496func (t *http2Client) createAudience(callHdr *CallHdr) string {
497 // Create an audience string only if needed.
498 if len(t.perRPCCreds) == 0 && callHdr.Creds == nil {
499 return ""
500 }
501 // Construct URI required to get auth request metadata.
502 // Omit port if it is the default one.
503 host := strings.TrimSuffix(callHdr.Host, ":443")
504 pos := strings.LastIndex(callHdr.Method, "/")
505 if pos == -1 {
506 pos = len(callHdr.Method)
507 }
508 return "https://" + host + callHdr.Method[:pos]
509}
510
511func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[string]string, error) {
512 if len(t.perRPCCreds) == 0 {
513 return nil, nil
514 }
515 authData := map[string]string{}
516 for _, c := range t.perRPCCreds {
517 data, err := c.GetRequestMetadata(ctx, audience)
518 if err != nil {
519 if _, ok := status.FromError(err); ok {
520 return nil, err
521 }
522
523 return nil, status.Errorf(codes.Unauthenticated, "transport: %v", err)
524 }
525 for k, v := range data {
526 // Capital header names are illegal in HTTP/2.
527 k = strings.ToLower(k)
528 authData[k] = v
529 }
530 }
531 return authData, nil
532}
533
534func (t *http2Client) getCallAuthData(ctx context.Context, audience string, callHdr *CallHdr) (map[string]string, error) {
535 var callAuthData map[string]string
536 // Check if credentials.PerRPCCredentials were provided via call options.
537 // Note: if these credentials are provided both via dial options and call
538 // options, then both sets of credentials will be applied.
539 if callCreds := callHdr.Creds; callCreds != nil {
540 if !t.isSecure && callCreds.RequireTransportSecurity() {
541 return nil, status.Error(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure connection")
542 }
543 data, err := callCreds.GetRequestMetadata(ctx, audience)
544 if err != nil {
545 return nil, status.Errorf(codes.Internal, "transport: %v", err)
546 }
547 callAuthData = make(map[string]string, len(data))
548 for k, v := range data {
549 // Capital header names are illegal in HTTP/2
550 k = strings.ToLower(k)
551 callAuthData[k] = v
552 }
553 }
554 return callAuthData, nil
555}
556
557// NewStream creates a stream and registers it into the transport as "active"
558// streams.
559func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) {
560 ctx = peer.NewContext(ctx, t.getPeer())
561 headerFields, err := t.createHeaderFields(ctx, callHdr)
562 if err != nil {
563 return nil, err
564 }
565 s := t.newStream(ctx, callHdr)
566 cleanup := func(err error) {
567 if s.swapState(streamDone) == streamDone {
568 // If it was already done, return.
569 return
570 }
571 // The stream was unprocessed by the server.
572 atomic.StoreUint32(&s.unprocessed, 1)
573 s.write(recvMsg{err: err})
574 close(s.done)
575 // If headerChan isn't closed, then close it.
576 if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
577 close(s.headerChan)
578 }
579 }
580 hdr := &headerFrame{
581 hf: headerFields,
582 endStream: false,
583 initStream: func(id uint32) error {
584 t.mu.Lock()
585 if state := t.state; state != reachable {
586 t.mu.Unlock()
587 // Do a quick cleanup.
588 err := error(errStreamDrain)
589 if state == closing {
590 err = ErrConnClosing
591 }
592 cleanup(err)
593 return err
594 }
595 t.activeStreams[id] = s
596 if channelz.IsOn() {
597 atomic.AddInt64(&t.czData.streamsStarted, 1)
598 atomic.StoreInt64(&t.czData.lastStreamCreatedTime, time.Now().UnixNano())
599 }
600 // If the keepalive goroutine has gone dormant, wake it up.
601 if t.kpDormant {
602 t.kpDormancyCond.Signal()
603 }
604 t.mu.Unlock()
605 return nil
606 },
607 onOrphaned: cleanup,
608 wq: s.wq,
609 }
610 firstTry := true
611 var ch chan struct{}
612 checkForStreamQuota := func(it interface{}) bool {
613 if t.streamQuota <= 0 { // Can go negative if server decreases it.
614 if firstTry {
615 t.waitingStreams++
616 }
617 ch = t.streamsQuotaAvailable
618 return false
619 }
620 if !firstTry {
621 t.waitingStreams--
622 }
623 t.streamQuota--
624 h := it.(*headerFrame)
625 h.streamID = t.nextID
626 t.nextID += 2
627 s.id = h.streamID
628 s.fc = &inFlow{limit: uint32(t.initialWindowSize)}
629 if t.streamQuota > 0 && t.waitingStreams > 0 {
630 select {
631 case t.streamsQuotaAvailable <- struct{}{}:
632 default:
633 }
634 }
635 return true
636 }
637 var hdrListSizeErr error
638 checkForHeaderListSize := func(it interface{}) bool {
639 if t.maxSendHeaderListSize == nil {
640 return true
641 }
642 hdrFrame := it.(*headerFrame)
643 var sz int64
644 for _, f := range hdrFrame.hf {
645 if sz += int64(f.Size()); sz > int64(*t.maxSendHeaderListSize) {
646 hdrListSizeErr = status.Errorf(codes.Internal, "header list size to send violates the maximum size (%d bytes) set by server", *t.maxSendHeaderListSize)
647 return false
648 }
649 }
650 return true
651 }
652 for {
653 success, err := t.controlBuf.executeAndPut(func(it interface{}) bool {
654 if !checkForStreamQuota(it) {
655 return false
656 }
657 if !checkForHeaderListSize(it) {
658 return false
659 }
660 return true
661 }, hdr)
662 if err != nil {
663 return nil, err
664 }
665 if success {
666 break
667 }
668 if hdrListSizeErr != nil {
669 return nil, hdrListSizeErr
670 }
671 firstTry = false
672 select {
673 case <-ch:
674 case <-s.ctx.Done():
675 return nil, ContextErr(s.ctx.Err())
676 case <-t.goAway:
677 return nil, errStreamDrain
678 case <-t.ctx.Done():
679 return nil, ErrConnClosing
680 }
681 }
682 if t.statsHandler != nil {
Scott Baker105df152020-04-13 15:55:14 -0700683 header, ok := metadata.FromOutgoingContext(ctx)
684 if ok {
685 header.Set("user-agent", t.userAgent)
686 } else {
687 header = metadata.Pairs("user-agent", t.userAgent)
688 }
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000689 outHeader := &stats.OutHeader{
690 Client: true,
691 FullMethod: callHdr.Method,
692 RemoteAddr: t.remoteAddr,
693 LocalAddr: t.localAddr,
694 Compression: callHdr.SendCompress,
Scott Baker105df152020-04-13 15:55:14 -0700695 Header: header,
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000696 }
697 t.statsHandler.HandleRPC(s.ctx, outHeader)
698 }
699 return s, nil
700}
701
702// CloseStream clears the footprint of a stream when the stream is not needed any more.
703// This must not be executed in reader's goroutine.
704func (t *http2Client) CloseStream(s *Stream, err error) {
705 var (
706 rst bool
707 rstCode http2.ErrCode
708 )
709 if err != nil {
710 rst = true
711 rstCode = http2.ErrCodeCancel
712 }
713 t.closeStream(s, err, rst, rstCode, status.Convert(err), nil, false)
714}
715
716func (t *http2Client) closeStream(s *Stream, err error, rst bool, rstCode http2.ErrCode, st *status.Status, mdata map[string][]string, eosReceived bool) {
717 // Set stream status to done.
718 if s.swapState(streamDone) == streamDone {
719 // If it was already done, return. If multiple closeStream calls
720 // happen simultaneously, wait for the first to finish.
721 <-s.done
722 return
723 }
724 // status and trailers can be updated here without any synchronization because the stream goroutine will
725 // only read it after it sees an io.EOF error from read or write and we'll write those errors
726 // only after updating this.
727 s.status = st
728 if len(mdata) > 0 {
729 s.trailer = mdata
730 }
731 if err != nil {
732 // This will unblock reads eventually.
733 s.write(recvMsg{err: err})
734 }
735 // If headerChan isn't closed, then close it.
736 if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
737 s.noHeaders = true
738 close(s.headerChan)
739 }
740 cleanup := &cleanupStream{
741 streamID: s.id,
742 onWrite: func() {
743 t.mu.Lock()
744 if t.activeStreams != nil {
745 delete(t.activeStreams, s.id)
746 }
747 t.mu.Unlock()
748 if channelz.IsOn() {
749 if eosReceived {
750 atomic.AddInt64(&t.czData.streamsSucceeded, 1)
751 } else {
752 atomic.AddInt64(&t.czData.streamsFailed, 1)
753 }
754 }
755 },
756 rst: rst,
757 rstCode: rstCode,
758 }
759 addBackStreamQuota := func(interface{}) bool {
760 t.streamQuota++
761 if t.streamQuota > 0 && t.waitingStreams > 0 {
762 select {
763 case t.streamsQuotaAvailable <- struct{}{}:
764 default:
765 }
766 }
767 return true
768 }
769 t.controlBuf.executeAndPut(addBackStreamQuota, cleanup)
770 // This will unblock write.
771 close(s.done)
772}
773
774// Close kicks off the shutdown process of the transport. This should be called
775// only once on a transport. Once it is called, the transport should not be
776// accessed any more.
777//
778// This method blocks until the addrConn that initiated this transport is
779// re-connected. This happens because t.onClose() begins reconnect logic at the
780// addrConn level and blocks until the addrConn is successfully connected.
781func (t *http2Client) Close() error {
782 t.mu.Lock()
783 // Make sure we only Close once.
784 if t.state == closing {
785 t.mu.Unlock()
786 return nil
787 }
788 // Call t.onClose before setting the state to closing to prevent the client
789 // from attempting to create new streams ASAP.
790 t.onClose()
791 t.state = closing
792 streams := t.activeStreams
793 t.activeStreams = nil
794 if t.kpDormant {
795 // If the keepalive goroutine is blocked on this condition variable, we
796 // should unblock it so that the goroutine eventually exits.
797 t.kpDormancyCond.Signal()
798 }
799 t.mu.Unlock()
800 t.controlBuf.finish()
801 t.cancel()
802 err := t.conn.Close()
803 if channelz.IsOn() {
804 channelz.RemoveEntry(t.channelzID)
805 }
806 // Notify all active streams.
807 for _, s := range streams {
808 t.closeStream(s, ErrConnClosing, false, http2.ErrCodeNo, status.New(codes.Unavailable, ErrConnClosing.Desc), nil, false)
809 }
810 if t.statsHandler != nil {
811 connEnd := &stats.ConnEnd{
812 Client: true,
813 }
814 t.statsHandler.HandleConn(t.ctx, connEnd)
815 }
816 return err
817}
818
819// GracefulClose sets the state to draining, which prevents new streams from
820// being created and causes the transport to be closed when the last active
821// stream is closed. If there are no active streams, the transport is closed
822// immediately. This does nothing if the transport is already draining or
823// closing.
824func (t *http2Client) GracefulClose() {
825 t.mu.Lock()
826 // Make sure we move to draining only from active.
827 if t.state == draining || t.state == closing {
828 t.mu.Unlock()
829 return
830 }
831 t.state = draining
832 active := len(t.activeStreams)
833 t.mu.Unlock()
834 if active == 0 {
835 t.Close()
836 return
837 }
838 t.controlBuf.put(&incomingGoAway{})
839}
840
841// Write formats the data into HTTP2 data frame(s) and sends it out. The caller
842// should proceed only if Write returns nil.
843func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error {
844 if opts.Last {
845 // If it's the last message, update stream state.
846 if !s.compareAndSwapState(streamActive, streamWriteDone) {
847 return errStreamDone
848 }
849 } else if s.getState() != streamActive {
850 return errStreamDone
851 }
852 df := &dataFrame{
853 streamID: s.id,
854 endStream: opts.Last,
855 }
856 if hdr != nil || data != nil { // If it's not an empty data frame.
857 // Add some data to grpc message header so that we can equally
858 // distribute bytes across frames.
859 emptyLen := http2MaxFrameLen - len(hdr)
860 if emptyLen > len(data) {
861 emptyLen = len(data)
862 }
863 hdr = append(hdr, data[:emptyLen]...)
864 data = data[emptyLen:]
865 df.h, df.d = hdr, data
866 // TODO(mmukhi): The above logic in this if can be moved to loopyWriter's data handler.
867 if err := s.wq.get(int32(len(hdr) + len(data))); err != nil {
868 return err
869 }
870 }
871 return t.controlBuf.put(df)
872}
873
874func (t *http2Client) getStream(f http2.Frame) *Stream {
875 t.mu.Lock()
876 s := t.activeStreams[f.Header().StreamID]
877 t.mu.Unlock()
878 return s
879}
880
881// adjustWindow sends out extra window update over the initial window size
882// of stream if the application is requesting data larger in size than
883// the window.
884func (t *http2Client) adjustWindow(s *Stream, n uint32) {
885 if w := s.fc.maybeAdjust(n); w > 0 {
886 t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w})
887 }
888}
889
890// updateWindow adjusts the inbound quota for the stream.
891// Window updates will be sent out when the cumulative quota
892// exceeds the corresponding threshold.
893func (t *http2Client) updateWindow(s *Stream, n uint32) {
894 if w := s.fc.onRead(n); w > 0 {
895 t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w})
896 }
897}
898
899// updateFlowControl updates the incoming flow control windows
900// for the transport and the stream based on the current bdp
901// estimation.
902func (t *http2Client) updateFlowControl(n uint32) {
903 t.mu.Lock()
904 for _, s := range t.activeStreams {
905 s.fc.newLimit(n)
906 }
907 t.mu.Unlock()
908 updateIWS := func(interface{}) bool {
909 t.initialWindowSize = int32(n)
910 return true
911 }
912 t.controlBuf.executeAndPut(updateIWS, &outgoingWindowUpdate{streamID: 0, increment: t.fc.newLimit(n)})
913 t.controlBuf.put(&outgoingSettings{
914 ss: []http2.Setting{
915 {
916 ID: http2.SettingInitialWindowSize,
917 Val: n,
918 },
919 },
920 })
921}
922
923func (t *http2Client) handleData(f *http2.DataFrame) {
924 size := f.Header().Length
925 var sendBDPPing bool
926 if t.bdpEst != nil {
927 sendBDPPing = t.bdpEst.add(size)
928 }
929 // Decouple connection's flow control from application's read.
930 // An update on connection's flow control should not depend on
931 // whether user application has read the data or not. Such a
932 // restriction is already imposed on the stream's flow control,
933 // and therefore the sender will be blocked anyways.
934 // Decoupling the connection flow control will prevent other
935 // active(fast) streams from starving in presence of slow or
936 // inactive streams.
937 //
938 if w := t.fc.onData(size); w > 0 {
939 t.controlBuf.put(&outgoingWindowUpdate{
940 streamID: 0,
941 increment: w,
942 })
943 }
944 if sendBDPPing {
945 // Avoid excessive ping detection (e.g. in an L7 proxy)
946 // by sending a window update prior to the BDP ping.
947
948 if w := t.fc.reset(); w > 0 {
949 t.controlBuf.put(&outgoingWindowUpdate{
950 streamID: 0,
951 increment: w,
952 })
953 }
954
955 t.controlBuf.put(bdpPing)
956 }
957 // Select the right stream to dispatch.
958 s := t.getStream(f)
959 if s == nil {
960 return
961 }
962 if size > 0 {
963 if err := s.fc.onData(size); err != nil {
964 t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false)
965 return
966 }
967 if f.Header().Flags.Has(http2.FlagDataPadded) {
968 if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 {
969 t.controlBuf.put(&outgoingWindowUpdate{s.id, w})
970 }
971 }
972 // TODO(bradfitz, zhaoq): A copy is required here because there is no
973 // guarantee f.Data() is consumed before the arrival of next frame.
974 // Can this copy be eliminated?
975 if len(f.Data()) > 0 {
976 buffer := t.bufferPool.get()
977 buffer.Reset()
978 buffer.Write(f.Data())
979 s.write(recvMsg{buffer: buffer})
980 }
981 }
982 // The server has closed the stream without sending trailers. Record that
983 // the read direction is closed, and set the status appropriately.
984 if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) {
985 t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.New(codes.Internal, "server closed the stream without sending trailers"), nil, true)
986 }
987}
988
989func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) {
990 s := t.getStream(f)
991 if s == nil {
992 return
993 }
994 if f.ErrCode == http2.ErrCodeRefusedStream {
995 // The stream was unprocessed by the server.
996 atomic.StoreUint32(&s.unprocessed, 1)
997 }
998 statusCode, ok := http2ErrConvTab[f.ErrCode]
999 if !ok {
1000 warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode)
1001 statusCode = codes.Unknown
1002 }
1003 if statusCode == codes.Canceled {
1004 if d, ok := s.ctx.Deadline(); ok && !d.After(time.Now()) {
1005 // Our deadline was already exceeded, and that was likely the cause
1006 // of this cancelation. Alter the status code accordingly.
1007 statusCode = codes.DeadlineExceeded
1008 }
1009 }
1010 t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %v", f.ErrCode), nil, false)
1011}
1012
1013func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) {
1014 if f.IsAck() {
1015 return
1016 }
1017 var maxStreams *uint32
1018 var ss []http2.Setting
1019 var updateFuncs []func()
1020 f.ForeachSetting(func(s http2.Setting) error {
1021 switch s.ID {
1022 case http2.SettingMaxConcurrentStreams:
1023 maxStreams = new(uint32)
1024 *maxStreams = s.Val
1025 case http2.SettingMaxHeaderListSize:
1026 updateFuncs = append(updateFuncs, func() {
1027 t.maxSendHeaderListSize = new(uint32)
1028 *t.maxSendHeaderListSize = s.Val
1029 })
1030 default:
1031 ss = append(ss, s)
1032 }
1033 return nil
1034 })
1035 if isFirst && maxStreams == nil {
1036 maxStreams = new(uint32)
1037 *maxStreams = math.MaxUint32
1038 }
1039 sf := &incomingSettings{
1040 ss: ss,
1041 }
1042 if maxStreams != nil {
1043 updateStreamQuota := func() {
1044 delta := int64(*maxStreams) - int64(t.maxConcurrentStreams)
1045 t.maxConcurrentStreams = *maxStreams
1046 t.streamQuota += delta
1047 if delta > 0 && t.waitingStreams > 0 {
1048 close(t.streamsQuotaAvailable) // wake all of them up.
1049 t.streamsQuotaAvailable = make(chan struct{}, 1)
1050 }
1051 }
1052 updateFuncs = append(updateFuncs, updateStreamQuota)
1053 }
1054 t.controlBuf.executeAndPut(func(interface{}) bool {
1055 for _, f := range updateFuncs {
1056 f()
1057 }
1058 return true
1059 }, sf)
1060}
1061
1062func (t *http2Client) handlePing(f *http2.PingFrame) {
1063 if f.IsAck() {
1064 // Maybe it's a BDP ping.
1065 if t.bdpEst != nil {
1066 t.bdpEst.calculate(f.Data)
1067 }
1068 return
1069 }
1070 pingAck := &ping{ack: true}
1071 copy(pingAck.data[:], f.Data[:])
1072 t.controlBuf.put(pingAck)
1073}
1074
1075func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) {
1076 t.mu.Lock()
1077 if t.state == closing {
1078 t.mu.Unlock()
1079 return
1080 }
1081 if f.ErrCode == http2.ErrCodeEnhanceYourCalm {
1082 infof("Client received GoAway with http2.ErrCodeEnhanceYourCalm.")
1083 }
1084 id := f.LastStreamID
1085 if id > 0 && id%2 != 1 {
1086 t.mu.Unlock()
1087 t.Close()
1088 return
1089 }
1090 // A client can receive multiple GoAways from the server (see
1091 // https://github.com/grpc/grpc-go/issues/1387). The idea is that the first
1092 // GoAway will be sent with an ID of MaxInt32 and the second GoAway will be
1093 // sent after an RTT delay with the ID of the last stream the server will
1094 // process.
1095 //
1096 // Therefore, when we get the first GoAway we don't necessarily close any
1097 // streams. While in case of second GoAway we close all streams created after
1098 // the GoAwayId. This way streams that were in-flight while the GoAway from
1099 // server was being sent don't get killed.
1100 select {
1101 case <-t.goAway: // t.goAway has been closed (i.e.,multiple GoAways).
1102 // If there are multiple GoAways the first one should always have an ID greater than the following ones.
1103 if id > t.prevGoAwayID {
1104 t.mu.Unlock()
1105 t.Close()
1106 return
1107 }
1108 default:
1109 t.setGoAwayReason(f)
1110 close(t.goAway)
1111 t.controlBuf.put(&incomingGoAway{})
1112 // Notify the clientconn about the GOAWAY before we set the state to
1113 // draining, to allow the client to stop attempting to create streams
1114 // before disallowing new streams on this connection.
1115 t.onGoAway(t.goAwayReason)
1116 t.state = draining
1117 }
1118 // All streams with IDs greater than the GoAwayId
1119 // and smaller than the previous GoAway ID should be killed.
1120 upperLimit := t.prevGoAwayID
1121 if upperLimit == 0 { // This is the first GoAway Frame.
1122 upperLimit = math.MaxUint32 // Kill all streams after the GoAway ID.
1123 }
1124 for streamID, stream := range t.activeStreams {
1125 if streamID > id && streamID <= upperLimit {
1126 // The stream was unprocessed by the server.
1127 atomic.StoreUint32(&stream.unprocessed, 1)
1128 t.closeStream(stream, errStreamDrain, false, http2.ErrCodeNo, statusGoAway, nil, false)
1129 }
1130 }
1131 t.prevGoAwayID = id
1132 active := len(t.activeStreams)
1133 t.mu.Unlock()
1134 if active == 0 {
1135 t.Close()
1136 }
1137}
1138
1139// setGoAwayReason sets the value of t.goAwayReason based
1140// on the GoAway frame received.
1141// It expects a lock on transport's mutext to be held by
1142// the caller.
1143func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) {
1144 t.goAwayReason = GoAwayNoReason
1145 switch f.ErrCode {
1146 case http2.ErrCodeEnhanceYourCalm:
1147 if string(f.DebugData()) == "too_many_pings" {
1148 t.goAwayReason = GoAwayTooManyPings
1149 }
1150 }
1151}
1152
1153func (t *http2Client) GetGoAwayReason() GoAwayReason {
1154 t.mu.Lock()
1155 defer t.mu.Unlock()
1156 return t.goAwayReason
1157}
1158
1159func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) {
1160 t.controlBuf.put(&incomingWindowUpdate{
1161 streamID: f.Header().StreamID,
1162 increment: f.Increment,
1163 })
1164}
1165
1166// operateHeaders takes action on the decoded headers.
1167func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) {
1168 s := t.getStream(frame)
1169 if s == nil {
1170 return
1171 }
1172 endStream := frame.StreamEnded()
1173 atomic.StoreUint32(&s.bytesReceived, 1)
1174 initialHeader := atomic.LoadUint32(&s.headerChanClosed) == 0
1175
1176 if !initialHeader && !endStream {
1177 // 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.
1178 st := status.New(codes.Internal, "a HEADERS frame cannot appear in the middle of a stream")
1179 t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, false)
1180 return
1181 }
1182
1183 state := &decodeState{}
1184 // 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.
1185 state.data.isGRPC = !initialHeader
1186 if err := state.decodeHeader(frame); err != nil {
1187 t.closeStream(s, err, true, http2.ErrCodeProtocol, status.Convert(err), nil, endStream)
1188 return
1189 }
1190
1191 isHeader := false
1192 defer func() {
1193 if t.statsHandler != nil {
1194 if isHeader {
1195 inHeader := &stats.InHeader{
1196 Client: true,
1197 WireLength: int(frame.Header().Length),
Dinesh Belwalkar396b6522020-02-06 22:11:53 +00001198 Header: s.header.Copy(),
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +00001199 }
1200 t.statsHandler.HandleRPC(s.ctx, inHeader)
1201 } else {
1202 inTrailer := &stats.InTrailer{
1203 Client: true,
1204 WireLength: int(frame.Header().Length),
Dinesh Belwalkar396b6522020-02-06 22:11:53 +00001205 Trailer: s.trailer.Copy(),
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +00001206 }
1207 t.statsHandler.HandleRPC(s.ctx, inTrailer)
1208 }
1209 }
1210 }()
1211
1212 // If headerChan hasn't been closed yet
1213 if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
1214 s.headerValid = true
1215 if !endStream {
1216 // HEADERS frame block carries a Response-Headers.
1217 isHeader = true
1218 // These values can be set without any synchronization because
1219 // stream goroutine will read it only after seeing a closed
1220 // headerChan which we'll close after setting this.
1221 s.recvCompress = state.data.encoding
1222 if len(state.data.mdata) > 0 {
1223 s.header = state.data.mdata
1224 }
1225 } else {
1226 // HEADERS frame block carries a Trailers-Only.
1227 s.noHeaders = true
1228 }
1229 close(s.headerChan)
1230 }
1231
1232 if !endStream {
1233 return
1234 }
1235
1236 // if client received END_STREAM from server while stream was still active, send RST_STREAM
1237 rst := s.getState() == streamActive
1238 t.closeStream(s, io.EOF, rst, http2.ErrCodeNo, state.status(), state.data.mdata, true)
1239}
1240
1241// reader runs as a separate goroutine in charge of reading data from network
1242// connection.
1243//
1244// TODO(zhaoq): currently one reader per transport. Investigate whether this is
1245// optimal.
1246// TODO(zhaoq): Check the validity of the incoming frame sequence.
1247func (t *http2Client) reader() {
1248 defer close(t.readerDone)
1249 // Check the validity of server preface.
1250 frame, err := t.framer.fr.ReadFrame()
1251 if err != nil {
1252 t.Close() // this kicks off resetTransport, so must be last before return
1253 return
1254 }
1255 t.conn.SetReadDeadline(time.Time{}) // reset deadline once we get the settings frame (we didn't time out, yay!)
1256 if t.keepaliveEnabled {
1257 atomic.StoreInt64(&t.lastRead, time.Now().UnixNano())
1258 }
1259 sf, ok := frame.(*http2.SettingsFrame)
1260 if !ok {
1261 t.Close() // this kicks off resetTransport, so must be last before return
1262 return
1263 }
1264 t.onPrefaceReceipt()
1265 t.handleSettings(sf, true)
1266
1267 // loop to keep reading incoming messages on this transport.
1268 for {
1269 t.controlBuf.throttle()
1270 frame, err := t.framer.fr.ReadFrame()
1271 if t.keepaliveEnabled {
1272 atomic.StoreInt64(&t.lastRead, time.Now().UnixNano())
1273 }
1274 if err != nil {
1275 // Abort an active stream if the http2.Framer returns a
1276 // http2.StreamError. This can happen only if the server's response
1277 // is malformed http2.
1278 if se, ok := err.(http2.StreamError); ok {
1279 t.mu.Lock()
1280 s := t.activeStreams[se.StreamID]
1281 t.mu.Unlock()
1282 if s != nil {
1283 // use error detail to provide better err message
1284 code := http2ErrConvTab[se.Code]
1285 msg := t.framer.fr.ErrorDetail().Error()
1286 t.closeStream(s, status.Error(code, msg), true, http2.ErrCodeProtocol, status.New(code, msg), nil, false)
1287 }
1288 continue
1289 } else {
1290 // Transport error.
1291 t.Close()
1292 return
1293 }
1294 }
1295 switch frame := frame.(type) {
1296 case *http2.MetaHeadersFrame:
1297 t.operateHeaders(frame)
1298 case *http2.DataFrame:
1299 t.handleData(frame)
1300 case *http2.RSTStreamFrame:
1301 t.handleRSTStream(frame)
1302 case *http2.SettingsFrame:
1303 t.handleSettings(frame, false)
1304 case *http2.PingFrame:
1305 t.handlePing(frame)
1306 case *http2.GoAwayFrame:
1307 t.handleGoAway(frame)
1308 case *http2.WindowUpdateFrame:
1309 t.handleWindowUpdate(frame)
1310 default:
1311 errorf("transport: http2Client.reader got unhandled frame type %v.", frame)
1312 }
1313 }
1314}
1315
1316func minTime(a, b time.Duration) time.Duration {
1317 if a < b {
1318 return a
1319 }
1320 return b
1321}
1322
1323// keepalive running in a separate goroutune makes sure the connection is alive by sending pings.
1324func (t *http2Client) keepalive() {
1325 p := &ping{data: [8]byte{}}
1326 // True iff a ping has been sent, and no data has been received since then.
1327 outstandingPing := false
1328 // Amount of time remaining before which we should receive an ACK for the
1329 // last sent ping.
1330 timeoutLeft := time.Duration(0)
1331 // Records the last value of t.lastRead before we go block on the timer.
1332 // This is required to check for read activity since then.
1333 prevNano := time.Now().UnixNano()
1334 timer := time.NewTimer(t.kp.Time)
1335 for {
1336 select {
1337 case <-timer.C:
1338 lastRead := atomic.LoadInt64(&t.lastRead)
1339 if lastRead > prevNano {
1340 // There has been read activity since the last time we were here.
1341 outstandingPing = false
1342 // Next timer should fire at kp.Time seconds from lastRead time.
1343 timer.Reset(time.Duration(lastRead) + t.kp.Time - time.Duration(time.Now().UnixNano()))
1344 prevNano = lastRead
1345 continue
1346 }
1347 if outstandingPing && timeoutLeft <= 0 {
1348 t.Close()
1349 return
1350 }
1351 t.mu.Lock()
1352 if t.state == closing {
1353 // If the transport is closing, we should exit from the
1354 // keepalive goroutine here. If not, we could have a race
1355 // between the call to Signal() from Close() and the call to
1356 // Wait() here, whereby the keepalive goroutine ends up
1357 // blocking on the condition variable which will never be
1358 // signalled again.
1359 t.mu.Unlock()
1360 return
1361 }
1362 if len(t.activeStreams) < 1 && !t.kp.PermitWithoutStream {
1363 // If a ping was sent out previously (because there were active
1364 // streams at that point) which wasn't acked and its timeout
1365 // hadn't fired, but we got here and are about to go dormant,
1366 // we should make sure that we unconditionally send a ping once
1367 // we awaken.
1368 outstandingPing = false
1369 t.kpDormant = true
1370 t.kpDormancyCond.Wait()
1371 }
1372 t.kpDormant = false
1373 t.mu.Unlock()
1374
1375 // We get here either because we were dormant and a new stream was
1376 // created which unblocked the Wait() call, or because the
1377 // keepalive timer expired. In both cases, we need to send a ping.
1378 if !outstandingPing {
1379 if channelz.IsOn() {
1380 atomic.AddInt64(&t.czData.kpCount, 1)
1381 }
1382 t.controlBuf.put(p)
1383 timeoutLeft = t.kp.Timeout
1384 outstandingPing = true
1385 }
1386 // The amount of time to sleep here is the minimum of kp.Time and
1387 // timeoutLeft. This will ensure that we wait only for kp.Time
1388 // before sending out the next ping (for cases where the ping is
1389 // acked).
1390 sleepDuration := minTime(t.kp.Time, timeoutLeft)
1391 timeoutLeft -= sleepDuration
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +00001392 timer.Reset(sleepDuration)
1393 case <-t.ctx.Done():
1394 if !timer.Stop() {
1395 <-timer.C
1396 }
1397 return
1398 }
1399 }
1400}
1401
1402func (t *http2Client) Error() <-chan struct{} {
1403 return t.ctx.Done()
1404}
1405
1406func (t *http2Client) GoAway() <-chan struct{} {
1407 return t.goAway
1408}
1409
1410func (t *http2Client) ChannelzMetric() *channelz.SocketInternalMetric {
1411 s := channelz.SocketInternalMetric{
1412 StreamsStarted: atomic.LoadInt64(&t.czData.streamsStarted),
1413 StreamsSucceeded: atomic.LoadInt64(&t.czData.streamsSucceeded),
1414 StreamsFailed: atomic.LoadInt64(&t.czData.streamsFailed),
1415 MessagesSent: atomic.LoadInt64(&t.czData.msgSent),
1416 MessagesReceived: atomic.LoadInt64(&t.czData.msgRecv),
1417 KeepAlivesSent: atomic.LoadInt64(&t.czData.kpCount),
1418 LastLocalStreamCreatedTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastStreamCreatedTime)),
1419 LastMessageSentTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastMsgSentTime)),
1420 LastMessageReceivedTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastMsgRecvTime)),
1421 LocalFlowControlWindow: int64(t.fc.getSize()),
1422 SocketOptions: channelz.GetSocketOption(t.conn),
1423 LocalAddr: t.localAddr,
1424 RemoteAddr: t.remoteAddr,
1425 // RemoteName :
1426 }
1427 if au, ok := t.authInfo.(credentials.ChannelzSecurityInfo); ok {
1428 s.Security = au.GetSecurityValue()
1429 }
1430 s.RemoteFlowControlWindow = t.getOutFlowWindow()
1431 return &s
1432}
1433
1434func (t *http2Client) RemoteAddr() net.Addr { return t.remoteAddr }
1435
1436func (t *http2Client) IncrMsgSent() {
1437 atomic.AddInt64(&t.czData.msgSent, 1)
1438 atomic.StoreInt64(&t.czData.lastMsgSentTime, time.Now().UnixNano())
1439}
1440
1441func (t *http2Client) IncrMsgRecv() {
1442 atomic.AddInt64(&t.czData.msgRecv, 1)
1443 atomic.StoreInt64(&t.czData.lastMsgRecvTime, time.Now().UnixNano())
1444}
1445
1446func (t *http2Client) getOutFlowWindow() int64 {
1447 resp := make(chan uint32, 1)
1448 timer := time.NewTimer(time.Second)
1449 defer timer.Stop()
1450 t.controlBuf.put(&outFlowControlSizeRequest{resp})
1451 select {
1452 case sz := <-resp:
1453 return int64(sz)
1454 case <-t.ctxDone:
1455 return -1
1456 case <-timer.C:
1457 return -2
1458 }
1459}