#!/usr/local/bin/perl

# Parameters supported:
#
# config
# autoconf
#
# Magic markers:
#%# family=auto
#%# capabilities=autoconf

use strict;
use warnings;
use LWP;
use JSON qw/decode_json/;

=head1 NAME

elasticsearch_open_files - A munin plugin that collects the number of open files in your elasticsearch instances

=head1 APPLICABLE SYSTEMS

Elasticsearch

=head1 CONFIGURATION

None

=head1 BUGS

None known so far. If you find any, let me know.

=head1 AUTHOR

Kentaro Yoshida - https://github.com/y-ken
Rowan Wookey - https://www.rwky.net

=head1 LICENSE

MIT

=cut

my $url = exists $ENV{'url'} ? $ENV{'url'} : 'http://localhost:9200';

my $ua = LWP::UserAgent->new;
$ua->timeout(10);

sub autoconf {
    my $res  = $ua->get( $url, 'Content-Type' => 'application/json' );
    my $data = do {
        local $@;
        eval { decode_json( $res->content ) }
    };
    if ( $data->{version}->{number} ) {
        print("yes\n");
    }
    else {
        print("no\n");
    }
    exit(0);
}

if ( $ARGV[0] and $ARGV[0] eq 'autoconf' ) {
    autoconf();
}

sub get_json_from_url {
    my $uri = shift;
    my $res = $ua->get( $url . $uri, 'Content-Type' => 'application/json' );
    Carp::confess( $res->code . " for " . $uri ) unless $res->is_success;
    my $data = do {
        local $@;
        eval { decode_json( $res->content ) }
    };
    die( "Could not decode JSON from: " . $res->content ) unless $data;
    return $data;
}

sub collect_max_file_descriptors {
    my $data = get_json_from_url("/_nodes/_local/stats/process");
    foreach my $full_node_name ( keys %{ $data->{nodes} } ) {
        return $data->{nodes}{$full_node_name}{process}{max_file_descriptors};
    }
}

sub collect_open_file_descriptors {
    my $data = get_json_from_url("/_nodes/_local/stats/process");
    foreach my $full_node_name ( keys %{ $data->{nodes} } ) {
        return $data->{nodes}{$full_node_name}{process}{open_file_descriptors};
    }
}

my %out = (
    max_file_descriptors  => collect_max_file_descriptors,
    open_file_descriptors => collect_open_file_descriptors
);

if ( $ARGV[0] and $ARGV[0] eq 'config' ) {
    print "graph_title Elasticsearch open files\n";
    print "graph_args --base 1000 -l 0\n";
    print "graph_vlabel number of open files\n";
    print "graph_category elasticsearch\n";
    print "open_file_descriptors.label open files\n";
    print "open_file_descriptors.type GAUGE\n";
    print "open_file_descriptors.info The number of currently open files.\n";
    print "max_file_descriptors.label max open files\n";
    print "max_file_descriptors.type GAUGE\n";
}
else {
    print "max_file_descriptors.value $out{max_file_descriptors}\n";
    print "open_file_descriptors.value $out{open_file_descriptors}\n";
}
