metrics.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2020 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "context"
  19. "net/http"
  20. "runtime/debug"
  21. "time"
  22. "github.com/prometheus/client_golang/prometheus"
  23. "github.com/prometheus/client_golang/prometheus/promauto"
  24. "github.com/prometheus/client_golang/prometheus/promhttp"
  25. log "maunium.net/go/maulogger/v2"
  26. "maunium.net/go/mautrix/event"
  27. "maunium.net/go/mautrix/id"
  28. "maunium.net/go/mautrix-whatsapp/database"
  29. )
  30. type MetricsHandler struct {
  31. db *database.Database
  32. server *http.Server
  33. log log.Logger
  34. running bool
  35. ctx context.Context
  36. stopRecorder func()
  37. messageHandling *prometheus.HistogramVec
  38. countCollection prometheus.Histogram
  39. disconnections *prometheus.CounterVec
  40. puppetCount prometheus.Gauge
  41. userCount prometheus.Gauge
  42. messageCount prometheus.Gauge
  43. portalCount *prometheus.GaugeVec
  44. encryptedGroupCount prometheus.Gauge
  45. encryptedPrivateCount prometheus.Gauge
  46. unencryptedGroupCount prometheus.Gauge
  47. unencryptedPrivateCount prometheus.Gauge
  48. }
  49. func NewMetricsHandler(address string, log log.Logger, db *database.Database) *MetricsHandler {
  50. portalCount := promauto.NewGaugeVec(prometheus.GaugeOpts{
  51. Name: "whatsapp_portals_total",
  52. Help: "Number of portal rooms on Matrix",
  53. }, []string{"type", "encrypted"})
  54. return &MetricsHandler{
  55. db: db,
  56. server: &http.Server{Addr: address, Handler: promhttp.Handler()},
  57. log: log,
  58. running: false,
  59. messageHandling: promauto.NewHistogramVec(prometheus.HistogramOpts{
  60. Name: "matrix_event",
  61. Help: "Time spent processing Matrix events",
  62. }, []string{"event_type"}),
  63. countCollection: promauto.NewHistogram(prometheus.HistogramOpts{
  64. Name: "whatsapp_count_collection",
  65. Help: "Time spent collecting the whatsapp_*_total metrics",
  66. }),
  67. disconnections: promauto.NewCounterVec(prometheus.CounterOpts{
  68. Name: "whatsapp_disconnections",
  69. Help: "Number of times a Matrix user has been disconnected from WhatsApp",
  70. }, []string{"user_id"}),
  71. puppetCount: promauto.NewGauge(prometheus.GaugeOpts{
  72. Name: "whatsapp_puppets_total",
  73. Help: "Number of WhatsApp users bridged into Matrix",
  74. }),
  75. userCount: promauto.NewGauge(prometheus.GaugeOpts{
  76. Name: "whatsapp_users_total",
  77. Help: "Number of Matrix users using the bridge",
  78. }),
  79. messageCount: promauto.NewGauge(prometheus.GaugeOpts{
  80. Name: "whatsapp_messages_total",
  81. Help: "Number of messages bridged",
  82. }),
  83. portalCount: portalCount,
  84. encryptedGroupCount: portalCount.With(prometheus.Labels{"type": "group", "encrypted": "true"}),
  85. encryptedPrivateCount: portalCount.With(prometheus.Labels{"type": "private", "encrypted": "true"}),
  86. unencryptedGroupCount: portalCount.With(prometheus.Labels{"type": "group", "encrypted": "false"}),
  87. unencryptedPrivateCount: portalCount.With(prometheus.Labels{"type": "private", "encrypted": "false"}),
  88. }
  89. }
  90. func noop() {}
  91. func (mh *MetricsHandler) TrackEvent(eventType event.Type) func() {
  92. if !mh.running {
  93. return noop
  94. }
  95. start := time.Now()
  96. return func() {
  97. duration := time.Now().Sub(start)
  98. mh.messageHandling.
  99. With(prometheus.Labels{"event_type": eventType.Type}).
  100. Observe(duration.Seconds())
  101. }
  102. }
  103. func (mh *MetricsHandler) TrackDisconnection(userID id.UserID) {
  104. if !mh.running {
  105. return
  106. }
  107. mh.disconnections.With(prometheus.Labels{"user_id": string(userID)}).Inc()
  108. }
  109. func (mh *MetricsHandler) updateStats() {
  110. start := time.Now()
  111. var puppetCount int
  112. err := mh.db.QueryRowContext(mh.ctx, "SELECT COUNT(*) FROM puppet").Scan(&puppetCount)
  113. if err != nil {
  114. mh.log.Warnln("Failed to scan number of puppets:", err)
  115. } else {
  116. mh.puppetCount.Set(float64(puppetCount))
  117. }
  118. var userCount int
  119. err = mh.db.QueryRowContext(mh.ctx, `SELECT COUNT(*) FROM "user"`).Scan(&userCount)
  120. if err != nil {
  121. mh.log.Warnln("Failed to scan number of users:", err)
  122. } else {
  123. mh.userCount.Set(float64(userCount))
  124. }
  125. var messageCount int
  126. err = mh.db.QueryRowContext(mh.ctx, "SELECT COUNT(*) FROM message").Scan(&messageCount)
  127. if err != nil {
  128. mh.log.Warnln("Failed to scan number of messages:", err)
  129. } else {
  130. mh.messageCount.Set(float64(messageCount))
  131. }
  132. var encryptedGroupCount, encryptedPrivateCount, unencryptedGroupCount, unencryptedPrivateCount int
  133. err = mh.db.QueryRowContext(mh.ctx, `
  134. SELECT
  135. COUNT(CASE WHEN jid LIKE '%@g.us' AND encrypted THEN 1 END) AS encrypted_group_portals,
  136. COUNT(CASE WHEN jid LIKE '%@s.whatsapp.net' AND encrypted THEN 1 END) AS encrypted_private_portals,
  137. COUNT(CASE WHEN jid LIKE '%@g.us' AND NOT encrypted THEN 1 END) AS unencrypted_group_portals,
  138. COUNT(CASE WHEN jid LIKE '%@s.whatsapp.net' AND NOT encrypted THEN 1 END) AS unencrypted_private_portals
  139. FROM portal WHERE mxid<>''
  140. `).Scan(&encryptedGroupCount, &encryptedPrivateCount, &unencryptedGroupCount, &unencryptedPrivateCount)
  141. if err != nil {
  142. mh.log.Warnln("Failed to scan number of portals:", err)
  143. } else {
  144. mh.encryptedGroupCount.Set(float64(encryptedGroupCount))
  145. mh.encryptedPrivateCount.Set(float64(encryptedPrivateCount))
  146. mh.unencryptedGroupCount.Set(float64(unencryptedGroupCount))
  147. mh.unencryptedPrivateCount.Set(float64(encryptedPrivateCount))
  148. }
  149. mh.countCollection.Observe(time.Now().Sub(start).Seconds())
  150. }
  151. func (mh *MetricsHandler) startUpdatingStats() {
  152. defer func() {
  153. err := recover()
  154. if err != nil {
  155. mh.log.Fatalfln("Panic in metric updater: %v\n%s", err, string(debug.Stack()))
  156. }
  157. }()
  158. ticker := time.Tick(10 * time.Second)
  159. for {
  160. mh.updateStats()
  161. select {
  162. case <-mh.ctx.Done():
  163. return
  164. case <-ticker:
  165. }
  166. }
  167. }
  168. func (mh *MetricsHandler) Start() {
  169. mh.running = true
  170. mh.ctx, mh.stopRecorder = context.WithCancel(context.Background())
  171. go mh.startUpdatingStats()
  172. err := mh.server.ListenAndServe()
  173. mh.running = false
  174. if err != nil && err != http.ErrServerClosed {
  175. mh.log.Fatalln("Error in metrics listener:", err)
  176. }
  177. }
  178. func (mh *MetricsHandler) Stop() {
  179. if !mh.running {
  180. return
  181. }
  182. mh.stopRecorder()
  183. err := mh.server.Close()
  184. if err != nil {
  185. mh.log.Errorln("Error closing metrics listener:", err)
  186. }
  187. }