#!/bin/bash
# sip-stress [index]
# Runs SIP stress against bono nodes.  The optional index parameter specifies
# which instance of SIPP to run (and which bono to target).

# Increase our connection limit.
ulimit -Hn 100000
ulimit -Sn 100000

# Read in config.
. /etc/clearwater/config

# Figure out our index, either from the passed-in parameter or from the node
# index
index=$1
[ -n "$index" ] || index=$node_idx
[ -n "$index" ] || index=1

# Identify the stress target.  This can be a configuration parameter, or
# deduced from the list of bonos.
if [ -z "$stress_target" ]
then
  # Get cluster settings if they exist.
  [ ! -f /etc/clearwater/cluster_settings ] || . /etc/clearwater/cluster_settings
  # Default the stress targets to the list of bono servers, or the home domain
  # if we don't have a list of bonos.
  stress_targets=$bono_servers
  [ -n "$stress_targets" ] || stress_targets=$home_domain
  # Calculate the stress target index by taking the index of this sipp
  # instance ($index) modulo the number of stress targets (found by turning
  # the comma-separated list into a newline-separated list and then counting
  # the lines).  Since the indices we're using are 1-based, we must subtract 1
  # before doing the modulo operator and then add one after.
  stress_target_idx=$((((index - 1) % $(echo $stress_targets | sed -e 's/,/\n/g' | wc -l)) + 1))
  # Pull the stress target out of the list by making it newline-separated and
  # then using tail.
  stress_target=$(echo $stress_targets | sed -e 's/,/\n/g' | tail -n +$stress_target_idx | head -1)
fi

# Calculate the number of users.
num_users=$(($(wc -l < /usr/share/clearwater/sip-stress/users.csv.$index) - 1))

# Keep running sipp until we're killed.
while true
do
  logger -p daemon.error -t sip-stress Restarting sipp instance $index - targeting $stress_target...

  # Copy the script file, then move it - moves within a partition are atomic.
  cp /usr/share/clearwater/sip-stress/sip-stress.xml /var/log/clearwater-sipp/sip-stress.xml.$index
  mv /var/log/clearwater-sipp/sip-stress.xml.$index /var/log/clearwater-sipp/sip-stress.xml

  # sipp wants a terminal.  Give it a dumb one (we're going to send it to file anyway).
  export TERM=dumb

  # Actually run sipp.
  nice -n-20 /usr/share/clearwater/bin/sipp -i $local_ip -sf /var/log/clearwater-sipp/sip-stress.xml $stress_target:5060 -t tn -s $home_domain -inf /usr/share/clearwater/sip-stress/users.csv.$index -users $num_users -m $num_users -default_behaviors all,-bye -max_socket 65000 -trace_stat -trace_rtt -trace_counts -trace_err -max_reconnect -1 -reconnect_sleep 0 -reconnect_close 0 -send_timeout 4000 -recv_timeout 12000 -nostdin >> /var/log/clearwater-sipp/sip-stress.$index.out 2>&1

  logger -p daemon.error -t sip-stress sipp instance $index terminated - waiting

  # Wait for 60s for TCP connections to time out
  sleep 60
done
