metrics.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import calendar
  15. import logging
  16. import time
  17. from typing import TYPE_CHECKING, Dict, List, Tuple, cast
  18. from synapse.metrics import GaugeBucketCollector
  19. from synapse.metrics.background_process_metrics import wrap_as_background_process
  20. from synapse.storage._base import SQLBaseStore
  21. from synapse.storage.database import (
  22. DatabasePool,
  23. LoggingDatabaseConnection,
  24. LoggingTransaction,
  25. )
  26. from synapse.storage.databases.main.event_push_actions import (
  27. EventPushActionsWorkerStore,
  28. )
  29. if TYPE_CHECKING:
  30. from synapse.server import HomeServer
  31. logger = logging.getLogger(__name__)
  32. # Collect metrics on the number of forward extremities that exist.
  33. _extremities_collecter = GaugeBucketCollector(
  34. "synapse_forward_extremities",
  35. "Number of rooms on the server with the given number of forward extremities"
  36. " or fewer",
  37. buckets=[1, 2, 3, 5, 7, 10, 15, 20, 50, 100, 200, 500],
  38. )
  39. # we also expose metrics on the "number of excess extremity events", which is
  40. # (E-1)*N, where E is the number of extremities and N is the number of state
  41. # events in the room. This is an approximation to the number of state events
  42. # we could remove from state resolution by reducing the graph to a single
  43. # forward extremity.
  44. _excess_state_events_collecter = GaugeBucketCollector(
  45. "synapse_excess_extremity_events",
  46. "Number of rooms on the server with the given number of excess extremity "
  47. "events, or fewer",
  48. buckets=[0] + [1 << n for n in range(12)],
  49. )
  50. class ServerMetricsStore(EventPushActionsWorkerStore, SQLBaseStore):
  51. """Functions to pull various metrics from the DB, for e.g. phone home
  52. stats and prometheus metrics.
  53. """
  54. def __init__(
  55. self,
  56. database: DatabasePool,
  57. db_conn: LoggingDatabaseConnection,
  58. hs: "HomeServer",
  59. ):
  60. super().__init__(database, db_conn, hs)
  61. # Read the extrems every 60 minutes
  62. if hs.config.worker.run_background_tasks:
  63. self._clock.looping_call(self._read_forward_extremities, 60 * 60 * 1000)
  64. # Used in _generate_user_daily_visits to keep track of progress
  65. self._last_user_visit_update = self._get_start_of_day()
  66. @wrap_as_background_process("read_forward_extremities")
  67. async def _read_forward_extremities(self) -> None:
  68. def fetch(txn: LoggingTransaction) -> List[Tuple[int, int]]:
  69. txn.execute(
  70. """
  71. SELECT t1.c, t2.c
  72. FROM (
  73. SELECT room_id, COUNT(*) c FROM event_forward_extremities
  74. GROUP BY room_id
  75. ) t1 LEFT JOIN (
  76. SELECT room_id, COUNT(*) c FROM current_state_events
  77. GROUP BY room_id
  78. ) t2 ON t1.room_id = t2.room_id
  79. """
  80. )
  81. return cast(List[Tuple[int, int]], txn.fetchall())
  82. res = await self.db_pool.runInteraction("read_forward_extremities", fetch)
  83. _extremities_collecter.update_data(x[0] for x in res)
  84. _excess_state_events_collecter.update_data(
  85. (x[0] - 1) * x[1] for x in res if x[1]
  86. )
  87. async def count_daily_e2ee_messages(self) -> int:
  88. """
  89. Returns an estimate of the number of messages sent in the last day.
  90. If it has been significantly less or more than one day since the last
  91. call to this function, it will return None.
  92. """
  93. def _count_messages(txn: LoggingTransaction) -> int:
  94. sql = """
  95. SELECT COUNT(*) FROM events
  96. WHERE type = 'm.room.encrypted'
  97. AND stream_ordering > ?
  98. """
  99. txn.execute(sql, (self.stream_ordering_day_ago,))
  100. (count,) = cast(Tuple[int], txn.fetchone())
  101. return count
  102. return await self.db_pool.runInteraction("count_e2ee_messages", _count_messages)
  103. async def count_daily_sent_e2ee_messages(self) -> int:
  104. def _count_messages(txn: LoggingTransaction) -> int:
  105. # This is good enough as if you have silly characters in your own
  106. # hostname then that's your own fault.
  107. like_clause = "%:" + self.hs.hostname
  108. sql = """
  109. SELECT COUNT(*) FROM events
  110. WHERE type = 'm.room.encrypted'
  111. AND sender LIKE ?
  112. AND stream_ordering > ?
  113. """
  114. txn.execute(sql, (like_clause, self.stream_ordering_day_ago))
  115. (count,) = cast(Tuple[int], txn.fetchone())
  116. return count
  117. return await self.db_pool.runInteraction(
  118. "count_daily_sent_e2ee_messages", _count_messages
  119. )
  120. async def count_daily_active_e2ee_rooms(self) -> int:
  121. def _count(txn: LoggingTransaction) -> int:
  122. sql = """
  123. SELECT COUNT(DISTINCT room_id) FROM events
  124. WHERE type = 'm.room.encrypted'
  125. AND stream_ordering > ?
  126. """
  127. txn.execute(sql, (self.stream_ordering_day_ago,))
  128. (count,) = cast(Tuple[int], txn.fetchone())
  129. return count
  130. return await self.db_pool.runInteraction(
  131. "count_daily_active_e2ee_rooms", _count
  132. )
  133. async def count_daily_messages(self) -> int:
  134. """
  135. Returns an estimate of the number of messages sent in the last day.
  136. If it has been significantly less or more than one day since the last
  137. call to this function, it will return None.
  138. """
  139. def _count_messages(txn: LoggingTransaction) -> int:
  140. sql = """
  141. SELECT COUNT(*) FROM events
  142. WHERE type = 'm.room.message'
  143. AND stream_ordering > ?
  144. """
  145. txn.execute(sql, (self.stream_ordering_day_ago,))
  146. (count,) = cast(Tuple[int], txn.fetchone())
  147. return count
  148. return await self.db_pool.runInteraction("count_messages", _count_messages)
  149. async def count_daily_sent_messages(self) -> int:
  150. def _count_messages(txn: LoggingTransaction) -> int:
  151. # This is good enough as if you have silly characters in your own
  152. # hostname then that's your own fault.
  153. like_clause = "%:" + self.hs.hostname
  154. sql = """
  155. SELECT COUNT(*) FROM events
  156. WHERE type = 'm.room.message'
  157. AND sender LIKE ?
  158. AND stream_ordering > ?
  159. """
  160. txn.execute(sql, (like_clause, self.stream_ordering_day_ago))
  161. (count,) = cast(Tuple[int], txn.fetchone())
  162. return count
  163. return await self.db_pool.runInteraction(
  164. "count_daily_sent_messages", _count_messages
  165. )
  166. async def count_daily_active_rooms(self) -> int:
  167. def _count(txn: LoggingTransaction) -> int:
  168. sql = """
  169. SELECT COUNT(DISTINCT room_id) FROM events
  170. WHERE type = 'm.room.message'
  171. AND stream_ordering > ?
  172. """
  173. txn.execute(sql, (self.stream_ordering_day_ago,))
  174. (count,) = cast(Tuple[int], txn.fetchone())
  175. return count
  176. return await self.db_pool.runInteraction("count_daily_active_rooms", _count)
  177. async def count_daily_users(self) -> int:
  178. """
  179. Counts the number of users who used this homeserver in the last 24 hours.
  180. """
  181. yesterday = int(self._clock.time_msec()) - (1000 * 60 * 60 * 24)
  182. return await self.db_pool.runInteraction(
  183. "count_daily_users", self._count_users, yesterday
  184. )
  185. async def count_monthly_users(self) -> int:
  186. """
  187. Counts the number of users who used this homeserver in the last 30 days.
  188. Note this method is intended for phonehome metrics only and is different
  189. from the mau figure in synapse.storage.monthly_active_users which,
  190. amongst other things, includes a 3 day grace period before a user counts.
  191. """
  192. thirty_days_ago = int(self._clock.time_msec()) - (1000 * 60 * 60 * 24 * 30)
  193. return await self.db_pool.runInteraction(
  194. "count_monthly_users", self._count_users, thirty_days_ago
  195. )
  196. def _count_users(self, txn: LoggingTransaction, time_from: int) -> int:
  197. """
  198. Returns number of users seen in the past time_from period
  199. """
  200. sql = """
  201. SELECT COUNT(*) FROM (
  202. SELECT user_id FROM user_ips
  203. WHERE last_seen > ?
  204. GROUP BY user_id
  205. ) u
  206. """
  207. txn.execute(sql, (time_from,))
  208. # Mypy knows that fetchone() might return None if there are no rows.
  209. # We know better: "SELECT COUNT(...) FROM ..." without any GROUP BY always
  210. # returns exactly one row.
  211. (count,) = cast(Tuple[int], txn.fetchone())
  212. return count
  213. async def count_r30v2_users(self) -> Dict[str, int]:
  214. """
  215. Counts the number of 30 day retained users, defined as users that:
  216. - Appear more than once in the past 60 days
  217. - Have more than 30 days between the most and least recent appearances that
  218. occurred in the past 60 days.
  219. (This is the second version of this metric, hence R30'v2')
  220. Returns:
  221. A mapping from client type to the number of 30-day retained users for that client.
  222. The dict keys are:
  223. - "all" (a combined number of users across any and all clients)
  224. - "android" (Element Android)
  225. - "ios" (Element iOS)
  226. - "electron" (Element Desktop)
  227. - "web" (any web application -- it's not possible to distinguish Element Web here)
  228. """
  229. def _count_r30v2_users(txn: LoggingTransaction) -> Dict[str, int]:
  230. thirty_days_in_secs = 86400 * 30
  231. now = int(self._clock.time())
  232. sixty_days_ago_in_secs = now - 2 * thirty_days_in_secs
  233. one_day_from_now_in_secs = now + 86400
  234. # This is the 'per-platform' count.
  235. sql = """
  236. SELECT
  237. client_type,
  238. count(client_type)
  239. FROM
  240. (
  241. SELECT
  242. user_id,
  243. CASE
  244. WHEN
  245. LOWER(user_agent) LIKE '%%riot%%' OR
  246. LOWER(user_agent) LIKE '%%element%%'
  247. THEN CASE
  248. WHEN
  249. LOWER(user_agent) LIKE '%%electron%%'
  250. THEN 'electron'
  251. WHEN
  252. LOWER(user_agent) LIKE '%%android%%'
  253. THEN 'android'
  254. WHEN
  255. LOWER(user_agent) LIKE '%%ios%%'
  256. THEN 'ios'
  257. ELSE 'unknown'
  258. END
  259. WHEN
  260. LOWER(user_agent) LIKE '%%mozilla%%' OR
  261. LOWER(user_agent) LIKE '%%gecko%%'
  262. THEN 'web'
  263. ELSE 'unknown'
  264. END as client_type
  265. FROM
  266. user_daily_visits
  267. WHERE
  268. timestamp > ?
  269. AND
  270. timestamp < ?
  271. GROUP BY
  272. user_id,
  273. client_type
  274. HAVING
  275. max(timestamp) - min(timestamp) > ?
  276. ) AS temp
  277. GROUP BY
  278. client_type
  279. ;
  280. """
  281. # We initialise all the client types to zero, so we get an explicit
  282. # zero if they don't appear in the query results
  283. results = {"ios": 0, "android": 0, "web": 0, "electron": 0}
  284. txn.execute(
  285. sql,
  286. (
  287. sixty_days_ago_in_secs * 1000,
  288. one_day_from_now_in_secs * 1000,
  289. thirty_days_in_secs * 1000,
  290. ),
  291. )
  292. for row in txn:
  293. if row[0] == "unknown":
  294. continue
  295. results[row[0]] = row[1]
  296. # This is the 'all users' count.
  297. sql = """
  298. SELECT COUNT(*) FROM (
  299. SELECT
  300. 1
  301. FROM
  302. user_daily_visits
  303. WHERE
  304. timestamp > ?
  305. AND
  306. timestamp < ?
  307. GROUP BY
  308. user_id
  309. HAVING
  310. max(timestamp) - min(timestamp) > ?
  311. ) AS r30_users
  312. """
  313. txn.execute(
  314. sql,
  315. (
  316. sixty_days_ago_in_secs * 1000,
  317. one_day_from_now_in_secs * 1000,
  318. thirty_days_in_secs * 1000,
  319. ),
  320. )
  321. (count,) = cast(Tuple[int], txn.fetchone())
  322. results["all"] = count
  323. return results
  324. return await self.db_pool.runInteraction(
  325. "count_r30v2_users", _count_r30v2_users
  326. )
  327. def _get_start_of_day(self) -> int:
  328. """
  329. Returns millisecond unixtime for start of UTC day.
  330. """
  331. now = time.gmtime(self._clock.time())
  332. today_start = calendar.timegm((now.tm_year, now.tm_mon, now.tm_mday, 0, 0, 0))
  333. return today_start * 1000
  334. @wrap_as_background_process("generate_user_daily_visits")
  335. async def generate_user_daily_visits(self) -> None:
  336. """
  337. Generates daily visit data for use in cohort/ retention analysis
  338. """
  339. def _generate_user_daily_visits(txn: LoggingTransaction) -> None:
  340. logger.info("Calling _generate_user_daily_visits")
  341. today_start = self._get_start_of_day()
  342. a_day_in_milliseconds = 24 * 60 * 60 * 1000
  343. now = self._clock.time_msec()
  344. # A note on user_agent. Technically a given device can have multiple
  345. # user agents, so we need to decide which one to pick. We could have
  346. # handled this in number of ways, but given that we don't care
  347. # _that_ much we have gone for MAX(). For more details of the other
  348. # options considered see
  349. # https://github.com/matrix-org/synapse/pull/8503#discussion_r502306111
  350. sql = """
  351. INSERT INTO user_daily_visits (user_id, device_id, timestamp, user_agent)
  352. SELECT u.user_id, u.device_id, ?, MAX(u.user_agent)
  353. FROM user_ips AS u
  354. LEFT JOIN (
  355. SELECT user_id, device_id, timestamp FROM user_daily_visits
  356. WHERE timestamp = ?
  357. ) udv
  358. ON u.user_id = udv.user_id AND u.device_id=udv.device_id
  359. INNER JOIN users ON users.name=u.user_id
  360. WHERE ? <= last_seen AND last_seen < ?
  361. AND udv.timestamp IS NULL AND users.is_guest=0
  362. AND users.appservice_id IS NULL
  363. GROUP BY u.user_id, u.device_id
  364. """
  365. # This means that the day has rolled over but there could still
  366. # be entries from the previous day. There is an edge case
  367. # where if the user logs in at 23:59 and overwrites their
  368. # last_seen at 00:01 then they will not be counted in the
  369. # previous day's stats - it is important that the query is run
  370. # often to minimise this case.
  371. if today_start > self._last_user_visit_update:
  372. yesterday_start = today_start - a_day_in_milliseconds
  373. txn.execute(
  374. sql,
  375. (
  376. yesterday_start,
  377. yesterday_start,
  378. self._last_user_visit_update,
  379. today_start,
  380. ),
  381. )
  382. self._last_user_visit_update = today_start
  383. txn.execute(
  384. sql, (today_start, today_start, self._last_user_visit_update, now)
  385. )
  386. # Update _last_user_visit_update to now. The reason to do this
  387. # rather just clamping to the beginning of the day is to limit
  388. # the size of the join - meaning that the query can be run more
  389. # frequently
  390. self._last_user_visit_update = now
  391. await self.db_pool.runInteraction(
  392. "generate_user_daily_visits", _generate_user_daily_visits
  393. )