Debian Codegraph @

dns/transaction.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 import collections
4 from typing import Any, Callable, Iterator, List, Tuple
5
6 import dns.exception
7 import dns.name
8 import dns.node
9 import dns.rdata
10 import dns.rdataclass
11 import dns.rdataset
12 import dns.rdatatype
13 import dns.rrset
14 import dns.serial
15 import dns.ttl
16
17
18 class TransactionManager:
19 def reader(self) -> "Transaction":
20 """Begin a read-only transaction."""
21 raise NotImplementedError # pragma: no cover
22
23 def writer(self, replacement: bool = False) -> "Transaction":
24 """Begin a writable transaction.
25
26 *replacement*, a ``bool``. If `True`, the content of the
27 transaction completely replaces any prior content. If False,
28 the default, then the content of the transaction updates the
29 existing content.
30 """
31 raise NotImplementedError # pragma: no cover
32
33 def origin_information(
34 self,
35 ) -> Tuple[dns.name.Name | None, bool, dns.name.Name | None]:
36 """Returns a tuple
37
38 (absolute_origin, relativize, effective_origin)
39
40 giving the absolute name of the default origin for any
41 relative domain names, the "effective origin", and whether
42 names should be relativized. The "effective origin" is the
43 absolute origin if relativize is False, and the empty name if
44 relativize is true. (The effective origin is provided even
45 though it can be computed from the absolute_origin and
46 relativize setting because it avoids a lot of code
47 duplication.)
48
49 If the returned names are `None`, then no origin information is
50 available.
51
52 This information is used by code working with transactions to
53 allow it to coordinate relativization. The transaction code
54 itself takes what it gets (i.e. does not change name
55 relativity).
56
57 """
58 raise NotImplementedError # pragma: no cover
59
60 def get_class(self) -> dns.rdataclass.RdataClass:
61 """The class of the transaction manager."""
62 raise NotImplementedError # pragma: no cover
63
64 def from_wire_origin(self) -> dns.name.Name | None:
65 """Origin to use in from_wire() calls."""
66 (absolute_origin, relativize, _) = self.origin_information()
67 if relativize:
68 return absolute_origin
69 else:
70 return None
71
72
73 class DeleteNotExact(dns.exception.DNSException):
74 """Existing data did not match data specified by an exact delete."""
75
76
77 class ReadOnly(dns.exception.DNSException):
78 """Tried to write to a read-only transaction."""
79
80
81 class AlreadyEnded(dns.exception.DNSException):
82 """Tried to use an already-ended transaction."""
83
84
85 def _ensure_immutable_rdataset(rdataset):
86 if rdataset is None or isinstance(rdataset, dns.rdataset.ImmutableRdataset):
87 return rdataset
88 return dns.rdataset.ImmutableRdataset(rdataset)
89
90
91 def _ensure_immutable_node(node):
92 if node is None or node.is_immutable():
93 return node
94 return dns.node.ImmutableNode(node)
95
96
97 CheckPutRdatasetType = Callable[
98 ["Transaction", dns.name.Name, dns.rdataset.Rdataset], None
99 ]
100 CheckDeleteRdatasetType = Callable[
101 ["Transaction", dns.name.Name, dns.rdatatype.RdataType, dns.rdatatype.RdataType],
102 None,
103 ]
104 CheckDeleteNameType = Callable[["Transaction", dns.name.Name], None]
105
106
107 class Transaction:
108 def __init__(
109 self,
110 manager: TransactionManager,
111 replacement: bool = False,
112 read_only: bool = False,
113 ):
114 self.manager = manager
115 self.replacement = replacement
116 self.read_only = read_only
117 self._ended = False
118 self._check_put_rdataset: List[CheckPutRdatasetType] = []
119 self._check_delete_rdataset: List[CheckDeleteRdatasetType] = []
120 self._check_delete_name: List[CheckDeleteNameType] = []
121
122 #
123 # This is the high level API
124 #
125 # Note that we currently use non-immutable types in the return type signature to
126 # avoid covariance problems, e.g. if the caller has a List[Rdataset], mypy will be
127 # unhappy if we return an ImmutableRdataset.
128
129 def get(
130 self,
131 name: dns.name.Name | str | None,
132 rdtype: dns.rdatatype.RdataType | str,
133 covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE,
134 ) -> dns.rdataset.Rdataset:
135 """Return the rdataset associated with *name*, *rdtype*, and *covers*,
136 or `None` if not found.
137
138 Note that the returned rdataset is immutable.
139 """
140 self._check_ended()
141 if isinstance(name, str):
142 name = dns.name.from_text(name, None)
143 rdtype = dns.rdatatype.RdataType.make(rdtype)
144 covers = dns.rdatatype.RdataType.make(covers)
145 rdataset = self._get_rdataset(name, rdtype, covers)
146 return _ensure_immutable_rdataset(rdataset)
147
148 def get_node(self, name: dns.name.Name) -> dns.node.Node | None:
149 """Return the node at *name*, if any.
150
151 Returns an immutable node or ``None``.
152 """
153 return _ensure_immutable_node(self._get_node(name))
154
155 def _check_read_only(self) -> None:
156 if self.read_only:
157 raise ReadOnly
158
159 def add(self, *args: Any) -> None:
160 """Add records.
161
162 The arguments may be:
163
164 - rrset
165
166 - name, rdataset...
167
168 - name, ttl, rdata...
169 """
170 self._check_ended()
171 self._check_read_only()
172 self._add(False, args)
173
174 def replace(self, *args: Any) -> None:
175 """Replace the existing rdataset at the name with the specified
176 rdataset, or add the specified rdataset if there was no existing
177 rdataset.
178
179 The arguments may be:
180
181 - rrset
182
183 - name, rdataset...
184
185 - name, ttl, rdata...
186
187 Note that if you want to replace the entire node, you should do
188 a delete of the name followed by one or more calls to add() or
189 replace().
190 """
191 self._check_ended()
192 self._check_read_only()
193 self._add(True, args)
194
195 def delete(self, *args: Any) -> None:
196 """Delete records.
197
198 It is not an error if some of the records are not in the existing
199 set.
200
201 The arguments may be:
202
203 - rrset
204
205 - name
206
207 - name, rdatatype, [covers]
208
209 - name, rdataset...
210
211 - name, rdata...
212 """
213 self._check_ended()
214 self._check_read_only()
215 self._delete(False, args)
216
217 def delete_exact(self, *args: Any) -> None:
218 """Delete records.
219
220 The arguments may be:
221
222 - rrset
223
224 - name
225
226 - name, rdatatype, [covers]
227
228 - name, rdataset...
229
230 - name, rdata...
231
232 Raises dns.transaction.DeleteNotExact if some of the records
233 are not in the existing set.
234
235 """
236 self._check_ended()
237 self._check_read_only()
238 self._delete(True, args)
239
240 def name_exists(self, name: dns.name.Name | str) -> bool:
241 """Does the specified name exist?"""
242 self._check_ended()
243 if isinstance(name, str):
244 name = dns.name.from_text(name, None)
245 return self._name_exists(name)
246
247 def update_serial(
248 self,
249 value: int = 1,
250 relative: bool = True,
251 name: dns.name.Name = dns.name.empty,
252 ) -> None:
253 """Update the serial number.
254
255 *value*, an `int`, is an increment if *relative* is `True`, or the
256 actual value to set if *relative* is `False`.
257
258 Raises `KeyError` if there is no SOA rdataset at *name*.
259
260 Raises `ValueError` if *value* is negative or if the increment is
261 so large that it would cause the new serial to be less than the
262 prior value.
263 """
264 self._check_ended()
265 if value < 0:
266 raise ValueError("negative update_serial() value")
267 if isinstance(name, str):
268 name = dns.name.from_text(name, None)
269 rdataset = self._get_rdataset(name, dns.rdatatype.SOA, dns.rdatatype.NONE)
270 if rdataset is None or len(rdataset) == 0:
271 raise KeyError
272 if relative:
273 serial = dns.serial.Serial(rdataset[0].serial) + value
274 else:
275 serial = dns.serial.Serial(value)
276 serial = serial.value # convert back to int
277 if serial == 0:
278 serial = 1
279 rdata = rdataset[0].replace(serial=serial)
280 new_rdataset = dns.rdataset.from_rdata(rdataset.ttl, rdata)
281 self.replace(name, new_rdataset)
282
283 def __iter__(self):
284 self._check_ended()
285 return self._iterate_rdatasets()
286
287 def changed(self) -> bool:
288 """Has this transaction changed anything?
289
290 For read-only transactions, the result is always `False`.
291
292 For writable transactions, the result is `True` if at some time
293 during the life of the transaction, the content was changed.
294 """
295 self._check_ended()
296 return self._changed()
297
298 def commit(self) -> None:
299 """Commit the transaction.
300
301 Normally transactions are used as context managers and commit
302 or rollback automatically, but it may be done explicitly if needed.
303 A ``dns.transaction.Ended`` exception will be raised if you try
304 to use a transaction after it has been committed or rolled back.
305
306 Raises an exception if the commit fails (in which case the transaction
307 is also rolled back.
308 """
309 self._end(True)
310
311 def rollback(self) -> None:
312 """Rollback the transaction.
313
314 Normally transactions are used as context managers and commit
315 or rollback automatically, but it may be done explicitly if needed.
316 A ``dns.transaction.AlreadyEnded`` exception will be raised if you try
317 to use a transaction after it has been committed or rolled back.
318
319 Rollback cannot otherwise fail.
320 """
321 self._end(False)
322
323 def check_put_rdataset(self, check: CheckPutRdatasetType) -> None:
324 """Call *check* before putting (storing) an rdataset.
325
326 The function is called with the transaction, the name, and the rdataset.
327
328 The check function may safely make non-mutating transaction method
329 calls, but behavior is undefined if mutating transaction methods are
330 called. The check function should raise an exception if it objects to
331 the put, and otherwise should return ``None``.
332 """
333 self._check_put_rdataset.append(check)
334
335 def check_delete_rdataset(self, check: CheckDeleteRdatasetType) -> None:
336 """Call *check* before deleting an rdataset.
337
338 The function is called with the transaction, the name, the rdatatype,
339 and the covered rdatatype.
340
341 The check function may safely make non-mutating transaction method
342 calls, but behavior is undefined if mutating transaction methods are
343 called. The check function should raise an exception if it objects to
344 the put, and otherwise should return ``None``.
345 """
346 self._check_delete_rdataset.append(check)
347
348 def check_delete_name(self, check: CheckDeleteNameType) -> None:
349 """Call *check* before putting (storing) an rdataset.
350
351 The function is called with the transaction and the name.
352
353 The check function may safely make non-mutating transaction method
354 calls, but behavior is undefined if mutating transaction methods are
355 called. The check function should raise an exception if it objects to
356 the put, and otherwise should return ``None``.
357 """
358 self._check_delete_name.append(check)
359
360 def iterate_rdatasets(
361 self,
362 ) -> Iterator[Tuple[dns.name.Name, dns.rdataset.Rdataset]]:
363 """Iterate all the rdatasets in the transaction, returning
364 (`dns.name.Name`, `dns.rdataset.Rdataset`) tuples.
365
366 Note that as is usual with python iterators, adding or removing items
367 while iterating will invalidate the iterator and may raise `RuntimeError`
368 or fail to iterate over all entries."""
369 self._check_ended()
370 return self._iterate_rdatasets()
371
372 def iterate_names(self) -> Iterator[dns.name.Name]:
373 """Iterate all the names in the transaction.
374
375 Note that as is usual with python iterators, adding or removing names
376 while iterating will invalidate the iterator and may raise `RuntimeError`
377 or fail to iterate over all entries."""
378 self._check_ended()
379 return self._iterate_names()
380
381 #
382 # Helper methods
383 #
384
385 def _raise_if_not_empty(self, method, args):
386 if len(args) != 0:
387 raise TypeError(f"extra parameters to {method}")
388
389 def _rdataset_from_args(self, method, deleting, args):
390 try:
391 arg = args.popleft()
392 if isinstance(arg, dns.rrset.RRset):
393 rdataset = arg.to_rdataset()
394 elif isinstance(arg, dns.rdataset.Rdataset):
395 rdataset = arg
396 else:
397 if deleting:
398 ttl = 0
399 else:
400 if isinstance(arg, int):
401 ttl = arg
402 if ttl > dns.ttl.MAX_TTL:
403 raise ValueError(f"{method}: TTL value too big")
404 else:
405 raise TypeError(f"{method}: expected a TTL")
406 arg = args.popleft()
407 if isinstance(arg, dns.rdata.Rdata):
408 rdataset = dns.rdataset.from_rdata(ttl, arg)
409 else:
410 raise TypeError(f"{method}: expected an Rdata")
411 return rdataset
412 except IndexError:
413 if deleting:
414 return None
415 else:
416 # reraise
417 raise TypeError(f"{method}: expected more arguments")
418
419 def _add(self, replace, args):
420 if replace:
421 method = "replace()"
422 else:
423 method = "add()"
424 try:
425 args = collections.deque(args)
426 arg = args.popleft()
427 if isinstance(arg, str):
428 arg = dns.name.from_text(arg, None)
429 if isinstance(arg, dns.name.Name):
430 name = arg
431 rdataset = self._rdataset_from_args(method, False, args)
432 elif isinstance(arg, dns.rrset.RRset):
433 rrset = arg
434 name = rrset.name
435 # rrsets are also rdatasets, but they don't print the
436 # same and can't be stored in nodes, so convert.
437 rdataset = rrset.to_rdataset()
438 else:
439 raise TypeError(
440 f"{method} requires a name or RRset as the first argument"
441 )
442 assert rdataset is not None # for type checkers
443 if rdataset.rdclass != self.manager.get_class():
444 raise ValueError(f"{method} has objects of wrong RdataClass")
445 if rdataset.rdtype == dns.rdatatype.SOA:
446 (_, _, origin) = self._origin_information()
447 if name != origin:
448 raise ValueError(f"{method} has non-origin SOA")
449 self._raise_if_not_empty(method, args)
450 if not replace:
451 existing = self._get_rdataset(name, rdataset.rdtype, rdataset.covers)
452 if existing is not None:
453 if isinstance(existing, dns.rdataset.ImmutableRdataset):
454 trds = dns.rdataset.Rdataset(
455 existing.rdclass, existing.rdtype, existing.covers
456 )
457 trds.update(existing)
458 existing = trds
459 rdataset = existing.union(rdataset)
460 self._checked_put_rdataset(name, rdataset)
461 except IndexError:
462 raise TypeError(f"not enough parameters to {method}")
463
464 def _delete(self, exact, args):
465 if exact:
466 method = "delete_exact()"
467 else:
468 method = "delete()"
469 try:
470 args = collections.deque(args)
471 arg = args.popleft()
472 if isinstance(arg, str):
473 arg = dns.name.from_text(arg, None)
474 if isinstance(arg, dns.name.Name):
475 name = arg
476 if len(args) > 0 and (
477 isinstance(args[0], int) or isinstance(args[0], str)
478 ):
479 # deleting by type and (optionally) covers
480 rdtype = dns.rdatatype.RdataType.make(args.popleft())
481 if len(args) > 0:
482 covers = dns.rdatatype.RdataType.make(args.popleft())
483 else:
484 covers = dns.rdatatype.NONE
485 self._raise_if_not_empty(method, args)
486 existing = self._get_rdataset(name, rdtype, covers)
487 if existing is None:
488 if exact:
489 raise DeleteNotExact(f"{method}: missing rdataset")
490 else:
491 self._checked_delete_rdataset(name, rdtype, covers)
492 return
493 else:
494 rdataset = self._rdataset_from_args(method, True, args)
495 elif isinstance(arg, dns.rrset.RRset):
496 rdataset = arg # rrsets are also rdatasets
497 name = rdataset.name
498 else:
499 raise TypeError(
500 f"{method} requires a name or RRset as the first argument"
501 )
502 self._raise_if_not_empty(method, args)
503 if rdataset:
504 if rdataset.rdclass != self.manager.get_class():
505 raise ValueError(f"{method} has objects of wrong RdataClass")
506 existing = self._get_rdataset(name, rdataset.rdtype, rdataset.covers)
507 if existing is not None:
508 if exact:
509 intersection = existing.intersection(rdataset)
510 if intersection != rdataset:
511 raise DeleteNotExact(f"{method}: missing rdatas")
512 rdataset = existing.difference(rdataset)
513 if len(rdataset) == 0:
514 self._checked_delete_rdataset(
515 name, rdataset.rdtype, rdataset.covers
516 )
517 else:
518 self._checked_put_rdataset(name, rdataset)
519 elif exact:
520 raise DeleteNotExact(f"{method}: missing rdataset")
521 else:
522 if exact and not self._name_exists(name):
523 raise DeleteNotExact(f"{method}: name not known")
524 self._checked_delete_name(name)
525 except IndexError:
526 raise TypeError(f"not enough parameters to {method}")
527
528 def _check_ended(self):
529 if self._ended:
530 raise AlreadyEnded
531
532 def _end(self, commit):
533 self._check_ended()
534 try:
535 self._end_transaction(commit)
536 finally:
537 self._ended = True
538
539 def _checked_put_rdataset(self, name, rdataset):
540 for check in self._check_put_rdataset:
541 check(self, name, rdataset)
542 self._put_rdataset(name, rdataset)
543
544 def _checked_delete_rdataset(self, name, rdtype, covers):
545 for check in self._check_delete_rdataset:
546 check(self, name, rdtype, covers)
547 self._delete_rdataset(name, rdtype, covers)
548
549 def _checked_delete_name(self, name):
550 for check in self._check_delete_name:
551 check(self, name)
552 self._delete_name(name)
553
554 #
555 # Transactions are context managers.
556 #
557
558 def __enter__(self):
559 return self
560
561 def __exit__(self, exc_type, exc_val, exc_tb):
562 if not self._ended:
563 if exc_type is None:
564 self.commit()
565 else:
566 self.rollback()
567 return False
568
569 #
570 # This is the low level API, which must be implemented by subclasses
571 # of Transaction.
572 #
573
574 def _get_rdataset(self, name, rdtype, covers):
575 """Return the rdataset associated with *name*, *rdtype*, and *covers*,
576 or `None` if not found.
577 """
578 raise NotImplementedError # pragma: no cover
579
580 def _put_rdataset(self, name, rdataset):
581 """Store the rdataset."""
582 raise NotImplementedError # pragma: no cover
583
584 def _delete_name(self, name):
585 """Delete all data associated with *name*.
586
587 It is not an error if the name does not exist.
588 """
589 raise NotImplementedError # pragma: no cover
590
591 def _delete_rdataset(self, name, rdtype, covers):
592 """Delete all data associated with *name*, *rdtype*, and *covers*.
593
594 It is not an error if the rdataset does not exist.
595 """
596 raise NotImplementedError # pragma: no cover
597
598 def _name_exists(self, name):
599 """Does name exist?
600
601 Returns a bool.
602 """
603 raise NotImplementedError # pragma: no cover
604
605 def _changed(self):
606 """Has this transaction changed anything?"""
607 raise NotImplementedError # pragma: no cover
608
609 def _end_transaction(self, commit):
610 """End the transaction.
611
612 *commit*, a bool. If ``True``, commit the transaction, otherwise
613 roll it back.
614
615 If committing and the commit fails, then roll back and raise an
616 exception.
617 """
618 raise NotImplementedError # pragma: no cover
619
620 def _set_origin(self, origin):
621 """Set the origin.
622
623 This method is called when reading a possibly relativized
624 source, and an origin setting operation occurs (e.g. $ORIGIN
625 in a zone file).
626 """
627 raise NotImplementedError # pragma: no cover
628
629 def _iterate_rdatasets(self):
630 """Return an iterator that yields (name, rdataset) tuples."""
631 raise NotImplementedError # pragma: no cover
632
633 def _iterate_names(self):
634 """Return an iterator that yields a name."""
635 raise NotImplementedError # pragma: no cover
636
637 def _get_node(self, name):
638 """Return the node at *name*, if any.
639
640 Returns a node or ``None``.
641 """
642 raise NotImplementedError # pragma: no cover
643
644 #
645 # Low-level API with a default implementation, in case a subclass needs
646 # to override.
647 #
648
649 def _origin_information(self):
650 # This is only used by _add()
651 return self.manager.origin_information()