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