12.19.2014

user process limit on Linix

最近在Linux遇到了一個ulimits (limits)問題,因為對這部份之前沒研究,infra team的人又在忙沒空看,只好自己上網找解,噴掉了我快2天的時間,想說跟大家分享一下!這個錯會在你執行指令時發生,如下:

[apprm@OTALOG logs]$ ls -lrt

-bash: fork: retry: Resource temporarily unavailable
-bash: fork: retry: Resource temporarily unavailable
-bash: fork: retry: Resource temporarily unavailable
-bash: fork: retry: Resource temporarily unavailable
-bash: fork: Resource temporarily unavailable

一開始google,很多篇都說是因為file descriptor用完了(也就是open file限制),查了後並沒有問題,後來發現其實是因為"max user processes"限制,下面來介紹一下面對這個問題可能的原因。

1. File descriptor用完了

一般來說,會出錯這個錯是因為file descriptor用完了,在Linux有分幾種不同的file descriptor限制
1.1 系統整體的file descriptor限制
[apprm@OTALOG ~]$ sysctl fs.file-nr
fs.file-nr = 2656 0 10240
這個指令會印出3個數字,第一個是目前使用的file descriptor數目,第二個是分配但未使用的數目,第三個則是系統最大的file descriptor。以上面來看,明顯問題不是在這。
1.2 特定user的file descriptor限制
[apprm@OTALOG ~]$ ulimit -Hn
8192
[apprm@OTALOG ~]$ ulimit -Sn
8192
[apprm@OTALOG ~]$ lsof -u apprm  | wc -l
4058
user的file descriptor限制分為soft limit和hard limit。soft limit一般而言不會是問題,因為process在執行時若有需要可自行突破上限;而hard limit則不行,除非有root權限才能突破hard limit限制。從執行的指令來看,hard limit設20480,soft limit設為8192,目前使用者用了4058,看來問題也不是在user limit。

若你在1.1或1.2的使用值非常接近或等於上限,恭喜你找到問題點!你要去修改相對應的檔案 針對1.1,要在/etc/sysctl.conf加上一行"fs.file-max = 10240",10240視情況而定(必需大於hard limit) 針對1.2,要在/etc/security/limits.conf 分別設定soft limit和hard limit * soft nofile 8192 * hard nofile 8192

2. 到達最大process(max user processes)限制

若問題不是出在file descriptor,那應該就是因為max user processes限制(預設為1024,root不受限制)。Linux並沒有thread,只有light weight processes(LWPs),基本上LWPs就跟其他作業系統的thread一樣,所以你可能只起一個application server instance,但為了performance,可能一開始就建立了200個thread的thread pool,在計算每個user process時,包含了user起的所有process以及LWPs,因此當server instance一多,很容易就達到預設上限
[apprm@OTALOG logs]$ ulimit -a | grep processes
max user processes              (-u) 1024
[apprm@OTALOG logs]$ ps -eLF | grep ^apprm | wc -l
1023
在第一個查詢我們得知目前的max user processes為1024,第二個查詢發現,apprm已經使用了1023個processes!Bingo!找到問題了!
修正方式是在要在/etc/security/limits.conf 加入下面設定 (2048可視需求調整) apprm - nproc 2048

No comments: