#!/bin/sh
# devel.a0fs.ru -- ncc.mon.kvm.tool:/root/libexec/qemu-ga.watcher.sh -- v0.r202312.1
# Запускается через crontab:
#   */15  *   *   *   *  /bin/sh /root/libexec/qemu-ga.watcher.sh
#
export PATH="/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin"

NAME="qemu-ga"


log () {
    logger -t "qemu-ga.watcher" "$@"
}


check_get_proc () {
    ps -Ao comm,pcpu | awk -v pname="$NAME" '\
    BEGIN {buf = 0}; \
    $1 == pname {if (buf < $2) buf = $2 * 10 } \
    END {print buf} \
    '
}


check () {
    [ $(check_get_proc) -ge 800 ]
}


{
    flag="1"
    echo CHECK
    if check ; then
        log -p user.error "qemu agent overload: watching..."
        cntr=0

        while [ $cntr -le 100 ] ; do
            sleep 1
            cntr=$(( $cntr + 1 ))
            
            if ! check ; then
                flag=""
                break

            fi
        done

        if [ "$flag" ] ; then
            log -p user.error "qemu agent overload: restarting"
            systemctl restart qemu-guest-agent
        
        fi

} 2>&1 | log

