Debian Codegraph @

vendor/google.golang.org/grpc/transport/http2_server.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 "errors"
24 "fmt"
25 "io"
26 "math"
27 "math/rand"
28 "net"
29 "strconv"
30 "sync"
31 "sync/atomic"
32 "time"
33
34 "github.com/golang/protobuf/proto"
35 "golang.org/x/net/context"
36 "golang.org/x/net/http2"
37 "golang.org/x/net/http2/hpack"
38 "google.golang.org/grpc/codes"
39 "google.golang.org/grpc/credentials"
40 "google.golang.org/grpc/keepalive"
41 "google.golang.org/grpc/metadata"
42 "google.golang.org/grpc/peer"
43 "google.golang.org/grpc/stats"
44 "google.golang.org/grpc/status"
45 "google.golang.org/grpc/tap"
46 )
47
48 // ErrIllegalHeaderWrite indicates that setting header is illegal because of
49 // the stream's state.
50 var ErrIllegalHeaderWrite = errors.New("transport: the stream is done or WriteHeader was already called")
51
52 // http2Server implements the ServerTransport interface with HTTP2.
53 type http2Server struct {
54 ctx context.Context
55 cancel context.CancelFunc
56 conn net.Conn
57 remoteAddr net.Addr
58 localAddr net.Addr
59 maxStreamID uint32 // max stream ID ever seen
60 authInfo credentials.AuthInfo // auth info about the connection
61 inTapHandle tap.ServerInHandle
62 framer *framer
63 hBuf *bytes.Buffer // the buffer for HPACK encoding
64 hEnc *hpack.Encoder // HPACK encoder
65 // The max number of concurrent streams.
66 maxStreams uint32
67 // controlBuf delivers all the control related tasks (e.g., window
68 // updates, reset streams, and various settings) to the controller.
69 controlBuf *controlBuffer
70 fc *inFlow
71 // sendQuotaPool provides flow control to outbound message.
72 sendQuotaPool *quotaPool
73 stats stats.Handler
74 // Flag to keep track of reading activity on transport.
75 // 1 is true and 0 is false.
76 activity uint32 // Accessed atomically.
77 // Keepalive and max-age parameters for the server.
78 kp keepalive.ServerParameters
79
80 // Keepalive enforcement policy.
81 kep keepalive.EnforcementPolicy
82 // The time instance last ping was received.
83 lastPingAt time.Time
84 // Number of times the client has violated keepalive ping policy so far.
85 pingStrikes uint8
86 // Flag to signify that number of ping strikes should be reset to 0.
87 // This is set whenever data or header frames are sent.
88 // 1 means yes.
89 resetPingStrikes uint32 // Accessed atomically.
90 initialWindowSize int32
91 bdpEst *bdpEstimator
92
93 mu sync.Mutex // guard the following
94
95 // drainChan is initialized when drain(...) is called the first time.
96 // After which the server writes out the first GoAway(with ID 2^31-1) frame.
97 // Then an independent goroutine will be launched to later send the second GoAway.
98 // During this time we don't want to write another first GoAway(with ID 2^31 -1) frame.
99 // Thus call to drain(...) will be a no-op if drainChan is already initialized since draining is
100 // already underway.
101 drainChan chan struct{}
102 state transportState
103 activeStreams map[uint32]*Stream
104 // the per-stream outbound flow control window size set by the peer.
105 streamSendQuota uint32
106 // idle is the time instant when the connection went idle.
107 // This is either the beginning of the connection or when the number of
108 // RPCs go down to 0.
109 // When the connection is busy, this value is set to 0.
110 idle time.Time
111 }
112
113 // newHTTP2Server constructs a ServerTransport based on HTTP2. ConnectionError is
114 // returned if something goes wrong.
115 func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err error) {
116 writeBufSize := defaultWriteBufSize
117 if config.WriteBufferSize > 0 {
118 writeBufSize = config.WriteBufferSize
119 }
120 readBufSize := defaultReadBufSize
121 if config.ReadBufferSize > 0 {
122 readBufSize = config.ReadBufferSize
123 }
124 framer := newFramer(conn, writeBufSize, readBufSize)
125 // Send initial settings as connection preface to client.
126 var isettings []http2.Setting
127 // TODO(zhaoq): Have a better way to signal "no limit" because 0 is
128 // permitted in the HTTP2 spec.
129 maxStreams := config.MaxStreams
130 if maxStreams == 0 {
131 maxStreams = math.MaxUint32
132 } else {
133 isettings = append(isettings, http2.Setting{
134 ID: http2.SettingMaxConcurrentStreams,
135 Val: maxStreams,
136 })
137 }
138 dynamicWindow := true
139 iwz := int32(initialWindowSize)
140 if config.InitialWindowSize >= defaultWindowSize {
141 iwz = config.InitialWindowSize
142 dynamicWindow = false
143 }
144 icwz := int32(initialWindowSize)
145 if config.InitialConnWindowSize >= defaultWindowSize {
146 icwz = config.InitialConnWindowSize
147 dynamicWindow = false
148 }
149 if iwz != defaultWindowSize {
150 isettings = append(isettings, http2.Setting{
151 ID: http2.SettingInitialWindowSize,
152 Val: uint32(iwz)})
153 }
154 if err := framer.fr.WriteSettings(isettings...); err != nil {
155 return nil, connectionErrorf(false, err, "transport: %v", err)
156 }
157 // Adjust the connection flow control window if needed.
158 if delta := uint32(icwz - defaultWindowSize); delta > 0 {
159 if err := framer.fr.WriteWindowUpdate(0, delta); err != nil {
160 return nil, connectionErrorf(false, err, "transport: %v", err)
161 }
162 }
163 kp := config.KeepaliveParams
164 if kp.MaxConnectionIdle == 0 {
165 kp.MaxConnectionIdle = defaultMaxConnectionIdle
166 }
167 if kp.MaxConnectionAge == 0 {
168 kp.MaxConnectionAge = defaultMaxConnectionAge
169 }
170 // Add a jitter to MaxConnectionAge.
171 kp.MaxConnectionAge += getJitter(kp.MaxConnectionAge)
172 if kp.MaxConnectionAgeGrace == 0 {
173 kp.MaxConnectionAgeGrace = defaultMaxConnectionAgeGrace
174 }
175 if kp.Time == 0 {
176 kp.Time = defaultServerKeepaliveTime
177 }
178 if kp.Timeout == 0 {
179 kp.Timeout = defaultServerKeepaliveTimeout
180 }
181 kep := config.KeepalivePolicy
182 if kep.MinTime == 0 {
183 kep.MinTime = defaultKeepalivePolicyMinTime
184 }
185 var buf bytes.Buffer
186 ctx, cancel := context.WithCancel(context.Background())
187 t := &http2Server{
188 ctx: ctx,
189 cancel: cancel,
190 conn: conn,
191 remoteAddr: conn.RemoteAddr(),
192 localAddr: conn.LocalAddr(),
193 authInfo: config.AuthInfo,
194 framer: framer,
195 hBuf: &buf,
196 hEnc: hpack.NewEncoder(&buf),
197 maxStreams: maxStreams,
198 inTapHandle: config.InTapHandle,
199 controlBuf: newControlBuffer(),
200 fc: &inFlow{limit: uint32(icwz)},
201 sendQuotaPool: newQuotaPool(defaultWindowSize),
202 state: reachable,
203 activeStreams: make(map[uint32]*Stream),
204 streamSendQuota: defaultWindowSize,
205 stats: config.StatsHandler,
206 kp: kp,
207 idle: time.Now(),
208 kep: kep,
209 initialWindowSize: iwz,
210 }
211 if dynamicWindow {
212 t.bdpEst = &bdpEstimator{
213 bdp: initialWindowSize,
214 updateFlowControl: t.updateFlowControl,
215 }
216 }
217 if t.stats != nil {
218 t.ctx = t.stats.TagConn(t.ctx, &stats.ConnTagInfo{
219 RemoteAddr: t.remoteAddr,
220 LocalAddr: t.localAddr,
221 })
222 connBegin := &stats.ConnBegin{}
223 t.stats.HandleConn(t.ctx, connBegin)
224 }
225 t.framer.writer.Flush()
226
227 // Check the validity of client preface.
228 preface := make([]byte, len(clientPreface))
229 if _, err := io.ReadFull(t.conn, preface); err != nil {
230 return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to receive the preface from client: %v", err)
231 }
232 if !bytes.Equal(preface, clientPreface) {
233 return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams received bogus greeting from client: %q", preface)
234 }
235
236 frame, err := t.framer.fr.ReadFrame()
237 if err == io.EOF || err == io.ErrUnexpectedEOF {
238 t.Close()
239 return
240 }
241 if err != nil {
242 return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to read initial settings frame: %v", err)
243 }
244 atomic.StoreUint32(&t.activity, 1)
245 sf, ok := frame.(*http2.SettingsFrame)
246 if !ok {
247 return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams saw invalid preface type %T from client", frame)
248 }
249 t.handleSettings(sf)
250
251 go func() {
252 loopyWriter(t.ctx, t.controlBuf, t.itemHandler)
253 t.Close()
254 }()
255 go t.keepalive()
256 return t, nil
257 }
258
259 // operateHeader takes action on the decoded headers.
260 func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func(*Stream), traceCtx func(context.Context, string) context.Context) (close bool) {
261 streamID := frame.Header().StreamID
262
263 var state decodeState
264 for _, hf := range frame.Fields {
265 if err := state.processHeaderField(hf); err != nil {
266 if se, ok := err.(StreamError); ok {
267 t.controlBuf.put(&resetStream{streamID, statusCodeConvTab[se.Code]})
268 }
269 return
270 }
271 }
272
273 buf := newRecvBuffer()
274 s := &Stream{
275 id: streamID,
276 st: t,
277 buf: buf,
278 fc: &inFlow{limit: uint32(t.initialWindowSize)},
279 recvCompress: state.encoding,
280 method: state.method,
281 }
282
283 if frame.StreamEnded() {
284 // s is just created by the caller. No lock needed.
285 s.state = streamReadDone
286 }
287 if state.timeoutSet {
288 s.ctx, s.cancel = context.WithTimeout(t.ctx, state.timeout)
289 } else {
290 s.ctx, s.cancel = context.WithCancel(t.ctx)
291 }
292 pr := &peer.Peer{
293 Addr: t.remoteAddr,
294 }
295 // Attach Auth info if there is any.
296 if t.authInfo != nil {
297 pr.AuthInfo = t.authInfo
298 }
299 s.ctx = peer.NewContext(s.ctx, pr)
300 // Cache the current stream to the context so that the server application
301 // can find out. Required when the server wants to send some metadata
302 // back to the client (unary call only).
303 s.ctx = newContextWithStream(s.ctx, s)
304 // Attach the received metadata to the context.
305 if len(state.mdata) > 0 {
306 s.ctx = metadata.NewIncomingContext(s.ctx, state.mdata)
307 }
308 if state.statsTags != nil {
309 s.ctx = stats.SetIncomingTags(s.ctx, state.statsTags)
310 }
311 if state.statsTrace != nil {
312 s.ctx = stats.SetIncomingTrace(s.ctx, state.statsTrace)
313 }
314 if t.inTapHandle != nil {
315 var err error
316 info := &tap.Info{
317 FullMethodName: state.method,
318 }
319 s.ctx, err = t.inTapHandle(s.ctx, info)
320 if err != nil {
321 warningf("transport: http2Server.operateHeaders got an error from InTapHandle: %v", err)
322 t.controlBuf.put(&resetStream{s.id, http2.ErrCodeRefusedStream})
323 return
324 }
325 }
326 t.mu.Lock()
327 if t.state != reachable {
328 t.mu.Unlock()
329 return
330 }
331 if uint32(len(t.activeStreams)) >= t.maxStreams {
332 t.mu.Unlock()
333 t.controlBuf.put(&resetStream{streamID, http2.ErrCodeRefusedStream})
334 return
335 }
336 if streamID%2 != 1 || streamID <= t.maxStreamID {
337 t.mu.Unlock()
338 // illegal gRPC stream id.
339 errorf("transport: http2Server.HandleStreams received an illegal stream id: %v", streamID)
340 return true
341 }
342 t.maxStreamID = streamID
343 s.sendQuotaPool = newQuotaPool(int(t.streamSendQuota))
344 s.localSendQuota = newQuotaPool(defaultLocalSendQuota)
345 t.activeStreams[streamID] = s
346 if len(t.activeStreams) == 1 {
347 t.idle = time.Time{}
348 }
349 t.mu.Unlock()
350 s.requestRead = func(n int) {
351 t.adjustWindow(s, uint32(n))
352 }
353 s.ctx = traceCtx(s.ctx, s.method)
354 if t.stats != nil {
355 s.ctx = t.stats.TagRPC(s.ctx, &stats.RPCTagInfo{FullMethodName: s.method})
356 inHeader := &stats.InHeader{
357 FullMethod: s.method,
358 RemoteAddr: t.remoteAddr,
359 LocalAddr: t.localAddr,
360 Compression: s.recvCompress,
361 WireLength: int(frame.Header().Length),
362 }
363 t.stats.HandleRPC(s.ctx, inHeader)
364 }
365 s.trReader = &transportReader{
366 reader: &recvBufferReader{
367 ctx: s.ctx,
368 recv: s.buf,
369 },
370 windowHandler: func(n int) {
371 t.updateWindow(s, uint32(n))
372 },
373 }
374 handle(s)
375 return
376 }
377
378 // HandleStreams receives incoming streams using the given handler. This is
379 // typically run in a separate goroutine.
380 // traceCtx attaches trace to ctx and returns the new context.
381 func (t *http2Server) HandleStreams(handle func(*Stream), traceCtx func(context.Context, string) context.Context) {
382 for {
383 frame, err := t.framer.fr.ReadFrame()
384 atomic.StoreUint32(&t.activity, 1)
385 if err != nil {
386 if se, ok := err.(http2.StreamError); ok {
387 t.mu.Lock()
388 s := t.activeStreams[se.StreamID]
389 t.mu.Unlock()
390 if s != nil {
391 t.closeStream(s)
392 }
393 t.controlBuf.put(&resetStream{se.StreamID, se.Code})
394 continue
395 }
396 if err == io.EOF || err == io.ErrUnexpectedEOF {
397 t.Close()
398 return
399 }
400 warningf("transport: http2Server.HandleStreams failed to read frame: %v", err)
401 t.Close()
402 return
403 }
404 switch frame := frame.(type) {
405 case *http2.MetaHeadersFrame:
406 if t.operateHeaders(frame, handle, traceCtx) {
407 t.Close()
408 break
409 }
410 case *http2.DataFrame:
411 t.handleData(frame)
412 case *http2.RSTStreamFrame:
413 t.handleRSTStream(frame)
414 case *http2.SettingsFrame:
415 t.handleSettings(frame)
416 case *http2.PingFrame:
417 t.handlePing(frame)
418 case *http2.WindowUpdateFrame:
419 t.handleWindowUpdate(frame)
420 case *http2.GoAwayFrame:
421 // TODO: Handle GoAway from the client appropriately.
422 default:
423 errorf("transport: http2Server.HandleStreams found unhandled frame type %v.", frame)
424 }
425 }
426 }
427
428 func (t *http2Server) getStream(f http2.Frame) (*Stream, bool) {
429 t.mu.Lock()
430 defer t.mu.Unlock()
431 if t.activeStreams == nil {
432 // The transport is closing.
433 return nil, false
434 }
435 s, ok := t.activeStreams[f.Header().StreamID]
436 if !ok {
437 // The stream is already done.
438 return nil, false
439 }
440 return s, true
441 }
442
443 // adjustWindow sends out extra window update over the initial window size
444 // of stream if the application is requesting data larger in size than
445 // the window.
446 func (t *http2Server) adjustWindow(s *Stream, n uint32) {
447 s.mu.Lock()
448 defer s.mu.Unlock()
449 if s.state == streamDone {
450 return
451 }
452 if w := s.fc.maybeAdjust(n); w > 0 {
453 if cw := t.fc.resetPendingUpdate(); cw > 0 {
454 t.controlBuf.put(&windowUpdate{0, cw})
455 }
456 t.controlBuf.put(&windowUpdate{s.id, w})
457 }
458 }
459
460 // updateWindow adjusts the inbound quota for the stream and the transport.
461 // Window updates will deliver to the controller for sending when
462 // the cumulative quota exceeds the corresponding threshold.
463 func (t *http2Server) updateWindow(s *Stream, n uint32) {
464 s.mu.Lock()
465 defer s.mu.Unlock()
466 if s.state == streamDone {
467 return
468 }
469 if w := s.fc.onRead(n); w > 0 {
470 if cw := t.fc.resetPendingUpdate(); cw > 0 {
471 t.controlBuf.put(&windowUpdate{0, cw})
472 }
473 t.controlBuf.put(&windowUpdate{s.id, w})
474 }
475 }
476
477 // updateFlowControl updates the incoming flow control windows
478 // for the transport and the stream based on the current bdp
479 // estimation.
480 func (t *http2Server) updateFlowControl(n uint32) {
481 t.mu.Lock()
482 for _, s := range t.activeStreams {
483 s.fc.newLimit(n)
484 }
485 t.initialWindowSize = int32(n)
486 t.mu.Unlock()
487 t.controlBuf.put(&windowUpdate{0, t.fc.newLimit(n)})
488 t.controlBuf.put(&settings{
489 ack: false,
490 ss: []http2.Setting{
491 {
492 ID: http2.SettingInitialWindowSize,
493 Val: uint32(n),
494 },
495 },
496 })
497
498 }
499
500 func (t *http2Server) handleData(f *http2.DataFrame) {
501 size := f.Header().Length
502 var sendBDPPing bool
503 if t.bdpEst != nil {
504 sendBDPPing = t.bdpEst.add(uint32(size))
505 }
506 // Decouple connection's flow control from application's read.
507 // An update on connection's flow control should not depend on
508 // whether user application has read the data or not. Such a
509 // restriction is already imposed on the stream's flow control,
510 // and therefore the sender will be blocked anyways.
511 // Decoupling the connection flow control will prevent other
512 // active(fast) streams from starving in presence of slow or
513 // inactive streams.
514 //
515 // Furthermore, if a bdpPing is being sent out we can piggyback
516 // connection's window update for the bytes we just received.
517 if sendBDPPing {
518 if size != 0 { // Could be an empty frame.
519 t.controlBuf.put(&windowUpdate{0, uint32(size)})
520 }
521 t.controlBuf.put(bdpPing)
522 } else {
523 if err := t.fc.onData(uint32(size)); err != nil {
524 errorf("transport: http2Server %v", err)
525 t.Close()
526 return
527 }
528 if w := t.fc.onRead(uint32(size)); w > 0 {
529 t.controlBuf.put(&windowUpdate{0, w})
530 }
531 }
532 // Select the right stream to dispatch.
533 s, ok := t.getStream(f)
534 if !ok {
535 return
536 }
537 if size > 0 {
538 s.mu.Lock()
539 if s.state == streamDone {
540 s.mu.Unlock()
541 return
542 }
543 if err := s.fc.onData(uint32(size)); err != nil {
544 s.mu.Unlock()
545 t.closeStream(s)
546 t.controlBuf.put(&resetStream{s.id, http2.ErrCodeFlowControl})
547 return
548 }
549 if f.Header().Flags.Has(http2.FlagDataPadded) {
550 if w := s.fc.onRead(uint32(size) - uint32(len(f.Data()))); w > 0 {
551 t.controlBuf.put(&windowUpdate{s.id, w})
552 }
553 }
554 s.mu.Unlock()
555 // TODO(bradfitz, zhaoq): A copy is required here because there is no
556 // guarantee f.Data() is consumed before the arrival of next frame.
557 // Can this copy be eliminated?
558 if len(f.Data()) > 0 {
559 data := make([]byte, len(f.Data()))
560 copy(data, f.Data())
561 s.write(recvMsg{data: data})
562 }
563 }
564 if f.Header().Flags.Has(http2.FlagDataEndStream) {
565 // Received the end of stream from the client.
566 s.mu.Lock()
567 if s.state != streamDone {
568 s.state = streamReadDone
569 }
570 s.mu.Unlock()
571 s.write(recvMsg{err: io.EOF})
572 }
573 }
574
575 func (t *http2Server) handleRSTStream(f *http2.RSTStreamFrame) {
576 s, ok := t.getStream(f)
577 if !ok {
578 return
579 }
580 t.closeStream(s)
581 }
582
583 func (t *http2Server) handleSettings(f *http2.SettingsFrame) {
584 if f.IsAck() {
585 return
586 }
587 var ss []http2.Setting
588 f.ForeachSetting(func(s http2.Setting) error {
589 ss = append(ss, s)
590 return nil
591 })
592 t.controlBuf.put(&settings{ack: true, ss: ss})
593 }
594
595 func (t *http2Server) applySettings(ss []http2.Setting) {
596 for _, s := range ss {
597 if s.ID == http2.SettingInitialWindowSize {
598 t.mu.Lock()
599 for _, stream := range t.activeStreams {
600 stream.sendQuotaPool.addAndUpdate(int(s.Val) - int(t.streamSendQuota))
601 }
602 t.streamSendQuota = s.Val
603 t.mu.Unlock()
604 }
605
606 }
607 }
608
609 const (
610 maxPingStrikes = 2
611 defaultPingTimeout = 2 * time.Hour
612 )
613
614 func (t *http2Server) handlePing(f *http2.PingFrame) {
615 if f.IsAck() {
616 if f.Data == goAwayPing.data && t.drainChan != nil {
617 close(t.drainChan)
618 return
619 }
620 // Maybe it's a BDP ping.
621 if t.bdpEst != nil {
622 t.bdpEst.calculate(f.Data)
623 }
624 return
625 }
626 pingAck := &ping{ack: true}
627 copy(pingAck.data[:], f.Data[:])
628 t.controlBuf.put(pingAck)
629
630 now := time.Now()
631 defer func() {
632 t.lastPingAt = now
633 }()
634 // A reset ping strikes means that we don't need to check for policy
635 // violation for this ping and the pingStrikes counter should be set
636 // to 0.
637 if atomic.CompareAndSwapUint32(&t.resetPingStrikes, 1, 0) {
638 t.pingStrikes = 0
639 return
640 }
641 t.mu.Lock()
642 ns := len(t.activeStreams)
643 t.mu.Unlock()
644 if ns < 1 && !t.kep.PermitWithoutStream {
645 // Keepalive shouldn't be active thus, this new ping should
646 // have come after at least defaultPingTimeout.
647 if t.lastPingAt.Add(defaultPingTimeout).After(now) {
648 t.pingStrikes++
649 }
650 } else {
651 // Check if keepalive policy is respected.
652 if t.lastPingAt.Add(t.kep.MinTime).After(now) {
653 t.pingStrikes++
654 }
655 }
656
657 if t.pingStrikes > maxPingStrikes {
658 // Send goaway and close the connection.
659 errorf("transport: Got to too many pings from the client, closing the connection.")
660 t.controlBuf.put(&goAway{code: http2.ErrCodeEnhanceYourCalm, debugData: []byte("too_many_pings"), closeConn: true})
661 }
662 }
663
664 func (t *http2Server) handleWindowUpdate(f *http2.WindowUpdateFrame) {
665 id := f.Header().StreamID
666 incr := f.Increment
667 if id == 0 {
668 t.sendQuotaPool.add(int(incr))
669 return
670 }
671 if s, ok := t.getStream(f); ok {
672 s.sendQuotaPool.add(int(incr))
673 }
674 }
675
676 // WriteHeader sends the header metedata md back to the client.
677 func (t *http2Server) WriteHeader(s *Stream, md metadata.MD) error {
678 select {
679 case <-s.ctx.Done():
680 return ContextErr(s.ctx.Err())
681 case <-t.ctx.Done():
682 return ErrConnClosing
683 default:
684 }
685
686 s.mu.Lock()
687 if s.headerOk || s.state == streamDone {
688 s.mu.Unlock()
689 return ErrIllegalHeaderWrite
690 }
691 s.headerOk = true
692 if md.Len() > 0 {
693 if s.header.Len() > 0 {
694 s.header = metadata.Join(s.header, md)
695 } else {
696 s.header = md
697 }
698 }
699 md = s.header
700 s.mu.Unlock()
701 // TODO(mmukhi): Benchmark if the perfomance gets better if count the metadata and other header fields
702 // first and create a slice of that exact size.
703 headerFields := make([]hpack.HeaderField, 0, 2) // at least :status, content-type will be there if none else.
704 headerFields = append(headerFields, hpack.HeaderField{Name: ":status", Value: "200"})
705 headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: "application/grpc"})
706 if s.sendCompress != "" {
707 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: s.sendCompress})
708 }
709 for k, vv := range md {
710 if isReservedHeader(k) {
711 // Clients don't tolerate reading restricted headers after some non restricted ones were sent.
712 continue
713 }
714 for _, v := range vv {
715 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
716 }
717 }
718 t.controlBuf.put(&headerFrame{
719 streamID: s.id,
720 hf: headerFields,
721 endStream: false,
722 })
723 if t.stats != nil {
724 outHeader := &stats.OutHeader{
725 //WireLength: // TODO(mmukhi): Revisit this later, if needed.
726 }
727 t.stats.HandleRPC(s.Context(), outHeader)
728 }
729 return nil
730 }
731
732 // WriteStatus sends stream status to the client and terminates the stream.
733 // There is no further I/O operations being able to perform on this stream.
734 // TODO(zhaoq): Now it indicates the end of entire stream. Revisit if early
735 // OK is adopted.
736 func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error {
737 select {
738 case <-t.ctx.Done():
739 return ErrConnClosing
740 default:
741 }
742
743 var headersSent, hasHeader bool
744 s.mu.Lock()
745 if s.state == streamDone {
746 s.mu.Unlock()
747 return nil
748 }
749 if s.headerOk {
750 headersSent = true
751 }
752 if s.header.Len() > 0 {
753 hasHeader = true
754 }
755 s.mu.Unlock()
756
757 if !headersSent && hasHeader {
758 t.WriteHeader(s, nil)
759 headersSent = true
760 }
761
762 // TODO(mmukhi): Benchmark if the perfomance gets better if count the metadata and other header fields
763 // first and create a slice of that exact size.
764 headerFields := make([]hpack.HeaderField, 0, 2) // grpc-status and grpc-message will be there if none else.
765 if !headersSent {
766 headerFields = append(headerFields, hpack.HeaderField{Name: ":status", Value: "200"})
767 headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: "application/grpc"})
768 }
769 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-status", Value: strconv.Itoa(int(st.Code()))})
770 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-message", Value: encodeGrpcMessage(st.Message())})
771
772 if p := st.Proto(); p != nil && len(p.Details) > 0 {
773 stBytes, err := proto.Marshal(p)
774 if err != nil {
775 // TODO: return error instead, when callers are able to handle it.
776 panic(err)
777 }
778
779 headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-status-details-bin", Value: encodeBinHeader(stBytes)})
780 }
781
782 // Attach the trailer metadata.
783 for k, vv := range s.trailer {
784 // Clients don't tolerate reading restricted headers after some non restricted ones were sent.
785 if isReservedHeader(k) {
786 continue
787 }
788 for _, v := range vv {
789 headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
790 }
791 }
792 t.controlBuf.put(&headerFrame{
793 streamID: s.id,
794 hf: headerFields,
795 endStream: true,
796 })
797 if t.stats != nil {
798 t.stats.HandleRPC(s.Context(), &stats.OutTrailer{})
799 }
800 t.closeStream(s)
801 return nil
802 }
803
804 // Write converts the data into HTTP2 data frame and sends it out. Non-nil error
805 // is returns if it fails (e.g., framing error, transport error).
806 func (t *http2Server) Write(s *Stream, hdr []byte, data []byte, opts *Options) (err error) {
807 select {
808 case <-s.ctx.Done():
809 return ContextErr(s.ctx.Err())
810 case <-t.ctx.Done():
811 return ErrConnClosing
812 default:
813 }
814
815 var writeHeaderFrame bool
816 s.mu.Lock()
817 if s.state == streamDone {
818 s.mu.Unlock()
819 return streamErrorf(codes.Unknown, "the stream has been done")
820 }
821 if !s.headerOk {
822 writeHeaderFrame = true
823 }
824 s.mu.Unlock()
825 if writeHeaderFrame {
826 t.WriteHeader(s, nil)
827 }
828 // Add data to header frame so that we can equally distribute data across frames.
829 emptyLen := http2MaxFrameLen - len(hdr)
830 if emptyLen > len(data) {
831 emptyLen = len(data)
832 }
833 hdr = append(hdr, data[:emptyLen]...)
834 data = data[emptyLen:]
835 for _, r := range [][]byte{hdr, data} {
836 for len(r) > 0 {
837 size := http2MaxFrameLen
838 // Wait until the stream has some quota to send the data.
839 quotaChan, quotaVer := s.sendQuotaPool.acquireWithVersion()
840 sq, err := wait(s.ctx, t.ctx, nil, nil, quotaChan)
841 if err != nil {
842 return err
843 }
844 // Wait until the transport has some quota to send the data.
845 tq, err := wait(s.ctx, t.ctx, nil, nil, t.sendQuotaPool.acquire())
846 if err != nil {
847 return err
848 }
849 if sq < size {
850 size = sq
851 }
852 if tq < size {
853 size = tq
854 }
855 if size > len(r) {
856 size = len(r)
857 }
858 p := r[:size]
859 ps := len(p)
860 if ps < tq {
861 // Overbooked transport quota. Return it back.
862 t.sendQuotaPool.add(tq - ps)
863 }
864 // Acquire local send quota to be able to write to the controlBuf.
865 ltq, err := wait(s.ctx, t.ctx, nil, nil, s.localSendQuota.acquire())
866 if err != nil {
867 if _, ok := err.(ConnectionError); !ok {
868 t.sendQuotaPool.add(ps)
869 }
870 return err
871 }
872 s.localSendQuota.add(ltq - ps) // It's ok we make this negative.
873 // Reset ping strikes when sending data since this might cause
874 // the peer to send ping.
875 atomic.StoreUint32(&t.resetPingStrikes, 1)
876 success := func() {
877 t.controlBuf.put(&dataFrame{streamID: s.id, endStream: false, d: p, f: func() {
878 s.localSendQuota.add(ps)
879 }})
880 if ps < sq {
881 // Overbooked stream quota. Return it back.
882 s.sendQuotaPool.lockedAdd(sq - ps)
883 }
884 r = r[ps:]
885 }
886 failure := func() {
887 s.sendQuotaPool.lockedAdd(sq)
888 }
889 if !s.sendQuotaPool.compareAndExecute(quotaVer, success, failure) {
890 t.sendQuotaPool.add(ps)
891 s.localSendQuota.add(ps)
892 }
893 }
894 }
895 return nil
896 }
897
898 // keepalive running in a separate goroutine does the following:
899 // 1. Gracefully closes an idle connection after a duration of keepalive.MaxConnectionIdle.
900 // 2. Gracefully closes any connection after a duration of keepalive.MaxConnectionAge.
901 // 3. Forcibly closes a connection after an additive period of keepalive.MaxConnectionAgeGrace over keepalive.MaxConnectionAge.
902 // 4. Makes sure a connection is alive by sending pings with a frequency of keepalive.Time and closes a non-responsive connection
903 // after an additional duration of keepalive.Timeout.
904 func (t *http2Server) keepalive() {
905 p := &ping{}
906 var pingSent bool
907 maxIdle := time.NewTimer(t.kp.MaxConnectionIdle)
908 maxAge := time.NewTimer(t.kp.MaxConnectionAge)
909 keepalive := time.NewTimer(t.kp.Time)
910 // NOTE: All exit paths of this function should reset their
911 // respective timers. A failure to do so will cause the
912 // following clean-up to deadlock and eventually leak.
913 defer func() {
914 if !maxIdle.Stop() {
915 <-maxIdle.C
916 }
917 if !maxAge.Stop() {
918 <-maxAge.C
919 }
920 if !keepalive.Stop() {
921 <-keepalive.C
922 }
923 }()
924 for {
925 select {
926 case <-maxIdle.C:
927 t.mu.Lock()
928 idle := t.idle
929 if idle.IsZero() { // The connection is non-idle.
930 t.mu.Unlock()
931 maxIdle.Reset(t.kp.MaxConnectionIdle)
932 continue
933 }
934 val := t.kp.MaxConnectionIdle - time.Since(idle)
935 t.mu.Unlock()
936 if val <= 0 {
937 // The connection has been idle for a duration of keepalive.MaxConnectionIdle or more.
938 // Gracefully close the connection.
939 t.drain(http2.ErrCodeNo, []byte{})
940 // Reseting the timer so that the clean-up doesn't deadlock.
941 maxIdle.Reset(infinity)
942 return
943 }
944 maxIdle.Reset(val)
945 case <-maxAge.C:
946 t.drain(http2.ErrCodeNo, []byte{})
947 maxAge.Reset(t.kp.MaxConnectionAgeGrace)
948 select {
949 case <-maxAge.C:
950 // Close the connection after grace period.
951 t.Close()
952 // Reseting the timer so that the clean-up doesn't deadlock.
953 maxAge.Reset(infinity)
954 case <-t.ctx.Done():
955 }
956 return
957 case <-keepalive.C:
958 if atomic.CompareAndSwapUint32(&t.activity, 1, 0) {
959 pingSent = false
960 keepalive.Reset(t.kp.Time)
961 continue
962 }
963 if pingSent {
964 t.Close()
965 // Reseting the timer so that the clean-up doesn't deadlock.
966 keepalive.Reset(infinity)
967 return
968 }
969 pingSent = true
970 t.controlBuf.put(p)
971 keepalive.Reset(t.kp.Timeout)
972 case <-t.ctx.Done():
973 return
974 }
975 }
976 }
977
978 var goAwayPing = &ping{data: [8]byte{1, 6, 1, 8, 0, 3, 3, 9}}
979
980 // TODO(mmukhi): A lot of this code(and code in other places in the tranpsort layer)
981 // is duplicated between the client and the server.
982 // The transport layer needs to be refactored to take care of this.
983 func (t *http2Server) itemHandler(i item) error {
984 switch i := i.(type) {
985 case *dataFrame:
986 if err := t.framer.fr.WriteData(i.streamID, i.endStream, i.d); err != nil {
987 return err
988 }
989 i.f()
990 return nil
991 case *headerFrame:
992 t.hBuf.Reset()
993 for _, f := range i.hf {
994 t.hEnc.WriteField(f)
995 }
996 first := true
997 endHeaders := false
998 for !endHeaders {
999 size := t.hBuf.Len()
1000 if size > http2MaxFrameLen {
1001 size = http2MaxFrameLen
1002 } else {
1003 endHeaders = true
1004 }
1005 var err error
1006 if first {
1007 first = false
1008 err = t.framer.fr.WriteHeaders(http2.HeadersFrameParam{
1009 StreamID: i.streamID,
1010 BlockFragment: t.hBuf.Next(size),
1011 EndStream: i.endStream,
1012 EndHeaders: endHeaders,
1013 })
1014 } else {
1015 err = t.framer.fr.WriteContinuation(
1016 i.streamID,
1017 endHeaders,
1018 t.hBuf.Next(size),
1019 )
1020 }
1021 if err != nil {
1022 return err
1023 }
1024 }
1025 atomic.StoreUint32(&t.resetPingStrikes, 1)
1026 return nil
1027 case *windowUpdate:
1028 return t.framer.fr.WriteWindowUpdate(i.streamID, i.increment)
1029 case *settings:
1030 if i.ack {
1031 t.applySettings(i.ss)
1032 return t.framer.fr.WriteSettingsAck()
1033 }
1034 return t.framer.fr.WriteSettings(i.ss...)
1035 case *resetStream:
1036 return t.framer.fr.WriteRSTStream(i.streamID, i.code)
1037 case *goAway:
1038 t.mu.Lock()
1039 if t.state == closing {
1040 t.mu.Unlock()
1041 // The transport is closing.
1042 return fmt.Errorf("transport: Connection closing")
1043 }
1044 sid := t.maxStreamID
1045 if !i.headsUp {
1046 // Stop accepting more streams now.
1047 t.state = draining
1048 t.mu.Unlock()
1049 if err := t.framer.fr.WriteGoAway(sid, i.code, i.debugData); err != nil {
1050 return err
1051 }
1052 if i.closeConn {
1053 // Abruptly close the connection following the GoAway (via
1054 // loopywriter). But flush out what's inside the buffer first.
1055 t.framer.writer.Flush()
1056 return fmt.Errorf("transport: Connection closing")
1057 }
1058 return nil
1059 }
1060 t.mu.Unlock()
1061 // For a graceful close, send out a GoAway with stream ID of MaxUInt32,
1062 // Follow that with a ping and wait for the ack to come back or a timer
1063 // to expire. During this time accept new streams since they might have
1064 // originated before the GoAway reaches the client.
1065 // After getting the ack or timer expiration send out another GoAway this
1066 // time with an ID of the max stream server intends to process.
1067 if err := t.framer.fr.WriteGoAway(math.MaxUint32, http2.ErrCodeNo, []byte{}); err != nil {
1068 return err
1069 }
1070 if err := t.framer.fr.WritePing(false, goAwayPing.data); err != nil {
1071 return err
1072 }
1073 go func() {
1074 timer := time.NewTimer(time.Minute)
1075 defer timer.Stop()
1076 select {
1077 case <-t.drainChan:
1078 case <-timer.C:
1079 case <-t.ctx.Done():
1080 return
1081 }
1082 t.controlBuf.put(&goAway{code: i.code, debugData: i.debugData})
1083 }()
1084 return nil
1085 case *flushIO:
1086 return t.framer.writer.Flush()
1087 case *ping:
1088 if !i.ack {
1089 t.bdpEst.timesnap(i.data)
1090 }
1091 return t.framer.fr.WritePing(i.ack, i.data)
1092 default:
1093 err := status.Errorf(codes.Internal, "transport: http2Server.controller got unexpected item type %t", i)
1094 errorf("%v", err)
1095 return err
1096 }
1097 }
1098
1099 // Close starts shutting down the http2Server transport.
1100 // TODO(zhaoq): Now the destruction is not blocked on any pending streams. This
1101 // could cause some resource issue. Revisit this later.
1102 func (t *http2Server) Close() error {
1103 t.mu.Lock()
1104 if t.state == closing {
1105 t.mu.Unlock()
1106 return errors.New("transport: Close() was already called")
1107 }
1108 t.state = closing
1109 streams := t.activeStreams
1110 t.activeStreams = nil
1111 t.mu.Unlock()
1112 t.cancel()
1113 err := t.conn.Close()
1114 // Cancel all active streams.
1115 for _, s := range streams {
1116 s.cancel()
1117 }
1118 if t.stats != nil {
1119 connEnd := &stats.ConnEnd{}
1120 t.stats.HandleConn(t.ctx, connEnd)
1121 }
1122 return err
1123 }
1124
1125 // closeStream clears the footprint of a stream when the stream is not needed
1126 // any more.
1127 func (t *http2Server) closeStream(s *Stream) {
1128 t.mu.Lock()
1129 delete(t.activeStreams, s.id)
1130 if len(t.activeStreams) == 0 {
1131 t.idle = time.Now()
1132 }
1133 if t.state == draining && len(t.activeStreams) == 0 {
1134 defer t.Close()
1135 }
1136 t.mu.Unlock()
1137 // In case stream sending and receiving are invoked in separate
1138 // goroutines (e.g., bi-directional streaming), cancel needs to be
1139 // called to interrupt the potential blocking on other goroutines.
1140 s.cancel()
1141 s.mu.Lock()
1142 if s.state == streamDone {
1143 s.mu.Unlock()
1144 return
1145 }
1146 s.state = streamDone
1147 s.mu.Unlock()
1148 }
1149
1150 func (t *http2Server) RemoteAddr() net.Addr {
1151 return t.remoteAddr
1152 }
1153
1154 func (t *http2Server) Drain() {
1155 t.drain(http2.ErrCodeNo, []byte{})
1156 }
1157
1158 func (t *http2Server) drain(code http2.ErrCode, debugData []byte) {
1159 t.mu.Lock()
1160 defer t.mu.Unlock()
1161 if t.drainChan != nil {
1162 return
1163 }
1164 t.drainChan = make(chan struct{})
1165 t.controlBuf.put(&goAway{code: code, debugData: debugData, headsUp: true})
1166 }
1167
1168 var rgen = rand.New(rand.NewSource(time.Now().UnixNano()))
1169
1170 func getJitter(v time.Duration) time.Duration {
1171 if v == infinity {
1172 return 0
1173 }
1174 // Generate a jitter between +/- 10% of the value.
1175 r := int64(v / 10)
1176 j := rgen.Int63n(2*r) - r
1177 return time.Duration(j)
1178 }