7 from collections import deque
9 from twisted.internet import reactor, defer
10 from twisted.application import service
11 from twisted.application.internet import TimerService
12 from zope.interface import implements
14 from foolscap.logging.gatherer import get_local_ip_for
16 from allmydata.util import log
17 from allmydata.interfaces import RIStatsProvider, RIStatsGatherer, IStatsProducer
19 class LoadMonitor(service.MultiService):
20 implements(IStatsProducer)
25 def __init__(self, provider, warn_if_delay_exceeds=1):
26 service.MultiService.__init__(self)
27 self.provider = provider
28 self.warn_if_delay_exceeds = warn_if_delay_exceeds
33 def startService(self):
36 reactor.callLater(self.loop_interval, self.loop)
37 service.MultiService.startService(self)
39 def stopService(self):
46 if self.last is not None:
47 delay = now - self.last - self.loop_interval
48 if delay > self.warn_if_delay_exceeds:
49 log.msg(format='excessive reactor delay (%ss)', args=(delay,),
51 self.stats.append(delay)
52 while len(self.stats) > self.num_samples:
56 reactor.callLater(self.loop_interval, self.loop)
60 avg = sum(self.stats) / len(self.stats)
64 return { 'load_monitor.avg_load': avg,
65 'load_monitor.max_load': m_x, }
67 class StatsProvider(foolscap.Referenceable, service.MultiService):
68 implements(RIStatsProvider)
70 def __init__(self, node, gatherer_furl):
71 service.MultiService.__init__(self)
73 self.gatherer_furl = gatherer_furl
76 self.stats_producers = []
78 self.load_monitor = LoadMonitor(self)
79 self.load_monitor.setServiceParent(self)
80 self.register_producer(self.load_monitor)
82 def startService(self):
84 d = self.node.when_tub_ready()
86 nickname = self.node.get_config('nickname')
87 self.node.tub.connectTo(self.gatherer_furl, self._connected, nickname)
88 d.addCallback(connect)
89 service.MultiService.startService(self)
91 def count(self, name, delta):
92 val = self.counters.setdefault(name, 0)
93 self.counters[name] = val + delta
95 def register_producer(self, stats_producer):
96 self.stats_producers.append(IStatsProducer(stats_producer))
98 def remote_get_stats(self):
100 for sp in self.stats_producers:
101 stats.update(sp.get_stats())
102 return { 'counters': self.counters, 'stats': stats }
104 def _connected(self, gatherer, nickname):
105 gatherer.callRemote('provide', self, nickname or '')
107 class StatsGatherer(foolscap.Referenceable, service.MultiService):
108 implements(RIStatsGatherer)
112 def __init__(self, tub):
113 service.MultiService.__init__(self)
119 def startService(self):
120 self.timer = TimerService(self.poll_interval, self.poll)
121 self.timer.setServiceParent(self)
122 service.MultiService.startService(self)
125 return self.tub.registerReference(self, furlFile='stats_gatherer.furl')
127 def get_tubid(self, rref):
128 return foolscap.SturdyRef(rref.tracker.getURL()).getTubRef().getTubID()
130 def remote_provide(self, provider, nickname):
131 tubid = self.get_tubid(provider)
132 if tubid == '<unauth>':
133 print "WARNING: failed to get tubid for %s (%s)" % (provider, nickname)
134 # don't add to clients to poll (polluting data) don't care about disconnect
136 self.clients[tubid] = provider
137 self.nicknames[tubid] = nickname
138 provider.notifyOnDisconnect(self.lost_client, tubid)
140 def lost_client(self, tubid):
141 del self.clients[tubid]
142 del self.nicknames[tubid]
145 for tubid,client in self.clients.items():
146 nickname = self.nicknames.get(tubid)
147 d = client.callRemote('get_stats')
148 d.addCallback(self.got_stats, tubid, nickname)
150 def got_stats(self, stats, tubid, nickname):
151 raise NotImplementedError()
153 class StdOutStatsGatherer(StatsGatherer):
154 def remote_provide(self, provider, nickname):
155 tubid = self.get_tubid(provider)
156 print 'connect "%s" [%s]' % (nickname, tubid)
157 StatsGatherer.remote_provide(self, provider, nickname)
159 def lost_client(self, tubid):
160 print 'disconnect "%s" [%s]:' % (self.nicknames[tubid], tubid)
161 StatsGatherer.lost_client(self, tubid)
163 def got_stats(self, stats, tubid, nickname):
164 print '"%s" [%s]:' % (nickname, tubid)
167 class PickleStatsGatherer(StdOutStatsGatherer): # for connect/disconnect notifications;
168 #class PickleStatsGatherer(StatsGatherer):
169 def __init__(self, tub, picklefile):
170 StatsGatherer.__init__(self, tub)
171 self.picklefile = picklefile
173 if os.path.exists(picklefile):
174 f = open(picklefile, 'rb')
175 self.gathered_stats = pickle.load(f)
178 self.gathered_stats = {}
180 def got_stats(self, stats, tubid, nickname):
181 s = self.gathered_stats.setdefault(tubid, {})
182 s['timestamp'] = time.time()
183 s['nickname'] = nickname
187 def dump_pickle(self):
188 tmp = "%s.tmp" % (self.picklefile,)
190 pickle.dump(self.gathered_stats, f)
192 if os.path.exists(self.picklefile):
193 os.unlink(self.picklefile)
194 os.rename(tmp, self.picklefile)
196 class GathererApp(object):
199 d.addCallback(self._tub_ready)
202 self._tub = foolscap.Tub(certFile="stats_gatherer.pem")
203 self._tub.setOption("logLocalFailures", True)
204 self._tub.setOption("logRemoteFailures", True)
205 self._tub.startService()
206 portnumfile = "portnum"
208 portnum = int(open(portnumfile, "r").read())
209 except (EnvironmentError, ValueError):
211 self._tub.listenOn("tcp:%d" % portnum)
212 d = defer.maybeDeferred(get_local_ip_for)
213 d.addCallback(self._set_location)
214 d.addCallback(lambda res: self._tub)
217 def _set_location(self, local_address):
218 if local_address is None:
219 local_addresses = ["127.0.0.1"]
221 local_addresses = [local_address, "127.0.0.1"]
222 l = self._tub.getListeners()[0]
223 portnum = l.getPortnum()
224 portnumfile = "portnum"
225 open(portnumfile, "w").write("%d\n" % portnum)
226 local_addresses = [ "%s:%d" % (addr, portnum,)
227 for addr in local_addresses ]
228 assert len(local_addresses) >= 1
229 location = ",".join(local_addresses)
230 self._tub.setLocation(location)
232 def _tub_ready(self, tub):
233 sg = PickleStatsGatherer(tub, 'stats.pickle')
234 sg.setServiceParent(tub)
236 print '\nStatsGatherer: %s\n' % (sg.get_furl(),)
242 if __name__ == '__main__':