496a7fd0ed3a77b6f0a6e6b43e8aed811139f6c0
[influxdb-pipes] / ifstat.pl
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4 use autodie;
5
6 my $host = shift @ARGV || die "usage: INFLUX=http://127.0.0.1:8086/write?db=snmp COMMUNITY=snmp-comminity $0 host";
7 my $community = $ENV{COMMUNITY} || 'public';
8 my $influx    = $ENV{INFLUX} || 'http://127.0.0.1:8086/write?db=snmp';
9
10 use Data::Dump qw(dump);
11 sub XXX { warn "XXX ",scalar @_, Data::Dump::dump(@_) };
12
13 my ($sec,$min,$hour,$dd,$mm,$yyyy) = localtime(time); $mm++;
14 my $time;
15 use Time::Local;
16 sub update_time {
17         warn "# time $yyyy-$mm-$dd $hour:$min:$sec $time\n";
18         $time = timelocal($sec,$min,$hour,$dd,$mm-1,$yyyy) * 1000_000_000;
19         return $time;
20 }
21
22 # FIXME add -A to pull interfaces if they go up and down
23 # -l loopback
24 # -a all
25 my $cmd = qq{ifstat -s '$community@#$host' -b -n -t 1};
26 warn "# $cmd\n";
27 open(my $ifstat, '-|', $cmd);
28
29 my $first_skipped = 0;
30
31 my $curl;
32 sub reopen_curl {
33         if ( $ENV{INFLUX} ) {
34                 open($curl, '|-', qq( curl -i -XPOST $influx --data-binary \@- ));
35         } else {
36                 open($curl, '|-', 'cat');
37         }
38 }
39
40 my $stat;
41
42 my @if;
43 my @direction;
44
45 my $lines;
46
47 while(<$ifstat>) {
48         chomp;
49         #warn "# [$_]\n";
50         s/^\s+//;
51         s/(\w) (in|out)/$1_$2/g;
52         my @v = split(/\s+/);
53         if ( $v[0] eq 'Time' ) {
54                 shift @v;
55                 @if = @v;
56         } elsif ( $v[0] eq 'HH:MM:SS' ) {
57                 shift @v;
58                 @direction = map { s/\W+/_/g; s/^K//; $_ } @v;
59         } elsif ( $v[0] =~ m/^(\d\d):(\d\d):(\d\d)/ ) {
60                 next unless $first_skipped++;
61 XXX $stat;
62                 $hour = $1; $min = $2; $sec = $3; update_time;
63
64                 reopen_curl;
65                 my $total;
66
67                 foreach my $i ( 0 .. $#if ) {
68
69                         my $port = $if[$i];
70                         my $vlan = '';
71                         my $is_port = 'T';
72                         $vlan = ",vlan=$1" if $port =~ m/if(\d\d\d\d\d\d)/;
73
74                         print $curl "ifstat,host=$host,port=$port$vlan ",
75                                 $direction[$i*2],   "=", $v[$i*2+1]   * 1024, ",",
76                                 $direction[$i*2+1], "=", $v[$i*2+2] * 1024,
77                                 " $time\n";
78
79                         $total += $v[$i*2+1];
80
81                         $lines++;
82                 }
83
84                 warn "# $host ", $curl->tell, " total=$total\n";
85                 close($curl);
86         } else {
87                 die "UNPARSED [$_]";
88         }
89 }
90
91