1
from twisted.internet.defer import maybeDeferred
2
from twisted.internet.task import LoopingCall
3
from twisted.python import log
5
from functools import wraps
7
from twisted.application.service import Service
10
class ReportingService(Service):
15
def schedule(self, function, interval, report_function):
17
Schedule C{function} to be called every C{interval} seconds and then
18
report gathered metrics to C{Graphite} using C{report_function}.
20
task = LoopingCall(self.wrapped(function, report_function))
21
self.tasks.append((task, interval))
23
def wrapped(self, function, report_function):
24
def report_metrics(metrics):
25
"""For each metric returned, call C{report_function} with it."""
26
for name, value in metrics.items():
27
report_function(name, value)
32
"""Wrap C{function} to report metrics or log a failure."""
33
deferred = maybeDeferred(function)
34
deferred.addCallback(report_metrics)
35
deferred.addErrback(lambda failure: log.err(
36
failure, "Error while processing %s" % function.func_name))
40
def startService(self):
41
for task, interval in self.tasks:
42
task.start(interval, now=False)
44
def stopService(self):
45
for task, interval in self.tasks: