metrics.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 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. "go.mau.fi/whatsmeow/types"
  27. "maunium.net/go/mautrix/event"
  28. "maunium.net/go/mautrix/id"
  29. "maunium.net/go/mautrix-whatsapp/database"
  30. )
  31. type MetricsHandler struct {
  32. db *database.Database
  33. server *http.Server
  34. log log.Logger
  35. running bool
  36. ctx context.Context
  37. stopRecorder func()
  38. matrixEventHandling *prometheus.HistogramVec
  39. whatsappMessageAge prometheus.Histogram
  40. whatsappMessageHandling *prometheus.HistogramVec
  41. countCollection prometheus.Histogram
  42. disconnections *prometheus.CounterVec
  43. puppetCount prometheus.Gauge
  44. userCount prometheus.Gauge
  45. messageCount prometheus.Gauge
  46. portalCount *prometheus.GaugeVec
  47. encryptedGroupCount prometheus.Gauge
  48. encryptedPrivateCount prometheus.Gauge
  49. unencryptedGroupCount prometheus.Gauge
  50. unencryptedPrivateCount prometheus.Gauge
  51. connected prometheus.Gauge
  52. connectedState map[string]bool
  53. loggedIn prometheus.Gauge
  54. loggedInState map[string]bool
  55. }
  56. func NewMetricsHandler(address string, log log.Logger, db *database.Database) *MetricsHandler {
  57. portalCount := promauto.NewGaugeVec(prometheus.GaugeOpts{
  58. Name: "whatsapp_portals_total",
  59. Help: "Number of portal rooms on Matrix",
  60. }, []string{"type", "encrypted"})
  61. return &MetricsHandler{
  62. db: db,
  63. server: &http.Server{Addr: address, Handler: promhttp.Handler()},
  64. log: log,
  65. running: false,
  66. matrixEventHandling: promauto.NewHistogramVec(prometheus.HistogramOpts{
  67. Name: "matrix_event",
  68. Help: "Time spent processing Matrix events",
  69. }, []string{"event_type"}),
  70. whatsappMessageAge: promauto.NewHistogram(prometheus.HistogramOpts{
  71. Name: "remote_event_age",
  72. Help: "Age of messages received from WhatsApp",
  73. Buckets: []float64{1, 2, 3, 5, 7.5, 10, 20, 30, 60},
  74. }),
  75. whatsappMessageHandling: promauto.NewHistogramVec(prometheus.HistogramOpts{
  76. Name: "remote_event",
  77. Help: "Time spent processing WhatsApp messages",
  78. }, []string{"message_type"}),
  79. countCollection: promauto.NewHistogram(prometheus.HistogramOpts{
  80. Name: "whatsapp_count_collection",
  81. Help: "Time spent collecting the whatsapp_*_total metrics",
  82. }),
  83. disconnections: promauto.NewCounterVec(prometheus.CounterOpts{
  84. Name: "whatsapp_disconnections",
  85. Help: "Number of times a Matrix user has been disconnected from WhatsApp",
  86. }, []string{"user_id"}),
  87. puppetCount: promauto.NewGauge(prometheus.GaugeOpts{
  88. Name: "whatsapp_puppets_total",
  89. Help: "Number of WhatsApp users bridged into Matrix",
  90. }),
  91. userCount: promauto.NewGauge(prometheus.GaugeOpts{
  92. Name: "whatsapp_users_total",
  93. Help: "Number of Matrix users using the bridge",
  94. }),
  95. messageCount: promauto.NewGauge(prometheus.GaugeOpts{
  96. Name: "whatsapp_messages_total",
  97. Help: "Number of messages bridged",
  98. }),
  99. portalCount: portalCount,
  100. encryptedGroupCount: portalCount.With(prometheus.Labels{"type": "group", "encrypted": "true"}),
  101. encryptedPrivateCount: portalCount.With(prometheus.Labels{"type": "private", "encrypted": "true"}),
  102. unencryptedGroupCount: portalCount.With(prometheus.Labels{"type": "group", "encrypted": "false"}),
  103. unencryptedPrivateCount: portalCount.With(prometheus.Labels{"type": "private", "encrypted": "false"}),
  104. loggedIn: promauto.NewGauge(prometheus.GaugeOpts{
  105. Name: "bridge_logged_in",
  106. Help: "Users logged into the bridge",
  107. }),
  108. loggedInState: make(map[string]bool),
  109. connected: promauto.NewGauge(prometheus.GaugeOpts{
  110. Name: "bridge_connected",
  111. Help: "Bridge users connected to WhatsApp",
  112. }),
  113. connectedState: make(map[string]bool),
  114. }
  115. }
  116. func noop() {}
  117. func (mh *MetricsHandler) TrackMatrixEvent(eventType event.Type) func() {
  118. if !mh.running {
  119. return noop
  120. }
  121. start := time.Now()
  122. return func() {
  123. duration := time.Now().Sub(start)
  124. mh.matrixEventHandling.
  125. With(prometheus.Labels{"event_type": eventType.Type}).
  126. Observe(duration.Seconds())
  127. }
  128. }
  129. func (mh *MetricsHandler) TrackWhatsAppMessage(timestamp time.Time, messageType string) func() {
  130. if !mh.running {
  131. return noop
  132. }
  133. start := time.Now()
  134. return func() {
  135. duration := time.Now().Sub(start)
  136. mh.whatsappMessageHandling.
  137. With(prometheus.Labels{"message_type": messageType}).
  138. Observe(duration.Seconds())
  139. mh.whatsappMessageAge.Observe(time.Now().Sub(timestamp).Seconds())
  140. }
  141. }
  142. func (mh *MetricsHandler) TrackDisconnection(userID id.UserID) {
  143. if !mh.running {
  144. return
  145. }
  146. mh.disconnections.With(prometheus.Labels{"user_id": string(userID)}).Inc()
  147. }
  148. func (mh *MetricsHandler) TrackLoginState(jid types.JID, loggedIn bool) {
  149. if !mh.running {
  150. return
  151. }
  152. currentVal, ok := mh.loggedInState[jid.User]
  153. if !ok || currentVal != loggedIn {
  154. mh.loggedInState[jid.User] = loggedIn
  155. if loggedIn {
  156. mh.loggedIn.Inc()
  157. } else {
  158. mh.loggedIn.Dec()
  159. }
  160. }
  161. }
  162. func (mh *MetricsHandler) TrackConnectionState(jid types.JID, connected bool) {
  163. if !mh.running {
  164. return
  165. }
  166. currentVal, ok := mh.connectedState[jid.User]
  167. if !ok || currentVal != connected {
  168. mh.connectedState[jid.User] = connected
  169. if connected {
  170. mh.connected.Inc()
  171. } else {
  172. mh.connected.Dec()
  173. }
  174. }
  175. }
  176. func (mh *MetricsHandler) updateStats() {
  177. start := time.Now()
  178. var puppetCount int
  179. err := mh.db.QueryRowContext(mh.ctx, "SELECT COUNT(*) FROM puppet").Scan(&puppetCount)
  180. if err != nil {
  181. mh.log.Warnln("Failed to scan number of puppets:", err)
  182. } else {
  183. mh.puppetCount.Set(float64(puppetCount))
  184. }
  185. var userCount int
  186. err = mh.db.QueryRowContext(mh.ctx, `SELECT COUNT(*) FROM "user"`).Scan(&userCount)
  187. if err != nil {
  188. mh.log.Warnln("Failed to scan number of users:", err)
  189. } else {
  190. mh.userCount.Set(float64(userCount))
  191. }
  192. var messageCount int
  193. err = mh.db.QueryRowContext(mh.ctx, "SELECT COUNT(*) FROM message").Scan(&messageCount)
  194. if err != nil {
  195. mh.log.Warnln("Failed to scan number of messages:", err)
  196. } else {
  197. mh.messageCount.Set(float64(messageCount))
  198. }
  199. var encryptedGroupCount, encryptedPrivateCount, unencryptedGroupCount, unencryptedPrivateCount int
  200. err = mh.db.QueryRowContext(mh.ctx, `
  201. SELECT
  202. COUNT(CASE WHEN jid LIKE '%@g.us' AND encrypted THEN 1 END) AS encrypted_group_portals,
  203. COUNT(CASE WHEN jid LIKE '%@s.whatsapp.net' AND encrypted THEN 1 END) AS encrypted_private_portals,
  204. COUNT(CASE WHEN jid LIKE '%@g.us' AND NOT encrypted THEN 1 END) AS unencrypted_group_portals,
  205. COUNT(CASE WHEN jid LIKE '%@s.whatsapp.net' AND NOT encrypted THEN 1 END) AS unencrypted_private_portals
  206. FROM portal WHERE mxid<>''
  207. `).Scan(&encryptedGroupCount, &encryptedPrivateCount, &unencryptedGroupCount, &unencryptedPrivateCount)
  208. if err != nil {
  209. mh.log.Warnln("Failed to scan number of portals:", err)
  210. } else {
  211. mh.encryptedGroupCount.Set(float64(encryptedGroupCount))
  212. mh.encryptedPrivateCount.Set(float64(encryptedPrivateCount))
  213. mh.unencryptedGroupCount.Set(float64(unencryptedGroupCount))
  214. mh.unencryptedPrivateCount.Set(float64(encryptedPrivateCount))
  215. }
  216. mh.countCollection.Observe(time.Now().Sub(start).Seconds())
  217. }
  218. func (mh *MetricsHandler) startUpdatingStats() {
  219. defer func() {
  220. err := recover()
  221. if err != nil {
  222. mh.log.Fatalfln("Panic in metric updater: %v\n%s", err, string(debug.Stack()))
  223. }
  224. }()
  225. ticker := time.Tick(10 * time.Second)
  226. for {
  227. mh.updateStats()
  228. select {
  229. case <-mh.ctx.Done():
  230. return
  231. case <-ticker:
  232. }
  233. }
  234. }
  235. func (mh *MetricsHandler) Start() {
  236. mh.running = true
  237. mh.ctx, mh.stopRecorder = context.WithCancel(context.Background())
  238. go mh.startUpdatingStats()
  239. err := mh.server.ListenAndServe()
  240. mh.running = false
  241. if err != nil && err != http.ErrServerClosed {
  242. mh.log.Fatalln("Error in metrics listener:", err)
  243. }
  244. }
  245. func (mh *MetricsHandler) Stop() {
  246. if !mh.running {
  247. return
  248. }
  249. mh.stopRecorder()
  250. err := mh.server.Close()
  251. if err != nil {
  252. mh.log.Errorln("Error closing metrics listener:", err)
  253. }
  254. }