muxmetrics.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. package h2mux
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/cloudflare/cloudflared/logger"
  6. "github.com/golang-collections/collections/queue"
  7. "github.com/prometheus/client_golang/prometheus"
  8. )
  9. // data points used to compute average receive window and send window size
  10. const (
  11. // data points used to compute average receive window and send window size
  12. dataPoints = 100
  13. // updateFreq is set to 1 sec so we can get inbound & outbound byes/sec
  14. updateFreq = time.Second
  15. )
  16. type muxMetricsUpdater interface {
  17. // metrics returns the latest metrics
  18. metrics() *MuxerMetrics
  19. // run is a blocking call to start the event loop
  20. run(logger logger.Service) error
  21. // updateRTTChan is called by muxReader to report new RTT measurements
  22. updateRTT(rtt *roundTripMeasurement)
  23. //updateReceiveWindowChan is called by muxReader and muxWriter when receiveWindow size is updated
  24. updateReceiveWindow(receiveWindow uint32)
  25. //updateSendWindowChan is called by muxReader and muxWriter when sendWindow size is updated
  26. updateSendWindow(sendWindow uint32)
  27. // updateInBoundBytesChan is called periodicallyby muxReader to report bytesRead
  28. updateInBoundBytes(inBoundBytes uint64)
  29. // updateOutBoundBytesChan is called periodically by muxWriter to report bytesWrote
  30. updateOutBoundBytes(outBoundBytes uint64)
  31. }
  32. type muxMetricsUpdaterImpl struct {
  33. // rttData keeps record of rtt, rttMin, rttMax and last measured time
  34. rttData *rttData
  35. // receiveWindowData keeps record of receive window measurement
  36. receiveWindowData *flowControlData
  37. // sendWindowData keeps record of send window measurement
  38. sendWindowData *flowControlData
  39. // inBoundRate is incoming bytes/sec
  40. inBoundRate *rate
  41. // outBoundRate is outgoing bytes/sec
  42. outBoundRate *rate
  43. // updateRTTChan is the channel to receive new RTT measurement
  44. updateRTTChan chan *roundTripMeasurement
  45. //updateReceiveWindowChan is the channel to receive updated receiveWindow size
  46. updateReceiveWindowChan chan uint32
  47. //updateSendWindowChan is the channel to receive updated sendWindow size
  48. updateSendWindowChan chan uint32
  49. // updateInBoundBytesChan us the channel to receive bytesRead
  50. updateInBoundBytesChan chan uint64
  51. // updateOutBoundBytesChan us the channel to receive bytesWrote
  52. updateOutBoundBytesChan chan uint64
  53. // shutdownC is to signal the muxerMetricsUpdater to shutdown
  54. abortChan <-chan struct{}
  55. compBytesBefore, compBytesAfter *AtomicCounter
  56. }
  57. type MuxerMetrics struct {
  58. RTT, RTTMin, RTTMax time.Duration
  59. ReceiveWindowAve, SendWindowAve float64
  60. ReceiveWindowMin, ReceiveWindowMax, SendWindowMin, SendWindowMax uint32
  61. InBoundRateCurr, InBoundRateMin, InBoundRateMax uint64
  62. OutBoundRateCurr, OutBoundRateMin, OutBoundRateMax uint64
  63. CompBytesBefore, CompBytesAfter *AtomicCounter
  64. }
  65. func (m *MuxerMetrics) CompRateAve() float64 {
  66. if m.CompBytesBefore.Value() == 0 {
  67. return 1.
  68. }
  69. return float64(m.CompBytesAfter.Value()) / float64(m.CompBytesBefore.Value())
  70. }
  71. type roundTripMeasurement struct {
  72. receiveTime, sendTime time.Time
  73. }
  74. type rttData struct {
  75. rtt, rttMin, rttMax time.Duration
  76. lastMeasurementTime time.Time
  77. lock sync.RWMutex
  78. }
  79. type flowControlData struct {
  80. sum uint64
  81. min, max uint32
  82. queue *queue.Queue
  83. lock sync.RWMutex
  84. }
  85. type rate struct {
  86. curr uint64
  87. min, max uint64
  88. lock sync.RWMutex
  89. }
  90. func newMuxMetricsUpdater(
  91. abortChan <-chan struct{},
  92. compBytesBefore, compBytesAfter *AtomicCounter,
  93. ) muxMetricsUpdater {
  94. updateRTTChan := make(chan *roundTripMeasurement, 1)
  95. updateReceiveWindowChan := make(chan uint32, 1)
  96. updateSendWindowChan := make(chan uint32, 1)
  97. updateInBoundBytesChan := make(chan uint64)
  98. updateOutBoundBytesChan := make(chan uint64)
  99. return &muxMetricsUpdaterImpl{
  100. rttData: newRTTData(),
  101. receiveWindowData: newFlowControlData(),
  102. sendWindowData: newFlowControlData(),
  103. inBoundRate: newRate(),
  104. outBoundRate: newRate(),
  105. updateRTTChan: updateRTTChan,
  106. updateReceiveWindowChan: updateReceiveWindowChan,
  107. updateSendWindowChan: updateSendWindowChan,
  108. updateInBoundBytesChan: updateInBoundBytesChan,
  109. updateOutBoundBytesChan: updateOutBoundBytesChan,
  110. abortChan: abortChan,
  111. compBytesBefore: compBytesBefore,
  112. compBytesAfter: compBytesAfter,
  113. }
  114. }
  115. func (updater *muxMetricsUpdaterImpl) metrics() *MuxerMetrics {
  116. m := &MuxerMetrics{}
  117. m.RTT, m.RTTMin, m.RTTMax = updater.rttData.metrics()
  118. m.ReceiveWindowAve, m.ReceiveWindowMin, m.ReceiveWindowMax = updater.receiveWindowData.metrics()
  119. m.SendWindowAve, m.SendWindowMin, m.SendWindowMax = updater.sendWindowData.metrics()
  120. m.InBoundRateCurr, m.InBoundRateMin, m.InBoundRateMax = updater.inBoundRate.get()
  121. m.OutBoundRateCurr, m.OutBoundRateMin, m.OutBoundRateMax = updater.outBoundRate.get()
  122. m.CompBytesBefore, m.CompBytesAfter = updater.compBytesBefore, updater.compBytesAfter
  123. return m
  124. }
  125. func (updater *muxMetricsUpdaterImpl) run(logger logger.Service) error {
  126. defer logger.Debug("mux - metrics: event loop finished")
  127. for {
  128. select {
  129. case <-updater.abortChan:
  130. logger.Infof("mux - metrics: Stopping mux metrics updater")
  131. return nil
  132. case roundTripMeasurement := <-updater.updateRTTChan:
  133. go updater.rttData.update(roundTripMeasurement)
  134. logger.Debug("mux - metrics: Update rtt")
  135. case receiveWindow := <-updater.updateReceiveWindowChan:
  136. go updater.receiveWindowData.update(receiveWindow)
  137. logger.Debug("mux - metrics: Update receive window")
  138. case sendWindow := <-updater.updateSendWindowChan:
  139. go updater.sendWindowData.update(sendWindow)
  140. logger.Debug("mux - metrics: Update send window")
  141. case inBoundBytes := <-updater.updateInBoundBytesChan:
  142. // inBoundBytes is bytes/sec because the update interval is 1 sec
  143. go updater.inBoundRate.update(inBoundBytes)
  144. logger.Debugf("mux - metrics: Inbound bytes %d", inBoundBytes)
  145. case outBoundBytes := <-updater.updateOutBoundBytesChan:
  146. // outBoundBytes is bytes/sec because the update interval is 1 sec
  147. go updater.outBoundRate.update(outBoundBytes)
  148. logger.Debugf("mux - metrics: Outbound bytes %d", outBoundBytes)
  149. }
  150. }
  151. }
  152. func (updater *muxMetricsUpdaterImpl) updateRTT(rtt *roundTripMeasurement) {
  153. select {
  154. case updater.updateRTTChan <- rtt:
  155. case <-updater.abortChan:
  156. }
  157. }
  158. func (updater *muxMetricsUpdaterImpl) updateReceiveWindow(receiveWindow uint32) {
  159. select {
  160. case updater.updateReceiveWindowChan <- receiveWindow:
  161. case <-updater.abortChan:
  162. }
  163. }
  164. func (updater *muxMetricsUpdaterImpl) updateSendWindow(sendWindow uint32) {
  165. select {
  166. case updater.updateSendWindowChan <- sendWindow:
  167. case <-updater.abortChan:
  168. }
  169. }
  170. func (updater *muxMetricsUpdaterImpl) updateInBoundBytes(inBoundBytes uint64) {
  171. select {
  172. case updater.updateInBoundBytesChan <- inBoundBytes:
  173. case <-updater.abortChan:
  174. }
  175. }
  176. func (updater *muxMetricsUpdaterImpl) updateOutBoundBytes(outBoundBytes uint64) {
  177. select {
  178. case updater.updateOutBoundBytesChan <- outBoundBytes:
  179. case <-updater.abortChan:
  180. }
  181. }
  182. func newRTTData() *rttData {
  183. return &rttData{}
  184. }
  185. func (r *rttData) update(measurement *roundTripMeasurement) {
  186. r.lock.Lock()
  187. defer r.lock.Unlock()
  188. // discard pings before lastMeasurementTime
  189. if r.lastMeasurementTime.After(measurement.sendTime) {
  190. return
  191. }
  192. r.lastMeasurementTime = measurement.sendTime
  193. r.rtt = measurement.receiveTime.Sub(measurement.sendTime)
  194. if r.rttMax < r.rtt {
  195. r.rttMax = r.rtt
  196. }
  197. if r.rttMin == 0 || r.rttMin > r.rtt {
  198. r.rttMin = r.rtt
  199. }
  200. }
  201. func (r *rttData) metrics() (rtt, rttMin, rttMax time.Duration) {
  202. r.lock.RLock()
  203. defer r.lock.RUnlock()
  204. return r.rtt, r.rttMin, r.rttMax
  205. }
  206. func newFlowControlData() *flowControlData {
  207. return &flowControlData{queue: queue.New()}
  208. }
  209. func (f *flowControlData) update(measurement uint32) {
  210. f.lock.Lock()
  211. defer f.lock.Unlock()
  212. var firstItem uint32
  213. // store new data into queue, remove oldest data if queue is full
  214. f.queue.Enqueue(measurement)
  215. if f.queue.Len() > dataPoints {
  216. // data type should always be uint32
  217. firstItem = f.queue.Dequeue().(uint32)
  218. }
  219. // if (measurement - firstItem) < 0, uint64(measurement - firstItem)
  220. // will overflow and become a large positive number
  221. f.sum += uint64(measurement)
  222. f.sum -= uint64(firstItem)
  223. if measurement > f.max {
  224. f.max = measurement
  225. }
  226. if f.min == 0 || measurement < f.min {
  227. f.min = measurement
  228. }
  229. }
  230. // caller of ave() should acquire lock first
  231. func (f *flowControlData) ave() float64 {
  232. if f.queue.Len() == 0 {
  233. return 0
  234. }
  235. return float64(f.sum) / float64(f.queue.Len())
  236. }
  237. func (f *flowControlData) metrics() (ave float64, min, max uint32) {
  238. f.lock.RLock()
  239. defer f.lock.RUnlock()
  240. return f.ave(), f.min, f.max
  241. }
  242. func newRate() *rate {
  243. return &rate{}
  244. }
  245. func (r *rate) update(measurement uint64) {
  246. r.lock.Lock()
  247. defer r.lock.Unlock()
  248. r.curr = measurement
  249. // if measurement is 0, then there is no incoming/outgoing connection, don't update min/max
  250. if r.curr == 0 {
  251. return
  252. }
  253. if measurement > r.max {
  254. r.max = measurement
  255. }
  256. if r.min == 0 || measurement < r.min {
  257. r.min = measurement
  258. }
  259. }
  260. func (r *rate) get() (curr, min, max uint64) {
  261. r.lock.RLock()
  262. defer r.lock.RUnlock()
  263. return r.curr, r.min, r.max
  264. }
  265. func NewActiveStreamsMetrics(namespace, subsystem string) prometheus.Gauge {
  266. activeStreams := prometheus.NewGauge(prometheus.GaugeOpts{
  267. Namespace: namespace,
  268. Subsystem: subsystem,
  269. Name: "active_streams",
  270. Help: "Number of active streams created by all muxers.",
  271. })
  272. prometheus.MustRegister(activeStreams)
  273. return activeStreams
  274. }