#!/usr/bin/perl
use strict;
use Sys::Hostname;

my $cgbin;
my $zsbin;
my $zconfig;
my %daemons = (
    'httpd' => [],
    'mysqld' => [],
    'named' => [],
    'sshd' => [],
    'dovecot' => [],
    'exim' => [],
);
my %data;
my %old;


checks();
populate();
collect();
get_old_data();
generate_report();
tell_zabbix();


sub checks { 
    # make sure things we need are there, collect some data we need to send our info to zabbix
    if ( ! -d '/sys/fs/cgroup' ) {
        die "[!] cgroups are not enabled!\n";
    }
    chomp($cgbin = `/usr/bin/which cgclassify 2>/dev/null`);
    if ( ! -x $cgbin ) {
        die "[!] cgclassify binary is not installed! You need to yum install libcgroup\n";
    }
    chomp($zsbin = `/usr/bin/which zabbix_sender 2>/dev/null`);
    if ( ! $zsbin ) {
        my @locations = (
            '/usr/bin/zabbix_sender',
            '/opt/zabbix/bin/zabbix_sender'
        );
        foreach my $location ( @locations ) {
            if ( -x $location ) {
                $zsbin = $location;
            }
        }
    }
    if ( ! $zsbin ) {
        die "[!] zabbix_sender binary is not installed! You need to yum install zabbix-sender\n";
    }
    my @locations = (
        '/etc/zabbix/zabbix_agentd.conf',
        '/opt/zabbix/etc/zabbix_agentd.conf'
    );
    foreach my $location ( @locations ) {
        if ( -f $location ) {
            $zconfig = $location;
        }
    }
    if ( ! $zconfig ) {
        die "[!] Could not find zabbix_agentd.conf. Please check!\n";
    }
}

sub populate {
    # populate the cgroups with currently running pids. This is fast, so running it every time doesn't hurt anything, and ensures we have daemons in cgroups if they get restarted.
    opendir(my $dir, '/proc');
        foreach my $pid ( grep { /^[0-9]+$/ && -d '/proc/' . $_ } readdir($dir) ) {
            next unless -f '/proc/' . $pid . '/comm';
            open(my $comm, '<', '/proc/' . $pid . '/comm');
                chomp(my $bin = <$comm>);
            close($comm);
            push(@{$daemons{$bin}}, $pid) if defined($daemons{$bin});
        }
    closedir($dir);
    mkdir('/sys/fs/cgroup/DAEMONS') unless -d '/sys/fs/cgroup/DAEMONS';
    foreach my $daemon ( keys %daemons ) {
        mkdir('/sys/fs/cgroup/DAEMONS/' . $daemon) unless -d '/sys/fs/cgroup/DAEMONS/' . $daemon;
        system($cgbin . ' -g *:DAEMONS/' . $daemon . ' ' . join(' ', @{$daemons{$daemon}} . ' 2>/dev/null'));
    }
}

sub collect {
    # collect the cgroup data
    get_system_cpu();
    get_system_memory();
    get_system_io();
    get_user_cpu();
    get_user_memory();
    get_daemon_cpu();
    get_daemon_memory();
    foreach my $daemon ( keys %daemons ) {
        get_cpu($daemon);
        get_memory($daemon);
        get_io($daemon);
    }
}

sub get_old_data {
    # we pull the last reports data so we can calculate the delta
    open(my $fh, '<', '/tmp/zabbix_sender.old');
        while(<$fh>) {
            my ( $key, $value ) = split(' ');
            my ( undef, $daemon, $category, $zkey ) = split(/\./, $key);
            $old{$daemon}->{$category}->{$zkey} = $value;
        }
    close($fh);
}

sub generate_report {
    # generate the report to send to zabbix
    my $hostname = hostname();
    open(my $report, '>', '/tmp/zabbix_sender.tmp');
    open(my $delta, '>', '/tmp/zabbix_sender.old');
        foreach my $daemon ( keys %data ) {
            foreach my $category ( keys %{$data{$daemon}} ) {
                foreach my $key ( keys %{$data{$daemon}->{$category}} ) {
                    print $report "$hostname cgroups.$daemon.$category.$key " . calculate_delta($daemon, $category, $key) . "\n";
                    print $delta "cgroups.$daemon.$category.$key $data{$daemon}->{$category}->{$key}\n";
                }
            }
            next if $daemon eq 'system';
            print $report "$hostname cgroups.$daemon.cpu.percentage " . get_percentage($daemon) . "\n";
        }
    close($report);
    close($delta);
}

sub tell_zabbix {
    # send the data to zabbix
    die "[!] Report file [/tmp/zabbix_sender.tmp] failed to generate. Please check!\n" unless -f '/tmp/zabbix_sender.tmp';
    # sleep some amount of time to make sure we don't have the whole farm flooding zabbix at exactly the same second
    sleep(int(rand(120)));
    system("$zsbin -c $zconfig -i /tmp/zabbix_sender.tmp >/dev/null");
    if ( $? ) {
        die "[!] Zabbix sender failed, please review output\n";
    }
    unlink('/tmp/zabbix_sender.tmp');
}

sub calculate_delta {
    my ( $daemon, $category, $key ) = @_;
    # if there is no old value, return 0, as there is no difference
    if ( ! defined($old{$daemon}->{$category}->{$key}) ) {
        return('0');
    } else { # otherwise, calculate the delta and return that
        return($data{$daemon}->{$category}->{$key} - $old{$daemon}->{$category}->{$key});
    }
}

sub get_percentage {
    my $daemon = shift;
    my $pct = ( 100 * (( calculate_delta($daemon, 'cpu', 'system') + calculate_delta($daemon, 'cpu', 'user') ) / ( calculate_delta('system', 'cpu', 'system') + calculate_delta('system', 'cpu', 'user') )) );
    return(sprintf("%.2f", $pct));
}

# collection subroutines
sub get_system_cpu {
    open(my $fh, '<', '/sys/fs/cgroup/cpuacct.stat');
        while (<$fh>) {
            chomp();
            my ( $key, $value ) = split(' ');
            $data{'system'}->{'cpu'}->{$key} = $value;
        }
    close($fh);
}

sub get_system_memory {
    my @wanted = qw(total_cache total_rss total_swap total_active_anon total_inactive_anon);
    open(my $fh, '<', '/sys/fs/cgroup/memory.stat');
        while (<$fh>) {
            chomp();
            my ( $key, $value ) = split(' ');
            next unless grep(/^$key$/, @wanted);
            $data{'system'}->{'memory'}->{$key} = $value;
        }
    close($fh);
}

sub get_system_io {
    # iops
    open(my $fh, '<', '/sys/fs/cgroup/blkio.throttle.io_serviced');
        while (<$fh>) {
            chomp();
            next unless $_ =~ /^[0-9]+:[0-9]+/;
            my ( $device, $key, $value ) = split(' ');
            $data{'system'}->{'iops'}->{$key} += $value;
        }
    close($fh);

    # bps
    open($fh, '<', '/sys/fs/cgroup/blkio.throttle.io_service_bytes');
        while (<$fh>) {
            chomp();
            next unless $_ =~ /^[0-9]+:[0-9]+/;
            my ( $device, $key, $value ) = split(' ');
            $data{'system'}->{'bps'}->{$key} += $value;
        }
    close($fh);
}

sub get_daemon_cpu {
    open(my $fh, '<', '/sys/fs/cgroup/DAEMONS/cpuacct.stat');
        while (<$fh>) {
            chomp();
            my ( $key, $value ) = split(' ');
            $data{'daemon'}->{'cpu'}->{$key} = $value;
        }
    close($fh);
}

sub get_daemon_memory {
    my @wanted = qw(total_cache total_rss total_swap total_active_anon total_inactive_anon);
    open(my $fh, '<', '/sys/fs/cgroup/DAEMONS/memory.stat');
        while (<$fh>) {
            chomp();
            my ( $key, $value ) = split(' ');
            next unless grep(/^$key$/, @wanted);
            $data{'daemon'}->{'memory'}->{$key} = $value;
        }
    close($fh);
}

sub get_user_cpu {
    open(my $fh, '<', '/sys/fs/cgroup/USERS/cpuacct.stat');
        while (<$fh>) {
            chomp();
            my ( $key, $value ) = split(' ');
            $data{'user'}->{'cpu'}->{$key} = $value;
        }
    close($fh);
}

sub get_user_memory {
    my @wanted = qw(total_cache total_rss total_swap total_active_anon total_inactive_anon);
    open(my $fh, '<', '/sys/fs/cgroup/USERS/memory.stat');
        while (<$fh>) {
            chomp();
            my ( $key, $value ) = split(' ');
            next unless grep(/^$key$/, @wanted);
            $data{'user'}->{'memory'}->{$key} = $value;
        }
    close($fh);
}

sub get_cpu {
    my $daemon = shift;
    open(my $fh, '<', '/sys/fs/cgroup/DAEMONS/' . $daemon . '/cpuacct.stat');
        while (<$fh>) {
            chomp();
            my ( $key, $value ) = split(' ');
            $data{$daemon}->{'cpu'}->{$key} = $value;
        }
    close($fh);
}

sub get_memory {
    my $daemon = shift;
    my @wanted = qw(total_cache total_rss total_swap total_active_anon total_inactive_anon);
    open(my $fh, '<', '/sys/fs/cgroup/DAEMONS/' . $daemon . '/memory.stat');
        while (<$fh>) {
            chomp();
            my ( $key, $value ) = split(' ');
            next unless grep(/^$key$/, @wanted);
            $data{$daemon}->{'memory'}->{$key} = $value;
        }
    close($fh);
}

sub get_io {
    my $daemon = shift;
    # iops
    open(my $fh, '<', '/sys/fs/cgroup/DAEMONS/' . $daemon . '/blkio.throttle.io_serviced');
        while (<$fh>) {
            chomp();
            next unless $_ =~ /^[0-9]+:[0-9]+/;
            my ( $device, $key, $value ) = split(' ');
            $data{$daemon}->{'iops'}->{$key} += $value;
        }
    close($fh);

    # bps
    open($fh, '<', '/sys/fs/cgroup/DAEMONS/' . $daemon . '/blkio.throttle.io_service_bytes');
        while (<$fh>) {
            chomp();
            next unless $_ =~ /^[0-9]+:[0-9]+/;
            my ( $device, $key, $value ) = split(' ');
            $data{$daemon}->{'bps'}->{$key} += $value;
        }
    close($fh);
}
