#!/bin/sh
# Copyright (c) 2016 Alexey Anikanov (alexey.anikanov@gmail.com)
# License GPLv2
# This plugin monitors number of workers, total memory used and average memory per process for puma,
# a ruby web server built for concurrency http://puma.io
# Here are the symlinks to enable it
#
#  ln -s /usr/share/munin/plugins/puma_ /etc/munin/plugins/puma_average
#  ln -s /usr/share/munin/plugins/puma_ /etc/munin/plugins/puma_memory
#  ln -s /usr/share/munin/plugins/puma_ /etc/munin/plugins/puma_processes

mode=$(echo $0 | cut -d _ -f 2)

if [ "$1" = "suggest" ]; then
  echo "memory"
  echo "processes"
  echo "average"
  exit 0
fi

if [ "$mode" = "memory" ]; then
  if [ "$1" = "config" ]; then
    echo "graph_title Total Puma Memory"
    echo "graph_vlabel Total RAM"
    echo "graph_category webserver"
    echo "graph_args --base 1024"
    echo "ram.label Total RAM"
    exit 0
  else
    processes_memory="$(ps auwx | egrep "puma.* worker" | grep -v grep | awk '{print $6 }')"
    for process_memory in $processes_memory; do
      total_memory=$(( $total_memory + ( $process_memory * 1024) ))
    done
    printf "ram.value %s\n" "$total_memory"
  fi
elif [ "$mode" = "processes" ]; then
  if [ "$1" = "config" ]; then
    echo "graph_title puma Processes"
    echo "graph_vlabel Processes"
    echo "graph_category webserver"
    echo "processes.label active processes"
  else
    printf "processes.value %s\n" "$(ps awwwux | egrep "puma.* worker" | grep -v grep | wc -l)"
    exit 0
  fi
elif [ "$mode" = "average" ]; then
  if [ "$1" = "config" ]; then
    echo 'graph_title Puma Average Process Size'
    echo 'graph_args --base 1024 -l 0 '
    echo 'graph_vlabel Average Process Size'
    echo 'graph_category webserver'
    echo 'puma_average.label Average Process Size'
    echo 'puma_average.draw LINE2'
    echo 'puma_average.info The average process size for puma'
  else
    printf "puma_average.value %s\n" "$(ps awwwux | egrep "puma.* worker" | grep -v grep | grep -v master | awk '{total_mem = $6 * 1024 + total_mem; total_proc++} END{printf("%d\n", total_mem / total_proc)}')"
    exit 0
  fi
fi
exit 0
