summaryrefslogtreecommitdiff
path: root/tests/responsiveness/watchdog.py
blob: 88f4fa67a81dea26b24126481dc4e1ec535fa5aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from twisted.internet import defer, reactor
from twisted.internet.task import LoopingCall
from twisted.internet.threads import deferToThread


class Watchdog(object):

    DEBUG = False

    def __init__(self, delay=0.01):
        self.delay = delay
        self.loop_call = LoopingCall.withCount(self.watch)
        self.blocked = 0
        self.checks = []
        self.d = None

    def start(self):
        self.debug("\n[watchdog] starting")
        self.loop_call.start(self.delay)
        self.d = defer.Deferred()
        return self.d

    def watch(self, count):
        self.debug("[watchdog] watching (%d)" % count)
        if (self.loop_call.running):
            self.checks.append(deferToThread(self._check, count))

    def _check(self, count):
        # self.debug("[watchdog] _checking (%d)" % count)
        if count > 1:
            self.blocked += count

    def stop(self):
        # delay the actual stop so we make sure at least one check watch will
        # run in the reactor.
        reactor.callLater(2 * self.delay, self._stop)

    @defer.inlineCallbacks
    def _stop(self):
        if not self.loop_call.running:
            return

        self.loop_call.stop()
        yield defer.gatherResults(self.checks)
        self.d.callback(None)

    @property
    def seconds_blocked(self):
        return self.blocked * self.delay

    def debug(self, s):
        if self.DEBUG:
            print(s)