Tuesday 16 September 2014

Process which using high swap memory in linux


Here the threshold is 40% . If any process using swap memory more than 40% we will print the process id, TotalSwap, SwapUsed, SwapUsed in percentage.

Note: Below script only works where the VmSwap line prints in /proc/processid/status file (Works in RHEL/Centos 6 2.6.32-279.2.1.el6.centos.plus.x86_64)

#!/bin/bash
##Author == Md. Mansoor
for id in `ps aux | sort -k 4 -k 3 -nr | head -n5 | awk '{print $2}'`
do
swapkb=`cat /proc/$id/status | grep -i swap | awk '{print $2}'`
swapusedMB=`echo $((swapkb/1024))`
total=`free -m | awk 'FNR == 4 {print $2}'`
foutyper=`bc <<< $total*40/100`
swapusedper=`bc -l <<< $swapusedMB/$total*100 | awk -F. '{print $1}'`
if [ $swapusedMB -gt $foutyper ]; then
user=`ps aux | grep $id | grep -v grep | awk '{print $1}'`
cmd=`cat /proc/$id/cmdline`
echo "Above 40% swap used ProcessID = $id TotalSwap = $total SwapUsed = $swapusedMB SwapUsedin% = $swapusedper% MB User = $user Command = $cmd"
fi
done


##Another Script:
##This works for all linux version including old kernel
##Server running lower than procpu-3.2.7-26.rpm package should instead of above use below script. Reference: https://rhn.redhat.com/errata/RHBA-2013-1338.html

#! /bin/bash
# Author: Md. Mansoor
for i in /proc/[0-9]*; do
  pid=$(echo $i | sed -e 's/\/proc\///g')
#echo $pid
  swap_pid=$(cat /proc/$pid/smaps | awk 'BEGIN{total=0}/^Swap:/{total+=$2}END{print total}')
total=`free -m | awk 'FNR == 4 {print $2}'`
swapusedMB=`echo $((swap_pid/1024))`
#echo "swap used in MB $swapusedMB MB"
swapusedper=`bc -l <<< $swapusedMB/$total*100 | awk -F. '{print $1}'`
#echo "$swapusedper in percentage"
foutyper=`bc <<< $total*10/100`
user=`ps aux | grep $pid | grep -v grep | awk '{print $1}'`
if [ $swapusedMB -gt $foutyper ]; then
cmd=`cat /proc/$pid/cmdline`
echo "Above 40% swap used ProcessID = $pid TotalSwap = $total SwapUsed = $swapusedMB SwapUsedin% = $swapusedper% MB User = $user Command = $cmd"
fi
done


Reference: http://www.quora.com/How-can-I-determine-which-process-is-contributing-to-paging-on-Linux

No comments:

Post a Comment