client_ips.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from twisted.internet import defer, reactor
  17. from ._base import Cache
  18. from . import background_updates
  19. from synapse.util.caches import CACHE_SIZE_FACTOR
  20. from six import iteritems
  21. logger = logging.getLogger(__name__)
  22. # Number of msec of granularity to store the user IP 'last seen' time. Smaller
  23. # times give more inserts into the database even for readonly API hits
  24. # 120 seconds == 2 minutes
  25. LAST_SEEN_GRANULARITY = 120 * 1000
  26. class ClientIpStore(background_updates.BackgroundUpdateStore):
  27. def __init__(self, db_conn, hs):
  28. self.client_ip_last_seen = Cache(
  29. name="client_ip_last_seen",
  30. keylen=4,
  31. max_entries=50000 * CACHE_SIZE_FACTOR,
  32. )
  33. super(ClientIpStore, self).__init__(db_conn, hs)
  34. self.register_background_index_update(
  35. "user_ips_device_index",
  36. index_name="user_ips_device_id",
  37. table="user_ips",
  38. columns=["user_id", "device_id", "last_seen"],
  39. )
  40. self.register_background_index_update(
  41. "user_ips_last_seen_index",
  42. index_name="user_ips_last_seen",
  43. table="user_ips",
  44. columns=["user_id", "last_seen"],
  45. )
  46. self.register_background_index_update(
  47. "user_ips_last_seen_only_index",
  48. index_name="user_ips_last_seen_only",
  49. table="user_ips",
  50. columns=["last_seen"],
  51. )
  52. # (user_id, access_token, ip) -> (user_agent, device_id, last_seen)
  53. self._batch_row_update = {}
  54. self._client_ip_looper = self._clock.looping_call(
  55. self._update_client_ips_batch, 5 * 1000
  56. )
  57. reactor.addSystemEventTrigger("before", "shutdown", self._update_client_ips_batch)
  58. def insert_client_ip(self, user_id, access_token, ip, user_agent, device_id,
  59. now=None):
  60. if not now:
  61. now = int(self._clock.time_msec())
  62. key = (user_id, access_token, ip)
  63. try:
  64. last_seen = self.client_ip_last_seen.get(key)
  65. except KeyError:
  66. last_seen = None
  67. # Rate-limited inserts
  68. if last_seen is not None and (now - last_seen) < LAST_SEEN_GRANULARITY:
  69. return
  70. self.client_ip_last_seen.prefill(key, now)
  71. self._batch_row_update[key] = (user_agent, device_id, now)
  72. def _update_client_ips_batch(self):
  73. to_update = self._batch_row_update
  74. self._batch_row_update = {}
  75. return self.runInteraction(
  76. "_update_client_ips_batch", self._update_client_ips_batch_txn, to_update
  77. )
  78. def _update_client_ips_batch_txn(self, txn, to_update):
  79. self.database_engine.lock_table(txn, "user_ips")
  80. for entry in iteritems(to_update):
  81. (user_id, access_token, ip), (user_agent, device_id, last_seen) = entry
  82. self._simple_upsert_txn(
  83. txn,
  84. table="user_ips",
  85. keyvalues={
  86. "user_id": user_id,
  87. "access_token": access_token,
  88. "ip": ip,
  89. "user_agent": user_agent,
  90. "device_id": device_id,
  91. },
  92. values={
  93. "last_seen": last_seen,
  94. },
  95. lock=False,
  96. )
  97. @defer.inlineCallbacks
  98. def get_last_client_ip_by_device(self, user_id, device_id):
  99. """For each device_id listed, give the user_ip it was last seen on
  100. Args:
  101. user_id (str)
  102. device_id (str): If None fetches all devices for the user
  103. Returns:
  104. defer.Deferred: resolves to a dict, where the keys
  105. are (user_id, device_id) tuples. The values are also dicts, with
  106. keys giving the column names
  107. """
  108. res = yield self.runInteraction(
  109. "get_last_client_ip_by_device",
  110. self._get_last_client_ip_by_device_txn,
  111. user_id, device_id,
  112. retcols=(
  113. "user_id",
  114. "access_token",
  115. "ip",
  116. "user_agent",
  117. "device_id",
  118. "last_seen",
  119. ),
  120. )
  121. ret = {(d["user_id"], d["device_id"]): d for d in res}
  122. for key in self._batch_row_update:
  123. uid, access_token, ip = key
  124. if uid == user_id:
  125. user_agent, did, last_seen = self._batch_row_update[key]
  126. if not device_id or did == device_id:
  127. ret[(user_id, device_id)] = {
  128. "user_id": user_id,
  129. "access_token": access_token,
  130. "ip": ip,
  131. "user_agent": user_agent,
  132. "device_id": did,
  133. "last_seen": last_seen,
  134. }
  135. defer.returnValue(ret)
  136. @classmethod
  137. def _get_last_client_ip_by_device_txn(cls, txn, user_id, device_id, retcols):
  138. where_clauses = []
  139. bindings = []
  140. if device_id is None:
  141. where_clauses.append("user_id = ?")
  142. bindings.extend((user_id, ))
  143. else:
  144. where_clauses.append("(user_id = ? AND device_id = ?)")
  145. bindings.extend((user_id, device_id))
  146. if not where_clauses:
  147. return []
  148. inner_select = (
  149. "SELECT MAX(last_seen) mls, user_id, device_id FROM user_ips "
  150. "WHERE %(where)s "
  151. "GROUP BY user_id, device_id"
  152. ) % {
  153. "where": " OR ".join(where_clauses),
  154. }
  155. sql = (
  156. "SELECT %(retcols)s FROM user_ips "
  157. "JOIN (%(inner_select)s) ips ON"
  158. " user_ips.last_seen = ips.mls AND"
  159. " user_ips.user_id = ips.user_id AND"
  160. " (user_ips.device_id = ips.device_id OR"
  161. " (user_ips.device_id IS NULL AND ips.device_id IS NULL)"
  162. " )"
  163. ) % {
  164. "retcols": ",".join("user_ips." + c for c in retcols),
  165. "inner_select": inner_select,
  166. }
  167. txn.execute(sql, bindings)
  168. return cls.cursor_to_dict(txn)
  169. @defer.inlineCallbacks
  170. def get_user_ip_and_agents(self, user):
  171. user_id = user.to_string()
  172. results = {}
  173. for key in self._batch_row_update:
  174. uid, access_token, ip = key
  175. if uid == user_id:
  176. user_agent, _, last_seen = self._batch_row_update[key]
  177. results[(access_token, ip)] = (user_agent, last_seen)
  178. rows = yield self._simple_select_list(
  179. table="user_ips",
  180. keyvalues={"user_id": user_id},
  181. retcols=[
  182. "access_token", "ip", "user_agent", "last_seen"
  183. ],
  184. desc="get_user_ip_and_agents",
  185. )
  186. results.update(
  187. ((row["access_token"], row["ip"]), (row["user_agent"], row["last_seen"]))
  188. for row in rows
  189. )
  190. defer.returnValue(list(
  191. {
  192. "access_token": access_token,
  193. "ip": ip,
  194. "user_agent": user_agent,
  195. "last_seen": last_seen,
  196. }
  197. for (access_token, ip), (user_agent, last_seen) in iteritems(results)
  198. ))