metrics.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. "github.com/Rhymen/go-whatsapp"
  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[whatsapp.JID]bool
  53. loggedIn prometheus.Gauge
  54. loggedInState map[whatsapp.JID]bool
  55. syncLocked prometheus.Gauge
  56. syncLockedState map[whatsapp.JID]bool
  57. bufferLength *prometheus.GaugeVec
  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: "whatsapp_message_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: "whatsapp_message",
  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[whatsapp.JID]bool),
  112. connected: promauto.NewGauge(prometheus.GaugeOpts{
  113. Name: "bridge_connected",
  114. Help: "Bridge users connected to WhatsApp",
  115. }),
  116. connectedState: make(map[whatsapp.JID]bool),
  117. syncLocked: promauto.NewGauge(prometheus.GaugeOpts{
  118. Name: "bridge_sync_locked",
  119. Help: "Bridge users locked in post-login sync",
  120. }),
  121. syncLockedState: make(map[whatsapp.JID]bool),
  122. bufferLength: promauto.NewGaugeVec(prometheus.GaugeOpts{
  123. Name: "bridge_buffer_size",
  124. Help: "Number of messages in buffer",
  125. }, []string{"user_id"}),
  126. }
  127. }
  128. func noop() {}
  129. func (mh *MetricsHandler) TrackMatrixEvent(eventType event.Type) func() {
  130. if !mh.running {
  131. return noop
  132. }
  133. start := time.Now()
  134. return func() {
  135. duration := time.Now().Sub(start)
  136. mh.matrixEventHandling.
  137. With(prometheus.Labels{"event_type": eventType.Type}).
  138. Observe(duration.Seconds())
  139. }
  140. }
  141. func (mh *MetricsHandler) TrackWhatsAppMessage(timestamp uint64, messageType string) func() {
  142. if !mh.running {
  143. return noop
  144. }
  145. start := time.Now()
  146. return func() {
  147. duration := time.Now().Sub(start)
  148. mh.whatsappMessageHandling.
  149. With(prometheus.Labels{"message_type": messageType}).
  150. Observe(duration.Seconds())
  151. mh.whatsappMessageAge.Observe(time.Now().Sub(time.Unix(int64(timestamp), 0)).Seconds())
  152. }
  153. }
  154. func (mh *MetricsHandler) TrackDisconnection(userID id.UserID) {
  155. if !mh.running {
  156. return
  157. }
  158. mh.disconnections.With(prometheus.Labels{"user_id": string(userID)}).Inc()
  159. }
  160. func (mh *MetricsHandler) TrackLoginState(jid whatsapp.JID, loggedIn bool) {
  161. if !mh.running {
  162. return
  163. }
  164. currentVal, ok := mh.loggedInState[jid]
  165. if !ok || currentVal != loggedIn {
  166. mh.loggedInState[jid] = loggedIn
  167. if loggedIn {
  168. mh.loggedIn.Inc()
  169. } else {
  170. mh.loggedIn.Dec()
  171. }
  172. }
  173. }
  174. func (mh *MetricsHandler) TrackConnectionState(jid whatsapp.JID, connected bool) {
  175. if !mh.running {
  176. return
  177. }
  178. currentVal, ok := mh.connectedState[jid]
  179. if !ok || currentVal != connected {
  180. mh.connectedState[jid] = connected
  181. if connected {
  182. mh.connected.Inc()
  183. } else {
  184. mh.connected.Dec()
  185. }
  186. }
  187. }
  188. func (mh *MetricsHandler) TrackSyncLock(jid whatsapp.JID, locked bool) {
  189. if !mh.running {
  190. return
  191. }
  192. currentVal, ok := mh.syncLockedState[jid]
  193. if !ok || currentVal != locked {
  194. mh.syncLockedState[jid] = locked
  195. if locked {
  196. mh.syncLocked.Inc()
  197. } else {
  198. mh.syncLocked.Dec()
  199. }
  200. }
  201. }
  202. func (mh *MetricsHandler) TrackBufferLength(id id.UserID, length int) {
  203. if !mh.running {
  204. return
  205. }
  206. mh.bufferLength.With(prometheus.Labels{"user_id": string(id)}).Set(float64(length))
  207. }
  208. func (mh *MetricsHandler) updateStats() {
  209. start := time.Now()
  210. var puppetCount int
  211. err := mh.db.QueryRowContext(mh.ctx, "SELECT COUNT(*) FROM puppet").Scan(&puppetCount)
  212. if err != nil {
  213. mh.log.Warnln("Failed to scan number of puppets:", err)
  214. } else {
  215. mh.puppetCount.Set(float64(puppetCount))
  216. }
  217. var userCount int
  218. err = mh.db.QueryRowContext(mh.ctx, `SELECT COUNT(*) FROM "user"`).Scan(&userCount)
  219. if err != nil {
  220. mh.log.Warnln("Failed to scan number of users:", err)
  221. } else {
  222. mh.userCount.Set(float64(userCount))
  223. }
  224. var messageCount int
  225. err = mh.db.QueryRowContext(mh.ctx, "SELECT COUNT(*) FROM message").Scan(&messageCount)
  226. if err != nil {
  227. mh.log.Warnln("Failed to scan number of messages:", err)
  228. } else {
  229. mh.messageCount.Set(float64(messageCount))
  230. }
  231. var encryptedGroupCount, encryptedPrivateCount, unencryptedGroupCount, unencryptedPrivateCount int
  232. err = mh.db.QueryRowContext(mh.ctx, `
  233. SELECT
  234. COUNT(CASE WHEN jid LIKE '%@g.us' AND encrypted THEN 1 END) AS encrypted_group_portals,
  235. COUNT(CASE WHEN jid LIKE '%@s.whatsapp.net' AND encrypted THEN 1 END) AS encrypted_private_portals,
  236. COUNT(CASE WHEN jid LIKE '%@g.us' AND NOT encrypted THEN 1 END) AS unencrypted_group_portals,
  237. COUNT(CASE WHEN jid LIKE '%@s.whatsapp.net' AND NOT encrypted THEN 1 END) AS unencrypted_private_portals
  238. FROM portal WHERE mxid<>''
  239. `).Scan(&encryptedGroupCount, &encryptedPrivateCount, &unencryptedGroupCount, &unencryptedPrivateCount)
  240. if err != nil {
  241. mh.log.Warnln("Failed to scan number of portals:", err)
  242. } else {
  243. mh.encryptedGroupCount.Set(float64(encryptedGroupCount))
  244. mh.encryptedPrivateCount.Set(float64(encryptedPrivateCount))
  245. mh.unencryptedGroupCount.Set(float64(unencryptedGroupCount))
  246. mh.unencryptedPrivateCount.Set(float64(encryptedPrivateCount))
  247. }
  248. mh.countCollection.Observe(time.Now().Sub(start).Seconds())
  249. }
  250. func (mh *MetricsHandler) startUpdatingStats() {
  251. defer func() {
  252. err := recover()
  253. if err != nil {
  254. mh.log.Fatalfln("Panic in metric updater: %v\n%s", err, string(debug.Stack()))
  255. }
  256. }()
  257. ticker := time.Tick(10 * time.Second)
  258. for {
  259. mh.updateStats()
  260. select {
  261. case <-mh.ctx.Done():
  262. return
  263. case <-ticker:
  264. }
  265. }
  266. }
  267. func (mh *MetricsHandler) Start() {
  268. mh.running = true
  269. mh.ctx, mh.stopRecorder = context.WithCancel(context.Background())
  270. go mh.startUpdatingStats()
  271. err := mh.server.ListenAndServe()
  272. mh.running = false
  273. if err != nil && err != http.ErrServerClosed {
  274. mh.log.Fatalln("Error in metrics listener:", err)
  275. }
  276. }
  277. func (mh *MetricsHandler) Stop() {
  278. if !mh.running {
  279. return
  280. }
  281. mh.stopRecorder()
  282. err := mh.server.Close()
  283. if err != nil {
  284. mh.log.Errorln("Error closing metrics listener:", err)
  285. }
  286. }