Created
January 28, 2019 03:05
-
-
Save diyism/dad823df5e71a8aa08b193c6b210f893 to your computer and use it in GitHub Desktop.
set_overcommit_ratio.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//sudo crontab -e 里加"* * * * * /usr/bin/php /home/malcolm/set_overcommit_ratio.php" | |
//MemFree需要保留200MB给系统(否则iowait很高桌面就卡住了), Cached有一部份是释放不掉的, 只能先用drop_caches释放下然后计算剩余内存时就不用算Cached的可释放部分了, | |
//预算超占率采用130%(firefox新开一个标签页时的超占率130%, chrome新开一个标签页是145%), 这个值是非常保守的, sublime,firefox等程序启动都在190%到220%之间, 也是考虑到每分钟才跑一次预占超出去了后再强行缩小会导致/usr/bin/X挂掉 | |
$start_time=time(); | |
shell_exec('sync && echo 3 > /proc/sys/vm/drop_caches'); | |
$mems=array(); | |
$tmp=explode("\n", trim(shell_exec('cat /proc/meminfo | grep -P "Mem|Commit|Cached"'))); | |
foreach ($tmp as $v) | |
{ | |
$v=explode(':', $v); | |
$mems[$v[0]]=intval($v[1]); | |
} | |
//var_export($mems); | |
$overcommit_ratio=round(($mems['Committed_AS']+$mems['MemFree']*1.30)/$mems['MemTotal']*100); | |
//echo $overcommit_ratio."\n"; | |
echo shell_exec("/sbin/sysctl vm.overcommit_memory=2"); //拒绝分配超过1.3倍, 第一重预防 | |
echo shell_exec("/sbin/sysctl vm.overcommit_ratio={$overcommit_ratio}"); | |
echo shell_exec('pgrep -f "/usr/bin/X" | while read PID; do echo -17 > /proc/$PID/oom_adj; done'); //lxsession内存利用率高不担心, oom统计默认只排除了systemd-udevd和sshd漏了Xorg | |
while (time()-$start_time<56) //1分钟还剩不到4秒就不要继续循环了, 避免跟crontab启动的任务重叠 | |
{ | |
$tmp=explode(':', trim(shell_exec('cat /proc/meminfo | grep -P "MemFree"')), 2); | |
$free=intval($tmp[1]); | |
$tmp=explode(':', trim(shell_exec('cat /proc/meminfo | grep -P "Buffers"')), 2); | |
$buffers=intval($tmp[1]); | |
$tmp=explode(':', trim(shell_exec('cat /proc/meminfo | grep -P "Cached"')), 2); | |
$cached=intval($tmp[1]); | |
$tmp=$free+$buffers+$cached; //这才是真正剩余的内存 | |
//echo $tmp."\n"; | |
if ($tmp>0 && $tmp<200000) //是numeric并且小于200MB才开始预防性杀oom统计的坏进程, 第二重预防 | |
{ | |
$bad=preg_split("/\s+/", trim(@shell_exec('for proc in $(find /proc -maxdepth 1 -regex "/proc/[0-9]+"); do printf "%2d %5d %s\n" "$(cat $proc/oom_score)" "$(basename $proc)" "$(cat $proc/cmdline | tr "\0" " " | head -c 50)"; done 2>/dev/null | sort -nr | head -n 1')), 3); | |
//var_export($bad); | |
$bad_name=$bad[2]; | |
$bad=$bad[1]; | |
echo $bad_name."\n"; | |
if (is_numeric($bad)) | |
{ | |
echo shell_exec("kill -9 {$bad}"); | |
file_put_contents('/home/malcolm/set_overcommit_ratio.txt', date('Ymd His:').$bad_name."\n", FILE_APPEND); | |
} | |
} | |
sleep(3); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment