<s> """<STR_LIT>""" <EOL> from collections import defaultdict <EOL> import diamond . collector <EOL> try : <EOL> import psutil <EOL> except ImportError : <EOL> psutil = None <EOL> def get_port_stats ( port ) : <EOL> """<STR_LIT>""" <EOL> cnts = defaultdict ( int ) <EOL> for c in psutil . net_connections ( ) : <EOL> c_port = c . laddr [ <NUM_LIT:1> ] <EOL> if c_port != port : <EOL> continue <EOL> status = c . status . lower ( ) <EOL> cnts [ status ] += <NUM_LIT:1> <EOL> return cnts <EOL> class PortStatCollector ( diamond . collector . Collector ) : <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> super ( PortStatCollector , self ) . __init__ ( * args , ** kwargs ) <EOL> self . ports = { } <EOL> for port_name , cfg in self . config [ '<STR_LIT:port>' ] . items ( ) : <EOL> port_cfg = { } <EOL> for key in ( '<STR_LIT>' , ) : <EOL> port_cfg [ key ] = cfg . get ( key , [ ] ) <EOL> self . ports [ port_name ] = port_cfg <EOL> def get_default_config_help ( self ) : <EOL> config_help = super ( PortStatCollector , self ) . get_default_config_help ( ) <EOL> config_help . update ( { <EOL> } ) <EOL> return config_help <EOL> def get_default_config ( self ) : <EOL> config = super ( PortStatCollector , self ) . get_default_config ( ) <EOL> config . update ( { <EOL> '<STR_LIT:path>' : '<STR_LIT:port>' , <EOL> '<STR_LIT:port>' : { } , <EOL> } ) <EOL> return config <EOL> def collect ( self ) : <EOL> """<STR_LIT>""" <EOL> if psutil is None : <EOL> self . log . error ( '<STR_LIT>' ) <EOL> return { } <EOL> for port_name , port_cfg in self . ports . iteritems ( ) : <EOL> port = int ( port_cfg [ '<STR_LIT>' ] ) <EOL> stats = get_port_stats ( port ) <EOL> for stat_name , stat_value in stats . iteritems ( ) : <EOL> metric_name = '<STR_LIT>' % ( port_name , stat_name ) <EOL> self . publish ( metric_name , stat_value ) </s>
