#!/bin/bash
#
DumpFile=/edoc2Docs/edoc2_$(date +%F).dump
LogPath=/tmp/edoc2-dump
ThreadLimit=700
CPU_Limit=80
SVC=edoc2

cpu_idle=$(
    top -b -d 0.1 -n 3 | grep Cpu | tail -n 1 | awk -F'[ ,]+' '{print $8}' | cut -f 1 -d "."
)

cpu_usage=$(
    awk -v idle=$cpu_idle 'BEGIN{print int(100-idle)}'
)

if [ ! -d $LogPath ]; then
    mkdir -p $LogPath
fi

ID=$(
    docker ps | grep "${SVC}:" | awk '{print $1}'| head -1
)

if [ -n "$ID" ]; then
    docker exec $ID test -f $DumpFile
    if [ $? -ne 0 ]; then
        pid=$(
            docker exec $ID ps -e -o comm,pid | grep dotnet | awk '{print $2}'
        )
        threads=$(
            docker exec $ID curl -s --connect-timeout 8 http://localhost/api/values/1 | 
            grep -oP '\"threadsCount\":\d+' | grep -oP '\d+'
        )
        if [[ -n "$threads" && "$threads" -ge $ThreadLimit ]] || [[ "$cpu_usage" -ge "$CPU_Limit" ]]; then
            echo "$(date +"%F %T") $SVC CPU usage: ${cpu_usage}% thread: $threads, collect dump file." >> $LogPath/dump.log
            docker exec $ID /opt/tools/dotnet-dump collect -p $pid -o /edoc2Docs/edoc2_${ID}_$(date +%F).dump
            if [ $? -eq 0 ]; then
                docker  exec $ID top -H -b -n 1 -p $pid > $LogPath/top_$(date +%F).txt
                echo "$(date +"%F %T") collect $SVC dump file success." >> $LogPath/dump.log
            else
                echo "$(date +"%F %T") collect $SVC dump file failed." >> $LogPath/dump.log
            fi
        fi
    fi
fi
