srv_resolver.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2019 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. import random
  18. import time
  19. from typing import List
  20. import attr
  21. from twisted.internet.error import ConnectError
  22. from twisted.names import client, dns
  23. from twisted.names.error import DNSNameError, DomainError
  24. from synapse.logging.context import make_deferred_yieldable
  25. logger = logging.getLogger(__name__)
  26. SERVER_CACHE = {}
  27. @attr.s(slots=True, frozen=True)
  28. class Server:
  29. """
  30. Our record of an individual server which can be tried to reach a destination.
  31. Attributes:
  32. host (bytes): target hostname
  33. port (int):
  34. priority (int):
  35. weight (int):
  36. expires (int): when the cache should expire this record - in *seconds* since
  37. the epoch
  38. """
  39. host = attr.ib()
  40. port = attr.ib()
  41. priority = attr.ib(default=0)
  42. weight = attr.ib(default=0)
  43. expires = attr.ib(default=0)
  44. def _sort_server_list(server_list):
  45. """Given a list of SRV records sort them into priority order and shuffle
  46. each priority with the given weight.
  47. """
  48. priority_map = {}
  49. for server in server_list:
  50. priority_map.setdefault(server.priority, []).append(server)
  51. results = []
  52. for priority in sorted(priority_map):
  53. servers = priority_map[priority]
  54. # This algorithms roughly follows the algorithm described in RFC2782,
  55. # changed to remove an off-by-one error.
  56. #
  57. # N.B. Weights can be zero, which means that they should be picked
  58. # rarely.
  59. total_weight = sum(s.weight for s in servers)
  60. # Total weight can become zero if there are only zero weight servers
  61. # left, which we handle by just shuffling and appending to the results.
  62. while servers and total_weight:
  63. target_weight = random.randint(1, total_weight)
  64. for s in servers:
  65. target_weight -= s.weight
  66. if target_weight <= 0:
  67. break
  68. results.append(s)
  69. servers.remove(s)
  70. total_weight -= s.weight
  71. if servers:
  72. random.shuffle(servers)
  73. results.extend(servers)
  74. return results
  75. class SrvResolver:
  76. """Interface to the dns client to do SRV lookups, with result caching.
  77. The default resolver in twisted.names doesn't do any caching (it has a CacheResolver,
  78. but the cache never gets populated), so we add our own caching layer here.
  79. Args:
  80. dns_client (twisted.internet.interfaces.IResolver): twisted resolver impl
  81. cache (dict): cache object
  82. get_time (callable): clock implementation. Should return seconds since the epoch
  83. """
  84. def __init__(self, dns_client=client, cache=SERVER_CACHE, get_time=time.time):
  85. self._dns_client = dns_client
  86. self._cache = cache
  87. self._get_time = get_time
  88. async def resolve_service(self, service_name: bytes) -> List[Server]:
  89. """Look up a SRV record
  90. Args:
  91. service_name (bytes): record to look up
  92. Returns:
  93. a list of the SRV records, or an empty list if none found
  94. """
  95. now = int(self._get_time())
  96. if not isinstance(service_name, bytes):
  97. raise TypeError("%r is not a byte string" % (service_name,))
  98. cache_entry = self._cache.get(service_name, None)
  99. if cache_entry:
  100. if all(s.expires > now for s in cache_entry):
  101. servers = list(cache_entry)
  102. return _sort_server_list(servers)
  103. try:
  104. answers, _, _ = await make_deferred_yieldable(
  105. self._dns_client.lookupService(service_name)
  106. )
  107. except DNSNameError:
  108. # TODO: cache this. We can get the SOA out of the exception, and use
  109. # the negative-TTL value.
  110. return []
  111. except DomainError as e:
  112. # We failed to resolve the name (other than a NameError)
  113. # Try something in the cache, else rereaise
  114. cache_entry = self._cache.get(service_name, None)
  115. if cache_entry:
  116. logger.warning(
  117. "Failed to resolve %r, falling back to cache. %r", service_name, e
  118. )
  119. return list(cache_entry)
  120. else:
  121. raise e
  122. if (
  123. len(answers) == 1
  124. and answers[0].type == dns.SRV
  125. and answers[0].payload
  126. and answers[0].payload.target == dns.Name(b".")
  127. ):
  128. raise ConnectError("Service %s unavailable" % service_name)
  129. servers = []
  130. for answer in answers:
  131. if answer.type != dns.SRV or not answer.payload:
  132. continue
  133. payload = answer.payload
  134. servers.append(
  135. Server(
  136. host=payload.target.name,
  137. port=payload.port,
  138. priority=payload.priority,
  139. weight=payload.weight,
  140. expires=now + answer.ttl,
  141. )
  142. )
  143. self._cache[service_name] = list(servers)
  144. return _sort_server_list(servers)