Skip to content

Instantly share code, notes, and snippets.

@gabrik
Last active September 18, 2020 15:46
Show Gist options
  • Save gabrik/87d4ae5dadb262709ccaedd5880bb031 to your computer and use it in GitHub Desktop.
Save gabrik/87d4ae5dadb262709ccaedd5880bb031 to your computer and use it in GitHub Desktop.
Machine monitoring to csv
#!/usr/bin/perl
if ($#ARGV != 0 ) {
printf "usage: stat <container number>\n";
exit;
}
$cont=$ARGV[0];
open HOSTNAME, "hostname |";
$hostname = <HOSTNAME>;
$hostname =~ s/\n//g;
$filename = sprintf(">stat-%s-%s.csv", $hostname,$cont);
open WAN, "ip route |";
$wan = <WAN>;
@wan = split(' ',$wan);
# printf "%s",$wan[4];
$wan = $wan[4];
close WAN;
open FILE, $filename or die "Cannot open stat file";
printf "Monitoring started on %s\n", $hostname;
# printf "TIME,FREE,USED,TOTAL,CPU,LOAD_AVERAGE_1MIN,HOSTNAME,CONTAINERS,TX_RATE,RX_RATE\n";
printf FILE "TIME,FREE,USED,TOTAL,CPU,LOAD_AVERAGE_1MIN,HOSTNAME,CONTAINERS,TX_RATE,RX_RATE\n";
close FILE;
$wan_stat_tx = sprintf "cat /sys/class/net/%s/statistics/tx_bytes | ", $wan;
$wan_stat_rx = sprintf "cat /sys/class/net/%s/statistics/rx_bytes | ", $wan;
open RX,$wan_stat_rx;
open TX, $wan_stat_tx;
$tx_data = <TX>;
$rx_data = <RX>;
close TX;
close RX;
sleep 1;
open VMSTAT, "vmstat 1|";
<VMSTAT>; <VMSTAT>; # skip the header
while (<VMSTAT>) {
@now = split;
open RX, $wan_stat_rx;
open TX, $wan_stat_tx;
$tx_data_now = <TX> ;
$rx_data_now = <RX>;
close TX;
close RX;
$tx_rate = $tx_data_now - $tx_data;
$rx_rate = $rx_data_now - $rx_data;
$tx_data = $tx_data_now;
$rx_data = $rx_data_now;
$filename = sprintf(">>stat-%s-%s.csv", $hostname,$cont);
open FILE, $filename or die "Cannot open stat file";
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime (time);
open UPTIME, "uptime |";
open FREE,"free |";
<FREE>;
$data = <FREE>;
$uptime_data = <UPTIME>;
#printf "Data: %s\n", $data;
@mem = split(' ',$data);
@load_avg = split(' ',$uptime_data);
#printf "Load: %s\n", $load_avg[11];
printf FILE "%d-%02d-%02d %02d:%02d:%02d,%d,%d,%d,%d,%f,%s,%s,%d,%d\n", $year+1900, $mon, $mday, $hour, $min, $sec,
$now[3],$mem[2], $mem[1], $now[12] + $now[13], $load_avg[-3], $hostname,$cont,$tx_rate, $rx_rate;
# printf "%d-%02d-%02d %02d:%02d:%02d,%d,%d,%d,%d,%f,%s,%s,%d,%d\n", $year+1900, $mon, $mday, $hour, $min, $sec,
# $now[3],$mem[2], $mem[1], $now[12] + $now[13], $load_avg[-3], $hostname, $cont, $tx_rate, $rx_rate;
close FILE;
close FREE;
close UPTIME;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment