#!/bin/sh
#
# DRBD Munin plugin
# jorrizza@jrrzz.net
#
# Can be symlinked as drbd_net_N or drbd_disk_N to plot
# drbdN's network traffic and disk activity, respectively.
#

# Our interface name (X in drbdX)
INTERFACE=`basename $0 | sed 's/^drbd_.*_//g'`

# Our mode, net or disk
MODE=`basename $0 | sed 's/^drbd_//g' | sed 's/_[0-9]*$//g'`

# Handle the config
if [ "$1" == "config" -a "$MODE" == "net" ]; then
  echo  "graph_title drbd$INTERFACE network traffic
graph_args --base 1024
graph_vlabel bytes received (-) / sent (+) per \${graph_period}
graph_category drbd
graph_info The network traffic generated by the distributed redundant block device.
graph_order nr ns
nr.label received
nr.type COUNTER
nr.graph no
ns.label Bandwidth
ns.type COUNTER
ns.negative nr"
  exit 0
fi
if [ "$1" == "config" -a "$MODE" == "disk" ]; then
  echo  "graph_title drbd$INTERFACE disk activity
graph_args --base 1024
graph_vlabel bytes read (-) / written (+) per \${graph_period}
graph_category drbd
graph_info The disk activity generated by the distributed redundant block device.
graph_order dr dw
dr.label read
dr.type COUNTER
dr.graph no
dw.label Bandwidth
dw.type COUNTER
dw.negative dr"
  exit 0
fi

# Check whether the DRBD block device is connected
# Otherwise, return -1
CONNECTED=`awk -F'[: \t]+' -v interface="$INTERFACE" '
NR > 2 + interface * 4 && NR <= 6 + interface * 4 {
  sub(/^[\t ]*/,"")
  if ($2 == "cs")
    print $3
}' /proc/drbd`
if [ "$CONNECTED" != "Connected" ]; then
  printf "Block device drbd%d is not connected!\n" $INTERFACE
  exit -1
fi

# The AWK stuff for displaying the DRBD data
awk -F'[: \t]+' -v interface="$INTERFACE" -v mode="$MODE" '
NR > 2 + interface * 4 && NR <= 6 + interface * 4 {
  sub(/^[\t ]*/,"")
  if (NR == 4 + interface * 4) {
    if (mode == "net") {
      print "ns.value "($2 * 1024)
      print "nr.value "($4 * 1024)
    }
    if (mode == "disk") {
      print "dw.value "($6 * 1024)
      print "dr.value "($8 * 1024)
    }
  }
}' /proc/drbd 
