<s> from collections import deque <EOL> import gaffer . tornado_pyuv as ioloop <EOL> class MovingAverage ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , period = <NUM_LIT:10> ) : <EOL> """<STR_LIT>""" <EOL> self . period = period <EOL> self . stream = deque ( ) <EOL> self . sum = <NUM_LIT:0> <EOL> self . accumulator = <NUM_LIT:0> <EOL> self . last_average = <NUM_LIT:0> <EOL> def add ( self , n ) : <EOL> """<STR_LIT>""" <EOL> self . accumulator += n <EOL> def flush ( self ) : <EOL> """<STR_LIT>""" <EOL> n = self . accumulator <EOL> self . accumulator = <NUM_LIT:0> <EOL> stream = self . stream <EOL> stream . append ( n ) <EOL> self . sum += n <EOL> streamlen = len ( stream ) <EOL> if streamlen > self . period : <EOL> self . sum -= stream . popleft ( ) <EOL> streamlen -= <NUM_LIT:1> <EOL> if streamlen == <NUM_LIT:0> : <EOL> self . last_average = <NUM_LIT:0> <EOL> else : <EOL> self . last_average = self . sum / float ( streamlen ) <EOL> class StatsCollector ( object ) : <EOL> def __init__ ( self , io_loop ) : <EOL> self . sess_active = <NUM_LIT:0> <EOL> self . sess_transports = dict ( ) <EOL> self . conn_active = <NUM_LIT:0> <EOL> self . conn_ps = MovingAverage ( ) <EOL> self . pack_sent_ps = MovingAverage ( ) <EOL> self . pack_recv_ps = MovingAverage ( ) <EOL> self . _callback = ioloop . PeriodicCallback ( self . _update , <EOL> <NUM_LIT:1000> , <EOL> io_loop ) <EOL> self . _callback . start ( ) <EOL> self . _callback . _timer . unref ( ) <EOL> def _update ( self ) : <EOL> self . conn_ps . flush ( ) <EOL> self . pack_sent_ps . flush ( ) <EOL> self . pack_recv_ps . flush ( ) <EOL> def dump ( self ) : <EOL> """<STR_LIT>""" <EOL> data = dict ( <EOL> sessions_active = self . sess_active , <EOL> connections_active = self . conn_active , <EOL> connections_ps = self . conn_ps . last_average , <EOL> packets_sent_ps = self . pack_sent_ps . last_average , <EOL> packets_recv_ps = self . pack_recv_ps . last_average <EOL> ) <EOL> for k , v in self . sess_transports . iteritems ( ) : <EOL> data [ '<STR_LIT>' + k ] = v <EOL> return data <EOL> def on_sess_opened ( self , transport ) : <EOL> self . sess_active += <NUM_LIT:1> <EOL> if transport not in self . sess_transports : <EOL> self . sess_transports [ transport ] = <NUM_LIT:0> <EOL> self . sess_transports [ transport ] += <NUM_LIT:1> <EOL> def on_sess_closed ( self , transport ) : <EOL> self . sess_active -= <NUM_LIT:1> <EOL> self . sess_transports [ transport ] -= <NUM_LIT:1> <EOL> def on_conn_opened ( self ) : <EOL> self . conn_active += <NUM_LIT:1> <EOL> self . conn_ps . add ( <NUM_LIT:1> ) <EOL> def on_conn_closed ( self ) : <EOL> self . conn_active -= <NUM_LIT:1> <EOL> def on_pack_sent ( self , num ) : <EOL> self . pack_sent_ps . add ( num ) <EOL> def on_pack_recv ( self , num ) : <EOL> self . pack_recv_ps . add ( num ) </s>
