1. 程式人生 > >Tomcat “Too many files open” issue

Tomcat “Too many files open” issue

遇到類似的問題,Tomcat 不管是 BIO 還是 NIO 模式,遇到 Server 太忙,應該是 server.xml 的設定有問題,都會造成 Server 掛掉,掛掉後都可以在 catalina.out 檔案裡看到:

2011-3-16 14:17:30 org.apache.tomcat.util.net.JIoEndpoint$Acceptor run
嚴重: Socket accept failed
java.net.SocketException: Too many open files
        at java.net.PlainSocketImpl.socketAccept(Native Method)
        at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:408)
        at java.net.ServerSocket.implAccept(ServerSocket.java:462)
        at java.net.ServerSocket.accept(ServerSocket.java:430)
        at org.apache.tomcat.util.net.DefaultServerSocketFactory.acceptSocket(DefaultServerSocketFactory.java:61)
        at org.apache.tomcat.util.net.JIoEndpoint$Acceptor.run(JIoEndpoint.java:317)
        at java.lang.Thread.run(Thread.java:662)
2011-3-16 14:17:30 org.apache.tomcat.util.net.JIoEndpoint$Acceptor run
嚴重: Socket accept failed
java.net.SocketException: Too many open files
        at java.net.PlainSocketImpl.socketAccept(Native Method)
        at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:408)
        at java.net.ServerSocket.implAccept(ServerSocket.java:462)
        at java.net.ServerSocket.accept(ServerSocket.java:430)

原因:
linux下有有檔案限制,結果檔案數操作最大限制,導致程式異常:問題是程式中有個靜態方法開啟檔案時忘記關閉。兩種解決方法,一是設定linux的最大檔案開啟數量(無法根本解決問題),二是解決程式中的bugs,即消除有問題的程式碼。

第一次解決
解決:
方法一、增大系統開啟檔案的數量(無法根本解決問題)、
1、預設linux同時最大開啟檔案數量為1024個,用命令檢視如下:ulimit -a:檢視系統上受限資源的設定(open files (-n) 1024):

程式碼
  1. core file size          (blocks, -c) 0
  2. data seg size           (kbytes, -d) unlimited
  3. scheduling priority             (-e) 0
  4. file size               (blocks, -f) unlimited
  5. pending signals                 (-i) 16384
  6. max locked memory       (kbytes, -l) 32
  7. max memory size         (kbytes, -m) unlimited
  8. open files                      (-n) 1024
  9. pipe size            (512 bytes, -p) 8
  10. POSIX message queues     (bytes, -q) 819200
  11. real-time priority              (-r) 0
  12. stack size              (kbytes, -s) 10240
  13. cpu time               (seconds, -t) unlimited
  14. max user processes              (-u) 16384
  15. virtual memory          (kbytes, -v) unlimited
  16. file locks                      (-x) unlimited

2、可以修改同時開啟檔案的最大數基本可以解決:ulimit -n 4096

程式碼
  1. core file size          (blocks, -c) 0
  2. data seg size           (kbytes, -d) unlimited
  3. scheduling priority             (-e) 0
  4. file size               (blocks, -f) unlimited
  5. pending signals                 (-i) 16384
  6. max locked memory       (kbytes, -l) 32
  7. max memory size         (kbytes, -m) unlimited
  8. open files                      (-n) 4096
  9. pipe size            (512 bytes, -p) 8
  10. POSIX message queues     (bytes, -q) 819200
  11. real-time priority              (-r) 0
  12. stack size              (kbytes, -s) 10240
  13. cpu time               (seconds, -t) unlimited
  14. max user processes              (-u) 16384
  15. virtual memory          (kbytes, -v) unlimited
  16. file locks                      (-x) unlimited

已經修改了最大開啟檔案數。

方法二、修改程式中的bugs:
程式中有個靜態的方法開啟檔案後,沒有關閉檔案,導致每次請求都會去開啟檔案,在程式中填入關閉輸入流的操作即可以:

程式碼
  1. public static List<GpsPoint> getArrayList() throws IOException {
  2.         List<GpsPoint> pointList = null;
  3.         // 讀取配置檔案
  4.         InputStream in = ParseGpsFile.class.getClassLoader().getResourceAsStream(“GPS1.TXT”);
  5.         // 讀路徑出錯,換另一種方式讀取配置檔案
  6.         if (null == in) {
  7.             System.out.println(“讀取檔案失敗”);
  8.             return pointList;
  9.         }
  10.         pointList = new ArrayList<GpsPoint>();
  11.         try {
  12.             BufferedReader br = new BufferedReader(new InputStreamReader(in));
  13.             String longtude = “”;
  14.             String latude = “”;
  15.             String elevation = “”;
  16.             while ((longtude = br.readLine()) != null) {
  17.                 // 讀下一行資料,讀緯度
  18.                 latude = br.readLine();
  19.                 if (null == latude) {
  20.                     // 退出迴圈
  21.                     break;
  22.                 }
  23.                 // 讀下一行資料,讀海拔
  24.                 elevation = br.readLine();
  25.                 if (null == latude) {
  26.                     // 退出迴圈
  27.                     break;
  28.                 }
  29.                 // 加入一個點
  30.                 pointList.add(gps2point(longtude, latude, elevation));
  31.             }
  32.             in.close();
  33.             System.out.println(“\n\n”);
  34.         } catch (Exception e) {
  35.             in.close();
  36.             e.printStackTrace();
  37.         }
  38.         return pointList;
  39.     }

問題徹底解決

—–
第二次解決:
實際測試後發現這個問題還沒有解決,最終又找了些方法,經過一段時間的測試,似乎解決了問題:

具體步驟如下:
linux為redhat伺服器版本(非個人版),必須設定的內容:

1、/etc/pam.d/login 新增

程式碼
  1. session required     /lib/security/pam_limits.so

# 注意看這個檔案的註釋
具體檔案的內容為:

程式碼
  1. [[email protected]**** ~]# vi /etc/pam.d/login
  2. #%PAM-1.0
  3. auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so
  4. auth       include      system-auth
  5. account    required     pam_nologin.so
  6. account    include      system-auth
  7. password   include      system-auth
  8. # pam_selinux.so close should be the first session rule
  9. session    required     pam_selinux.so close
  10. session    optional     pam_keyinit.so force revoke
  11. session    required     pam_loginuid.so
  12. session    include      system-auth
  13. session    optional     pam_console.so
  14. # pam_selinux.so open should only be followed by sessions to be executed in the user context
  15. session    required     pam_selinux.so open
  16. ~
  17. “/etc/pam.d/login” 15L, 644C

修改後的內容:

程式碼
  1. -bash: [[email protected]****: command not found
  2. [[email protected]**** ~]# cat /etc/pam.d/login
  3. #%PAM-1.0
  4. auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so
  5. auth       include      system-auth
  6. account    required     pam_nologin.so
  7. account    include      system-auth
  8. password   include      system-auth
  9. # pam_selinux.so close should be the first session rule
  10. session    required     pam_selinux.so close
  11. session    optional     pam_keyinit.so force revoke
  12. session    required     pam_loginuid.so
  13. session    include      system-auth
  14. session    optional     pam_console.so
  15. # pam_selinux.so open should only be followed by sessions to be executed in the user context
  16. session    required     pam_selinux.so open
  17. # kevin.xie added, fixed ‘too many open file’ bug, limit open max files 102420111024
  18. session required     /lib/security/pam_limits.so

2. /etc/security/limits.conf 新增

程式碼
  1. root          –    nofile       1006154

root 是一個使用者,如果是想所有使用者生效的話換成 * ,設定的數值與硬體配置有關,別設定太大了。
修改前內容

程式碼
  1. [[email protected]**** ~]# cat /etc/security/limits.conf
  2. # /etc/security/limits.conf
  3. #
  4. #Each line describes a limit for a user in the form:
  5. #
  6. #<domain>        <type>  <item>  <value>
  7. #
  8. #Where:
  9. #<domain> can be:
  10. #        – an user name
  11. #        – a group name, with @group syntax
  12. #        – the wildcard *, for default entry
  13. #        – the wildcard %, can be also used with %group syntax,
  14. #                 for maxlogin limit
  15. #
  16. #<type> can have the two values:
  17. #        – “soft” for enforcing the soft limits
  18. #        – “hard” for enforcing hard limits
  19. #
  20. #<item> can be one of the following:
  21. #        – core – limits the core file size (KB)
  22. #        – data – max data size (KB)
  23. #        – fsize – maximum filesize (KB)
  24. #        – memlock – max locked-in-memory address space (KB)
  25. #        – nofile – max number of open files
  26. #        – rss – max resident set size (KB)
  27. #        – stack – max stack size (KB)
  28. #        – cpu – max CPU time (MIN)
  29. #        – nproc – max number of processes
  30. #        – as – address space limit
  31. #        – maxlogins – max number of logins for this user
  32. #        – maxsyslogins – max number of logins on the system
  33. #        – priority – the priority to run user process with
  34. #        – locks – max number of file locks the user can hold
  35. #        – sigpending – max number of pending signals
  36. #        – msgqueue – max memory used by POSIX message queues (bytes)
  37. #        – nice – max nice priority allowed to raise to
  38. #        – rtprio – max realtime priority
  39. #
  40. #<domain>      <type>  <item>         <value>
  41. #
  42. #*               soft    core            0
  43. #*               hard    rss             10000
  44. #@student        hard    nproc           20
  45. #@faculty        soft    nproc           20
  46. #@faculty        hard    nproc           50
  47. #ftp             hard    nproc           0
  48. #@student        –       maxlogins       4
  49. # End of file
  50. [[email protected]**** ~]# cat /etc/security/limits.conf
  51. # /etc/security/limits.conf
  52. #
  53. #Each line describes a limit for a user in the form:
  54. #
  55. #<domain>        <type>  <item>  <value>
  56. #
  57. #Where:
  58. #<domain> can be:
  59. #        – an user name
  60. #        – a group name, with @group syntax
  61. #        – the wildcard *, for default entry
  62. #        – the wildcard %, can be also used with %group syntax,
  63. #                 for maxlogin limit
  64. #
  65. #<type> can have the two values:
  66. #        – “soft” for enforcing the soft limits
  67. #        – “hard” for enforcing hard limits
  68. #
  69. #<item> can be one of the following:
  70. #        – core – limits the core file size (KB)
  71. #        – data – max data size (KB)
  72. #        – fsize – maximum filesize (KB)
  73. #        – memlock – max locked-in-memory address space (KB)
  74. #        – nofile – max number of open files
  75. #        – rss – max resident set size (KB)
  76. #        – stack – max stack size (KB)
  77. #        – cpu – max CPU time (MIN)
  78. #        – nproc – max number of processes
  79. #        – as – address space limit
  80. #        – maxlogins – max number of logins for this user
  81. #        – maxsyslogins – max number of logins on the system
  82. #        – priority – the priority to run user process with
  83. #        – locks – max number of file locks the user can hold
  84. #        – sigpending – max number of pending signals
  85. #        – msgqueue – max memory used by POSIX message queues (bytes)
  86. #        – nice – max nice priority allowed to raise to
  87. #        – rtprio – max realtime priority
  88. #
  89. #<domain>      <type>  <item>         <value>
  90. #
  91. #*               soft    core            0
  92. #*               hard    rss             10000
  93. #@student        hard    nproc           20
  94. #@faculty        soft    nproc           20
  95. #@faculty        hard    nproc           50
  96. #ftp             hard    nproc           0
  97. #@student        –       maxlogins       4
  98. # kevin.xie added, fixed ‘too many open file’ bug, limit open max files 102420111024
  99. * – nofile 102400
  100. # End of file

3. 修改 /etc/rc.local   新增

程式碼
  1. echo 8061540 > /proc/sys/fs/file-max

修改前內容

程式碼
  1. [[email protected]**** ~]# cat /proc/sys/fs/file-max
  2. 4096

修改後內容

Java程式碼
  1. [[email protected]**** ~]# cat /proc/sys/fs/file-max
  2. 4096000

做完3個步驟,就可以了。

**************************************
補充說明:
/proc/sys/fs/file-max
該檔案指定了可以分配的檔案控制代碼的最大數目。如果使用者得到的錯誤訊息宣告由於開啟檔案數已經達到了最大值,從而他們不能開啟更多檔案,則可能需要增加該值。可將這個值設定成有任意多個檔案,並且能通過將一個新數字值寫入該檔案來更改該值。
預設設定:4096
/proc/sys/fs/file-nr
該檔案與 file-max 相關,它有三個值:
已分配檔案控制代碼的數目
已使用檔案控制代碼的數目
檔案控制代碼的最大數目
該檔案是隻讀的,僅用於顯示資訊。
關於“開啟檔案數”限制
Linux系統上對每一個使用者可使用的系統資源都是有限制的,這是多使用者系統必然要採用的一種資源管理手段,試想假如沒有這種機制,那麼任何一個普通使用者寫一個死迴圈程式,用不了多久系統就要“拒絕服務”了。
今天我遇到了tomcat日誌報的錯誤資訊”too many open files”,第一意識就想到了是ulimit控制的”open files“限制。然而問題來了。我在/etc/profile里加入了 ulimit -n 4096儲存之後,普通使用者登入的時候均會收到一條錯誤資訊ulimit: open files: cannot modify limit: Operation not permitted。然後普通使用者的open files限制還是預設值1024。
然後開始在網際網路上搜索關於ulimit的資訊。網際網路果然方便,資訊鋪天蓋地。大家也可以搜一下試一下。其中我瞭解到兩個以前不知道的相關內容。
第一個是核心引數 fs.file-max  ,影射為 /proc/sys/fs/file-max
第二個是配置檔案 /etc/security/limits.conf
其中大部分的資訊中提到 將 /proc/sys/fs/file-max的值設定為4096和ulimit -n 4096是相同的效果。對此我很懷疑,為什麼呢?首先ulimit 是一個普通使用者也可以使用的命令,而fs.file-max只有root有權設定。其次,很明顯fs.file-max是一個全域性的設定,而ulimit 是一個區域性的設定,很明顯的是不相同的。
帶著疑慮,又在網上搜索了許久,未果(實際上是我搜索的關鍵字不夠準確)。
最後終於在核心文件/usr/src/linux/Documentation/sysctl/fs.txt裡找到下面一段話:
file-max & file-nr:
The kernel allocates file handles dynamically, but as yet it doesn’t free them again. The value in file-max denotes the maximum number of file-handles that the Linux kernel will allocate. When you get lots of error messages about running out of file handles, you might want to increase this limit.
The three values in file-nr denote the number of allocated file handles, the number of unused file handles and the maximum number of file handles. When the allocated file handles come close to the maximum, but the number of unused file handles is significantly greater than 0, you’ve encountered a peak in your usage of file handles and you don’t need to increase the maximum.
這兩段話的大致意思是:
核心動態地分配和釋放“file handles”(控制代碼)。file-max的值是核心所能分配到的最大控制代碼數。當你收到大量關於控制代碼用完的錯誤資訊時,你可以需要增加這個值以打破老的限制。
file-nr中的三個值的含意分別是:系統已經分配出去(正在使用)的控制代碼數,沒有用到的控制代碼數和所有分配到的最大控制代碼數。當分配出去的控制代碼數接近 最大控制代碼數,而“無用的控制代碼數”大於零時,表明你遇到了一個“控制代碼”使用高峰,這意為著你不需要增加file-max的值。
看完這段話,相信大家都明白了。file-max是系統全域性的可用控制代碼數。根據我後來又翻查的資訊,以及對多個系統的檢視求證,這個引數的預設值是跟記憶體大小有關係的,增加實體記憶體以後重啟機器,這個值會增大。大約1G記憶體10萬個控制代碼的線性關係。
再回過頭來看這兩段話,不知道你意識到了沒有,文中只提到了file-max的增加,而沒有提到了該值的減少。那些在操作ulimit時同時操 作了file-max的哥們兒,估計無一例外地將file-max設定成了4096或者2048。但以似乎也沒有因此而導致系統無法開啟檔案或者建議連 接。(實際上,我將file-max的值裝置成256,然後使用shell編寫用vi開啟500個檔案角本執行,並沒有得到任何錯誤資訊,檢視file- nr的值,系統當前分配的控制代碼值已經遠超過了後面的最大值。所以我猜想對於file-max的任何減少的操作都是毫無意義的,姑且不去管他。實踐中需要減 少file-max的時候總是不多見的。 )實事證明我犯了一個致命的錯誤。我測試的時候使用的是root使用者,而當我再次使用普通使用者測試的時候,預料中的錯誤資訊出現了:”Too many open files in system”。可見,file-max的減少對系統也是影響力的。前面的結論“所以我猜想對於file-max的任何減少的操作都是毫無意義的”是錯誤 的。
然後便是/etc/security/limits.conf檔案,這個檔案很簡單,一看就能明白。
於是我按照註釋中描述的格式兩個兩行:
*  soft  nofile  4096
*  hard  nofile  4096
恐怖的是,網上居然有人說改了這個設定是需要重啟系統的!實在是讓人想不通啊,鼎鼎大名的UNIX系統,怎麼可能因為這麼小小的一個改動就需要 重啟系統呢?結果當我再次以普通使用者登入的時候,那個”ulimit: open files: cannot modify limit: Operation not permitted”提示沒有了,檢視ulimit -n,果然已經變成了4096。
linux lsof 修改控制代碼限制(轉)
在Linux下,我們使用ulimit -n 命令可以看到單個程序能夠開啟的最大檔案控制代碼數量(socket連線也算在裡面)。系統預設值1024。
對於一般的應用來說(象Apache、系統程序)1024完全足夠使用。但是如何象squid、mysql、java等單程序處理大量請求的應用來說就有點捉襟見肘了。如果單個程序開啟的檔案控制代碼數量超過了系統定義的值,就會提到“too many files open”的錯誤提示。如何知道當前程序打開了多少個檔案控制代碼呢?下面一段小指令碼可以幫你檢視:
lsof -n |awk ‘{print $2}’|sort|uniq -c |sort -nr|more
在系統訪問高峰時間以root使用者執行上面的指令碼,可能出現的結果如下:
# lsof -n|awk ‘{print $2}’|sort|uniq -c |sort -nr|more
131 24204
57 24244
57 24231
56 24264
其中第一行是開啟的檔案控制代碼數量,第二行是程序號。得到程序號後,我們可以通過ps命令得到程序的詳細內容。
ps -aef|grep 24204
mysql 24204 24162 99 16:15 ? 00:24:25 /usr/sbin/mysqld
哦,原來是mysql程序開啟最多檔案控制代碼數量。但是他目前只打開了131個檔案控制代碼數量,遠遠底於系統預設值1024。
但是如果系統併發特別大,尤其是squid伺服器,很有可能會超過1024。這時候就必須要調整系統引數,以適應應用變化。Linux有硬性限制和軟性限制。可以通過ulimit來設定這兩個引數。方法如下,以root使用者執行以下命令:
ulimit -HSn 4096
以上命令中,H指定了硬性大小,S指定了軟性大小,n表示設定單個程序最大的開啟檔案控制代碼數量。個人覺得最好不要超過4096,畢竟開啟的檔案控制代碼數越多響應時間肯定會越慢。設定控制代碼數量後,系統重啟後,又會恢復預設值。如果想永久儲存下來,可以修改.bash_profile檔案,可以修改 /etc/profile 把上面命令加到最後。

仍未處理的問題:
為什麼redhat9的個人版按照以上的方式修改1024tcp連線限制依然不行呢?
是因為個人版最多支援1024個tcp連線,還是修改方式、相關檔案會有所不同?

以上內容,來源網路並加自己親自測試,經過測試,似乎沒有再出現過問題,但不知道是否真的解決,有待更長時間的測試看看

同時在配置檔案 /etc/security/limits.conf  加了一個配置(該不該問題不大):
* soft nofile 65536
* hard nofile 65536

程式碼
  1. # 第二次解決新增的內容
  2. * – nofile 102400
  3. # 第三次(本次)解決新增的問題(不過這個應該可以不修改,沒有印證,也懶得修改了)
  4. * soft nofile 65536
  5. * hard nofile 65536