Profile picture

[Shell Script] 메모리(memory) 사용량 디스코드(Discord) 알림 전송

JaehyoJJAng2024년 05월 05일

메모리 점검

  • 전체 메모리에서 남는 free 메모리 용량이 12% 미만일 때, 도커 컨테이너 재시작

스크립트 작성

memory_container_restart.sh

#!/usr/bin/bash

CONTAINER_NAME="bdodb"
LOG_FILE="/var/log/$CONTAINER_NAME"

# Set the threshold for free memory percentage (12%)
THRESHOLD=12

TOTAL_MEMORY="$(free -m | awk '/Mem/{print $2}')"
FREE_MEMORY="$(free -m | awk '/Mem/{print $4}')"
TOTAL_MEMORY_GiB="$(free -g | awk '/Mem/{print $2}')"
FREE_MEMORY_GiB="$(free -m | awk '/Mem/{print $4}')"
CURRENT_TIME="$(date +"%H:%M:%S")"

# Calculate the free memory percentage
# RSS: 실제 점유하고 있는 물리 메모리 크기
FREE_PERCENTAGE="$(awk "BEGIN {printf \"%.2f\", $FREE_MEMORY / $TOTAL_MEMORY * 100}")"

# Calculate the total memoryt usage by mysqld GiB
MYSQLD_MEMORY=$(ps aux | grep 'mysqld' | grep -v 'grep' | awk '{sum += $6} END {printf "Total Memory Usage: %.2fGib\n", sum / (1024 * 1024)}')

exec 3>> "$LOG_FILE"
# Compare with the threshold
if (( $(echo "$FREE_PERCENTAGE < $THRESHOLD" | bc -l) ));
then
    echo "============" >&3
    echo "Current time: $CURRENT_TIME" >&3
    echo "Total memory is $TOTAL_MEMORY_GiB GiB" >&3
    echo "Free memory: $FREE_MEMORY_GiB GiB" >&3
    echo "Free percentage is $FREE_PERCENTAGE %" >&3
    echo "Mysqld memory usage: $MYSQLD_MEMORY MB" >&3
    echo "Free memory is below $THRESHOLD% of total." >&3
    echo "Mysqld was restarted due to insufficient memory." >&3
    echo "============" >&3
    echo " " >&3
    echo " " >&3

    # Execute the restart
    docker restart "$CONTAINER_NAME"
else
    echo "Free memory is above $THRESHOLD% of total." 
    echo "Total memory is $TOTAL_MEMORY_GiB GiB"
    echo "Free memory is $FREE_MEMORY_GiB GiB"
    echo "Free percentage is $FREE_PERCENTAGE %"
    echo "Apache memory usage is $APACHE_MEMORY"
fi
코드 설명
THRESHOLD=12 빈 메모리가 이 값(12%) 미만으로 떨어지면 MySQL 컨테이너를 재시작합니다.
TOTAL_MEMORY="$(free -m | awk '/Mem/{print $2}')" 시스템의 총 메모리를 MB 단위로 가져옵니다.
FREE_MEMORY="$(free -m | awk '/Mem/{print $4}')" 시스템의 사용 가능한 메모리를 MB 단위로 가져옵니다.
TOTAL_MEMORY_GiB="$(free -g | awk '/Mem/{print $2}')" 시스템의 총 메모리를 GB 단위로 가져옵니다.
FREE_MEMORY_GiB="$(free -m | awk '/Mem/{print $4}')" 시스템의 사용 가능한 메모리를 GB 단위로 가져옵니다.
CURRENT_TIME="$(date +"%H:%M:%S")" 현재 시간을 가져옵니다.
FREE_PERCENTAGE="$(awk "BEGIN {printf \"%.2f\", $FREE_MEMORY / $TOTAL_MEMORY * 100}")" 사용 가능한 메모리의 백분율을 계산합니다.
MYSQLD_MEMORY=$(ps aux | grep 'mysqld' | grep -v 'grep' | awk '{sum += $6} END {printf "Total Memory Usage: %.2fGib\n", sum / (1024 * 1024)}') MySQL 서버 프로세스의 메모리 사용량을 계산합니다.

실행 결과

해당 스크립트 실행

sudo bash memory_container_restart.sh

image

    Tag -

Loading script...