#!/bin/bash

BSCONFIG_IHOST=$1
BSCONFIG_IPORT=$2
INTERVAL=${3:-"1800"}

hostport=${BSCONFIG_IHOST}:${BSCONFIG_IPORT}
path=/db/bsconfig/webcache/${hostport}
fname=$path/${hostport}.csv

pid=0

handle_term()
{
    kill -TERM $pid
    exit 0
}

trap handle_term TERM

do_collect()
{
    local pid=`cat pids/saas_daemon`
    local ts=`date +%s`

    local disk_usage=`pidstat -d | awk -v pid=$pid '$2 == pid{printf "%s|%s", $3, $4}' | sed 's/,/./g'` # read|write speed
    local mem_usage=`pidstat -r | awk -v pid=$pid '$2 == pid{print $6}'` # RSS
    local cpu_cores=`pidstat -u | awk -v pid=$pid '$2 == pid{print $6}' | sed 's/,/./g'` # used cores

    mkdir -p $path
    tail -n 500  $fname > $fname.tmp
    mv $fname.tmp  $fname
    echo "$ts|$mem_usage|$cpu_cores|$disk_usage" >> $fname
}

while :
do
    do_collect
    sleep $INTERVAL &
    pid=@?
    wait
done

