diff.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. # Copyright (C) 2011 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. """
  16. This helps the XFR in process with accumulating parts of diff and applying
  17. it to the datasource.
  18. The name of the module is not yet fully decided. We might want to move it
  19. under isc.datasrc or somewhere else, because we might want to reuse it with
  20. future DDNS process. But until then, it lives here.
  21. """
  22. import isc.dns
  23. import isc.log
  24. from isc.log_messages.libxfrin_messages import *
  25. class NoSuchZone(Exception):
  26. """
  27. This is raised if a diff for non-existant zone is being created.
  28. """
  29. pass
  30. """
  31. This is the amount of changes we accumulate before calling Diff.apply
  32. automatically.
  33. The number 100 is just taken from BIND 9. We don't know the rationale
  34. for exactly this amount, but we think it is just some randomly chosen
  35. number.
  36. """
  37. # If changing this, modify the tests accordingly as well.
  38. DIFF_APPLY_TRESHOLD = 100
  39. logger = isc.log.Logger('libxfrin')
  40. class Diff:
  41. """
  42. The class represents a diff against current state of datasource on
  43. one zone. The usual way of working with it is creating it, then putting
  44. bunch of changes in and commiting at the end.
  45. If you change your mind, you can just stop using the object without
  46. really commiting it. In that case no changes will happen in the data
  47. sounce.
  48. The class works as a kind of a buffer as well, it does not direct
  49. the changes to underlying data source right away, but keeps them for
  50. a while.
  51. """
  52. def __init__(self, ds_client, zone, replace=False, journaling=False):
  53. """
  54. Initializes the diff to a ready state. It checks the zone exists
  55. in the datasource and if not, NoSuchZone is raised. This also creates
  56. a transaction in the data source.
  57. The ds_client is the datasource client containing the zone. Zone is
  58. isc.dns.Name object representing the name of the zone (its apex).
  59. If replace is True, the content of the whole zone is wiped out before
  60. applying the diff.
  61. If journaling is True, the history of subsequent updates will be
  62. recorded as well as the updates themselves as long as the underlying
  63. data source support the journaling. If the data source allows
  64. incoming updates but does not support journaling, the Diff object
  65. will still continue applying the diffs with disabling journaling.
  66. You can also expect isc.datasrc.Error or isc.datasrc.NotImplemented
  67. exceptions.
  68. """
  69. try:
  70. self.__updater = ds_client.get_updater(zone, replace, journaling)
  71. except isc.datasrc.NotImplemented as ex:
  72. if not journaling:
  73. raise ex
  74. self.__updater = ds_client.get_updater(zone, replace, False)
  75. logger.info(LIBXFRIN_NO_JOURNAL, zone, ds_client)
  76. if self.__updater is None:
  77. # The no such zone case
  78. raise NoSuchZone("Zone " + str(zone) +
  79. " does not exist in the data source " +
  80. str(ds_client))
  81. self.__buffer = []
  82. def __check_commited(self):
  83. """
  84. This checks if the diff is already commited or broken. If it is, it
  85. raises ValueError. This check is for methods that need to work only on
  86. yet uncommited diffs.
  87. """
  88. if self.__updater is None:
  89. raise ValueError("The diff is already commited or it has raised " +
  90. "an exception, you come late")
  91. def __data_common(self, rr, operation):
  92. """
  93. Schedules an operation with rr.
  94. It does all the real work of add_data and delete_data, including
  95. all checks.
  96. """
  97. self.__check_commited()
  98. if rr.get_rdata_count() != 1:
  99. raise ValueError('The rrset must contain exactly 1 Rdata, but ' +
  100. 'it holds ' + str(rr.get_rdata_count()))
  101. if rr.get_class() != self.__updater.get_class():
  102. raise ValueError("The rrset's class " + str(rr.get_class()) +
  103. " does not match updater's " +
  104. str(self.__updater.get_class()))
  105. self.__buffer.append((operation, rr))
  106. if len(self.__buffer) >= DIFF_APPLY_TRESHOLD:
  107. # Time to auto-apply, so the data don't accumulate too much
  108. self.apply()
  109. def add_data(self, rr):
  110. """
  111. Schedules addition of an RR into the zone in this diff.
  112. The rr is of isc.dns.RRset type and it must contain only one RR.
  113. If this is not the case or if the diff was already commited, this
  114. raises the ValueError exception.
  115. The rr class must match the one of the datasource client. If
  116. it does not, ValueError is raised.
  117. """
  118. self.__data_common(rr, 'add')
  119. def delete_data(self, rr):
  120. """
  121. Schedules deleting an RR from the zone in this diff.
  122. The rr is of isc.dns.RRset type and it must contain only one RR.
  123. If this is not the case or if the diff was already commited, this
  124. raises the ValueError exception.
  125. The rr class must match the one of the datasource client. If
  126. it does not, ValueError is raised.
  127. """
  128. self.__data_common(rr, 'delete')
  129. def compact(self):
  130. """
  131. Tries to compact the operations in buffer a little by putting some of
  132. the operations together, forming RRsets with more than one RR.
  133. This is called by apply before putting the data into datasource. You
  134. may, but not have to, call this manually.
  135. Currently it merges consecutive same operations on the same
  136. domain/type. We could do more fancy things, like sorting by the domain
  137. and do more merging, but such diffs should be rare in practice anyway,
  138. so we don't bother and do it this simple way.
  139. """
  140. buf = []
  141. for (op, rrset) in self.__buffer:
  142. old = buf[-1][1] if len(buf) > 0 else None
  143. if old is None or op != buf[-1][0] or \
  144. rrset.get_name() != old.get_name() or \
  145. rrset.get_type() != old.get_type():
  146. buf.append((op, isc.dns.RRset(rrset.get_name(),
  147. rrset.get_class(),
  148. rrset.get_type(),
  149. rrset.get_ttl())))
  150. if rrset.get_ttl() != buf[-1][1].get_ttl():
  151. logger.warn(LIBXFRIN_DIFFERENT_TTL, rrset.get_ttl(),
  152. buf[-1][1].get_ttl())
  153. for rdatum in rrset.get_rdata():
  154. buf[-1][1].add_rdata(rdatum)
  155. self.__buffer = buf
  156. def apply(self):
  157. """
  158. Push the buffered changes inside this diff down into the data source.
  159. This does not stop you from adding more changes later through this
  160. diff and it does not close the datasource transaction, so the changes
  161. will not be shown to others yet. It just means the internal memory
  162. buffer is flushed.
  163. This is called from time to time automatically, but you can call it
  164. manually if you really want to.
  165. This raises ValueError if the diff was already commited.
  166. It also can raise isc.datasrc.Error. If that happens, you should stop
  167. using this object and abort the modification.
  168. """
  169. self.__check_commited()
  170. # First, compact the data
  171. self.compact()
  172. try:
  173. # Then pass the data inside the data source
  174. for (operation, rrset) in self.__buffer:
  175. if operation == 'add':
  176. self.__updater.add_rrset(rrset)
  177. elif operation == 'delete':
  178. self.__updater.delete_rrset(rrset)
  179. else:
  180. raise ValueError('Unknown operation ' + operation)
  181. # As everything is already in, drop the buffer
  182. except:
  183. # If there's a problem, we can't continue.
  184. self.__updater = None
  185. raise
  186. self.__buffer = []
  187. def commit(self):
  188. """
  189. Writes all the changes into the data source and makes them visible.
  190. This closes the diff, you may not use it any more. If you try to use
  191. it, you'll get ValueError.
  192. This might raise isc.datasrc.Error.
  193. """
  194. self.__check_commited()
  195. # Push the data inside the data source
  196. self.apply()
  197. # Make sure they are visible.
  198. try:
  199. self.__updater.commit()
  200. finally:
  201. # Remove the updater. That will free some resources for one, but
  202. # mark this object as already commited, so we can check
  203. # We delete it even in case the commit failed, as that makes us
  204. # unusable.
  205. self.__updater = None
  206. def get_buffer(self):
  207. """
  208. Returns the current buffer of changes not yet passed into the data
  209. source. It is in a form like [('add', rrset), ('delete', rrset),
  210. ('delete', rrset), ...].
  211. Probably useful only for testing and introspection purposes. Don't
  212. modify the list.
  213. """
  214. return self.__buffer