metrics.go 9.5 KB

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