Debian Codegraph @

vendor/google.golang.org/grpc/transport/http2_client.go

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