srvresolver.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. logger = logging.getLogger(__name__)
  25. SERVER_CACHE = {}
  26. @attr.s
  27. class Server(object):
  28. """
  29. Our record of an individual server which can be tried to reach a destination.
  30. Attributes:
  31. host (bytes): target hostname
  32. port (int):
  33. priority (int):
  34. weight (int):
  35. expires (int): when the cache should expire this record - in *seconds* since
  36. the epoch
  37. """
  38. host = attr.ib()
  39. port = attr.ib()
  40. priority = attr.ib(default=0)
  41. weight = attr.ib(default=0)
  42. expires = attr.ib(default=0)
  43. def pick_server_from_list(server_list):
  44. """Randomly choose a server from the server list.
  45. :param server_list: List of candidate servers.
  46. :type server_list: list[Server]
  47. :returns a (host, port) pair for the chosen server.
  48. :rtype: Tuple[bytes, int]
  49. """
  50. if not server_list:
  51. raise RuntimeError("pick_server_from_list called with empty list")
  52. # TODO: currently we only use the lowest-priority servers. We should maintain a
  53. # cache of servers known to be "down" and filter them out
  54. min_priority = min(s.priority for s in server_list)
  55. eligible_servers = list(s for s in server_list if s.priority == min_priority)
  56. total_weight = sum(s.weight for s in eligible_servers)
  57. target_weight = random.randint(0, total_weight)
  58. for s in eligible_servers:
  59. target_weight -= s.weight
  60. if target_weight <= 0:
  61. return s.host, s.port
  62. # this should be impossible.
  63. raise RuntimeError(
  64. "pick_server_from_list got to end of eligible server list.",
  65. )
  66. class SrvResolver(object):
  67. """Interface to the dns client to do SRV lookups, with result caching.
  68. The default resolver in twisted.names doesn't do any caching (it has a CacheResolver,
  69. but the cache never gets populated), so we add our own caching layer here.
  70. :param dns_client: Twisted resolver impl
  71. :type dns_client: twisted.internet.interfaces.IResolver
  72. :param cache: cache object
  73. :type cache: Dict
  74. :param get_time: Clock implementation. Should return seconds since the epoch.
  75. :type get_time: callable
  76. """
  77. def __init__(self, dns_client=client, cache=SERVER_CACHE, get_time=time.time):
  78. self._dns_client = dns_client
  79. self._cache = cache
  80. self._get_time = get_time
  81. @defer.inlineCallbacks
  82. def resolve_service(self, service_name):
  83. """Look up a SRV record
  84. :param service_name: The record to look up.
  85. :type service_name: bytes
  86. :returns a list of the SRV records, or an empty list if none found.
  87. :rtype: Deferred[list[Server]]
  88. """
  89. now = int(self._get_time())
  90. if not isinstance(service_name, bytes):
  91. raise TypeError("%r is not a byte string" % (service_name,))
  92. cache_entry = self._cache.get(service_name, None)
  93. if cache_entry:
  94. if all(s.expires > now for s in cache_entry):
  95. servers = list(cache_entry)
  96. defer.returnValue(servers)
  97. try:
  98. answers, _, _ = yield self._dns_client.lookupService(service_name)
  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",
  110. service_name, e
  111. )
  112. defer.returnValue(list(cache_entry))
  113. else:
  114. raise e
  115. if (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. raise ConnectError("Service %s unavailable" % service_name)
  120. servers = []
  121. for answer in answers:
  122. if answer.type != dns.SRV or not answer.payload:
  123. continue
  124. payload = answer.payload
  125. servers.append(Server(
  126. host=payload.target.name,
  127. port=payload.port,
  128. priority=payload.priority,
  129. weight=payload.weight,
  130. expires=now + answer.ttl,
  131. ))
  132. self._cache[service_name] = list(servers)
  133. defer.returnValue(servers)