This callback can be stacked with another one, and will filter duplicate results.
Signed-off-by: Guido Trotter <[email protected]> --- lib/confd/client.py | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 78 insertions(+), 0 deletions(-) diff --git a/lib/confd/client.py b/lib/confd/client.py index 53d1673..537921b 100644 --- a/lib/confd/client.py +++ b/lib/confd/client.py @@ -271,3 +271,81 @@ class ConfdClientRequest(objects.ConfdRequest): if self.type not in constants.CONFD_REQS: raise errors.ConfdClientError("Invalid request type") + +class ConfdFilterCallback: + """Callback that calls another callback, but filters duplicate results. + + """ + def __init__(self, callback, logger=None): + """Constructor for ConfdFilterCallback + + @type callback: f(L{ConfdUpcallPayload}) + @param callback: function to call when getting answers + @type logger: L{logging.Logger} + @keyword logger: optional logger for internal conditions + + """ + if not callable(callback): + raise errors.ProgrammerError("callback must be callable") + + self._callback = callback + self._logger = logger + # answers contains a dict of salt -> answer + self._answers = {} + + def _LogFilter(self, salt, new_reply, old_reply): + if not self._logger: + return + + if new_reply.serial > old_reply.serial: + self._logger.debug("Filtering confirming answer, with newer" + - " serial for query %s" % salt) + elif new_reply.serial == old_reply.serial: + if new_reply.answer != old_reply.answer: + self._logger.debug("Got incoherent answers for query %s" + " (serial: %s)" % (salt, new_reply.serial)) + else: + self._logger.debug("Filtering confirming answer, with same" + " serial for query %s" % salt) + else: + self._logger.debug("Filtering outdated answer for query %s" + " serial: (%d < %d)" % (salt, old_reply.serial, + new_reply.serial)) + + def _HandleExpire(self, up): + if salt in self._answers: + del self._answers[salt] + + def _HandleReply(self, up): + filter_upcall = False + salt = up.salt + if salt not in self._answers: + self._answers[salt] = up.server_reply + elif up.server_reply.serial > self._answers[salt].serial: + old_answer = self._answers[salt] + self._answers[salt] = up.server_reply + if up.server_reply.answer == old_answer.answer: + filter_upcall = True + self._LogFilter(self, salt, up.server_reply, old_answer) + else: + filter_upcall = True + self._LogFilter(self, salt, up.server_reply, self._answers[salt]) + + return filter_upcall + + def __call__(self, up): + """Filtering callback + + @type up: L{ConfdUpcallPayload} + @param up: upper callback + + """ + filter_upcall = False + if up.type == UPCALL_REPLY: + filter_upcall = self._HandleReply(up) + elif up.type == UPCALL_EXPIRE: + self._HandleExpire(up) + + if not filter_upcall: + self._callback(up) + -- 1.6.3.3
