Skip to content

Instantly share code, notes, and snippets.

@mtak
Last active August 29, 2015 14:03
Show Gist options
  • Save mtak/1cddb08d191045e66a9c to your computer and use it in GitHub Desktop.
Save mtak/1cddb08d191045e66a9c to your computer and use it in GitHub Desktop.
Send Vyatta interface statistics to Graphite/Carbon
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
use IO::Socket::INET;
use POSIX;
my $carbon_host = "10.100.0.61";
my $carbon_port = "2003";
# Collect statistics
# Calculate delta
# Send to Carbon
our %data;
our $interval = 10;
sub collect_data {
open(my $fh, '-|', '/sbin/ifconfig') or die $!;
my $interface = '';
while (my $line = <$fh>) {
if ( $line =~ m/^(\S+)\s+/o ) {
$interface = $1;
}
if ( $line =~ m/RX bytes:(\d+).*TX bytes:(\d+)/o ) {
$data{$interface}{'rx'} = $1;
$data{$interface}{'tx'} = $2;
}
}
}
sub calculate_delta {
# Open socket
# auto-flush on socket
$| = 1;
# create a connecting socket
my $socket = new IO::Socket::INET (
PeerHost => $carbon_host,
PeerPort => $carbon_port,
Proto => 'tcp',
);
die "cannot connect to the server $!\n" unless $socket;
# Iterate over all interfaces and calculate the difference
foreach my $interface ( keys %data ) {
# Skip if there is no last rx and tx
if ( (! exists $data{$interface}{'last_rx'}) || (! exists $data{$interface}{'last_tx'}) ) {
$data{$interface}{'last_rx'} = $data{$interface}{'rx'};
$data{$interface}{'last_tx'} = $data{$interface}{'tx'};
next;
}
my $current_rx = $data{$interface}{'rx'};
my $current_tx = $data{$interface}{'tx'};
my $rx_delta = ceil(( $data{$interface}{'rx'} - $data{$interface}{'last_rx'} ) / $interval);
my $tx_delta = ceil(( $data{$interface}{'tx'} - $data{$interface}{'last_tx'} ) / $interval);
send_to_graphite("test.dr1.${interface}.rx", $rx_delta, $socket);
send_to_graphite("test.dr1.${interface}.tx", $tx_delta, $socket);
$data{$interface}{'last_rx'} = $data{$interface}{'rx'};
$data{$interface}{'last_tx'} = $data{$interface}{'tx'};
}
$socket->shutdown(2);
$socket->close();
}
sub send_to_graphite {
(my $label, my $value, my $socket) = @_;
my $timestamp = time();
my $string_to_send = "$label $value $timestamp\n";
# data to send to a server
my $size = $socket->send($string_to_send);
}
while (1==1) {
collect_data();
calculate_delta();
sleep $interval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment