metrics.go 8.7 KB

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