#!/bin/bash
#

NODE=$(hostname -s)
CPUS=$(lscpu | awk '/^CPU\(s\):/{print $2}')
MEM=$(lsmem | awk '/Total online/{print $NF}')
DATE=$(date +"%F %T")
LOGPATH=/tmp

if [ ! -d $LOGPATH ]; then
    mkdir -p $LOGPATH
fi
exec 5>&1
exec >> $LOGPATH/edoc2-hardware.txt

cpu_func(){
load=$(uptime | awk -F 'load average: ' '{print $2}')
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)"%"}')
cat << EOF
CPU总数: $CPUS
1分钟负载: $(echo $load | awk -F ', ' '{print $1}')
5分钟负载: $(echo $load | awk -F ', ' '{print $2}')
15分钟负载: $(echo $load | awk -F ', ' '{print $3}')
CPU使用率: $cpu_usage
EOF
echo 
}

mem_func(){
total=$(free -m | sed -n '2,2p' | awk '{print $2}')
mem_avai=$(free -m | sed -n '2,2p' | awk '{print $NF}')
mem_used=$((total-mem_avai))
mem_rate=$(awk -v t=$total -v u=$mem_used 'BEGIN{print int(u/t*100)"%"}')

cat << EOF
内存总数: $MEM
可用内存：${mem_avai}MB
内存使用数: ${mem_used}MB
内存使用率: $mem_rate
EOF
echo
}

process_top(){

echo "内存占用TOP10:"
ps -e --sort -rss -o comm,args,rss,pmem,pid,ppid | head -n 11
echo

echo "CPU占用TOP10:"
ps -e --sort=-%cpu -o comm,args,pcpu,pid,ppid | head -n 11
echo

}


vm_func(){
 vmstat 1 7 | column -t
 echo 
}

threadcheck(){
edoc2Thread=$(docker stats --no-stream | grep 'edoc2\.' |grep -v grep | awk '{print $NF}')
if [ -n "$edoc2Thread" ]; then
    echo "edoc2线程数: $edoc2Thread"
fi

}

io_func(){
command -v pidstat &>/dev/null
if [ $? -eq 0 ]; then
    echo "系统进程IO监控"
    echo
    echo "dotnet与java进程及PID列表"
    ps -e -o comm,args,pid,ppid | head -1
    ps -e -o comm,args,pid,ppid | egrep 'dotnet|java' | grep -v grep
    echo
    pidstat -d 1 4
    echo
fi

}

echo
echo "[$DATE Performance Monitor]"
echo
echo "主机名: $NODE"
cpu_func
mem_func
process_top
vm_func
io_func
threadcheck
exec 1>&5 5>&-

if [ $(du -b $LOGPATH/edoc2-hardware.txt | awk '{print $1}') -gt 1073741824 ]; then
    truncate -s 0 $LOGPATH/edoc2-hardware.txt
fi
