srv_resolver.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. import attr
  20. from twisted.internet import defer
  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
  28. class Server(object):
  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 pick_server_from_list(server_list):
  45. """Randomly choose a server from the server list
  46. Args:
  47. server_list (list[Server]): list of candidate servers
  48. Returns:
  49. Tuple[bytes, int]: (host, port) pair for the chosen server
  50. """
  51. if not server_list:
  52. raise RuntimeError("pick_server_from_list called with empty list")
  53. # TODO: currently we only use the lowest-priority servers. We should maintain a
  54. # cache of servers known to be "down" and filter them out
  55. min_priority = min(s.priority for s in server_list)
  56. eligible_servers = list(s for s in server_list if s.priority == min_priority)
  57. total_weight = sum(s.weight for s in eligible_servers)
  58. target_weight = random.randint(0, total_weight)
  59. for s in eligible_servers:
  60. target_weight -= s.weight
  61. if target_weight <= 0:
  62. return s.host, s.port
  63. # this should be impossible.
  64. raise RuntimeError("pick_server_from_list got to end of eligible server list.")
  65. class SrvResolver(object):
  66. """Interface to the dns client to do SRV lookups, with result caching.
  67. The default resolver in twisted.names doesn't do any caching (it has a CacheResolver,
  68. but the cache never gets populated), so we add our own caching layer here.
  69. Args:
  70. dns_client (twisted.internet.interfaces.IResolver): twisted resolver impl
  71. cache (dict): cache object
  72. get_time (callable): clock implementation. Should return seconds since the epoch
  73. """
  74. def __init__(self, dns_client=client, cache=SERVER_CACHE, get_time=time.time):
  75. self._dns_client = dns_client
  76. self._cache = cache
  77. self._get_time = get_time
  78. @defer.inlineCallbacks
  79. def resolve_service(self, service_name):
  80. """Look up a SRV record
  81. Args:
  82. service_name (bytes): record to look up
  83. Returns:
  84. Deferred[list[Server]]:
  85. a list of the SRV records, or an empty list if none found
  86. """
  87. now = int(self._get_time())
  88. if not isinstance(service_name, bytes):
  89. raise TypeError("%r is not a byte string" % (service_name,))
  90. cache_entry = self._cache.get(service_name, None)
  91. if cache_entry:
  92. if all(s.expires > now for s in cache_entry):
  93. servers = list(cache_entry)
  94. defer.returnValue(servers)
  95. try:
  96. answers, _, _ = yield make_deferred_yieldable(
  97. self._dns_client.lookupService(service_name)
  98. )
  99. except DNSNameError:
  100. # TODO: cache this. We can get the SOA out of the exception, and use
  101. # the negative-TTL value.
  102. defer.returnValue([])
  103. except DomainError as e:
  104. # We failed to resolve the name (other than a NameError)
  105. # Try something in the cache, else rereaise
  106. cache_entry = self._cache.get(service_name, None)
  107. if cache_entry:
  108. logger.warn(
  109. "Failed to resolve %r, falling back to cache. %r", service_name, e
  110. )
  111. defer.returnValue(list(cache_entry))
  112. else:
  113. raise e
  114. if (
  115. len(answers) == 1
  116. and answers[0].type == dns.SRV
  117. and answers[0].payload
  118. and answers[0].payload.target == dns.Name(b".")
  119. ):
  120. raise ConnectError("Service %s unavailable" % service_name)
  121. servers = []
  122. for answer in answers:
  123. if answer.type != dns.SRV or not answer.payload:
  124. continue
  125. payload = answer.payload
  126. servers.append(
  127. Server(
  128. host=payload.target.name,
  129. port=payload.port,
  130. priority=payload.priority,
  131. weight=payload.weight,
  132. expires=now + answer.ttl,
  133. )
  134. )
  135. self._cache[service_name] = list(servers)
  136. defer.returnValue(servers)