client_ips.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. logger = logging.getLogger(__name__)
  21. # Number of msec of granularity to store the user IP 'last seen' time. Smaller
  22. # times give more inserts into the database even for readonly API hits
  23. # 120 seconds == 2 minutes
  24. LAST_SEEN_GRANULARITY = 120 * 1000
  25. class ClientIpStore(background_updates.BackgroundUpdateStore):
  26. def __init__(self, db_conn, hs):
  27. self.client_ip_last_seen = Cache(
  28. name="client_ip_last_seen",
  29. keylen=4,
  30. max_entries=50000 * CACHE_SIZE_FACTOR,
  31. )
  32. super(ClientIpStore, self).__init__(db_conn, hs)
  33. self.register_background_index_update(
  34. "user_ips_device_index",
  35. index_name="user_ips_device_id",
  36. table="user_ips",
  37. columns=["user_id", "device_id", "last_seen"],
  38. )
  39. self.register_background_index_update(
  40. "user_ips_last_seen_index",
  41. index_name="user_ips_last_seen",
  42. table="user_ips",
  43. columns=["user_id", "last_seen"],
  44. )
  45. # (user_id, access_token, ip) -> (user_agent, device_id, last_seen)
  46. self._batch_row_update = {}
  47. self._client_ip_looper = self._clock.looping_call(
  48. self._update_client_ips_batch, 5 * 1000
  49. )
  50. reactor.addSystemEventTrigger("before", "shutdown", self._update_client_ips_batch)
  51. def insert_client_ip(self, user_id, access_token, ip, user_agent, device_id,
  52. now=None):
  53. if not now:
  54. now = int(self._clock.time_msec())
  55. key = (user_id, access_token, ip)
  56. try:
  57. last_seen = self.client_ip_last_seen.get(key)
  58. except KeyError:
  59. last_seen = None
  60. # Rate-limited inserts
  61. if last_seen is not None and (now - last_seen) < LAST_SEEN_GRANULARITY:
  62. return
  63. self.client_ip_last_seen.prefill(key, now)
  64. self._batch_row_update[key] = (user_agent, device_id, now)
  65. def _update_client_ips_batch(self):
  66. to_update = self._batch_row_update
  67. self._batch_row_update = {}
  68. return self.runInteraction(
  69. "_update_client_ips_batch", self._update_client_ips_batch_txn, to_update
  70. )
  71. def _update_client_ips_batch_txn(self, txn, to_update):
  72. self.database_engine.lock_table(txn, "user_ips")
  73. for entry in to_update.iteritems():
  74. (user_id, access_token, ip), (user_agent, device_id, last_seen) = entry
  75. self._simple_upsert_txn(
  76. txn,
  77. table="user_ips",
  78. keyvalues={
  79. "user_id": user_id,
  80. "access_token": access_token,
  81. "ip": ip,
  82. "user_agent": user_agent,
  83. "device_id": device_id,
  84. },
  85. values={
  86. "last_seen": last_seen,
  87. },
  88. lock=False,
  89. )
  90. @defer.inlineCallbacks
  91. def get_last_client_ip_by_device(self, user_id, device_id):
  92. """For each device_id listed, give the user_ip it was last seen on
  93. Args:
  94. user_id (str)
  95. device_id (str): If None fetches all devices for the user
  96. Returns:
  97. defer.Deferred: resolves to a dict, where the keys
  98. are (user_id, device_id) tuples. The values are also dicts, with
  99. keys giving the column names
  100. """
  101. res = yield self.runInteraction(
  102. "get_last_client_ip_by_device",
  103. self._get_last_client_ip_by_device_txn,
  104. user_id, device_id,
  105. retcols=(
  106. "user_id",
  107. "access_token",
  108. "ip",
  109. "user_agent",
  110. "device_id",
  111. "last_seen",
  112. ),
  113. )
  114. ret = {(d["user_id"], d["device_id"]): d for d in res}
  115. for key in self._batch_row_update:
  116. uid, access_token, ip = key
  117. if uid == user_id:
  118. user_agent, did, last_seen = self._batch_row_update[key]
  119. if not device_id or did == device_id:
  120. ret[(user_id, device_id)] = {
  121. "user_id": user_id,
  122. "access_token": access_token,
  123. "ip": ip,
  124. "user_agent": user_agent,
  125. "device_id": did,
  126. "last_seen": last_seen,
  127. }
  128. defer.returnValue(ret)
  129. @classmethod
  130. def _get_last_client_ip_by_device_txn(cls, txn, user_id, device_id, retcols):
  131. where_clauses = []
  132. bindings = []
  133. if device_id is None:
  134. where_clauses.append("user_id = ?")
  135. bindings.extend((user_id, ))
  136. else:
  137. where_clauses.append("(user_id = ? AND device_id = ?)")
  138. bindings.extend((user_id, device_id))
  139. if not where_clauses:
  140. return []
  141. inner_select = (
  142. "SELECT MAX(last_seen) mls, user_id, device_id FROM user_ips "
  143. "WHERE %(where)s "
  144. "GROUP BY user_id, device_id"
  145. ) % {
  146. "where": " OR ".join(where_clauses),
  147. }
  148. sql = (
  149. "SELECT %(retcols)s FROM user_ips "
  150. "JOIN (%(inner_select)s) ips ON"
  151. " user_ips.last_seen = ips.mls AND"
  152. " user_ips.user_id = ips.user_id AND"
  153. " (user_ips.device_id = ips.device_id OR"
  154. " (user_ips.device_id IS NULL AND ips.device_id IS NULL)"
  155. " )"
  156. ) % {
  157. "retcols": ",".join("user_ips." + c for c in retcols),
  158. "inner_select": inner_select,
  159. }
  160. txn.execute(sql, bindings)
  161. return cls.cursor_to_dict(txn)
  162. @defer.inlineCallbacks
  163. def get_user_ip_and_agents(self, user):
  164. user_id = user.to_string()
  165. results = {}
  166. for key in self._batch_row_update:
  167. uid, access_token, ip = key
  168. if uid == user_id:
  169. user_agent, _, last_seen = self._batch_row_update[key]
  170. results[(access_token, ip)] = (user_agent, last_seen)
  171. rows = yield self._simple_select_list(
  172. table="user_ips",
  173. keyvalues={"user_id": user_id},
  174. retcols=[
  175. "access_token", "ip", "user_agent", "last_seen"
  176. ],
  177. desc="get_user_ip_and_agents",
  178. )
  179. results.update(
  180. ((row["access_token"], row["ip"]), (row["user_agent"], row["last_seen"]))
  181. for row in rows
  182. )
  183. defer.returnValue(list(
  184. {
  185. "access_token": access_token,
  186. "ip": ip,
  187. "user_agent": user_agent,
  188. "last_seen": last_seen,
  189. }
  190. for (access_token, ip), (user_agent, last_seen) in results.iteritems()
  191. ))