~landscape/txstatsd/trunk

« back to all changes in this revision

Viewing changes to txstatsd/report.py

  • Committer: Sidnei da Silva
  • Date: 2011-07-27 20:35:23 UTC
  • mfrom: (11.2.6 txstatsd)
  • Revision ID: sidnei.da.silva@canonical.com-20110727203523-mmhr5clzkfyqva8f
- Merge from lp:txstatsd

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
from twisted.internet.defer import maybeDeferred
2
 
from twisted.internet.task import LoopingCall
3
 
from twisted.python import log
4
 
 
5
 
from functools import wraps
6
 
 
7
 
from twisted.application.service import Service
8
 
 
9
 
 
10
 
class ReportingService(Service):
11
 
 
12
 
    def __init__(self):
13
 
        self.tasks = []
14
 
 
15
 
    def schedule(self, function, interval, report_function):
16
 
        """
17
 
        Schedule C{function} to be called every C{interval} seconds and then
18
 
        report gathered metrics to C{Graphite} using C{report_function}.
19
 
        """
20
 
        task = LoopingCall(self.wrapped(function, report_function))
21
 
        self.tasks.append((task, interval))
22
 
 
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)
28
 
            return metrics
29
 
 
30
 
        @wraps(function)
31
 
        def wrapper():
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))
37
 
            return deferred
38
 
        return wrapper
39
 
 
40
 
    def startService(self):
41
 
        for task, interval in self.tasks:
42
 
            task.start(interval, now=False)
43
 
 
44
 
    def stopService(self):
45
 
        for task, interval in self.tasks:
46
 
            task.stop()