33
"golang.org/x/net/http2"
34
"golang.org/x/net/http2/hpack"
35
"google.golang.org/grpc/internal/grpcutil"
36
imetadata "google.golang.org/grpc/internal/metadata"
37
"google.golang.org/grpc/internal/transport/networktype"
39
"google.golang.org/grpc/codes"
40
"google.golang.org/grpc/credentials"
41
"google.golang.org/grpc/internal"
42
"google.golang.org/grpc/internal/channelz"
43
"google.golang.org/grpc/internal/syscall"
44
"google.golang.org/grpc/keepalive"
45
"google.golang.org/grpc/metadata"
46
"google.golang.org/grpc/peer"
47
"google.golang.org/grpc/resolver"
48
"google.golang.org/grpc/stats"
49
"google.golang.org/grpc/status"
55
var clientConnectionCounter uint64
58
type http2Client struct {
61
cancel context.CancelFunc
62
ctxDone <-chan struct{}
69
authInfo credentials.AuthInfo
71
readerDone chan struct{}
72
writerDone chan struct{}
80
controlBuf *controlBuffer
87
perRPCCreds []credentials.PerRPCCredentials
89
kp keepalive.ClientParameters
92
statsHandler stats.Handler
94
initialWindowSize int32
97
maxSendHeaderListSize *uint32
103
onPrefaceReceipt func()
105
maxConcurrentStreams uint32
107
streamsQuotaAvailable chan struct{}
108
waitingStreams uint32
113
activeStreams map[uint32]*Stream
118
goAwayReason GoAwayReason
124
kpDormancyCond *sync.Cond
134
onGoAway func(GoAwayReason)
137
bufferPool *bufferPool
142
func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr resolver.Address, useProxy bool, grpcUA string) (net.Conn, error) {
144
networkType, ok := networktype.Get(addr)
146
if networkType == "unix" && !strings.HasPrefix(address, "\x00") {
152
return fn(ctx, "unix://"+address)
154
return fn(ctx, address)
157
networkType, address = parseDialTarget(address)
159
if networkType == "tcp" && useProxy {
160
return proxyDial(ctx, address, grpcUA)
162
return (&net.Dialer{}).DialContext(ctx, networkType, address)
165
func isTemporary(err error) bool {
166
switch err := err.(type) {
170
return err.Temporary()
184
func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts ConnectOptions, onPrefaceReceipt func(), onGoAway func(GoAwayReason), onClose func()) (_ *http2Client, err error) {
186
ctx, cancel := context.WithCancel(ctx)
193
conn, err := dial(connectCtx, opts.Dialer, addr, opts.UseProxy, opts.UserAgent)
195
if opts.FailOnNonTempDialError {
196
return nil, connectionErrorf(isTemporary(err), err, "transport: error while dialing: %v", err)
198
return nil, connectionErrorf(true, err, "transport: Error while dialing %v", err)
201
defer func(conn net.Conn) {
206
kp := opts.KeepaliveParams
209
kp.Time = defaultClientKeepaliveTime
212
kp.Timeout = defaultClientKeepaliveTimeout
214
keepaliveEnabled := false
215
if kp.Time != infinity {
216
if err = syscall.SetTCPUserTimeout(conn, kp.Timeout); err != nil {
217
return nil, connectionErrorf(false, err, "transport: failed to set TCP_USER_TIMEOUT: %v", err)
219
keepaliveEnabled = true
223
authInfo credentials.AuthInfo
225
transportCreds := opts.TransportCredentials
226
perRPCCreds := opts.PerRPCCredentials
228
if b := opts.CredsBundle; b != nil {
229
if t := b.TransportCredentials(); t != nil {
232
if t := b.PerRPCCredentials(); t != nil {
233
perRPCCreds = append(perRPCCreds, t)
236
if transportCreds != nil {
241
contextWithHandshakeInfo := internal.NewClientHandshakeInfoContext.(func(context.Context, credentials.ClientHandshakeInfo) context.Context)
242
connectCtx = contextWithHandshakeInfo(connectCtx, credentials.ClientHandshakeInfo{Attributes: addr.Attributes})
243
conn, authInfo, err = transportCreds.ClientHandshake(connectCtx, addr.ServerName, conn)
245
return nil, connectionErrorf(isTemporary(err), err, "transport: authentication handshake failed: %v", err)
247
for _, cd := range perRPCCreds {
248
if cd.RequireTransportSecurity() {
249
if ci, ok := authInfo.(interface {
250
GetCommonAuthInfo() credentials.CommonAuthInfo
252
secLevel := ci.GetCommonAuthInfo().SecurityLevel
253
if secLevel != credentials.InvalidSecurityLevel && secLevel < credentials.PrivacyAndIntegrity {
254
return nil, connectionErrorf(true, nil, "transport: cannot send secure credentials on an insecure connection")
260
if transportCreds.Info().SecurityProtocol == "tls" {
264
dynamicWindow := true
265
icwz := int32(initialWindowSize)
266
if opts.InitialConnWindowSize >= defaultWindowSize {
267
icwz = opts.InitialConnWindowSize
268
dynamicWindow = false
270
writeBufSize := opts.WriteBufferSize
271
readBufSize := opts.ReadBufferSize
272
maxHeaderListSize := defaultClientMaxHeaderListSize
273
if opts.MaxHeaderListSize != nil {
274
maxHeaderListSize = *opts.MaxHeaderListSize
280
userAgent: opts.UserAgent,
282
remoteAddr: conn.RemoteAddr(),
283
localAddr: conn.LocalAddr(),
285
readerDone: make(chan struct{}),
286
writerDone: make(chan struct{}),
287
goAway: make(chan struct{}),
288
framer: newFramer(conn, writeBufSize, readBufSize, maxHeaderListSize),
289
fc: &trInFlow{limit: uint32(icwz)},
291
activeStreams: make(map[uint32]*Stream),
293
perRPCCreds: perRPCCreds,
295
statsHandler: opts.StatsHandler,
296
initialWindowSize: initialWindowSize,
297
onPrefaceReceipt: onPrefaceReceipt,
299
maxConcurrentStreams: defaultMaxStreamsClient,
300
streamQuota: defaultMaxStreamsClient,
301
streamsQuotaAvailable: make(chan struct{}, 1),
302
czData: new(channelzData),
305
keepaliveEnabled: keepaliveEnabled,
306
bufferPool: newBufferPool(),
309
if md, ok := addr.Metadata.(*metadata.MD); ok {
311
} else if md := imetadata.Get(addr); md != nil {
314
t.controlBuf = newControlBuffer(t.ctxDone)
315
if opts.InitialWindowSize >= defaultWindowSize {
316
t.initialWindowSize = opts.InitialWindowSize
317
dynamicWindow = false
320
t.bdpEst = &bdpEstimator{
321
bdp: initialWindowSize,
322
updateFlowControl: t.updateFlowControl,
325
if t.statsHandler != nil {
326
t.ctx = t.statsHandler.TagConn(t.ctx, &stats.ConnTagInfo{
327
RemoteAddr: t.remoteAddr,
328
LocalAddr: t.localAddr,
330
connBegin := &stats.ConnBegin{
333
t.statsHandler.HandleConn(t.ctx, connBegin)
336
t.channelzID = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, fmt.Sprintf("%s -> %s", t.localAddr, t.remoteAddr))
338
if t.keepaliveEnabled {
339
t.kpDormancyCond = sync.NewCond(&t.mu)
348
n, err := t.conn.Write(clientPreface)
351
return nil, connectionErrorf(true, err, "transport: failed to write client preface: %v", err)
353
if n != len(clientPreface) {
355
return nil, connectionErrorf(true, err, "transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface))
357
var ss []http2.Setting
359
if t.initialWindowSize != defaultWindowSize {
360
ss = append(ss, http2.Setting{
361
ID: http2.SettingInitialWindowSize,
362
Val: uint32(t.initialWindowSize),
365
if opts.MaxHeaderListSize != nil {
366
ss = append(ss, http2.Setting{
367
ID: http2.SettingMaxHeaderListSize,
368
Val: *opts.MaxHeaderListSize,
371
err = t.framer.fr.WriteSettings(ss...)
374
return nil, connectionErrorf(true, err, "transport: failed to write initial settings frame: %v", err)
377
if delta := uint32(icwz - defaultWindowSize); delta > 0 {
378
if err := t.framer.fr.WriteWindowUpdate(0, delta); err != nil {
380
return nil, connectionErrorf(true, err, "transport: failed to write window update: %v", err)
384
t.connectionID = atomic.AddUint64(&clientConnectionCounter, 1)
386
if err := t.framer.writer.Flush(); err != nil {
390
t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst)
393
if logger.V(logLevel) {
394
logger.Errorf("transport: loopyWriter.run returning. Err: %v", err)
399
if _, ok := err.(net.Error); !ok {
407
func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream {
411
done: make(chan struct{}),
412
method: callHdr.Method,
413
sendCompress: callHdr.SendCompress,
414
buf: newRecvBuffer(),
415
headerChan: make(chan struct{}),
416
contentSubtype: callHdr.ContentSubtype,
418
s.wq = newWriteQuota(defaultWriteQuota, s.done)
419
s.requestRead = func(n int) {
420
t.adjustWindow(s, uint32(n))
426
s.trReader = &transportReader{
427
reader: &recvBufferReader{
429
ctxDone: s.ctx.Done(),
431
closeStream: func(err error) {
432
t.CloseStream(s, err)
434
freeBuffer: t.bufferPool.put,
436
windowHandler: func(n int) {
437
t.updateWindow(s, uint32(n))
443
func (t *http2Client) getPeer() *peer.Peer {
446
AuthInfo: t.authInfo,
450
func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) ([]hpack.HeaderField, error) {
451
aud := t.createAudience(callHdr)
452
ri := credentials.RequestInfo{
453
Method: callHdr.Method,
454
AuthInfo: t.authInfo,
456
ctxWithRequestInfo := internal.NewRequestInfoContext.(func(context.Context, credentials.RequestInfo) context.Context)(ctx, ri)
457
authData, err := t.getTrAuthData(ctxWithRequestInfo, aud)
461
callAuthData, err := t.getCallAuthData(ctxWithRequestInfo, aud, callHdr)
469
hfLen += len(authData) + len(callAuthData)
470
headerFields := make([]hpack.HeaderField, 0, hfLen)
471
headerFields = append(headerFields, hpack.HeaderField{Name: ":method", Value: "POST"})
472
headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme})
473
headerFields = append(headerFields, hpack.HeaderField{Name: ":path", Value: callHdr.Method})
474
headerFields = append(headerFields, hpack.HeaderField{Name: ":authority", Value: callHdr.Host})
475
headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: grpcutil.ContentType(callHdr.ContentSubtype)})
476
headerFields = append(headerFields, hpack.HeaderField{Name: "user-agent", Value: t.userAgent})
477
headerFields = append(headerFields, hpack.HeaderField{Name: "te", Value: "trailers"})
478
if callHdr.PreviousAttempts > 0 {
479
headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-previous-rpc-attempts", Value: strconv.Itoa(callHdr.PreviousAttempts)})
482
if callHdr.SendCompress != "" {
483
headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress})
484
headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-accept-encoding", Value: callHdr.SendCompress})
486
if dl, ok := ctx.Deadline(); ok {
489
timeout := time.Until(dl)
490
headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-timeout", Value: grpcutil.EncodeDuration(timeout)})
492
for k, v := range authData {
493
headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
495
for k, v := range callAuthData {
496
headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
498
if b := stats.OutgoingTags(ctx); b != nil {
499
headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-tags-bin", Value: encodeBinHeader(b)})
501
if b := stats.OutgoingTrace(ctx); b != nil {
502
headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-trace-bin", Value: encodeBinHeader(b)})
505
if md, added, ok := metadata.FromOutgoingContextRaw(ctx); ok {
507
for k, vv := range md {
509
if isReservedHeader(k) {
512
for _, v := range vv {
513
headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
516
for _, vv := range added {
517
for i, v := range vv {
519
k = strings.ToLower(v)
523
if isReservedHeader(k) {
526
headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
530
for k, vv := range t.md {
531
if isReservedHeader(k) {
534
for _, v := range vv {
535
headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
538
return headerFields, nil
541
func (t *http2Client) createAudience(callHdr *CallHdr) string {
543
if len(t.perRPCCreds) == 0 && callHdr.Creds == nil {
548
host := strings.TrimSuffix(callHdr.Host, ":443")
549
pos := strings.LastIndex(callHdr.Method, "/")
551
pos = len(callHdr.Method)
553
return "https://" + host + callHdr.Method[:pos]
556
func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[string]string, error) {
557
if len(t.perRPCCreds) == 0 {
560
authData := map[string]string{}
561
for _, c := range t.perRPCCreds {
562
data, err := c.GetRequestMetadata(ctx, audience)
564
if _, ok := status.FromError(err); ok {
568
return nil, status.Errorf(codes.Unauthenticated, "transport: %v", err)
570
for k, v := range data {
572
k = strings.ToLower(k)
579
func (t *http2Client) getCallAuthData(ctx context.Context, audience string, callHdr *CallHdr) (map[string]string, error) {
580
var callAuthData map[string]string
584
if callCreds := callHdr.Creds; callCreds != nil {
585
if callCreds.RequireTransportSecurity() {
586
ri, _ := credentials.RequestInfoFromContext(ctx)
587
if !t.isSecure || credentials.CheckSecurityLevel(ri.AuthInfo, credentials.PrivacyAndIntegrity) != nil {
588
return nil, status.Error(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure connection")
591
data, err := callCreds.GetRequestMetadata(ctx, audience)
593
return nil, status.Errorf(codes.Internal, "transport: %v", err)
595
callAuthData = make(map[string]string, len(data))
596
for k, v := range data {
598
k = strings.ToLower(k)
602
return callAuthData, nil
607
type PerformedIOError struct {
612
func (p PerformedIOError) Error() string {
618
func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) {
619
ctx = peer.NewContext(ctx, t.getPeer())
620
headerFields, err := t.createHeaderFields(ctx, callHdr)
624
return nil, PerformedIOError{err}
626
s := t.newStream(ctx, callHdr)
627
cleanup := func(err error) {
628
if s.swapState(streamDone) == streamDone {
633
atomic.StoreUint32(&s.unprocessed, 1)
634
s.write(recvMsg{err: err})
637
if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
644
initStream: func(id uint32) error {
646
if state := t.state; state != reachable {
649
err := error(errStreamDrain)
650
if state == closing {
656
t.activeStreams[id] = s
658
atomic.AddInt64(&t.czData.streamsStarted, 1)
659
atomic.StoreInt64(&t.czData.lastStreamCreatedTime, time.Now().UnixNano())
663
t.kpDormancyCond.Signal()
673
checkForStreamQuota := func(it interface{}) bool {
674
if t.streamQuota <= 0 {
678
ch = t.streamsQuotaAvailable
685
h := it.(*headerFrame)
686
h.streamID = t.nextID
689
s.fc = &inFlow{limit: uint32(t.initialWindowSize)}
690
if t.streamQuota > 0 && t.waitingStreams > 0 {
692
case t.streamsQuotaAvailable <- struct{}{}:
698
var hdrListSizeErr error
699
checkForHeaderListSize := func(it interface{}) bool {
700
if t.maxSendHeaderListSize == nil {
703
hdrFrame := it.(*headerFrame)
705
for _, f := range hdrFrame.hf {
706
if sz += int64(f.Size()); sz > int64(*t.maxSendHeaderListSize) {
707
hdrListSizeErr = status.Errorf(codes.Internal, "header list size to send violates the maximum size (%d bytes) set by server", *t.maxSendHeaderListSize)
714
success, err := t.controlBuf.executeAndPut(func(it interface{}) bool {
715
if !checkForStreamQuota(it) {
718
if !checkForHeaderListSize(it) {
729
if hdrListSizeErr != nil {
730
return nil, hdrListSizeErr
736
return nil, ContextErr(s.ctx.Err())
738
return nil, errStreamDrain
740
return nil, ErrConnClosing
743
if t.statsHandler != nil {
744
header, ok := metadata.FromOutgoingContext(ctx)
746
header.Set("user-agent", t.userAgent)
748
header = metadata.Pairs("user-agent", t.userAgent)
752
outHeader := &stats.OutHeader{
754
FullMethod: callHdr.Method,
755
RemoteAddr: t.remoteAddr,
756
LocalAddr: t.localAddr,
757
Compression: callHdr.SendCompress,
760
t.statsHandler.HandleRPC(s.ctx, outHeader)
767
func (t *http2Client) CloseStream(s *Stream, err error) {
770
rstCode http2.ErrCode
774
rstCode = http2.ErrCodeCancel
776
t.closeStream(s, err, rst, rstCode, status.Convert(err), nil, false)
779
func (t *http2Client) closeStream(s *Stream, err error, rst bool, rstCode http2.ErrCode, st *status.Status, mdata map[string][]string, eosReceived bool) {
781
if s.swapState(streamDone) == streamDone {
796
s.write(recvMsg{err: err})
799
if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
803
cleanup := &cleanupStream{
807
if t.activeStreams != nil {
808
delete(t.activeStreams, s.id)
813
atomic.AddInt64(&t.czData.streamsSucceeded, 1)
815
atomic.AddInt64(&t.czData.streamsFailed, 1)
822
addBackStreamQuota := func(interface{}) bool {
824
if t.streamQuota > 0 && t.waitingStreams > 0 {
826
case t.streamsQuotaAvailable <- struct{}{}:
832
t.controlBuf.executeAndPut(addBackStreamQuota, cleanup)
844
func (t *http2Client) Close() error {
847
if t.state == closing {
855
streams := t.activeStreams
856
t.activeStreams = nil
860
t.kpDormancyCond.Signal()
863
t.controlBuf.finish()
865
err := t.conn.Close()
867
channelz.RemoveEntry(t.channelzID)
870
for _, s := range streams {
871
t.closeStream(s, ErrConnClosing, false, http2.ErrCodeNo, status.New(codes.Unavailable, ErrConnClosing.Desc), nil, false)
873
if t.statsHandler != nil {
874
connEnd := &stats.ConnEnd{
877
t.statsHandler.HandleConn(t.ctx, connEnd)
887
func (t *http2Client) GracefulClose() {
890
if t.state == draining || t.state == closing {
895
active := len(t.activeStreams)
901
t.controlBuf.put(&incomingGoAway{})
906
func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error {
909
if !s.compareAndSwapState(streamActive, streamWriteDone) {
912
} else if s.getState() != streamActive {
917
endStream: opts.Last,
921
if hdr != nil || data != nil {
922
if err := s.wq.get(int32(len(hdr) + len(data))); err != nil {
926
return t.controlBuf.put(df)
929
func (t *http2Client) getStream(f http2.Frame) *Stream {
931
s := t.activeStreams[f.Header().StreamID]
939
func (t *http2Client) adjustWindow(s *Stream, n uint32) {
940
if w := s.fc.maybeAdjust(n); w > 0 {
941
t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w})
948
func (t *http2Client) updateWindow(s *Stream, n uint32) {
949
if w := s.fc.onRead(n); w > 0 {
950
t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w})
957
func (t *http2Client) updateFlowControl(n uint32) {
959
for _, s := range t.activeStreams {
963
updateIWS := func(interface{}) bool {
964
t.initialWindowSize = int32(n)
967
t.controlBuf.executeAndPut(updateIWS, &outgoingWindowUpdate{streamID: 0, increment: t.fc.newLimit(n)})
968
t.controlBuf.put(&outgoingSettings{
971
ID: http2.SettingInitialWindowSize,
978
func (t *http2Client) handleData(f *http2.DataFrame) {
979
size := f.Header().Length
982
sendBDPPing = t.bdpEst.add(size)
993
if w := t.fc.onData(size); w > 0 {
994
t.controlBuf.put(&outgoingWindowUpdate{
1003
if w := t.fc.reset(); w > 0 {
1004
t.controlBuf.put(&outgoingWindowUpdate{
1010
t.controlBuf.put(bdpPing)
1018
if err := s.fc.onData(size); err != nil {
1019
t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false)
1022
if f.Header().Flags.Has(http2.FlagDataPadded) {
1023
if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 {
1024
t.controlBuf.put(&outgoingWindowUpdate{s.id, w})
1030
if len(f.Data()) > 0 {
1031
buffer := t.bufferPool.get()
1033
buffer.Write(f.Data())
1034
s.write(recvMsg{buffer: buffer})
1039
if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) {
1040
t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.New(codes.Internal, "server closed the stream without sending trailers"), nil, true)
1044
func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) {
1049
if f.ErrCode == http2.ErrCodeRefusedStream {
1051
atomic.StoreUint32(&s.unprocessed, 1)
1053
statusCode, ok := http2ErrConvTab[f.ErrCode]
1055
if logger.V(logLevel) {
1056
logger.Warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode)
1058
statusCode = codes.Unknown
1060
if statusCode == codes.Canceled {
1061
if d, ok := s.ctx.Deadline(); ok && !d.After(time.Now()) {
1064
statusCode = codes.DeadlineExceeded
1067
t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %v", f.ErrCode), nil, false)
1070
func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) {
1074
var maxStreams *uint32
1075
var ss []http2.Setting
1076
var updateFuncs []func()
1077
f.ForeachSetting(func(s http2.Setting) error {
1079
case http2.SettingMaxConcurrentStreams:
1080
maxStreams = new(uint32)
1082
case http2.SettingMaxHeaderListSize:
1083
updateFuncs = append(updateFuncs, func() {
1084
t.maxSendHeaderListSize = new(uint32)
1085
*t.maxSendHeaderListSize = s.Val
1092
if isFirst && maxStreams == nil {
1093
maxStreams = new(uint32)
1094
*maxStreams = math.MaxUint32
1096
sf := &incomingSettings{
1099
if maxStreams != nil {
1100
updateStreamQuota := func() {
1101
delta := int64(*maxStreams) - int64(t.maxConcurrentStreams)
1102
t.maxConcurrentStreams = *maxStreams
1103
t.streamQuota += delta
1104
if delta > 0 && t.waitingStreams > 0 {
1105
close(t.streamsQuotaAvailable)
1106
t.streamsQuotaAvailable = make(chan struct{}, 1)
1109
updateFuncs = append(updateFuncs, updateStreamQuota)
1111
t.controlBuf.executeAndPut(func(interface{}) bool {
1112
for _, f := range updateFuncs {
1119
func (t *http2Client) handlePing(f *http2.PingFrame) {
1122
if t.bdpEst != nil {
1123
t.bdpEst.calculate(f.Data)
1127
pingAck := &ping{ack: true}
1128
copy(pingAck.data[:], f.Data[:])
1129
t.controlBuf.put(pingAck)
1132
func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) {
1134
if t.state == closing {
1138
if f.ErrCode == http2.ErrCodeEnhanceYourCalm {
1139
if logger.V(logLevel) {
1140
logger.Infof("Client received GoAway with http2.ErrCodeEnhanceYourCalm.")
1143
id := f.LastStreamID
1144
if id > 0 && id%2 != 1 {
1162
if id > t.prevGoAwayID {
1168
t.setGoAwayReason(f)
1170
t.controlBuf.put(&incomingGoAway{})
1174
t.onGoAway(t.goAwayReason)
1179
upperLimit := t.prevGoAwayID
1180
if upperLimit == 0 {
1181
upperLimit = math.MaxUint32
1183
for streamID, stream := range t.activeStreams {
1184
if streamID > id && streamID <= upperLimit {
1186
atomic.StoreUint32(&stream.unprocessed, 1)
1187
t.closeStream(stream, errStreamDrain, false, http2.ErrCodeNo, statusGoAway, nil, false)
1191
active := len(t.activeStreams)
1202
func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) {
1203
t.goAwayReason = GoAwayNoReason
1205
case http2.ErrCodeEnhanceYourCalm:
1206
if string(f.DebugData()) == "too_many_pings" {
1207
t.goAwayReason = GoAwayTooManyPings
1212
func (t *http2Client) GetGoAwayReason() GoAwayReason {
1215
return t.goAwayReason
1218
func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) {
1219
t.controlBuf.put(&incomingWindowUpdate{
1220
streamID: f.Header().StreamID,
1221
increment: f.Increment,
1226
func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) {
1227
s := t.getStream(frame)
1231
endStream := frame.StreamEnded()
1232
atomic.StoreUint32(&s.bytesReceived, 1)
1233
initialHeader := atomic.LoadUint32(&s.headerChanClosed) == 0
1235
if !initialHeader && !endStream {
1237
st := status.New(codes.Internal, "a HEADERS frame cannot appear in the middle of a stream")
1238
t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, false)
1242
state := &decodeState{}
1244
state.data.isGRPC = !initialHeader
1245
if h2code, err := state.decodeHeader(frame); err != nil {
1246
t.closeStream(s, err, true, h2code, status.Convert(err), nil, endStream)
1252
if t.statsHandler != nil {
1254
inHeader := &stats.InHeader{
1256
WireLength: int(frame.Header().Length),
1257
Header: s.header.Copy(),
1258
Compression: s.recvCompress,
1260
t.statsHandler.HandleRPC(s.ctx, inHeader)
1262
inTrailer := &stats.InTrailer{
1264
WireLength: int(frame.Header().Length),
1265
Trailer: s.trailer.Copy(),
1267
t.statsHandler.HandleRPC(s.ctx, inTrailer)
1273
if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) {
1274
s.headerValid = true
1281
s.recvCompress = state.data.encoding
1282
if len(state.data.mdata) > 0 {
1283
s.header = state.data.mdata
1297
rst := s.getState() == streamActive
1298
t.closeStream(s, io.EOF, rst, http2.ErrCodeNo, state.status(), state.data.mdata, true)
1307
func (t *http2Client) reader() {
1308
defer close(t.readerDone)
1310
frame, err := t.framer.fr.ReadFrame()
1315
t.conn.SetReadDeadline(time.Time{})
1316
if t.keepaliveEnabled {
1317
atomic.StoreInt64(&t.lastRead, time.Now().UnixNano())
1319
sf, ok := frame.(*http2.SettingsFrame)
1324
t.onPrefaceReceipt()
1325
t.handleSettings(sf, true)
1329
t.controlBuf.throttle()
1330
frame, err := t.framer.fr.ReadFrame()
1331
if t.keepaliveEnabled {
1332
atomic.StoreInt64(&t.lastRead, time.Now().UnixNano())
1338
if se, ok := err.(http2.StreamError); ok {
1340
s := t.activeStreams[se.StreamID]
1344
code := http2ErrConvTab[se.Code]
1345
errorDetail := t.framer.fr.ErrorDetail()
1347
if errorDetail != nil {
1348
msg = errorDetail.Error()
1350
msg = "received invalid frame"
1352
t.closeStream(s, status.Error(code, msg), true, http2.ErrCodeProtocol, status.New(code, msg), nil, false)
1361
switch frame := frame.(type) {
1362
case *http2.MetaHeadersFrame:
1363
t.operateHeaders(frame)
1364
case *http2.DataFrame:
1366
case *http2.RSTStreamFrame:
1367
t.handleRSTStream(frame)
1368
case *http2.SettingsFrame:
1369
t.handleSettings(frame, false)
1370
case *http2.PingFrame:
1372
case *http2.GoAwayFrame:
1373
t.handleGoAway(frame)
1374
case *http2.WindowUpdateFrame:
1375
t.handleWindowUpdate(frame)
1377
if logger.V(logLevel) {
1378
logger.Errorf("transport: http2Client.reader got unhandled frame type %v.", frame)
1384
func minTime(a, b time.Duration) time.Duration {
1392
func (t *http2Client) keepalive() {
1393
p := &ping{data: [8]byte{}}
1395
outstandingPing := false
1398
timeoutLeft := time.Duration(0)
1401
prevNano := time.Now().UnixNano()
1402
timer := time.NewTimer(t.kp.Time)
1406
lastRead := atomic.LoadInt64(&t.lastRead)
1407
if lastRead > prevNano {
1409
outstandingPing = false
1411
timer.Reset(time.Duration(lastRead) + t.kp.Time - time.Duration(time.Now().UnixNano()))
1415
if outstandingPing && timeoutLeft <= 0 {
1420
if t.state == closing {
1430
if len(t.activeStreams) < 1 && !t.kp.PermitWithoutStream {
1436
outstandingPing = false
1438
t.kpDormancyCond.Wait()
1446
if !outstandingPing {
1447
if channelz.IsOn() {
1448
atomic.AddInt64(&t.czData.kpCount, 1)
1451
timeoutLeft = t.kp.Timeout
1452
outstandingPing = true
1458
sleepDuration := minTime(t.kp.Time, timeoutLeft)
1459
timeoutLeft -= sleepDuration
1460
timer.Reset(sleepDuration)
1461
case <-t.ctx.Done():
1470
func (t *http2Client) Error() <-chan struct{} {
1474
func (t *http2Client) GoAway() <-chan struct{} {
1478
func (t *http2Client) ChannelzMetric() *channelz.SocketInternalMetric {
1479
s := channelz.SocketInternalMetric{
1480
StreamsStarted: atomic.LoadInt64(&t.czData.streamsStarted),
1481
StreamsSucceeded: atomic.LoadInt64(&t.czData.streamsSucceeded),
1482
StreamsFailed: atomic.LoadInt64(&t.czData.streamsFailed),
1483
MessagesSent: atomic.LoadInt64(&t.czData.msgSent),
1484
MessagesReceived: atomic.LoadInt64(&t.czData.msgRecv),
1485
KeepAlivesSent: atomic.LoadInt64(&t.czData.kpCount),
1486
LastLocalStreamCreatedTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastStreamCreatedTime)),
1487
LastMessageSentTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastMsgSentTime)),
1488
LastMessageReceivedTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastMsgRecvTime)),
1489
LocalFlowControlWindow: int64(t.fc.getSize()),
1490
SocketOptions: channelz.GetSocketOption(t.conn),
1491
LocalAddr: t.localAddr,
1492
RemoteAddr: t.remoteAddr,
1495
if au, ok := t.authInfo.(credentials.ChannelzSecurityInfo); ok {
1496
s.Security = au.GetSecurityValue()
1498
s.RemoteFlowControlWindow = t.getOutFlowWindow()
1502
func (t *http2Client) RemoteAddr() net.Addr { return t.remoteAddr }
1504
func (t *http2Client) IncrMsgSent() {
1505
atomic.AddInt64(&t.czData.msgSent, 1)
1506
atomic.StoreInt64(&t.czData.lastMsgSentTime, time.Now().UnixNano())
1509
func (t *http2Client) IncrMsgRecv() {
1510
atomic.AddInt64(&t.czData.msgRecv, 1)
1511
atomic.StoreInt64(&t.czData.lastMsgRecvTime, time.Now().UnixNano())
1514
func (t *http2Client) getOutFlowWindow() int64 {
1515
resp := make(chan uint32, 1)
1516
timer := time.NewTimer(time.Second)
1518
t.controlBuf.put(&outFlowControlSizeRequest{resp})