versioned.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. """DNS Versioned Zones."""
  3. import collections
  4. try:
  5. import threading as _threading
  6. except ImportError: # pragma: no cover
  7. import dummy_threading as _threading # type: ignore
  8. import dns.exception
  9. import dns.immutable
  10. import dns.name
  11. import dns.rdataclass
  12. import dns.rdatatype
  13. import dns.rdtypes.ANY.SOA
  14. import dns.zone
  15. class UseTransaction(dns.exception.DNSException):
  16. """To alter a versioned zone, use a transaction."""
  17. # Backwards compatibility
  18. Node = dns.zone.VersionedNode
  19. ImmutableNode = dns.zone.ImmutableVersionedNode
  20. Version = dns.zone.Version
  21. WritableVersion = dns.zone.WritableVersion
  22. ImmutableVersion = dns.zone.ImmutableVersion
  23. Transaction = dns.zone.Transaction
  24. class Zone(dns.zone.Zone):
  25. __slots__ = ['_versions', '_versions_lock', '_write_txn',
  26. '_write_waiters', '_write_event', '_pruning_policy',
  27. '_readers']
  28. node_factory = Node
  29. def __init__(self, origin, rdclass=dns.rdataclass.IN, relativize=True,
  30. pruning_policy=None):
  31. """Initialize a versioned zone object.
  32. *origin* is the origin of the zone. It may be a ``dns.name.Name``,
  33. a ``str``, or ``None``. If ``None``, then the zone's origin will
  34. be set by the first ``$ORIGIN`` line in a zone file.
  35. *rdclass*, an ``int``, the zone's rdata class; the default is class IN.
  36. *relativize*, a ``bool``, determine's whether domain names are
  37. relativized to the zone's origin. The default is ``True``.
  38. *pruning policy*, a function taking a `Version` and returning
  39. a `bool`, or `None`. Should the version be pruned? If `None`,
  40. the default policy, which retains one version is used.
  41. """
  42. super().__init__(origin, rdclass, relativize)
  43. self._versions = collections.deque()
  44. self._version_lock = _threading.Lock()
  45. if pruning_policy is None:
  46. self._pruning_policy = self._default_pruning_policy
  47. else:
  48. self._pruning_policy = pruning_policy
  49. self._write_txn = None
  50. self._write_event = None
  51. self._write_waiters = collections.deque()
  52. self._readers = set()
  53. self._commit_version_unlocked(None,
  54. WritableVersion(self, replacement=True),
  55. origin)
  56. def reader(self, id=None, serial=None): # pylint: disable=arguments-differ
  57. if id is not None and serial is not None:
  58. raise ValueError('cannot specify both id and serial')
  59. with self._version_lock:
  60. if id is not None:
  61. version = None
  62. for v in reversed(self._versions):
  63. if v.id == id:
  64. version = v
  65. break
  66. if version is None:
  67. raise KeyError('version not found')
  68. elif serial is not None:
  69. if self.relativize:
  70. oname = dns.name.empty
  71. else:
  72. oname = self.origin
  73. version = None
  74. for v in reversed(self._versions):
  75. n = v.nodes.get(oname)
  76. if n:
  77. rds = n.get_rdataset(self.rdclass, dns.rdatatype.SOA)
  78. if rds and rds[0].serial == serial:
  79. version = v
  80. break
  81. if version is None:
  82. raise KeyError('serial not found')
  83. else:
  84. version = self._versions[-1]
  85. txn = Transaction(self, False, version)
  86. self._readers.add(txn)
  87. return txn
  88. def writer(self, replacement=False):
  89. event = None
  90. while True:
  91. with self._version_lock:
  92. # Checking event == self._write_event ensures that either
  93. # no one was waiting before we got lucky and found no write
  94. # txn, or we were the one who was waiting and got woken up.
  95. # This prevents "taking cuts" when creating a write txn.
  96. if self._write_txn is None and event == self._write_event:
  97. # Creating the transaction defers version setup
  98. # (i.e. copying the nodes dictionary) until we
  99. # give up the lock, so that we hold the lock as
  100. # short a time as possible. This is why we call
  101. # _setup_version() below.
  102. self._write_txn = Transaction(self, replacement,
  103. make_immutable=True)
  104. # give up our exclusive right to make a Transaction
  105. self._write_event = None
  106. break
  107. # Someone else is writing already, so we will have to
  108. # wait, but we want to do the actual wait outside the
  109. # lock.
  110. event = _threading.Event()
  111. self._write_waiters.append(event)
  112. # wait (note we gave up the lock!)
  113. #
  114. # We only wake one sleeper at a time, so it's important
  115. # that no event waiter can exit this method (e.g. via
  116. # cancellation) without returning a transaction or waking
  117. # someone else up.
  118. #
  119. # This is not a problem with Threading module threads as
  120. # they cannot be canceled, but could be an issue with trio
  121. # or curio tasks when we do the async version of writer().
  122. # I.e. we'd need to do something like:
  123. #
  124. # try:
  125. # event.wait()
  126. # except trio.Cancelled:
  127. # with self._version_lock:
  128. # self._maybe_wakeup_one_waiter_unlocked()
  129. # raise
  130. #
  131. event.wait()
  132. # Do the deferred version setup.
  133. self._write_txn._setup_version()
  134. return self._write_txn
  135. def _maybe_wakeup_one_waiter_unlocked(self):
  136. if len(self._write_waiters) > 0:
  137. self._write_event = self._write_waiters.popleft()
  138. self._write_event.set()
  139. # pylint: disable=unused-argument
  140. def _default_pruning_policy(self, zone, version):
  141. return True
  142. # pylint: enable=unused-argument
  143. def _prune_versions_unlocked(self):
  144. assert len(self._versions) > 0
  145. # Don't ever prune a version greater than or equal to one that
  146. # a reader has open. This pins versions in memory while the
  147. # reader is open, and importantly lets the reader open a txn on
  148. # a successor version (e.g. if generating an IXFR).
  149. #
  150. # Note our definition of least_kept also ensures we do not try to
  151. # delete the greatest version.
  152. if len(self._readers) > 0:
  153. least_kept = min(txn.version.id for txn in self._readers)
  154. else:
  155. least_kept = self._versions[-1].id
  156. while self._versions[0].id < least_kept and \
  157. self._pruning_policy(self, self._versions[0]):
  158. self._versions.popleft()
  159. def set_max_versions(self, max_versions):
  160. """Set a pruning policy that retains up to the specified number
  161. of versions
  162. """
  163. if max_versions is not None and max_versions < 1:
  164. raise ValueError('max versions must be at least 1')
  165. if max_versions is None:
  166. def policy(*_):
  167. return False
  168. else:
  169. def policy(zone, _):
  170. return len(zone._versions) > max_versions
  171. self.set_pruning_policy(policy)
  172. def set_pruning_policy(self, policy):
  173. """Set the pruning policy for the zone.
  174. The *policy* function takes a `Version` and returns `True` if
  175. the version should be pruned, and `False` otherwise. `None`
  176. may also be specified for policy, in which case the default policy
  177. is used.
  178. Pruning checking proceeds from the least version and the first
  179. time the function returns `False`, the checking stops. I.e. the
  180. retained versions are always a consecutive sequence.
  181. """
  182. if policy is None:
  183. policy = self._default_pruning_policy
  184. with self._version_lock:
  185. self._pruning_policy = policy
  186. self._prune_versions_unlocked()
  187. def _end_read(self, txn):
  188. with self._version_lock:
  189. self._readers.remove(txn)
  190. self._prune_versions_unlocked()
  191. def _end_write_unlocked(self, txn):
  192. assert self._write_txn == txn
  193. self._write_txn = None
  194. self._maybe_wakeup_one_waiter_unlocked()
  195. def _end_write(self, txn):
  196. with self._version_lock:
  197. self._end_write_unlocked(txn)
  198. def _commit_version_unlocked(self, txn, version, origin):
  199. self._versions.append(version)
  200. self._prune_versions_unlocked()
  201. self.nodes = version.nodes
  202. if self.origin is None:
  203. self.origin = origin
  204. # txn can be None in __init__ when we make the empty version.
  205. if txn is not None:
  206. self._end_write_unlocked(txn)
  207. def _commit_version(self, txn, version, origin):
  208. with self._version_lock:
  209. self._commit_version_unlocked(txn, version, origin)
  210. def _get_next_version_id(self):
  211. if len(self._versions) > 0:
  212. id = self._versions[-1].id + 1
  213. else:
  214. id = 1
  215. return id
  216. def find_node(self, name, create=False):
  217. if create:
  218. raise UseTransaction
  219. return super().find_node(name)
  220. def delete_node(self, name):
  221. raise UseTransaction
  222. def find_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE,
  223. create=False):
  224. if create:
  225. raise UseTransaction
  226. rdataset = super().find_rdataset(name, rdtype, covers)
  227. return dns.rdataset.ImmutableRdataset(rdataset)
  228. def get_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE,
  229. create=False):
  230. if create:
  231. raise UseTransaction
  232. rdataset = super().get_rdataset(name, rdtype, covers)
  233. return dns.rdataset.ImmutableRdataset(rdataset)
  234. def delete_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE):
  235. raise UseTransaction
  236. def replace_rdataset(self, name, replacement):
  237. raise UseTransaction