client_ips.py 7.2 KB

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