#!/bin/bash
#
LogPath=/tmp/edoc2-dump
ThreadLimit=700
ns=edoc2

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

edoc2_pod=$(kubectl -n $ns get pods | grep edoc2 | awk '{print $1}')
if [ -n "$edoc2_pod" ]; then
    for pod in $edoc2_pod; do
        kubectl -n $ns exec $pod -- test -f /edoc2Docs/${pod}_$(date +%F).dump &>/dev/null
        if [ $? -ne 0 ]; then
            pid=$(kubectl -n $ns exec $pod -- ps -e -o comm,pid | grep dotnet | awk '{print $2}')
            threads=$(kubectl -n $ns exec $pod -- curl -s --connect-timeout 8 http://localhost/api/values/1 | grep -oP '\"threadsCount\":\d+' | grep -oP '\d+')
            if [[ -n "$threads" && "$threads" -ge $ThreadLimit ]]; then
                echo "$(date +"%F %T") pod $pod current thread: $threads, greater than $ThreadLimit, collect dump file." >> $LogPath/dump.log
                kubectl -n $ns exec $pod -- /opt/tools/dotnet-dump collect -p $pid -o /edoc2Docs/${pod}_$(date +%F).dump
                if [ $? -eq 0 ]; then
                    kubectl -n $ns cp $pod:/edoc2Docs/${pod}_$(date +%F).dump ${LogPath}/${pod}_$(date +%F).dump &>/dev/null
                    kubectl -n $ns exec $pod -- top -H -b -n 1 -p $pid > $LogPath/top_$(date +%F).txt
                    echo "$(date +"%F %T") collect pod $pod dump file success." >> $LogPath/dump.log
                else
                    echo "$(date +"%F %T") collect pod $pod dump file failed." >> $LogPath/dump.log
                fi
            fi
        fi
    done
fi
