metrics.go 8.9 KB

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