Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1 | /* |
| 2 | * |
| 3 | * Copyright 2014 gRPC authors. |
| 4 | * |
| 5 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | * you may not use this file except in compliance with the License. |
| 7 | * You may obtain a copy of the License at |
| 8 | * |
| 9 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | * |
| 11 | * Unless required by applicable law or agreed to in writing, software |
| 12 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | * See the License for the specific language governing permissions and |
| 15 | * limitations under the License. |
| 16 | * |
| 17 | */ |
| 18 | |
| 19 | package transport |
| 20 | |
| 21 | import ( |
| 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" |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 38 | "google.golang.org/grpc/internal" |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 | |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 48 | // clientConnectionCounter counts the number of connections a client has |
| 49 | // initiated (equal to the number of http2Clients created). Must be accessed |
| 50 | // atomically. |
| 51 | var clientConnectionCounter uint64 |
| 52 | |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 53 | // http2Client implements the ClientTransport interface with HTTP2. |
| 54 | type http2Client struct { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 55 | lastRead int64 // Keep this field 64-bit aligned. Accessed atomically. |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 56 | ctx context.Context |
| 57 | cancel context.CancelFunc |
| 58 | ctxDone <-chan struct{} // Cache the ctx.Done() chan. |
| 59 | userAgent string |
| 60 | md interface{} |
| 61 | conn net.Conn // underlying communication channel |
| 62 | loopy *loopyWriter |
| 63 | remoteAddr net.Addr |
| 64 | localAddr net.Addr |
| 65 | authInfo credentials.AuthInfo // auth info about the connection |
| 66 | |
| 67 | readerDone chan struct{} // sync point to enable testing. |
| 68 | writerDone chan struct{} // sync point to enable testing. |
| 69 | // goAway is closed to notify the upper layer (i.e., addrConn.transportMonitor) |
| 70 | // that the server sent GoAway on this transport. |
| 71 | goAway chan struct{} |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 | |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 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 |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 134 | |
| 135 | connectionID uint64 |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 136 | } |
| 137 | |
| 138 | func 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 | |
| 145 | func 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. |
| 164 | func 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{}), |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 | } |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 294 | t.kpDormancyCond = sync.NewCond(&t.mu) |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 | |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 339 | t.connectionID = atomic.AddUint64(&clientConnectionCounter, 1) |
| 340 | |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 341 | if err := t.framer.writer.Flush(); err != nil { |
| 342 | return nil, err |
| 343 | } |
| 344 | go func() { |
| 345 | t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst) |
| 346 | err := t.loopy.run() |
| 347 | if err != nil { |
| 348 | errorf("transport: loopyWriter.run returning. Err: %v", err) |
| 349 | } |
| 350 | // If it's a connection error, let reader goroutine handle it |
| 351 | // since there might be data in the buffers. |
| 352 | if _, ok := err.(net.Error); !ok { |
| 353 | t.conn.Close() |
| 354 | } |
| 355 | close(t.writerDone) |
| 356 | }() |
| 357 | return t, nil |
| 358 | } |
| 359 | |
| 360 | func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream { |
| 361 | // TODO(zhaoq): Handle uint32 overflow of Stream.id. |
| 362 | s := &Stream{ |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 363 | ct: t, |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 | |
| 396 | func (t *http2Client) getPeer() *peer.Peer { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 397 | return &peer.Peer{ |
| 398 | Addr: t.remoteAddr, |
| 399 | AuthInfo: t.authInfo, |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 400 | } |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 401 | } |
| 402 | |
| 403 | func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) ([]hpack.HeaderField, error) { |
| 404 | aud := t.createAudience(callHdr) |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 405 | ri := credentials.RequestInfo{ |
| 406 | Method: callHdr.Method, |
| 407 | AuthInfo: t.authInfo, |
| 408 | } |
| 409 | ctxWithRequestInfo := internal.NewRequestInfoContext.(func(context.Context, credentials.RequestInfo) context.Context)(ctx, ri) |
| 410 | authData, err := t.getTrAuthData(ctxWithRequestInfo, aud) |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 411 | if err != nil { |
| 412 | return nil, err |
| 413 | } |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 414 | callAuthData, err := t.getCallAuthData(ctxWithRequestInfo, aud, callHdr) |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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}) |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 437 | headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-accept-encoding", Value: callHdr.SendCompress}) |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 438 | } |
| 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 | |
| 496 | func (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 | |
| 511 | func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[string]string, error) { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 512 | if len(t.perRPCCreds) == 0 { |
| 513 | return nil, nil |
| 514 | } |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 | |
| 534 | func (t *http2Client) getCallAuthData(ctx context.Context, audience string, callHdr *CallHdr) (map[string]string, error) { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 535 | var callAuthData map[string]string |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 | } |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 547 | callAuthData = make(map[string]string, len(data)) |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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. |
| 559 | func (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 | } |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 579 | } |
| 580 | hdr := &headerFrame{ |
| 581 | hf: headerFields, |
| 582 | endStream: false, |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 583 | initStream: func(id uint32) error { |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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) |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 593 | return err |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 | } |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 600 | // If the keepalive goroutine has gone dormant, wake it up. |
| 601 | if t.kpDormant { |
| 602 | t.kpDormancyCond.Signal() |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 603 | } |
| 604 | t.mu.Unlock() |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 605 | return nil |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 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 { |
amit.ghosh | 258d14c | 2020-10-02 15:13:38 +0200 | [diff] [blame] | 683 | 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 | } |
| 689 | // Note: The header fields are compressed with hpack after this call returns. |
| 690 | // No WireLength field is set here. |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 691 | outHeader := &stats.OutHeader{ |
| 692 | Client: true, |
| 693 | FullMethod: callHdr.Method, |
| 694 | RemoteAddr: t.remoteAddr, |
| 695 | LocalAddr: t.localAddr, |
| 696 | Compression: callHdr.SendCompress, |
amit.ghosh | 258d14c | 2020-10-02 15:13:38 +0200 | [diff] [blame] | 697 | Header: header, |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 698 | } |
| 699 | t.statsHandler.HandleRPC(s.ctx, outHeader) |
| 700 | } |
| 701 | return s, nil |
| 702 | } |
| 703 | |
| 704 | // CloseStream clears the footprint of a stream when the stream is not needed any more. |
| 705 | // This must not be executed in reader's goroutine. |
| 706 | func (t *http2Client) CloseStream(s *Stream, err error) { |
| 707 | var ( |
| 708 | rst bool |
| 709 | rstCode http2.ErrCode |
| 710 | ) |
| 711 | if err != nil { |
| 712 | rst = true |
| 713 | rstCode = http2.ErrCodeCancel |
| 714 | } |
| 715 | t.closeStream(s, err, rst, rstCode, status.Convert(err), nil, false) |
| 716 | } |
| 717 | |
| 718 | func (t *http2Client) closeStream(s *Stream, err error, rst bool, rstCode http2.ErrCode, st *status.Status, mdata map[string][]string, eosReceived bool) { |
| 719 | // Set stream status to done. |
| 720 | if s.swapState(streamDone) == streamDone { |
| 721 | // If it was already done, return. If multiple closeStream calls |
| 722 | // happen simultaneously, wait for the first to finish. |
| 723 | <-s.done |
| 724 | return |
| 725 | } |
| 726 | // status and trailers can be updated here without any synchronization because the stream goroutine will |
| 727 | // only read it after it sees an io.EOF error from read or write and we'll write those errors |
| 728 | // only after updating this. |
| 729 | s.status = st |
| 730 | if len(mdata) > 0 { |
| 731 | s.trailer = mdata |
| 732 | } |
| 733 | if err != nil { |
| 734 | // This will unblock reads eventually. |
| 735 | s.write(recvMsg{err: err}) |
| 736 | } |
| 737 | // If headerChan isn't closed, then close it. |
| 738 | if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) { |
| 739 | s.noHeaders = true |
| 740 | close(s.headerChan) |
| 741 | } |
| 742 | cleanup := &cleanupStream{ |
| 743 | streamID: s.id, |
| 744 | onWrite: func() { |
| 745 | t.mu.Lock() |
| 746 | if t.activeStreams != nil { |
| 747 | delete(t.activeStreams, s.id) |
| 748 | } |
| 749 | t.mu.Unlock() |
| 750 | if channelz.IsOn() { |
| 751 | if eosReceived { |
| 752 | atomic.AddInt64(&t.czData.streamsSucceeded, 1) |
| 753 | } else { |
| 754 | atomic.AddInt64(&t.czData.streamsFailed, 1) |
| 755 | } |
| 756 | } |
| 757 | }, |
| 758 | rst: rst, |
| 759 | rstCode: rstCode, |
| 760 | } |
| 761 | addBackStreamQuota := func(interface{}) bool { |
| 762 | t.streamQuota++ |
| 763 | if t.streamQuota > 0 && t.waitingStreams > 0 { |
| 764 | select { |
| 765 | case t.streamsQuotaAvailable <- struct{}{}: |
| 766 | default: |
| 767 | } |
| 768 | } |
| 769 | return true |
| 770 | } |
| 771 | t.controlBuf.executeAndPut(addBackStreamQuota, cleanup) |
| 772 | // This will unblock write. |
| 773 | close(s.done) |
| 774 | } |
| 775 | |
| 776 | // Close kicks off the shutdown process of the transport. This should be called |
| 777 | // only once on a transport. Once it is called, the transport should not be |
| 778 | // accessed any more. |
| 779 | // |
| 780 | // This method blocks until the addrConn that initiated this transport is |
| 781 | // re-connected. This happens because t.onClose() begins reconnect logic at the |
| 782 | // addrConn level and blocks until the addrConn is successfully connected. |
| 783 | func (t *http2Client) Close() error { |
| 784 | t.mu.Lock() |
| 785 | // Make sure we only Close once. |
| 786 | if t.state == closing { |
| 787 | t.mu.Unlock() |
| 788 | return nil |
| 789 | } |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 790 | // Call t.onClose before setting the state to closing to prevent the client |
| 791 | // from attempting to create new streams ASAP. |
| 792 | t.onClose() |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 793 | t.state = closing |
| 794 | streams := t.activeStreams |
| 795 | t.activeStreams = nil |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 796 | if t.kpDormant { |
| 797 | // If the keepalive goroutine is blocked on this condition variable, we |
| 798 | // should unblock it so that the goroutine eventually exits. |
| 799 | t.kpDormancyCond.Signal() |
| 800 | } |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 801 | t.mu.Unlock() |
| 802 | t.controlBuf.finish() |
| 803 | t.cancel() |
| 804 | err := t.conn.Close() |
| 805 | if channelz.IsOn() { |
| 806 | channelz.RemoveEntry(t.channelzID) |
| 807 | } |
| 808 | // Notify all active streams. |
| 809 | for _, s := range streams { |
| 810 | t.closeStream(s, ErrConnClosing, false, http2.ErrCodeNo, status.New(codes.Unavailable, ErrConnClosing.Desc), nil, false) |
| 811 | } |
| 812 | if t.statsHandler != nil { |
| 813 | connEnd := &stats.ConnEnd{ |
| 814 | Client: true, |
| 815 | } |
| 816 | t.statsHandler.HandleConn(t.ctx, connEnd) |
| 817 | } |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 818 | return err |
| 819 | } |
| 820 | |
| 821 | // GracefulClose sets the state to draining, which prevents new streams from |
| 822 | // being created and causes the transport to be closed when the last active |
| 823 | // stream is closed. If there are no active streams, the transport is closed |
| 824 | // immediately. This does nothing if the transport is already draining or |
| 825 | // closing. |
| 826 | func (t *http2Client) GracefulClose() { |
| 827 | t.mu.Lock() |
| 828 | // Make sure we move to draining only from active. |
| 829 | if t.state == draining || t.state == closing { |
| 830 | t.mu.Unlock() |
| 831 | return |
| 832 | } |
| 833 | t.state = draining |
| 834 | active := len(t.activeStreams) |
| 835 | t.mu.Unlock() |
| 836 | if active == 0 { |
| 837 | t.Close() |
| 838 | return |
| 839 | } |
| 840 | t.controlBuf.put(&incomingGoAway{}) |
| 841 | } |
| 842 | |
| 843 | // Write formats the data into HTTP2 data frame(s) and sends it out. The caller |
| 844 | // should proceed only if Write returns nil. |
| 845 | func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { |
| 846 | if opts.Last { |
| 847 | // If it's the last message, update stream state. |
| 848 | if !s.compareAndSwapState(streamActive, streamWriteDone) { |
| 849 | return errStreamDone |
| 850 | } |
| 851 | } else if s.getState() != streamActive { |
| 852 | return errStreamDone |
| 853 | } |
| 854 | df := &dataFrame{ |
| 855 | streamID: s.id, |
| 856 | endStream: opts.Last, |
| 857 | } |
| 858 | if hdr != nil || data != nil { // If it's not an empty data frame. |
| 859 | // Add some data to grpc message header so that we can equally |
| 860 | // distribute bytes across frames. |
| 861 | emptyLen := http2MaxFrameLen - len(hdr) |
| 862 | if emptyLen > len(data) { |
| 863 | emptyLen = len(data) |
| 864 | } |
| 865 | hdr = append(hdr, data[:emptyLen]...) |
| 866 | data = data[emptyLen:] |
| 867 | df.h, df.d = hdr, data |
| 868 | // TODO(mmukhi): The above logic in this if can be moved to loopyWriter's data handler. |
| 869 | if err := s.wq.get(int32(len(hdr) + len(data))); err != nil { |
| 870 | return err |
| 871 | } |
| 872 | } |
| 873 | return t.controlBuf.put(df) |
| 874 | } |
| 875 | |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 876 | func (t *http2Client) getStream(f http2.Frame) *Stream { |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 877 | t.mu.Lock() |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 878 | s := t.activeStreams[f.Header().StreamID] |
| 879 | t.mu.Unlock() |
| 880 | return s |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 881 | } |
| 882 | |
| 883 | // adjustWindow sends out extra window update over the initial window size |
| 884 | // of stream if the application is requesting data larger in size than |
| 885 | // the window. |
| 886 | func (t *http2Client) adjustWindow(s *Stream, n uint32) { |
| 887 | if w := s.fc.maybeAdjust(n); w > 0 { |
| 888 | t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) |
| 889 | } |
| 890 | } |
| 891 | |
| 892 | // updateWindow adjusts the inbound quota for the stream. |
| 893 | // Window updates will be sent out when the cumulative quota |
| 894 | // exceeds the corresponding threshold. |
| 895 | func (t *http2Client) updateWindow(s *Stream, n uint32) { |
| 896 | if w := s.fc.onRead(n); w > 0 { |
| 897 | t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) |
| 898 | } |
| 899 | } |
| 900 | |
| 901 | // updateFlowControl updates the incoming flow control windows |
| 902 | // for the transport and the stream based on the current bdp |
| 903 | // estimation. |
| 904 | func (t *http2Client) updateFlowControl(n uint32) { |
| 905 | t.mu.Lock() |
| 906 | for _, s := range t.activeStreams { |
| 907 | s.fc.newLimit(n) |
| 908 | } |
| 909 | t.mu.Unlock() |
| 910 | updateIWS := func(interface{}) bool { |
| 911 | t.initialWindowSize = int32(n) |
| 912 | return true |
| 913 | } |
| 914 | t.controlBuf.executeAndPut(updateIWS, &outgoingWindowUpdate{streamID: 0, increment: t.fc.newLimit(n)}) |
| 915 | t.controlBuf.put(&outgoingSettings{ |
| 916 | ss: []http2.Setting{ |
| 917 | { |
| 918 | ID: http2.SettingInitialWindowSize, |
| 919 | Val: n, |
| 920 | }, |
| 921 | }, |
| 922 | }) |
| 923 | } |
| 924 | |
| 925 | func (t *http2Client) handleData(f *http2.DataFrame) { |
| 926 | size := f.Header().Length |
| 927 | var sendBDPPing bool |
| 928 | if t.bdpEst != nil { |
| 929 | sendBDPPing = t.bdpEst.add(size) |
| 930 | } |
| 931 | // Decouple connection's flow control from application's read. |
| 932 | // An update on connection's flow control should not depend on |
| 933 | // whether user application has read the data or not. Such a |
| 934 | // restriction is already imposed on the stream's flow control, |
| 935 | // and therefore the sender will be blocked anyways. |
| 936 | // Decoupling the connection flow control will prevent other |
| 937 | // active(fast) streams from starving in presence of slow or |
| 938 | // inactive streams. |
| 939 | // |
| 940 | if w := t.fc.onData(size); w > 0 { |
| 941 | t.controlBuf.put(&outgoingWindowUpdate{ |
| 942 | streamID: 0, |
| 943 | increment: w, |
| 944 | }) |
| 945 | } |
| 946 | if sendBDPPing { |
| 947 | // Avoid excessive ping detection (e.g. in an L7 proxy) |
| 948 | // by sending a window update prior to the BDP ping. |
| 949 | |
| 950 | if w := t.fc.reset(); w > 0 { |
| 951 | t.controlBuf.put(&outgoingWindowUpdate{ |
| 952 | streamID: 0, |
| 953 | increment: w, |
| 954 | }) |
| 955 | } |
| 956 | |
| 957 | t.controlBuf.put(bdpPing) |
| 958 | } |
| 959 | // Select the right stream to dispatch. |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 960 | s := t.getStream(f) |
| 961 | if s == nil { |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 962 | return |
| 963 | } |
| 964 | if size > 0 { |
| 965 | if err := s.fc.onData(size); err != nil { |
| 966 | t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false) |
| 967 | return |
| 968 | } |
| 969 | if f.Header().Flags.Has(http2.FlagDataPadded) { |
| 970 | if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 { |
| 971 | t.controlBuf.put(&outgoingWindowUpdate{s.id, w}) |
| 972 | } |
| 973 | } |
| 974 | // TODO(bradfitz, zhaoq): A copy is required here because there is no |
| 975 | // guarantee f.Data() is consumed before the arrival of next frame. |
| 976 | // Can this copy be eliminated? |
| 977 | if len(f.Data()) > 0 { |
| 978 | buffer := t.bufferPool.get() |
| 979 | buffer.Reset() |
| 980 | buffer.Write(f.Data()) |
| 981 | s.write(recvMsg{buffer: buffer}) |
| 982 | } |
| 983 | } |
| 984 | // The server has closed the stream without sending trailers. Record that |
| 985 | // the read direction is closed, and set the status appropriately. |
| 986 | if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) { |
| 987 | t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.New(codes.Internal, "server closed the stream without sending trailers"), nil, true) |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 992 | s := t.getStream(f) |
| 993 | if s == nil { |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 994 | return |
| 995 | } |
| 996 | if f.ErrCode == http2.ErrCodeRefusedStream { |
| 997 | // The stream was unprocessed by the server. |
| 998 | atomic.StoreUint32(&s.unprocessed, 1) |
| 999 | } |
| 1000 | statusCode, ok := http2ErrConvTab[f.ErrCode] |
| 1001 | if !ok { |
| 1002 | warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode) |
| 1003 | statusCode = codes.Unknown |
| 1004 | } |
| 1005 | if statusCode == codes.Canceled { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1006 | if d, ok := s.ctx.Deadline(); ok && !d.After(time.Now()) { |
| 1007 | // Our deadline was already exceeded, and that was likely the cause |
| 1008 | // of this cancelation. Alter the status code accordingly. |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1009 | statusCode = codes.DeadlineExceeded |
| 1010 | } |
| 1011 | } |
| 1012 | t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %v", f.ErrCode), nil, false) |
| 1013 | } |
| 1014 | |
| 1015 | func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) { |
| 1016 | if f.IsAck() { |
| 1017 | return |
| 1018 | } |
| 1019 | var maxStreams *uint32 |
| 1020 | var ss []http2.Setting |
| 1021 | var updateFuncs []func() |
| 1022 | f.ForeachSetting(func(s http2.Setting) error { |
| 1023 | switch s.ID { |
| 1024 | case http2.SettingMaxConcurrentStreams: |
| 1025 | maxStreams = new(uint32) |
| 1026 | *maxStreams = s.Val |
| 1027 | case http2.SettingMaxHeaderListSize: |
| 1028 | updateFuncs = append(updateFuncs, func() { |
| 1029 | t.maxSendHeaderListSize = new(uint32) |
| 1030 | *t.maxSendHeaderListSize = s.Val |
| 1031 | }) |
| 1032 | default: |
| 1033 | ss = append(ss, s) |
| 1034 | } |
| 1035 | return nil |
| 1036 | }) |
| 1037 | if isFirst && maxStreams == nil { |
| 1038 | maxStreams = new(uint32) |
| 1039 | *maxStreams = math.MaxUint32 |
| 1040 | } |
| 1041 | sf := &incomingSettings{ |
| 1042 | ss: ss, |
| 1043 | } |
| 1044 | if maxStreams != nil { |
| 1045 | updateStreamQuota := func() { |
| 1046 | delta := int64(*maxStreams) - int64(t.maxConcurrentStreams) |
| 1047 | t.maxConcurrentStreams = *maxStreams |
| 1048 | t.streamQuota += delta |
| 1049 | if delta > 0 && t.waitingStreams > 0 { |
| 1050 | close(t.streamsQuotaAvailable) // wake all of them up. |
| 1051 | t.streamsQuotaAvailable = make(chan struct{}, 1) |
| 1052 | } |
| 1053 | } |
| 1054 | updateFuncs = append(updateFuncs, updateStreamQuota) |
| 1055 | } |
| 1056 | t.controlBuf.executeAndPut(func(interface{}) bool { |
| 1057 | for _, f := range updateFuncs { |
| 1058 | f() |
| 1059 | } |
| 1060 | return true |
| 1061 | }, sf) |
| 1062 | } |
| 1063 | |
| 1064 | func (t *http2Client) handlePing(f *http2.PingFrame) { |
| 1065 | if f.IsAck() { |
| 1066 | // Maybe it's a BDP ping. |
| 1067 | if t.bdpEst != nil { |
| 1068 | t.bdpEst.calculate(f.Data) |
| 1069 | } |
| 1070 | return |
| 1071 | } |
| 1072 | pingAck := &ping{ack: true} |
| 1073 | copy(pingAck.data[:], f.Data[:]) |
| 1074 | t.controlBuf.put(pingAck) |
| 1075 | } |
| 1076 | |
| 1077 | func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { |
| 1078 | t.mu.Lock() |
| 1079 | if t.state == closing { |
| 1080 | t.mu.Unlock() |
| 1081 | return |
| 1082 | } |
| 1083 | if f.ErrCode == http2.ErrCodeEnhanceYourCalm { |
| 1084 | infof("Client received GoAway with http2.ErrCodeEnhanceYourCalm.") |
| 1085 | } |
| 1086 | id := f.LastStreamID |
| 1087 | if id > 0 && id%2 != 1 { |
| 1088 | t.mu.Unlock() |
| 1089 | t.Close() |
| 1090 | return |
| 1091 | } |
| 1092 | // A client can receive multiple GoAways from the server (see |
| 1093 | // https://github.com/grpc/grpc-go/issues/1387). The idea is that the first |
| 1094 | // GoAway will be sent with an ID of MaxInt32 and the second GoAway will be |
| 1095 | // sent after an RTT delay with the ID of the last stream the server will |
| 1096 | // process. |
| 1097 | // |
| 1098 | // Therefore, when we get the first GoAway we don't necessarily close any |
| 1099 | // streams. While in case of second GoAway we close all streams created after |
| 1100 | // the GoAwayId. This way streams that were in-flight while the GoAway from |
| 1101 | // server was being sent don't get killed. |
| 1102 | select { |
| 1103 | case <-t.goAway: // t.goAway has been closed (i.e.,multiple GoAways). |
| 1104 | // If there are multiple GoAways the first one should always have an ID greater than the following ones. |
| 1105 | if id > t.prevGoAwayID { |
| 1106 | t.mu.Unlock() |
| 1107 | t.Close() |
| 1108 | return |
| 1109 | } |
| 1110 | default: |
| 1111 | t.setGoAwayReason(f) |
| 1112 | close(t.goAway) |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1113 | t.controlBuf.put(&incomingGoAway{}) |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1114 | // Notify the clientconn about the GOAWAY before we set the state to |
| 1115 | // draining, to allow the client to stop attempting to create streams |
| 1116 | // before disallowing new streams on this connection. |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1117 | t.onGoAway(t.goAwayReason) |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1118 | t.state = draining |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1119 | } |
| 1120 | // All streams with IDs greater than the GoAwayId |
| 1121 | // and smaller than the previous GoAway ID should be killed. |
| 1122 | upperLimit := t.prevGoAwayID |
| 1123 | if upperLimit == 0 { // This is the first GoAway Frame. |
| 1124 | upperLimit = math.MaxUint32 // Kill all streams after the GoAway ID. |
| 1125 | } |
| 1126 | for streamID, stream := range t.activeStreams { |
| 1127 | if streamID > id && streamID <= upperLimit { |
| 1128 | // The stream was unprocessed by the server. |
| 1129 | atomic.StoreUint32(&stream.unprocessed, 1) |
| 1130 | t.closeStream(stream, errStreamDrain, false, http2.ErrCodeNo, statusGoAway, nil, false) |
| 1131 | } |
| 1132 | } |
| 1133 | t.prevGoAwayID = id |
| 1134 | active := len(t.activeStreams) |
| 1135 | t.mu.Unlock() |
| 1136 | if active == 0 { |
| 1137 | t.Close() |
| 1138 | } |
| 1139 | } |
| 1140 | |
| 1141 | // setGoAwayReason sets the value of t.goAwayReason based |
| 1142 | // on the GoAway frame received. |
| 1143 | // It expects a lock on transport's mutext to be held by |
| 1144 | // the caller. |
| 1145 | func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) { |
| 1146 | t.goAwayReason = GoAwayNoReason |
| 1147 | switch f.ErrCode { |
| 1148 | case http2.ErrCodeEnhanceYourCalm: |
| 1149 | if string(f.DebugData()) == "too_many_pings" { |
| 1150 | t.goAwayReason = GoAwayTooManyPings |
| 1151 | } |
| 1152 | } |
| 1153 | } |
| 1154 | |
| 1155 | func (t *http2Client) GetGoAwayReason() GoAwayReason { |
| 1156 | t.mu.Lock() |
| 1157 | defer t.mu.Unlock() |
| 1158 | return t.goAwayReason |
| 1159 | } |
| 1160 | |
| 1161 | func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) { |
| 1162 | t.controlBuf.put(&incomingWindowUpdate{ |
| 1163 | streamID: f.Header().StreamID, |
| 1164 | increment: f.Increment, |
| 1165 | }) |
| 1166 | } |
| 1167 | |
| 1168 | // operateHeaders takes action on the decoded headers. |
| 1169 | func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1170 | s := t.getStream(frame) |
| 1171 | if s == nil { |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1172 | return |
| 1173 | } |
| 1174 | endStream := frame.StreamEnded() |
| 1175 | atomic.StoreUint32(&s.bytesReceived, 1) |
| 1176 | initialHeader := atomic.LoadUint32(&s.headerChanClosed) == 0 |
| 1177 | |
| 1178 | if !initialHeader && !endStream { |
| 1179 | // 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. |
| 1180 | st := status.New(codes.Internal, "a HEADERS frame cannot appear in the middle of a stream") |
| 1181 | t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, false) |
| 1182 | return |
| 1183 | } |
| 1184 | |
| 1185 | state := &decodeState{} |
| 1186 | // 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. |
| 1187 | state.data.isGRPC = !initialHeader |
| 1188 | if err := state.decodeHeader(frame); err != nil { |
| 1189 | t.closeStream(s, err, true, http2.ErrCodeProtocol, status.Convert(err), nil, endStream) |
| 1190 | return |
| 1191 | } |
| 1192 | |
| 1193 | isHeader := false |
| 1194 | defer func() { |
| 1195 | if t.statsHandler != nil { |
| 1196 | if isHeader { |
| 1197 | inHeader := &stats.InHeader{ |
amit.ghosh | 258d14c | 2020-10-02 15:13:38 +0200 | [diff] [blame] | 1198 | Client: true, |
| 1199 | WireLength: int(frame.Header().Length), |
| 1200 | Header: s.header.Copy(), |
| 1201 | Compression: s.recvCompress, |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1202 | } |
| 1203 | t.statsHandler.HandleRPC(s.ctx, inHeader) |
| 1204 | } else { |
| 1205 | inTrailer := &stats.InTrailer{ |
| 1206 | Client: true, |
| 1207 | WireLength: int(frame.Header().Length), |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1208 | Trailer: s.trailer.Copy(), |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1209 | } |
| 1210 | t.statsHandler.HandleRPC(s.ctx, inTrailer) |
| 1211 | } |
| 1212 | } |
| 1213 | }() |
| 1214 | |
| 1215 | // If headerChan hasn't been closed yet |
| 1216 | if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1217 | s.headerValid = true |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1218 | if !endStream { |
| 1219 | // HEADERS frame block carries a Response-Headers. |
| 1220 | isHeader = true |
| 1221 | // These values can be set without any synchronization because |
| 1222 | // stream goroutine will read it only after seeing a closed |
| 1223 | // headerChan which we'll close after setting this. |
| 1224 | s.recvCompress = state.data.encoding |
| 1225 | if len(state.data.mdata) > 0 { |
| 1226 | s.header = state.data.mdata |
| 1227 | } |
| 1228 | } else { |
| 1229 | // HEADERS frame block carries a Trailers-Only. |
| 1230 | s.noHeaders = true |
| 1231 | } |
| 1232 | close(s.headerChan) |
| 1233 | } |
| 1234 | |
| 1235 | if !endStream { |
| 1236 | return |
| 1237 | } |
| 1238 | |
| 1239 | // if client received END_STREAM from server while stream was still active, send RST_STREAM |
| 1240 | rst := s.getState() == streamActive |
| 1241 | t.closeStream(s, io.EOF, rst, http2.ErrCodeNo, state.status(), state.data.mdata, true) |
| 1242 | } |
| 1243 | |
| 1244 | // reader runs as a separate goroutine in charge of reading data from network |
| 1245 | // connection. |
| 1246 | // |
| 1247 | // TODO(zhaoq): currently one reader per transport. Investigate whether this is |
| 1248 | // optimal. |
| 1249 | // TODO(zhaoq): Check the validity of the incoming frame sequence. |
| 1250 | func (t *http2Client) reader() { |
| 1251 | defer close(t.readerDone) |
| 1252 | // Check the validity of server preface. |
| 1253 | frame, err := t.framer.fr.ReadFrame() |
| 1254 | if err != nil { |
| 1255 | t.Close() // this kicks off resetTransport, so must be last before return |
| 1256 | return |
| 1257 | } |
| 1258 | t.conn.SetReadDeadline(time.Time{}) // reset deadline once we get the settings frame (we didn't time out, yay!) |
| 1259 | if t.keepaliveEnabled { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1260 | atomic.StoreInt64(&t.lastRead, time.Now().UnixNano()) |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1261 | } |
| 1262 | sf, ok := frame.(*http2.SettingsFrame) |
| 1263 | if !ok { |
| 1264 | t.Close() // this kicks off resetTransport, so must be last before return |
| 1265 | return |
| 1266 | } |
| 1267 | t.onPrefaceReceipt() |
| 1268 | t.handleSettings(sf, true) |
| 1269 | |
| 1270 | // loop to keep reading incoming messages on this transport. |
| 1271 | for { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1272 | t.controlBuf.throttle() |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1273 | frame, err := t.framer.fr.ReadFrame() |
| 1274 | if t.keepaliveEnabled { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1275 | atomic.StoreInt64(&t.lastRead, time.Now().UnixNano()) |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1276 | } |
| 1277 | if err != nil { |
| 1278 | // Abort an active stream if the http2.Framer returns a |
| 1279 | // http2.StreamError. This can happen only if the server's response |
| 1280 | // is malformed http2. |
| 1281 | if se, ok := err.(http2.StreamError); ok { |
| 1282 | t.mu.Lock() |
| 1283 | s := t.activeStreams[se.StreamID] |
| 1284 | t.mu.Unlock() |
| 1285 | if s != nil { |
| 1286 | // use error detail to provide better err message |
| 1287 | code := http2ErrConvTab[se.Code] |
| 1288 | msg := t.framer.fr.ErrorDetail().Error() |
| 1289 | t.closeStream(s, status.Error(code, msg), true, http2.ErrCodeProtocol, status.New(code, msg), nil, false) |
| 1290 | } |
| 1291 | continue |
| 1292 | } else { |
| 1293 | // Transport error. |
| 1294 | t.Close() |
| 1295 | return |
| 1296 | } |
| 1297 | } |
| 1298 | switch frame := frame.(type) { |
| 1299 | case *http2.MetaHeadersFrame: |
| 1300 | t.operateHeaders(frame) |
| 1301 | case *http2.DataFrame: |
| 1302 | t.handleData(frame) |
| 1303 | case *http2.RSTStreamFrame: |
| 1304 | t.handleRSTStream(frame) |
| 1305 | case *http2.SettingsFrame: |
| 1306 | t.handleSettings(frame, false) |
| 1307 | case *http2.PingFrame: |
| 1308 | t.handlePing(frame) |
| 1309 | case *http2.GoAwayFrame: |
| 1310 | t.handleGoAway(frame) |
| 1311 | case *http2.WindowUpdateFrame: |
| 1312 | t.handleWindowUpdate(frame) |
| 1313 | default: |
| 1314 | errorf("transport: http2Client.reader got unhandled frame type %v.", frame) |
| 1315 | } |
| 1316 | } |
| 1317 | } |
| 1318 | |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1319 | func minTime(a, b time.Duration) time.Duration { |
| 1320 | if a < b { |
| 1321 | return a |
| 1322 | } |
| 1323 | return b |
| 1324 | } |
| 1325 | |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1326 | // keepalive running in a separate goroutune makes sure the connection is alive by sending pings. |
| 1327 | func (t *http2Client) keepalive() { |
| 1328 | p := &ping{data: [8]byte{}} |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1329 | // True iff a ping has been sent, and no data has been received since then. |
| 1330 | outstandingPing := false |
| 1331 | // Amount of time remaining before which we should receive an ACK for the |
| 1332 | // last sent ping. |
| 1333 | timeoutLeft := time.Duration(0) |
| 1334 | // Records the last value of t.lastRead before we go block on the timer. |
| 1335 | // This is required to check for read activity since then. |
| 1336 | prevNano := time.Now().UnixNano() |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1337 | timer := time.NewTimer(t.kp.Time) |
| 1338 | for { |
| 1339 | select { |
| 1340 | case <-timer.C: |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1341 | lastRead := atomic.LoadInt64(&t.lastRead) |
| 1342 | if lastRead > prevNano { |
| 1343 | // There has been read activity since the last time we were here. |
| 1344 | outstandingPing = false |
| 1345 | // Next timer should fire at kp.Time seconds from lastRead time. |
| 1346 | timer.Reset(time.Duration(lastRead) + t.kp.Time - time.Duration(time.Now().UnixNano())) |
| 1347 | prevNano = lastRead |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1348 | continue |
| 1349 | } |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1350 | if outstandingPing && timeoutLeft <= 0 { |
| 1351 | t.Close() |
| 1352 | return |
| 1353 | } |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1354 | t.mu.Lock() |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1355 | if t.state == closing { |
| 1356 | // If the transport is closing, we should exit from the |
| 1357 | // keepalive goroutine here. If not, we could have a race |
| 1358 | // between the call to Signal() from Close() and the call to |
| 1359 | // Wait() here, whereby the keepalive goroutine ends up |
| 1360 | // blocking on the condition variable which will never be |
| 1361 | // signalled again. |
| 1362 | t.mu.Unlock() |
| 1363 | return |
| 1364 | } |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1365 | if len(t.activeStreams) < 1 && !t.kp.PermitWithoutStream { |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1366 | // If a ping was sent out previously (because there were active |
| 1367 | // streams at that point) which wasn't acked and its timeout |
| 1368 | // hadn't fired, but we got here and are about to go dormant, |
| 1369 | // we should make sure that we unconditionally send a ping once |
| 1370 | // we awaken. |
| 1371 | outstandingPing = false |
| 1372 | t.kpDormant = true |
| 1373 | t.kpDormancyCond.Wait() |
| 1374 | } |
| 1375 | t.kpDormant = false |
| 1376 | t.mu.Unlock() |
| 1377 | |
| 1378 | // We get here either because we were dormant and a new stream was |
| 1379 | // created which unblocked the Wait() call, or because the |
| 1380 | // keepalive timer expired. In both cases, we need to send a ping. |
| 1381 | if !outstandingPing { |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1382 | if channelz.IsOn() { |
| 1383 | atomic.AddInt64(&t.czData.kpCount, 1) |
| 1384 | } |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1385 | t.controlBuf.put(p) |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1386 | timeoutLeft = t.kp.Timeout |
| 1387 | outstandingPing = true |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1388 | } |
Arjun E K | 57a7fcb | 2020-01-30 06:44:45 +0000 | [diff] [blame] | 1389 | // The amount of time to sleep here is the minimum of kp.Time and |
| 1390 | // timeoutLeft. This will ensure that we wait only for kp.Time |
| 1391 | // before sending out the next ping (for cases where the ping is |
| 1392 | // acked). |
| 1393 | sleepDuration := minTime(t.kp.Time, timeoutLeft) |
| 1394 | timeoutLeft -= sleepDuration |
| 1395 | timer.Reset(sleepDuration) |
Matteo Scandolo | a6a3aee | 2019-11-26 13:30:14 -0700 | [diff] [blame] | 1396 | case <-t.ctx.Done(): |
| 1397 | if !timer.Stop() { |
| 1398 | <-timer.C |
| 1399 | } |
| 1400 | return |
| 1401 | } |
| 1402 | } |
| 1403 | } |
| 1404 | |
| 1405 | func (t *http2Client) Error() <-chan struct{} { |
| 1406 | return t.ctx.Done() |
| 1407 | } |
| 1408 | |
| 1409 | func (t *http2Client) GoAway() <-chan struct{} { |
| 1410 | return t.goAway |
| 1411 | } |
| 1412 | |
| 1413 | func (t *http2Client) ChannelzMetric() *channelz.SocketInternalMetric { |
| 1414 | s := channelz.SocketInternalMetric{ |
| 1415 | StreamsStarted: atomic.LoadInt64(&t.czData.streamsStarted), |
| 1416 | StreamsSucceeded: atomic.LoadInt64(&t.czData.streamsSucceeded), |
| 1417 | StreamsFailed: atomic.LoadInt64(&t.czData.streamsFailed), |
| 1418 | MessagesSent: atomic.LoadInt64(&t.czData.msgSent), |
| 1419 | MessagesReceived: atomic.LoadInt64(&t.czData.msgRecv), |
| 1420 | KeepAlivesSent: atomic.LoadInt64(&t.czData.kpCount), |
| 1421 | LastLocalStreamCreatedTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastStreamCreatedTime)), |
| 1422 | LastMessageSentTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastMsgSentTime)), |
| 1423 | LastMessageReceivedTimestamp: time.Unix(0, atomic.LoadInt64(&t.czData.lastMsgRecvTime)), |
| 1424 | LocalFlowControlWindow: int64(t.fc.getSize()), |
| 1425 | SocketOptions: channelz.GetSocketOption(t.conn), |
| 1426 | LocalAddr: t.localAddr, |
| 1427 | RemoteAddr: t.remoteAddr, |
| 1428 | // RemoteName : |
| 1429 | } |
| 1430 | if au, ok := t.authInfo.(credentials.ChannelzSecurityInfo); ok { |
| 1431 | s.Security = au.GetSecurityValue() |
| 1432 | } |
| 1433 | s.RemoteFlowControlWindow = t.getOutFlowWindow() |
| 1434 | return &s |
| 1435 | } |
| 1436 | |
| 1437 | func (t *http2Client) RemoteAddr() net.Addr { return t.remoteAddr } |
| 1438 | |
| 1439 | func (t *http2Client) IncrMsgSent() { |
| 1440 | atomic.AddInt64(&t.czData.msgSent, 1) |
| 1441 | atomic.StoreInt64(&t.czData.lastMsgSentTime, time.Now().UnixNano()) |
| 1442 | } |
| 1443 | |
| 1444 | func (t *http2Client) IncrMsgRecv() { |
| 1445 | atomic.AddInt64(&t.czData.msgRecv, 1) |
| 1446 | atomic.StoreInt64(&t.czData.lastMsgRecvTime, time.Now().UnixNano()) |
| 1447 | } |
| 1448 | |
| 1449 | func (t *http2Client) getOutFlowWindow() int64 { |
| 1450 | resp := make(chan uint32, 1) |
| 1451 | timer := time.NewTimer(time.Second) |
| 1452 | defer timer.Stop() |
| 1453 | t.controlBuf.put(&outFlowControlSizeRequest{resp}) |
| 1454 | select { |
| 1455 | case sz := <-resp: |
| 1456 | return int64(sz) |
| 1457 | case <-t.ctxDone: |
| 1458 | return -1 |
| 1459 | case <-timer.C: |
| 1460 | return -2 |
| 1461 | } |
| 1462 | } |