#!/bin/sh

: << =cut

=head1 NAME

rabbitmq_connections - monitor the number of connections to RabbitMQ

=head1 CONFIGURATION

You will need to add configuration to
/etc/munin/plugin-conf.d/rabbitmq_connection.conf for this plugin to
work.

=over 2

=item C<user>

Required. Valid choices are C<rabbitmq> and C<root>. This is required
by C<rabbitmqctl>.

=item C<env.conn_warn>

Optional, default value is 500

=item C<env.conn_crit>

Optional, default value is 1000

=back

=head2 EXAMPLE CONFIGURATION

  [rabbitmq_connections]
    user rabbitmq
    env.conn_warn 512
    env.conn_crit 1024

=head1 MAGIC MARKERS

  #%# family=contrib

=cut

case $(whoami) in
    rabbitmq|root)
        ;;
    *)
        echo 'Error: Plugin requires "user" to be set in plugin configuration.' >&2
        echo 'See "munindoc rabbitmq_connections" for more information'  >&2
        exit 1
        ;;
esac

# If run with the "config"-parameter, give out information on how the
# graphs should look. 

if [ "$1" = "config" ]; then
        CONN_WARN=${conn_warn:-500}
        CONN_CRIT=${conn_crit:-1000}

	# The host name this plugin is for. (Can be overridden to have
	# one machine answer for several)

	# The title of the graph
	echo 'graph_title RabbitMQ connections'
	# Arguments to "rrdtool graph". In this case, tell it that the
	# lower limit of the graph is '0', and that 1k=1000 (not 1024)
	echo 'graph_args --base 1000 -l 0'
	# The Y-axis label
	echo 'graph_vlabel connections'
	# We want Cur/Min/Avg/Max unscaled (i.e. 0.42 load instead of
	# 420 milliload)
	#echo 'graph_scale no'
	echo 'graph_category chat'

	echo "connections.label Connections"
	echo "connections.warning $CONN_WARN"
	echo "connections.critical $CONN_CRIT"
	echo "connections.info Number of active connections"

	echo 'graph_info Shows the number of connections to RabbitMQ'
	# Last, if run with the "config"-parameter, quit here (don't
	# display any data)
	exit 0
fi

# If not run with any parameters at all (or only unknown ones), do the
# real work - i.e. display the data. Almost always this will be
# "value" subfield for every data field.

if command -v rabbitmqctl >/dev/null 2>&1; then
    connections=$(HOME=/tmp rabbitmqctl list_connections state | grep -c running)
else
    echo "$0: Could not run rabbitmqctl" >&2
    connections=U
fi

printf "connections.value %s\n" "$connections"
