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