原理說(shuō)明
在對(duì)服務(wù)器進(jìn)行維護(hù)時(shí),有時(shí)也遇到由于系統(tǒng) CPU(利用率)負(fù)載過(guò)高導(dǎo)致業(yè)務(wù)中斷的情況。服務(wù)器上可能運(yùn)行多個(gè)進(jìn)程,查看單個(gè)進(jìn)程的 CPU 都是正常的,但是整個(gè)系統(tǒng)的 CPU 負(fù)載可能是異常的。通過(guò)腳本對(duì)系統(tǒng) CPU 負(fù)載進(jìn)行時(shí)時(shí)監(jiān)控,可以在異常時(shí)及時(shí)發(fā)送告警,便于維護(hù)人員及時(shí)處理,預(yù)防事故發(fā)生。下面的函數(shù)可以檢測(cè)系統(tǒng) CPU 使用情況 。使用 vmstat 取 5 次系統(tǒng) CPU 的 idle 值,取平均值,然后通過(guò)與 100 取差得到當(dāng)前 CPU 的實(shí)際占用值。
vmstat(VirtualMeomoryStatistics,虛擬內(nèi)存統(tǒng)計(jì))是Linux中監(jiān)控內(nèi)存的常用工具,可對(duì)操作系統(tǒng)的虛擬內(nèi)存、進(jìn)程、CPU等的整體情況進(jìn)行監(jiān)視。該命令可以顯示關(guān)于系統(tǒng)各種資源之間相關(guān)性能的簡(jiǎn)要信息,這里我主要用它來(lái)看CPU的一個(gè)負(fù)載情況。
[root@host ~]# cat cpuload.sh
#!/bin/bash
#Author: Jaking
#Mail: Jaking1024@163.com
#Date:2018/7/11
#Function:This script is to get the CPU load.
function GetSysCPU
{
CpuIdle=`vmstat 1 5 |sed -n '3,$p' | awk '{x = x + $15} END {print x/5}' | awk -F. '{print $1}'`
CpuNum=`echo "100-$CpuIdle" | bc`
echo $CpuNum
}
cpu=`GetSysCPU`
echo "The system CPU is $cpu"
if [ $cpu -gt 80 ]
then
{
echo "The usage of system CPU is larger than 80%"
}
else
{
echo "The usage of system CPU is normal"
}
fi
[root@host ~]# bash cpuload.sh
The system CPU is 8
The usage of system CPU is normal
從上面的輸出可見(jiàn):當(dāng)前 Linux 服務(wù)器系統(tǒng) CPU 利用率為 8%,是正常的,沒(méi)有超過(guò) 80% 的告警限制。