#!/bin/bash

PROCESS_NAME="fluent-bit"
MEMORY_LIMIT_KB=$((13 * 1024)) # 内存阈值为13MB
CHECK_INTERVAL=60

get_fluent_bit_pid() {
    /bin/ps -ef | /bin/grep "$PROCESS_NAME" | /bin/grep -v grep | /usr/bin/awk 'NR==1{print $2}'
}

get_memory_info() {
    local pid=$1
    local status_file="/proc/$pid/status"

    if [[ ! -f "$status_file" ]]; then
        echo "ERROR"
        return
    fi

    local rss_anon=$(grep -E "RssAnon:" "$status_file" | awk '{print $2}')
    rss_anon=${rss_anon:-0}
    echo "${rss_anon}"
}

main() {
    local over_limit_count=0
    while true; do
        sleep "$CHECK_INTERVAL"

        local pid=$(get_fluent_bit_pid)
        if [[ -z "$pid" ]]; then
            over_limit_count=0
            continue
        fi

        local rss_anon=$(get_memory_info "$pid")
        if [[ "$rss_anon" == "ERROR" ]]; then
            over_limit_count=0
            continue
        fi

        if [[ $rss_anon -gt $MEMORY_LIMIT_KB ]]; then
            over_limit_count=$((over_limit_count + 1))
        else
            over_limit_count=0
        fi

        if [[ $over_limit_count -ge 3 ]]; then
            /bin/ps -ef | /bin/grep fluent-bit | /bin/grep -v grep | /usr/bin/awk 'NR==1{print $2}' | xargs /bin/kill -9 > /dev/null 2>&1
            exit 0
        fi
    done
}

main