Tomcat “Too many files open” issue

Posted in :

遇到類似的問題,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下有有文件數操作最大限制,超過限制(同時開啟1024個檔案)會導致程式異常,會發生這個問題通常時程式沒寫好,使用靜態方法打開文件時忘記關閉。兩種解決方法,一是設置linux的最大文件打開數量(無法根本解決問題),二是解決程序中的bugs,即消除有問題的代碼。

第一次解决
解决:
方法一、增大系统打开文件的数量(无法根本解决问题)、
1、默认linux同时最大打开文件数量为1024个,用命令查看如下:ulimit -a:查看系统上受限资源的设置(open files (-n) 1024): 代码

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

2、可以修改同时打开文件的最大数基本可以解决:ulimit -n 4096 代码

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

已经修改了最大打开文件数。

方法二、修改程序中的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. [root@**** ~]# 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: [root@****: command not found
  2. [root@**** ~]# clear
  3. [root@**** ~]# cat /etc/pam.d/login
  4. #%PAM-1.0
  5. auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so
  6. auth       include      system-auth
  7. account    required     pam_nologin.so
  8. account    include      system-auth
  9. password   include      system-auth
  10. # pam_selinux.so close should be the first session rule
  11. session    required     pam_selinux.so close
  12. session    optional     pam_keyinit.so force revoke
  13. session    required     pam_loginuid.so
  14. session    include      system-auth
  15. session    optional     pam_console.so
  16. # pam_selinux.so open should only be followed by sessions to be executed in the user context
  17. session    required     pam_selinux.so open
  18. # kevin.xie added, fixed ‘too many open file’ bug, limit open max files 1024, 2011-10-24
  19. session required     /lib/security/pam_limits.so
  20. [root@**** ~]#

2. /etc/security/limits.conf 添加 代码

  1. root          –    nofile       1006154

root 是一个用户,如果是想所有用户生效的话换成 * ,设置的数值与硬件配置有关,别设置太大了。
修改前内容 代码

  1. [root@**** ~]# 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. [root@**** ~]#
  51. [root@**** ~]# cat /etc/security/limits.conf
  52. # /etc/security/limits.conf
  53. #
  54. #Each line describes a limit for a user in the form:
  55. #
  56. #<domain>        <type>  <item>  <value>
  57. #
  58. #Where:
  59. #<domain> can be:
  60. #        – an user name
  61. #        – a group name, with @group syntax
  62. #        – the wildcard *, for default entry
  63. #        – the wildcard %, can be also used with %group syntax,
  64. #                 for maxlogin limit
  65. #
  66. #<type> can have the two values:
  67. #        – “soft” for enforcing the soft limits
  68. #        – “hard” for enforcing hard limits
  69. #
  70. #<item> can be one of the following:
  71. #        – core – limits the core file size (KB)
  72. #        – data – max data size (KB)
  73. #        – fsize – maximum filesize (KB)
  74. #        – memlock – max locked-in-memory address space (KB)
  75. #        – nofile – max number of open files
  76. #        – rss – max resident set size (KB)
  77. #        – stack – max stack size (KB)
  78. #        – cpu – max CPU time (MIN)
  79. #        – nproc – max number of processes
  80. #        – as – address space limit
  81. #        – maxlogins – max number of logins for this user
  82. #        – maxsyslogins – max number of logins on the system
  83. #        – priority – the priority to run user process with
  84. #        – locks – max number of file locks the user can hold
  85. #        – sigpending – max number of pending signals
  86. #        – msgqueue – max memory used by POSIX message queues (bytes)
  87. #        – nice – max nice priority allowed to raise to
  88. #        – rtprio – max realtime priority
  89. #
  90. #<domain>      <type>  <item>         <value>
  91. #
  92. #*               soft    core            0
  93. #*               hard    rss             10000
  94. #@student        hard    nproc           20
  95. #@faculty        soft    nproc           20
  96. #@faculty        hard    nproc           50
  97. #ftp             hard    nproc           0
  98. #@student        –       maxlogins       4
  99. # kevin.xie added, fixed ‘too many open file’ bug, limit open max files 1024, 2011-10-24
  100. * – nofile 102400
  101. # End of file
  102. [root@**** ~]#

3. 修改 /etc/rc.local   添加 代码

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

修改前内容 代码

  1. [root@**** ~]# cat /proc/sys/fs/file-max
  2. 4096

修改后内容 Java代码

  1. [root@**** ~]# 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

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *