#!/usr/bin/env bash

echo -e "\033[33mMemory Overcommit Check Started\033[0m"
echo -e "\033[0m====================\033[0m"

# Check if SWAP memory overcommit is being used
echo -e "\033[36mChecking if SWAP memory overcommit is in use\033[0m"
memSize=`free -m | awk '/Mem/ {print $2}'`
speed=`dd if=/dev/zero of=/dev/null bs=1M count=$memSize 2>&1 | awk '{print $(NF-1)}' | awk 'END {print}' | awk -F '，' '{print $NF}'`
speed=`echo $speed | awk '{printf("%.0f\n",$1)}'`
echo -e "\033[34mMemory IO speed: $speed GB/s\033[0m"
if [ $speed -lt 10 ]; then
    echo -e "\033[31mMemory IO speed is below 10 GB/s\033[0m"
    echo -e "\033[31mSWAP memory overcommit might be in use\033[0m"
else
    echo -e "\033[32mMemory IO speed is normal\033[0m"
    echo -e "\033[32mSWAP memory overcommit is not in use\033[0m"
fi
echo -e "\033[0m====================\033[0m"

# Check if Balloon driver (virtio_balloon) memory overcommit is in use
echo -e "\033[36mChecking if Balloon driver memory overcommit is in use\033[0m"
if lsmod | grep virtio_balloon > /dev/null; then
    echo -e "\033[31mvirtio_balloon module is present\033[0m"
    echo -e "\033[31mBalloon driver memory overcommit might be in use\033[0m"
else
    echo -e "\033[32mvirtio_balloon module is not present\033[0m"
    echo -e "\033[32mBalloon driver memory overcommit is not in use\033[0m"
fi
echo -e "\033[0m====================\033[0m"

# Check if Kernel Samepage Merging (KSM) memory overcommit is in use
echo -e "\033[36mChecking if Kernel Samepage Merging (KSM) memory overcommit is in use\033[0m"
if [ `cat /sys/kernel/mm/ksm/run` == 1 ]; then
    echo -e "\033[31mKernel Samepage Merging status is 1\033[0m"
    echo -e "\033[31mKSM memory overcommit might be in use\033[0m"
else
    echo -e "\033[32mKernel Samepage Merging status is normal\033[0m"
    echo -e "\033[32mKSM memory overcommit is not in use\033[0m"
fi
echo -e "\033[0m====================\033[0m"
