metrics.go 8.4 KB

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