如何监控Tomcat服务器

如何监控Tomcat服务器

发表于:2009-06-25来源:作者:点击数:2651 标签:tomcatTomcat服务器
在进行 性能测试 时,一般都需要对应用服务器进行监控,监控的指标包括应用服务器的JVM使用状况、可用连接数、队列长度等信息。商业的应用服务器如 WebLogic 、 WebSphere 等都提供了Console对这些指标进行监控,在性能测试时可以很容易观察这些指标的情况。

在进行性能测试时,一般都需要对应用服务器进行监控,监控的指标包括应用服务器的JVM使用状况、可用连接数、队列长度等信息。商业的应用服务器如WebLogicWebSphere等都提供了Console对这些指标进行监控,在性能测试时可以很容易观察这些指标的情况。

  Tomcat作为在国内得到广泛应用的J2EE服务器,在不少项目中都得到了使用。Tomcat小巧灵活、配置简单,非常适合小的WEB应用使用。但在对使用Tomcat的应用系统进行性能测试时,最头疼的问题就是不能获得应用服务器的相关性能指标数据。

   其实,从Tomcat 5.0开始,Tomcat就已经为自己提供了一个用于监控应用服务器性能指标的servelet —— status servelet。安装完Tomcat 5之后,通过访问 http://yourhost:port/manager/status 就可以获得当时的应用服务器监控数据。

  当然,为了安全起见,Tomcat 5在缺省安装时是不允许用户直接访问 http://yourhost:port/manager/status 的,访问的时候会给出一个403(forbidden)的错误信息。在Tomcat的Manual里说明了允许用户访问的方法:

   1. 转到Tomcat的安装目录下;
   2. 修改conf/tomcat-users.xml文件,在其中加入一行  <user username="servermon" password="passwd" roles="manager"/>

  这样就可以在访问 http://yourhost:port/manager/status 时给出 servermon 的用户名与口令,查看到应用服务器的相关性能指标数据。

You are not authorized to view this page. If you have not changed any configuration files, please examine the file conf/tomcat-users.xml in your installation. That file must contain the credentials to let you use this webapp.

For example, to add the manager-gui role to a user named tomcat with a password of s3cret, add the following to the config file listed above.

<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>

Note that for Tomcat 7 onwards, the roles required to use the manager application were changed from the single manager role to the following four roles. You will need to assign the role(s) required for the functionality you wish to access.

  • manager-gui - allows access to the HTML GUI and the status pages
  • manager-script - allows access to the text interface and the status pages
  • manager-jmx - allows access to the JMX proxy and the status pages
  • manager-status - allows access to the status pages only

The HTML interface is protected against CSRF but the text and JMX interfaces are not. To maintain the CSRF protection:

  • Users with the manager-gui role should not be granted either the manager-script or manager-jmx roles.
  • If the text or jmx interfaces are accessed through a browser (e.g. for testing since these interfaces are intended for tools not humans) then the browser must be closed afterwards to terminate the session.

For more information - please see the Manager App HOW-TO.

*************************************************************************************************************************************************************************************

前言:做了一个监控应用服务器的项目(支持Tocmat、WebSphere、WebLogic各版本), 过程也算是磕磕绊绊,由于网上缺少相关资料,或者深陷于知识的海洋难以寻觅到有效的资料,因而走过不少弯路,遇过不少困难。为了留下点印记,给后来人留下 点经验之谈,助之少走弯路,故将这些经验整理出来,与大家分享。水平有限,难免疏漏,还望指正。如有疑问,欢迎留言,或者加入Q群参与讨 论:35526521



监控Tomcat的常见方案有两种,比较如下:

方案一、使用Tomcat提供的manager应用进行数据采集
◆ 可以使用现有的成熟代码,减少工作量
◆ 支持各不同版本时无差别
◆ 可能存在特殊需求而manager不能满足的情况

◆ 最重要的一个优点是,配置比较简单

方案二、使用JMX接口开发监控程序
◆ 全部代码需要从零开始,代码量较大
◆ 支持各不同版本比较麻烦,每个版本可能有差异
◆ 可支配性强

◆ 最重要的一个缺点是,配置比较麻烦

 


方案一、使用 Tomcat提供的manager应用进行数据采集
Applications Manager(又称opManager)就是通过这种方式实现的。
使用这种方式,所监控Tomcat必须运行manager应用,缺省情况下,该应用总是运行在服务器中的。

增加manager角色用户

访问manager应用的用户的角色权限必须是 manager.
修改<TOMCAT_HOME>/conf目录下的tomcat-users.xml文件,在<tomcat-users>节点下添加一个user节点,即可创建一个用户。

Tomcat版本不同配置也有差异,5.x和6.x创建的用户角色应为manager,7.x创建的用户角色为manager-jmx,举例如下:

1、在5.x和6.x中创建一个manager角色的用户,用户名为admin,密码为chenfeng:
    <user username="admin" password="chenfeng" roles="manager"/>

2、在7.x中创建一个manager角色的用户,用户名为admin,密码为chenfeng:
    <user username="admin" password="chenfeng" roles="manager-jmx,manager-script,manager-status"/>

修改配置后,需要重新启动 Tomcat 服务器。
连接manager时将用户名/密码指定为admin/chenfeng

通过浏览器访问JMX Proxy Servlet

详见官方说明文档:
http://tomcat.apache.org/tomcat-6.0-doc/manager-howto.html#Using_the_JMX_Proxy_Servlet

What is JMX Proxy Servlet

Java代码  收藏代码
  1. The JMX Proxy Servlet is a lightweight proxy to get and set the tomcat internals. (Or any class that has been exposed via an MBean) Its usage is not very user friendly but the UI is extremely help for integrating command line scripts for monitoring and changing the internals of tomcat. You can do two things with the proxy: get information and set information. For you to really understand the JMX Proxy Servlet, you should have a general understanding of JMX. If you don't know what JMX is, then prepare to be confused.  

JMX Query command

Java代码  收藏代码
  1. This takes the form:  
  2. http://webserver/manager/jmxproxy/?qry=STUFF  
  3.   
  4. Where STUFF is the JMX query you wish to perform. For example, here are some queries you might wish to run:  
  5.   
  6. ◆ qry=*%3Atype%3DRequestProcessor%2C* --> type=RequestProcessorwhich will locate all workers which can process requests and report their state.  
  7.   
  8. ◆ qry=*%3Aj2eeType=Servlet%2c* --> j2eeType=Servletwhich return all loaded servlets.  
  9.   
  10. ◆ qry=Catalina%3Atype%3DEnvironment%2Cresourcetype%3DGlobal%2Cname%3DsimpleValue --> Catalina:type=Environment,resourcetype=Global,name=simpleValuewhich look for a specific MBean by the given name.  
  11.   
  12. You'll need to experiment with this to really understand its capabilites. If you provide no qry parameter, then all of the MBeans will be displayed. We really recommend looking at the tomcat source code and understand the JMX spec to get a better understanding of all the queries you may run.  

通过浏览器访问http://localhost:8080/manager/jmxproxy ,输入用户名密码,然后就可以看到返回了所有的监控信息

添加查询参数,返回特定的监控信息:
例如:

http://localhost:8080/manager/jmxproxy?qry=*%3Atype%3DRequestProcessor%2C*

其中 *%3Atype%3DRequestProcessor%2C* 其实就是 *:type=RequestProcessor,*

又如:

http://localhost:8080/manager/jmxproxy?qry=*%3Aj2eeType%3DWebModule%2Cname%3D//localhost/ajaxrpc%2C*


在代码中访问JMX Proxy Servlet


通过浏览器访问JMX Proxy Servlet需要输入用户名密码,所以通过Java访问JMX Proxy Servlet的URL也需要授权访问: URL url = new URL("http://localhost:8080/manager/jmxproxy?qry=*%3Atype%3DManager%2C*");

Java代码  收藏代码
  1. URLConnection conn = (URLConnection) url.openConnection();  
  2.   
  3. // URL授权访问 -- Begin  
  4. String password = "admin:chenfeng"; // manager角色的用户  
  5. String encodedPassword = new BASE64Encoder().encode(password.getBytes());  
  6. conn.setRequestProperty("Authorization", "Basic " + encodedPassword);  
  7. // URL授权访问 -- End  
  8.   
  9. InputStream is = conn.getInputStream();  
  10. BufferedReader bufreader = new BufferedReader(new InputStreamReader(is));  
  11. String line = null;  
  12. while ((line = bufreader.readLine()) != null) {  
  13.     System.out.println(line);  
  14. }  

几个具体的例子

下面展示两个例子,一个是采集服务器基本信息,一个是采集Web应用列表信息,注意Tomcat 7.x和Tomcat 5.x、6.x之间存在很大的区别。

◆ 采集服务器基本信息

通过serverinfo命令查看服务器基本信息
     http://localhost:8080/manager/serverinfo

Tomcat 7.x的查询URL有变化:
     http://localhost:8080/manager/text/serverinfo

返回信息:

Java代码  收藏代码
  1. OK - Server info  
  2. Tomcat Version: Apache Tomcat/7.0.11  
  3. OS Name: Windows Vista  
  4. OS Version: 6.1  
  5. OS Architecture: x86  
  6. JVM Version: 1.6.0_13-b03  
  7. JVM Vendor: Sun Microsystems Inc.  


◆ 采集Web应用列表信息

通过list命令查看Web应用列表和会话数信息
     http://localhost:8080/manager/list

Tomcat 7.x的查询URL有变化:
     http://localhost:8080/manager/text/list

返回信息:

Java代码  收藏代码
  1. OK - Listed applications for virtual host localhost  
  2. /:running:0:ROOT  
  3. /manager:running:1:manager  
  4. /docs:running:0:docs  
  5. /examples:running:0:examples  
  6. /host-manager:running:0:host-manager  

 

方案二、使用JMX 接口开发监控程序

Tomcat激活JMX远程配置

① 先修改Tomcat的启动脚本,window下tomcat的bin/catalina.bat(linux为catalina.sh),添加以下内 容,8999是jmxremote使用的端口号,第二个false表示不需要鉴权:

Java代码  收藏代码
  1. set JMX_REMOTE_CONFIG=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8999 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false  
  2. set CATALINA_OPTS=%CATALINA_OPTS% %JMX_REMOTE_CONFIG%  

可以加在if "%OS%" == "Windows_NT" setlocal 一句后的大段的注释后面。

参考官方说明:
http://tomcat.apache.org/tomcat-6.0-doc/monitoring.html#Enabling_JMX_Remote

② 上面的配置是不需要鉴权的,如果需要鉴权则添加的内容为:

Java代码  收藏代码
  1. set JMX_REMOTE_CONFIG=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8999 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.password.file=../conf/jmxremote.password -Dcom.sun.management.jmxremote.access.file=../conf/jmxremote.access  
  2. set CATALINA_OPTS=%CATALINA_OPTS% %JMX_REMOTE_CONFIG%  

然后复制并修改授权文件,$JAVA_HOME/jre/lib/management下有 jmxremote.access和jmxremote.password的模板文件,将两个文件复制到$CATALINA_BASE/conf目录下
● 修改$CATALINA_BASE/conf/jmxremote.access 添加内容:
     monitorRole readonly
     controlRole readwrite

● 修改$CATALINA_BASE/conf/jmxremote.password 添加内容:
     monitorRole tomcat
     controlRole tomcat

注意:如果只做第一步没有问题,进行了第二步Tomcat就启动不了,那么很可能是密码文件的权限问题!
需要修改jmxremote.password文件的权限,只有运行Tomcat的用户有访问权限:
Windows的NTFS文件系统下,选中文件,点右键 -->“属性”-->“安全”--> 点“高级”--> 点“更改权限”--> 去掉“从父项继承....”--> 弹出窗口中选“删除”,这样就删除了所有访问权限。再选“添加”--> “高级”--> “立即查找”,选中你的用户,例administrator,点“确定",“确定"。来到权限项目窗口,勾选“完全控制”,点“确定”,OK了。

官方的提示
The password file should be read-only and only accessible by the operating system user Tomcat is running as.


③ 重新启动Tomcat,在Windows命令行输入“netstat -a”查看配置的端口号是否已打开,如果打开,说明上面的配置成功了。

④ 使用jconsole测试JMX。

运行$JAVA_HOME/bin目录下的jconsole.exe,打开 J2SE监视和管理控制台,然后建立连接,如 果是本地的Tomcat则直接选择然后点击连接,如果是远程的,则进入远程选项卡,填写地址、端口号、用户名、口令即可连接。Mbean属性页中给出了相 应的数据,Catalina中是tomcat的,java.lang是jvm的。对于加粗的黑体属性值,需双击一下才可看内容。


使用JMX监控Tomcat示例代码:

Java代码  收藏代码
  1. String jmxURL = "service:jmx:rmi:///jndi/rmi://192.168.10.93:8999/jmxrmi";  
  2. JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);  
  3.   
  4. Map map = new HashMap();  
  5. // 用户名密码,在jmxremote.password文件中查看  
  6. String[] credentials = new String[] { "monitorRole", "tomcat" };  
  7. map.put("jmx.remote.credentials", credentials);  
  8. JMXConnector connector = JMXConnectorFactory.connect(serviceURL, map);  
  9. MBeanServerConnection mbsc = connector.getMBeanServerConnection();  
  10.   
  11. // 端口最好是动态取得  
  12. ObjectName threadObjName = new ObjectName("Catalina:type=ThreadPool,name=http-8080");  
  13. MBeanInfo mbInfo = mbsc.getMBeanInfo(threadObjName);  
  14.   
  15. // tomcat的线程数对应的属性值  
  16. String attrName = "currentThreadCount";  
  17. MBeanAttributeInfo[] mbAttributes = mbInfo.getAttributes();  
  18. System.out.println("currentThreadCount:" + mbsc.getAttribute(threadObjName, attrName));  

完整的示例代码文件:

Java代码  收藏代码
    1. import java.lang.management.MemoryUsage;  
    2. import java.text.SimpleDateFormat;  
    3. import java.util.Date;  
    4. import java.util.Formatter;  
    5. import java.util.HashMap;  
    6. import java.util.Iterator;  
    7. import java.util.Map;  
    8. import java.util.Set;  
    9.   
    10. import javax.management.MBeanAttributeInfo;  
    11. import javax.management.MBeanInfo;  
    12. import javax.management.MBeanServerConnection;  
    13. import javax.management.ObjectInstance;  
    14. import javax.management.ObjectName;  
    15. import javax.management.openmbean.CompositeDataSupport;  
    16. import javax.management.remote.JMXConnector;  
    17. import javax.management.remote.JMXConnectorFactory;  
    18. import javax.management.remote.JMXServiceURL;  
    19.   
    20. /** 
    21.  * 使用JMX监控Tomcat示例 
    22.  *  
    23.  * @author 陳峰 
    24.  */  
    25. public class JMXTest {  
    26.   
    27.     /** 
    28.      * @param args 
    29.      */  
    30.     public static void main(String[] args) {  
    31.         try {  
    32.   
    33.             String jmxURL = "service:jmx:rmi:///jndi/rmi://127.0.0.1:8999/jmxrmi";  
    34.   
    35.             JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);  
    36.   
    37.             Map map = new HashMap();  
    38.             String[] credentials = new String[] { "monitorRole", "tomcat" };  
    39.             map.put("jmx.remote.credentials", credentials);  
    40.             JMXConnector connector = JMXConnectorFactory.connect(serviceURL,  
    41.                     map);  
    42.             MBeanServerConnection mbsc = connector.getMBeanServerConnection();  
    43.   
    44.             // 端口最好是动态取得  
    45.             ObjectName threadObjName = new ObjectName(  
    46.                     "Catalina:type=ThreadPool,name=http-8080");  
    47.             MBeanInfo mbInfo = mbsc.getMBeanInfo(threadObjName);  
    48.   
    49.             String attrName = "currentThreadCount";// tomcat的线程数对应的属性值  
    50.             MBeanAttributeInfo[] mbAttributes = mbInfo.getAttributes();  
    51.             System.out.println("currentThreadCount:"  
    52.                     + mbsc.getAttribute(threadObjName, attrName));  
    53.   
    54.             // heap  
    55.             for (int j = 0; j < mbsc.getDomains().length; j++) {  
    56.                 System.out.println("###########" + mbsc.getDomains()[j]);  
    57.             }  
    58.             Set MBeanset = mbsc.queryMBeans(null, null);  
    59.             System.out.println("MBeanset.size() : " + MBeanset.size());  
    60.             Iterator MBeansetIterator = MBeanset.iterator();  
    61.             while (MBeansetIterator.hasNext()) {  
    62.                 ObjectInstance objectInstance = (ObjectInstance) MBeansetIterator  
    63.                         .next();  
    64.                 ObjectName objectName = objectInstance.getObjectName();  
    65.                 String canonicalName = objectName.getCanonicalName();  
    66.                 System.out.println("canonicalName : " + canonicalName);  
    67.                 if (canonicalName  
    68.                         .equals("Catalina:host=localhost,type=Cluster")) {  
    69.                     // Get details of cluster MBeans  
    70.                     System.out.println("Cluster MBeans Details:");  
    71.                     System.out  
    72.                             .println("=========================================");  
    73.                     // getMBeansDetails(canonicalName);  
    74.                     String canonicalKeyPropList = objectName  
    75.                             .getCanonicalKeyPropertyListString();  
    76.                 }  
    77.             }  
    78.             // ------------------------- system ----------------------  
    79.             ObjectName runtimeObjName = new ObjectName("java.lang:type=Runtime");  
    80.             System.out.println("厂商:"  
    81.                     + (String) mbsc.getAttribute(runtimeObjName, "VmVendor"));  
    82.             System.out.println("程序:"  
    83.                     + (String) mbsc.getAttribute(runtimeObjName, "VmName"));  
    84.             System.out.println("版本:"  
    85.                     + (String) mbsc.getAttribute(runtimeObjName, "VmVersion"));  
    86.             Date starttime = new Date((Long) mbsc.getAttribute(runtimeObjName,  
    87.                     "StartTime"));  
    88.             SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    89.             System.out.println("启动时间:" + df.format(starttime));  
    90.   
    91.             Long timespan = (Long) mbsc.getAttribute(runtimeObjName, "Uptime");  
    92.             System.out.println("连续工作时间:" + JMXTest.formatTimeSpan(timespan));  
    93.             // ------------------------ JVM -------------------------  
    94.             // 堆使用率  
    95.             ObjectName heapObjName = new ObjectName("java.lang:type=Memory");  
    96.             MemoryUsage heapMemoryUsage = MemoryUsage  
    97.                     .from((CompositeDataSupport) mbsc.getAttribute(heapObjName,  
    98.                             "HeapMemoryUsage"));  
    99.             long maxMemory = heapMemoryUsage.getMax();// 堆最大  
    100.             long commitMemory = heapMemoryUsage.getCommitted();// 堆当前分配  
    101.             long usedMemory = heapMemoryUsage.getUsed();  
    102.             System.out.println("heap:" + (double) usedMemory * 100  
    103.                     / commitMemory + "%");// 堆使用率  
    104.   
    105.             MemoryUsage nonheapMemoryUsage = MemoryUsage  
    106.                     .from((CompositeDataSupport) mbsc.getAttribute(heapObjName,  
    107.                             "NonHeapMemoryUsage"));  
    108.             long noncommitMemory = nonheapMemoryUsage.getCommitted();  
    109.             long nonusedMemory = heapMemoryUsage.getUsed();  
    110.             System.out.println("nonheap:" + (double) nonusedMemory * 100  
    111.                     / noncommitMemory + "%");  
    112.   
    113.             ObjectName permObjName = new ObjectName(  
    114.                     "java.lang:type=MemoryPool,name=Perm Gen");  
    115.             MemoryUsage permGenUsage = MemoryUsage  
    116.                     .from((CompositeDataSupport) mbsc.getAttribute(permObjName,  
    117.                             "Usage"));  
    118.             long committed = permGenUsage.getCommitted();// 持久堆大小  
    119.             long used = heapMemoryUsage.getUsed();//  
    120.             System.out.println("perm gen:" + (double) used * 100 / committed  
    121.                     + "%");// 持久堆使用率  
    122.   
    123.             // -------------------- Session ---------------  
    124.             ObjectName managerObjName = new ObjectName(  
    125.                     "Catalina:type=Manager,*");  
    126.             Set<ObjectName> s = mbsc.queryNames(managerObjName, null);  
    127.             for (ObjectName obj : s) {  
    128.                 System.out.println("应用名:" + obj.getKeyProperty("path"));  
    129.                 ObjectName objname = new ObjectName(obj.getCanonicalName());  
    130.                 System.out.println("最大会话数:"  
    131.                         + mbsc.getAttribute(objname, "maxActiveSessions"));  
    132.                 System.out.println("会话数:"  
    133.                         + mbsc.getAttribute(objname, "activeSessions"));  
    134.                 System.out.println("活动会话数:"  
    135.                         + mbsc.getAttribute(objname, "sessionCounter"));  
    136.             }  
    137.   
    138.             // ----------------- Thread Pool ----------------  
    139.             ObjectName threadpoolObjName = new ObjectName(  
    140.                     "Catalina:type=ThreadPool,*");  
    141.             Set<ObjectName> s2 = mbsc.queryNames(threadpoolObjName, null);  
    142.             for (ObjectName obj : s2) {  
    143.                 System.out.println("端口名:" + obj.getKeyProperty("name"));  
    144.                 ObjectName objname = new ObjectName(obj.getCanonicalName());  
    145.                 System.out.println("最大线程数:"  
    146.                         + mbsc.getAttribute(objname, "maxThreads"));  
    147.                 System.out.println("当前线程数:"  
    148.                         + mbsc.getAttribute(objname, "currentThreadCount"));  
    149.                 System.out.println("繁忙线程数:"  
    150.                         + mbsc.getAttribute(objname, "currentThreadsBusy"));  
    151.             }  
    152.   
    153.         } catch (Exception e) {  
    154.             e.printStackTrace();  
    155.         }  
    156.     }  
    157.   
    158.     public static String formatTimeSpan(long span) {  
    159.         long minseconds = span % 1000;  
    160.   
    161.         span = span / 1000;  
    162.         long seconds = span % 60;  
    163.   
    164.         span = span / 60;  
    165.         long mins = span % 60;  
    166.   
    167.         span = span / 60;  
    168.         long hours = span % 24;  
    169.   
    170.         span = span / 24;  
    171.         long days = span;  
    172.         return (new Formatter()).format("%1$d天 %2$02d:%3$02d:%4$02d.%5$03d",  
    173.                 days, hours, mins, seconds, minseconds).toString();  
    174.     }  
原文地址:https://www.cnblogs.com/zhengah/p/4623354.html