#!/usr/bin/env perl
# ex:ts=4

use strict;
use warnings;

use Cache::Memcached;

# Based on original plugin, extended to unix socket use
# https://github.com/western, westroads@gmail.com

=head1 example config for /plugin-conf.d/munin-node

[memcached_traffic_1]
env.server 127.0.0.1:11211
env.label "first local server"

[memcached_traffic_2]
env.server /var/run/memcached/memcached.sock
env.label "second local server"

=cut

my $label = exists $ENV{'label'} ? $ENV{'label'} : '';
unless( $label ){
	
	if( $0 =~ /memcached_ext_traffic_([\w\d]+)$/ ){
		$label = $1;
	}
}


my $cmd = shift || '';
if ($cmd eq 'config') {
	print "graph_title Memcached network traffic on $label\n";
	print "graph_args --base 1000 -l 0\n";
	print "graph_vlabel bits per \${graph_period}\n";
	print "graph_category memory\n";
	print "graph_info This graph monitors the network traffic of the memcached server.\n";
	print "up.label bits in\n";
	print "up.info Traffic received by memcached\n";
	print "up.min 0\n";
	print "up.cdef up,8,*\n";
	print "up.type COUNTER\n";
	print "up.draw AREA\n";
	print "down.label bits out\n";
	print "down.info Traffic sent by memcached\n";
	print "down.min 0\n";
	print "down.cdef down,8,*\n";
	print "down.type COUNTER\n";
	exit 0;
}

my $server = exists $ENV{'server'} ? $ENV{'server'} : '127.0.0.1:11211';

my $memd = new Cache::Memcached { 'servers' => [$server] };
my $memstats = $memd->stats(['misc']);

print "up.value " . $memstats->{hosts}->{$server}->{misc}->{bytes_read} . "\n";
print "down.value " . $memstats->{hosts}->{$server}->{misc}->{bytes_written} . "\n";
