<s> import cStringIO <EOL> import sys <EOL> import time <EOL> from gevent import socket <EOL> E_BADSPEC = "<STR_LIT>" <EOL> E_SENDFAIL = '<STR_LIT>' <EOL> class Sink ( object ) : <EOL> """<STR_LIT>""" <EOL> def error ( self , msg ) : <EOL> sys . stderr . write ( msg + '<STR_LIT:\n>' ) <EOL> def _parse_hostport ( self , spec ) : <EOL> try : <EOL> parts = spec . split ( '<STR_LIT::>' ) <EOL> if len ( parts ) == <NUM_LIT:2> : <EOL> return ( parts [ <NUM_LIT:0> ] , int ( parts [ <NUM_LIT:1> ] ) ) <EOL> if len ( parts ) == <NUM_LIT:1> : <EOL> return ( '<STR_LIT>' , int ( parts [ <NUM_LIT:0> ] ) ) <EOL> except ValueError , ex : <EOL> raise ValueError ( E_BADSPEC % ( spec , ex ) ) <EOL> raise ValueError ( "<STR_LIT>" % spec ) <EOL> class GraphiteSink ( Sink ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> self . _hosts = [ ] <EOL> def add ( self , spec ) : <EOL> self . _hosts . append ( self . _parse_hostport ( spec ) ) <EOL> def send ( self , stats ) : <EOL> "<STR_LIT>" <EOL> buf = cStringIO . StringIO ( ) <EOL> now = int ( time . time ( ) ) <EOL> num_stats = <NUM_LIT:0> <EOL> pct = stats . percent <EOL> timers = stats . timers <EOL> for key , vals in timers . iteritems ( ) : <EOL> if not vals : <EOL> continue <EOL> num = len ( vals ) <EOL> vals = sorted ( vals ) <EOL> vmin = vals [ <NUM_LIT:0> ] <EOL> vmax = vals [ - <NUM_LIT:1> ] <EOL> mean = vmin <EOL> max_at_thresh = vmax <EOL> if num > <NUM_LIT:1> : <EOL> idx = round ( ( pct / <NUM_LIT> ) * num ) <EOL> tmp = vals [ : int ( idx ) ] <EOL> if tmp : <EOL> max_at_thresh = tmp [ - <NUM_LIT:1> ] <EOL> mean = sum ( tmp ) / idx <EOL> key = '<STR_LIT>' % key <EOL> buf . write ( '<STR_LIT>' % ( key , mean , now ) ) <EOL> buf . write ( '<STR_LIT>' % ( key , vmax , now ) ) <EOL> buf . write ( '<STR_LIT>' % ( key , pct , max_at_thresh , now ) ) <EOL> buf . write ( '<STR_LIT>' % ( key , vmin , now ) ) <EOL> buf . write ( '<STR_LIT>' % ( key , num , now ) ) <EOL> num_stats += <NUM_LIT:1> <EOL> counts = stats . counts <EOL> for key , val in counts . iteritems ( ) : <EOL> buf . write ( '<STR_LIT>' % ( key , val / stats . interval , now ) ) <EOL> buf . write ( '<STR_LIT>' % ( key , val , now ) ) <EOL> num_stats += <NUM_LIT:1> <EOL> gauges = stats . gauges <EOL> for key , val in gauges . iteritems ( ) : <EOL> buf . write ( '<STR_LIT>' % ( key , val , now ) ) <EOL> buf . write ( '<STR_LIT>' % ( key , val , now ) ) <EOL> num_stats += <NUM_LIT:1> <EOL> buf . write ( '<STR_LIT>' % ( num_stats , now ) ) <EOL> for host in self . _hosts : <EOL> try : <EOL> sock = socket . create_connection ( host ) <EOL> sock . sendall ( buf . getvalue ( ) ) <EOL> sock . close ( ) <EOL> except Exception , ex : <EOL> self . error ( E_SENDFAIL % ( '<STR_LIT>' , host , ex ) ) </s>
