#!/bin/sh
#
# Plugin to monitor network connections.
#  forward: number of connections forwarder
#  local:   number of connections for the host itself
#
# Parameters:
#
# 	config   (required)
# 	autoconf (optional - only used by munin-config)
#
#
# Magic markers (optional - used by munin-config and some installation
# scripts):
#%# family=auto
#%# capabilities=autoconf
#
# NOTE: MUST RUN AS ROOT.
# /etc/munin/plugin-conf.d/global or other file in that dir must contain:
# [fw*]
#      user root


if [ "$1" = "autoconf" ]; then
	if ( cat /proc/net/ip_conntrack 2>/dev/null >/dev/null ); then
		echo yes
		exit 0
	else
		if [ $? -eq 127 ]
		then
			echo "no (ipconntrack not found)"
			exit 1
		else
			echo no
			exit 1
		fi
	fi
fi

if [ "$1" = "config" ]; then

	echo 'graph_title ipconntrack'
	echo 'graph_args -l 0 --base 1000'
	echo 'graph_vlabel established connections'
	echo 'graph_category network'
	echo 'forward.label forward'
	echo 'forward.type GAUGE'
	echo 'local.label local'
	echo 'local.type GAUGE'
	exit 0
fi

perl -ne '
    BEGIN { $forward=0; $local=0; }

    if ( ($src, $dst, $isrc, $idst) =
     /.*ESTABLISHED src=(.*) .*dst=(.*) sport.*src=(.*) .*dst=(.*) sport.*/ ) {
        if( $src eq $idst) {
	    $local++;
	} else {
            $forward++;
       }
    }
    END { print "forward.value $forward\nlocal.value $local\n" }
' </proc/net/ip_conntrack

