activestreammap.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package h2mux
  2. import (
  3. "sync"
  4. "github.com/prometheus/client_golang/prometheus"
  5. "golang.org/x/net/http2"
  6. )
  7. var (
  8. ActiveStreams = prometheus.NewGauge(prometheus.GaugeOpts{
  9. Namespace: "cloudflared",
  10. Subsystem: "tunnel",
  11. Name: "active_streams",
  12. Help: "Number of active streams created by all muxers.",
  13. })
  14. )
  15. func init() {
  16. prometheus.MustRegister(ActiveStreams)
  17. }
  18. // activeStreamMap is used to moderate access to active streams between the read and write
  19. // threads, and deny access to new peer streams while shutting down.
  20. type activeStreamMap struct {
  21. sync.RWMutex
  22. // streams tracks open streams.
  23. streams map[uint32]*MuxedStream
  24. // nextStreamID is the next ID to use on our side of the connection.
  25. // This is odd for clients, even for servers.
  26. nextStreamID uint32
  27. // maxPeerStreamID is the ID of the most recent stream opened by the peer.
  28. maxPeerStreamID uint32
  29. // activeStreams is a gauge shared by all muxers of this process to expose the total number of active streams
  30. activeStreams prometheus.Gauge
  31. // ignoreNewStreams is true when the connection is being shut down. New streams
  32. // cannot be registered.
  33. ignoreNewStreams bool
  34. // streamsEmpty is a chan that will be closed when no more streams are open.
  35. streamsEmptyChan chan struct{}
  36. closeOnce sync.Once
  37. }
  38. func newActiveStreamMap(useClientStreamNumbers bool, activeStreams prometheus.Gauge) *activeStreamMap {
  39. m := &activeStreamMap{
  40. streams: make(map[uint32]*MuxedStream),
  41. streamsEmptyChan: make(chan struct{}),
  42. nextStreamID: 1,
  43. activeStreams: activeStreams,
  44. }
  45. // Client initiated stream uses odd stream ID, server initiated stream uses even stream ID
  46. if !useClientStreamNumbers {
  47. m.nextStreamID = 2
  48. }
  49. return m
  50. }
  51. // This function should be called while `m` is locked.
  52. func (m *activeStreamMap) notifyStreamsEmpty() {
  53. m.closeOnce.Do(func() {
  54. close(m.streamsEmptyChan)
  55. })
  56. }
  57. // Len returns the number of active streams.
  58. func (m *activeStreamMap) Len() int {
  59. m.RLock()
  60. defer m.RUnlock()
  61. return len(m.streams)
  62. }
  63. func (m *activeStreamMap) Get(streamID uint32) (*MuxedStream, bool) {
  64. m.RLock()
  65. defer m.RUnlock()
  66. stream, ok := m.streams[streamID]
  67. return stream, ok
  68. }
  69. // Set returns true if the stream was assigned successfully. If a stream
  70. // already existed with that ID or we are shutting down, return false.
  71. func (m *activeStreamMap) Set(newStream *MuxedStream) bool {
  72. m.Lock()
  73. defer m.Unlock()
  74. if _, ok := m.streams[newStream.streamID]; ok {
  75. return false
  76. }
  77. if m.ignoreNewStreams {
  78. return false
  79. }
  80. m.streams[newStream.streamID] = newStream
  81. m.activeStreams.Inc()
  82. return true
  83. }
  84. // Delete stops tracking the stream. It should be called only after it is closed and resetted.
  85. func (m *activeStreamMap) Delete(streamID uint32) {
  86. m.Lock()
  87. defer m.Unlock()
  88. if _, ok := m.streams[streamID]; ok {
  89. delete(m.streams, streamID)
  90. m.activeStreams.Dec()
  91. }
  92. // shutting down, and now the map is empty
  93. if m.ignoreNewStreams && len(m.streams) == 0 {
  94. m.notifyStreamsEmpty()
  95. }
  96. }
  97. // Shutdown blocks new streams from being created.
  98. // It returns `done`, a channel that is closed once the last stream has closed
  99. // and `progress`, whether a shutdown was already in progress
  100. func (m *activeStreamMap) Shutdown() (done <-chan struct{}, alreadyInProgress bool) {
  101. m.Lock()
  102. defer m.Unlock()
  103. if m.ignoreNewStreams {
  104. // already shutting down
  105. return m.streamsEmptyChan, true
  106. }
  107. m.ignoreNewStreams = true
  108. if len(m.streams) == 0 {
  109. // there are no streams to wait for
  110. m.notifyStreamsEmpty()
  111. }
  112. return m.streamsEmptyChan, false
  113. }
  114. // AcquireLocalID acquires a new stream ID for a stream you're opening.
  115. func (m *activeStreamMap) AcquireLocalID() uint32 {
  116. m.Lock()
  117. defer m.Unlock()
  118. x := m.nextStreamID
  119. m.nextStreamID += 2
  120. return x
  121. }
  122. // ObservePeerID observes the ID of a stream opened by the peer. It returns true if we should accept
  123. // the new stream, or false to reject it. The ErrCode gives the reason why.
  124. func (m *activeStreamMap) AcquirePeerID(streamID uint32) (bool, http2.ErrCode) {
  125. m.Lock()
  126. defer m.Unlock()
  127. switch {
  128. case m.ignoreNewStreams:
  129. return false, http2.ErrCodeStreamClosed
  130. case streamID > m.maxPeerStreamID:
  131. m.maxPeerStreamID = streamID
  132. return true, http2.ErrCodeNo
  133. default:
  134. return false, http2.ErrCodeStreamClosed
  135. }
  136. }
  137. // IsPeerStreamID is true if the stream ID belongs to the peer.
  138. func (m *activeStreamMap) IsPeerStreamID(streamID uint32) bool {
  139. m.RLock()
  140. defer m.RUnlock()
  141. return (streamID % 2) != (m.nextStreamID % 2)
  142. }
  143. // IsLocalStreamID is true if it is a stream we have opened, even if it is now closed.
  144. func (m *activeStreamMap) IsLocalStreamID(streamID uint32) bool {
  145. m.RLock()
  146. defer m.RUnlock()
  147. return (streamID%2) == (m.nextStreamID%2) && streamID < m.nextStreamID
  148. }
  149. // LastPeerStreamID returns the most recently opened peer stream ID.
  150. func (m *activeStreamMap) LastPeerStreamID() uint32 {
  151. m.RLock()
  152. defer m.RUnlock()
  153. return m.maxPeerStreamID
  154. }
  155. // LastLocalStreamID returns the most recently opened local stream ID.
  156. func (m *activeStreamMap) LastLocalStreamID() uint32 {
  157. m.RLock()
  158. defer m.RUnlock()
  159. if m.nextStreamID > 1 {
  160. return m.nextStreamID - 2
  161. }
  162. return 0
  163. }
  164. // Abort closes every active stream and prevents new ones being created. This should be used to
  165. // return errors in pending read/writes when the underlying connection goes away.
  166. func (m *activeStreamMap) Abort() {
  167. m.Lock()
  168. defer m.Unlock()
  169. for _, stream := range m.streams {
  170. stream.Close()
  171. }
  172. m.ignoreNewStreams = true
  173. m.notifyStreamsEmpty()
  174. }