软件指南针:专注于软件传播与分享

Tomcat Manager指南(官方文档)

来源:原创 1372次浏览 0条评论
☞ 本文主要介绍软件Apache Tomcat的相关内容:Tomcat Manager指南(官方文档)

   其下列版本/分支可以参考本文:

  • 全部版本/分支

内容导航

介绍

在许多生产环境中,无需关闭和重启整个容器,就能够部署一个新的web应用或解除部署一个现有应用,是非常有用的。此外,你可以请求重新加载一个现有的web应用,即使你没有在Tomcat服务器配置文件中声明它为reloadable

为了支持这些功能,Tomcat包含了一个支持下列功能的web应用(默认安装的上下文路径为/manager):

  • 将一个上传的WAR文件部署为一个新的web应用。
  • 从服务器文件系统中部署一个新的web应用,并使用指定的上下文路径。
  • 列出当前已部署的web应用,和有效的会话信息。
  • 重新加载一个现有的web应用,从而反映/WEB-INF/classes/WEB-INF/lib文件中所发生的内容更改。
  • 列出该操作系统和JVM的属性值。
  • 列出可用的全局JNDI资源,以便在部署工具中使用,部署工具也就是预备的嵌套在<Context>部署描述中的<ResourceLink>元素。
  • 启动一个停止了的应用(从而使其再次可用)。
  • 停止一个现有的应用(使其不可用),但不解除对它的部署。
  • 解除对一个已部署的应用的部署,并删除它的文档基础目录(除非它是从文件系统中被部署)。

默认的Tomcat安装包含了Manager。为了将Manager的一个Context实例添加到一个新的主机上,请在$CATALINA_BASE/conf/[enginename]/[hostname]文件夹中安装manager.xml上下文配置文件。此处是一个示例:

<Context privileged="true" antiResourceLocking="false" docBase="${catalina.home}/webapps/manager">
  <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.0\.0\.1" />
</Context>
如果你已经配置了Tomcat支持多个虚拟主机(虚拟站点),你需要为每一个主机都配置一个Manager。

有三种方式可以使用Manager。

  • 作为一个带用户界面的应用程序,你可以在浏览器中使用。这里是一个URL示例,你可以使用自己的网站主机名称替换掉localhosthttp://localhost/manager/html/
  • 一个只使用HTTP请求的最小版本,它适合由系统管理员创建的脚本来使用。给定的命令将作为请求URI的一部分,而响应内容为简单的文本格式,并能够轻松地被解析和处理。你可以查看受支持的Manager命令以了解更多信息。
  • 为Ant(1.4及以上版本)定义的一套简单的任务。请查看使用Ant执行Manager命令以了解很多信息。

配置Manager应用程序的访问

下面的说明使用变量名$CATALINA_BASE来表示基本目录以应对大多数相对路径的解析,如果你没有通过设置一个CATALINA_BASE目录来配置多个Tomcat实例,那么$CATALINA_BASE将被设为$CATALINA_HOME的值,该目录中安装了Tomcat。

如果Tomcat的默认设置允许网络上的任何人执行你服务器上的Manager应用的话,这是相当不安全的。因此,Manager应用有附带的要求--任何企图使用它的人都必须进行身份验证,使用用户名和密码,并具备与之关联的manager-**角色权限中的一个(具体的角色名称取决于具体的功能需求)。进一步说,分配给那些角色的默认用户文件($CATALINA_BASE/conf/tomcat-users.xml)中没有用户名。因此,在默认情况下,Manager应用是完全禁止访问的。

你可以在Manager应用的web.xml文件中找到这些角色名称,可用的角色有:

  • manager-gui — 允许访问HTML接口。
  • manager-status — 只允许访问"Server Status"页面。
  • manager-script — 允许访问本文档中描述的那些工具友好的纯文本接口,以及"Server Status"页面。
  • manager-jmx — 允许访问JMX代理接口和"Server Status"页面。

HTML接口可以防御CSRF(Cross-Site Request Forgery/跨站请求伪造),但文本和JMX接口不受保护。为了保持CSRF防护:

  • 具备manager-gui的角色不应该再被授予manager-scriptmanager-jmx角色权限。
  • 如果你使用网络浏览器来访问Manager应用,用户具有manager-scriptmanager-jxm的角色权限(例如,为了测试纯文本或JXM接口),那么你必须在事后关闭所有的浏览器窗口来终止会话。

注意,JMX代理接口实际上是Tomcat低级的、像root那样的管理接口。如何他知道调用什么命令,那么他可以做很多事。你应该谨慎启用manager-jmx角色权限。

为了启用对web应用Manager的访问,你可以创建一个新的用户名/密码组合,并关联manager-**角色权限中的一个,或者,你也可以为现有的用户名/密码组合添加一个manager-**角色权限。由于本文多数内容都在描述纯文本接口的命令,因此,在进一步的例子中,我们让角色名称为manager-script。用户名/密码的具体配置取决于你使用了哪一种Realm实现。

  • MemoryRealm — 它配置于默认的$CATALINA_BASE/conf/server.xml文件之中。如果你没有实施不同的配置,或者使用不同的Realm实现取代它,该realm会读取存储于$CATALINA_BASE/conf/tomcat-users.xml的XML格式的文件,你可以使用任何文本编辑器对其进行编辑。该文件包含每个用户的XML <user>元素,它看起来像这样:
    <user name="craigmcc" password="secret" roles="standard,manager-script" />
    该元素定义了用于登录的用户名和密码,以及其所具备的角色名称。roles属性中的多个角色名称用英文逗号隔开。你可以类似这样创建一个或多个用户。
  • JDBCRealm — 你的用户和角色信息存储于数据库中,可通过JDBC访问。用户和角色信息的变动请遵照适用于你当前环境的标准程序。
  • JNDIRealm — Y你的用户和角色信息存储于一个目录服务器中,可通过LDAP访问。用户和角色信息的变动请遵照适用于你当前环境的标准程序。

你第一次尝试发出在下一部分中描述的一个Manager命令,你将被要求使用基本的身份认证进行登录。无论你输入什么用户名和密码,只要它们能识别用户数据库中一个有效的、具有manager-script角色权限的用户。

除了密码限制外,我们还可以通过添加RemoteAddrValve 或 RemoteHostValve让Manager只能被指定的远程IP地址或主机所访问。请查看valves文档以了解更多细节。这里是一个通过IP地址限制访问本地主机的例子:

<Context privileged="true">
         <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.0\.0\.1"/>
</Context>

支持的Manager命令

Manager知道如何处理的所有命令都被指定在像这样的一个请求URI中:

http://{host}:{port}/manager/text/{command}?{parameters}

{host}{port}代表运行的Tomcat的主机名和端口号,{command}代表你希望执行的Manager命令,{parameters}代表命令指定的查询参数。在下面的例证中,为你的安装自定义适当的主机和端口。

大多数命令接受一个或多个下列查询参数:

  • path - 需要处理的web应用的上下文路径(包括前面的斜杠)。如果要选择web应用ROOT,请指定为"/"。注意 - 无法执行作用于Manager应用自身的管理命令。
  • version - 用于并行部署功能的web应用的版本。
  • war - web应用归档文件(WAR)的URL,web应用所在目录的路径名称,或者是一个上下文配置".xml"文件。你可以以下列格式使用URL:
    • file:/absolute/path/to/a/directory - 已解压的web应用所在目录的绝对路径。该目录将会没有任何改动地被连接到你所指定的上下文路径上。
    • file:/absolute/path/to/a/webapp.war - web应用归档文件(.WAR)的绝对路径。这只对/deploy命令有效,也是该命令唯一能够接受的格式。
    • jar:file:/absolute/path/to/a/warfile.war!/ - 本地的web应用归档文档(WAR)的URL。你可以使用任何语法,只要它对JarURLConnection类来说是有效的,并且对引用整个JAR文件来说,也是有效的。
    • file:/absolute/path/to/a/context.xml - web应用的上下文配置".xml"文件的绝对路径,该文件中包括Context配置元素。
    • directory - 位于该Host的应用程序基础目录中的web应用的上下文目录名称。
    • webapp.war - 位于该Host的应用程序基础目录中的web应用的WAR文件的名称。

每个命令将返回一个text/plain格式(也就是没有HTML标记的ASCII文本)的响应,以便于让人们和程序都能够轻松阅读。响应的第一行将以OKFAIL开头,用以表示该请求命令成功与否。在失败的情况下,第一行的剩余部分将包含一个所遇到的问题的描述。如下面所说的那样,一些命令包含额外的多行信息。

国际化说明 - Manager应用程序将会在resource bundle中查找它的信息字符串,所以我们可以将其翻译为适用于当前平台的字符串。下面的例子显示信息的英文版本。

远程部署一个新的应用

http://localhost:8080/manager/text/deploy?path=/foo

上传web应用归档文件(WAR),归档文件被指定为HTTP PUT请求中的请求数据,将其安装到对应虚拟主机的appBase目录中,然后启动,使用目录名称或不带.war后缀的war文件名称作为路径。通过使用/undeploy命令,应用程序在之后被解除部署(并移除对应的应用程序目录)。

WAR文件可能包含Tomcat特定的部署配置,这是通过包含在一个上下文配置XML文件/META-INF/context.xml来实现的。

URL参数包括:

  • update: 设为true时,任何现有的更新将会被首先解除部署。默认值为false。
  • tag: 指定一个标签名称,从而通过一个标签将已部署的web应用关联起来。如果web应用被解除了部署,仅使用标签,它也能够在之后被需要时被重新部署。

注意- 此命令与/undeploy命令在逻辑上是相反的。

如果安装和启动成功,你将接收到类似这样的响应:

OK - Deployed application at context path /foo

否则,响应将以FAIL开头,并包含一个错误信息。可能导致问题的原因包括:

  • 已存在路径为/foo的应用程序

    当前所有正在运行的web应用的上下文路径必须是唯一的。因此,你必须解除部署使用该上下文路径的web应用,或者为新的应用选择一个不同的上下文路径。update参数可以被指定为URL的一个参数,使用true值来避免这个错误。在这种情况下,在执行部署之前,将会执行解除对现有应用的部署。

  • 遇到异常

    试图启动一个新的web应用时遇到了异常。检查Tomcat的日志记录以了解详细信息,但可能的原因也包括/WEB-INF/web.xml文件的解析问题,或者在初始化应用程序事件监听器和过滤器时遇到了类丢失。

从本地路径部署一个新的应用

部署并启动一个新的web应用,附属于指定的上下文path(必须是没有被任何其他web应用所使用)。此命令与/undeploy命令在逻辑上相反。

我们有几种不同的方式来使用部署命令。

部署一个以前部署过的web应用

这可以用来部署一个之前部署过的应用,使用tag属性来部署该应用。注意,Manager应用程序的工作目录将包含之前已部署的WAR文件;删除它将导致部署失败。

http://localhost:8080/manager/text/deploy?path=/footoo&tag=footag
通过URL部署一个目录或WAR文件

部署一个位于Tomcat服务器上的web应用目录或".war"文件。如果没有指定path,目录名称或不带".war"后缀的war文件名称将用作路径。war参数指定一个表示目录或web应用归档文件(WAR)的URL(包括file:协议)。指向一个WAR文件的URL所支持的语法请参见java.net.JarURLConnection类的Javadocs页面。仅使用指向整个WAR文件的URL。

在这个例子中,web应用位于Tomcat服务器上的/path/to/foo路径,并被部署为一个上下文叫做/footoo的web应用。

http://localhost:8080/manager/text/deploy?path=/footoo&war=file:/path/to/foo

在这个例子中,在Tomcat服务器上的".war"文件/path/to/bar.war被部署为一个上下文叫做/bar的web应用。注意,这里没有path参数,因此,上下文路径默认为没有".war"后缀的WAR文件名称(这里为"bar")。

http://localhost:8080/manager/text/deploy?war=jar:file:/path/to/bar.war!/
从Host appBase部署一个目录或WAR文件

Deploy a web application directory or ".war" file located in your Host appBase directory. The directory name or the war file name without the ".war" extension is used as the path.

In this example the web application located in a sub directory named foo in the Host appBase directory of the Tomcat server is deployed as the web application context named /foo. Notice that the context path used is the name of the web application directory.

http://localhost:8080/manager/text/deploy?war=foo

In this example the ".war" file bar.war located in your Host appBase directory on the Tomcat server is deployed as the web application context named /bar.

http://localhost:8080/manager/text/deploy?war=bar.war
Deploy using a Context configuration ".xml" file

If the Host deployXML flag is set to true you can deploy a web application using a Context configuration ".xml" file and an optional ".war" file or web application directory. The context path is not used when deploying a web application using a context ".xml" configuration file.

A Context configuration ".xml" file can contain valid XML for a web application Context just as if it were configured in your Tomcat server.xml configuration file. Here is an example:

<Context path="/foobar" docBase="/path/to/application/foobar">
</Context>

When the optional war parameter is set to the URL for a web application ".war" file or directory it overrides any docBase configured in the context configuration ".xml" file.

Here is an example of deploying an application using a Context configuration ".xml" file.

http://localhost:8080/manager/text/deploy?config=file:/path/context.xml

Here is an example of deploying an application using a Context configuration ".xml" file and a web application ".war" file located on the server.

http://localhost:8080/manager/text/deploy
 ?config=file:/path/context.xml&war=jar:file:/path/bar.war!/
部署说明

If the Host is configured with unpackWARs=true and you deploy a war file, the war will be unpacked into a directory in your Host appBase directory.

If the application war or directory is installed in your Host appBase directory and either the Host is configured with autoDeploy=true or the Context path must match the directory name or war file name without the ".war" extension.

For security when untrusted users can manage web applications, the Host deployXML flag can be set to false. This prevents untrusted users from deploying web applications using a configuration XML file and also prevents them from deploying application directories or ".war" files located outside of their Host appBase.

Deploy Response

If installation and startup is successful, you will receive a response like this:

OK - Deployed application at context path /foo

Otherwise, the response will start with FAIL and include an error message. Possible causes for problems include:

  • Application already exists at path /foo

    The context paths for all currently running web applications must be unique. Therefore, you must undeploy the existing web application using this context path, or choose a different context path for the new one. The update parameter may be specified as a parameter on the URL, with a value of true to avoid this error. In that case, an undeploy will be performed on an existing application before performing the deployment.

  • Document base does not exist or is not a readable directory

    The URL specified by the war parameter must identify a directory on this server that contains the "unpacked" version of a web application, or the absolute URL of a web application archive (WAR) file that contains this application. Correct the value specified by the war parameter.

  • Encountered exception

    An exception was encountered trying to start the new web application. Check the Tomcat logs for the details, but likely explanations include problems parsing your/WEB-INF/web.xml file, or missing classes encountered when initializing application event listeners and filters.

  • Invalid application URL was specified

    The URL for the directory or web application that you specified was not valid. Such URLs must start with file:, and URLs for a WAR file must end in ".war".

  • Invalid context path was specified

    The context path must start with a slash character. To reference the ROOT web application use "/".

  • Context path must match the directory or WAR file name:

    If the application war or directory is installed in your Host appBase directory and either the Host is configured with autoDeploy=true the Context path must match the directory name or war file name without the ".war" extension.

  • Only web applications in the Host web application directory can be installed

    If the Host deployXML flag is set to false this error will happen if an attempt is made to deploy a web application directory or ".war" file outside of the Host appBase directory.

列出当前已部署的应用

http://localhost:8080/manager/text/list

List the context paths, current status (running or stopped), and number of active sessions for all currently deployed web applications. A typical response immediately after starting Tomcat might look like this:

OK - Listed applications for virtual host localhost
/webdav:running:0
/examples:running:0
/manager:running:0
/:running:0

重新加载一个现有的应用

http://localhost:8080/manager/text/reload?path=/examples

Signal an existing application to shut itself down and reload. This can be useful when the web application context is not reloadable and you have updated classes or property files in the /WEB-INF/classes directory or when you have added or updated jar files in the /WEB-INF/lib directory.

NOTE: The /WEB-INF/web.xml web application configuration file is not reread on a reload. If you have made changes to your web.xml file you must stop then start the web application.

If this command succeeds, you will see a response like this:

OK - Reloaded application at context path /examples

Otherwise, the response will start with FAIL and include an error message. Possible causes for problems include:

  • Encountered exception

    An exception was encountered trying to restart the web application. Check the Tomcat logs for the details.

  • Invalid context path was specified

    The context path must start with a slash character. To reference the ROOT web application use "/".

  • No context exists for path /foo

    There is no deployed application on the context path that you specified.

  • No context path was specified

    The path parameter is required.

  • Reload not supported on WAR deployed at path /foo

    Currently, application reloading (to pick up changes to the classes or web.xml file) is not supported when a web application is deployed directly from a WAR file. It only works when the web application is deployed from an unpacked directory. If you are using a WAR file, you should undeploy and then deploy or deploy with the updateparameter the application again to pick up your changes.

List OS and JVM Properties

http://localhost:8080/manager/text/serverinfo

Lists information about the Tomcat version, OS, and JVM properties.

If an error occurs, the response will start with FAIL and include an error message. Possible causes for problems include:

  • Encountered exception

    An exception was encountered trying to enumerate the system properties. Check the Tomcat logs for the details.

List Available Global JNDI Resources

http://localhost:8080/manager/text/resources[?type=xxxxx]

List the global JNDI resources that are available for use in resource links for context configuration files. If you specify the type request parameter, the value must be the fully qualified Java class name of the resource type you are interested in (for example, you would specify javax.sql.DataSource to acquire the names of all available JDBC data sources). If you do not specify the type request parameter, resources of all types will be returned.

Depending on whether the type request parameter is specified or not, the first line of a normal response will be:

OK - Listed global resources of all types

or

OK - Listed global resources of type xxxxx

followed by one line for each resource. Each line is composed of fields delimited by colon characters (":"), as follows:

  • Global Resource Name - The name of this global JNDI resource, which would be used in the global attribute of a <ResourceLink> element.
  • Global Resource Type - The fully qualified Java class name of this global JNDI resource.

If an error occurs, the response will start with FAIL and include an error message. Possible causes for problems include:

  • Encountered exception

    An exception was encountered trying to enumerate the global JNDI resources. Check the Tomcat logs for the details.

  • No global JNDI resources are available

    The Tomcat server you are running has been configured without global JNDI resources.

Session Statistics

http://localhost:8080/manager/text/sessions?path=/examples

Display the default session timeout for a web application, and the number of currently active sessions that fall within ten-minute ranges of their actual timeout times. For example, after restarting Tomcat and then executing one of the JSP samples in the /examples web app, you might get something like this:

OK - Session information for application at context path /examples
Default maximum session inactive interval 30 minutes
30 - <40 minutes:1 sessions

Start an Existing Application

http://localhost:8080/manager/text/start?path=/examples

Signal a stopped application to restart, and make itself available again. Stopping and starting is useful, for example, if the database required by your application becomes temporarily unavailable. It is usually better to stop the web application that relies on this database rather than letting users continuously encounter database exceptions.

If this command succeeds, you will see a response like this:

OK - Started application at context path /examples

Otherwise, the response will start with FAIL and include an error message. Possible causes for problems include:

  • Encountered exception

    An exception was encountered trying to start the web application. Check the Tomcat logs for the details.

  • Invalid context path was specified

    The context path must start with a slash character. To reference the ROOT web application use "/".

  • No context exists for path /foo

    There is no deployed application on the context path that you specified.

  • No context path was specified

    The path parameter is required.

Stop an Existing Application

http://localhost:8080/manager/text/stop?path=/examples

Signal an existing application to make itself unavailable, but leave it deployed. Any request that comes in while an application is stopped will see an HTTP error 404, and this application will show as "stopped" on a list applications command.

If this command succeeds, you will see a response like this:

OK - Stopped application at context path /examples

Otherwise, the response will start with FAIL and include an error message. Possible causes for problems include:

  • Encountered exception

    An exception was encountered trying to stop the web application. Check the Tomcat logs for the details.

  • Invalid context path was specified

    The context path must start with a slash character. To reference the ROOT web application use "/".

  • No context exists for path /foo

    There is no deployed application on the context path that you specified.

  • No context path was specified The path parameter is required.

Undeploy an Existing Application

http://localhost:8080/manager/text/undeploy?path=/examples

WARNING - This command will delete any web application artifacts that exist within appBase directory (typically "webapps") for this virtual host. This will delete the the application .WAR, if present, the application directory resulting either from a deploy in unpacked form or from .WAR expansion as well as the XML Context definition from$CATALINA_BASE/conf/[enginename]/[hostname]/ directory. If you simply want to take an application out of service, you should use the /stop command instead.

Signal an existing application to gracefully shut itself down, and remove it from Tomcat (which also makes this context path available for reuse later). In addition, the document root directory is removed, if it exists in the appBase directory (typically "webapps") for this virtual host. This command is the logical opposite of the /deploycommand.

If this command succeeds, you will see a response like this:

OK - Undeployed application at context path /examples

Otherwise, the response will start with FAIL and include an error message. Possible causes for problems include:

  • Encountered exception

    An exception was encountered trying to undeploy the web application. Check the Tomcat logs for the details.

  • Invalid context path was specified

    The context path must start with a slash character. To reference the ROOT web application use "/".

  • No context exists for path /foo

    There is no deployed application on the context path that you specified.

  • No context path was specified The path parameter is required.

Finding memory leaks

http://localhost:8080/manager/text/findleaks[?statusLine=[true|false]]

The find leaks diagnostic triggers a full garbage collection. It should be used with extreme caution on production systems.

The find leaks diagnostic attempts to identify web applications that have caused memory leaks when they were stopped, reloaded or undeployed. Results should always be confirmed with a profiler. The diagnostic uses additional functionality provided by the StandardHost implementation. It will not work if a custom host is used that does not extend StandardHost.

Explicitly triggering a full garbage collection from Java code is documented to be unreliable. Furthermore, depending on the JVM used, there are options to disable explicit GC triggering, like -XX:+DisableExplicitGC. If you want to make sure, that the diagnostics were successfully running a full GC, you will need to check using tools like GC logging, JConsole or similar.

If this command succeeds, you will see a response like this:

/leaking-webapp

If you wish to see a status line included in the response then include the statusLine query parameter in the request with a value of true.

Each context path for a web application that was stopped, reloaded or undeployed, but which classes from the previous runs are still loaded in memory, thus causing a memory leak, will be listed on a new line. If an application has been reloaded several times, it may be listed several times.

If the command does not succeed, the response will start with FAIL and include an error message.

Connector SSL diagnostics

http://localhost:8080/manager/text/sslConnectorCiphers

The SSL Connector/Ciphers diagnostic lists the SSL ciphers that are currently configured for each connector. For BIO and NIO, the names of the individual cipher suites are listed. For APR, the value of SSLCipherSuite is returned.

The response will ook something like this:

OK - Connector / SSL Cipher information
Connector[HTTP/1.1-8080]
  SSL is not enabled for this connector
Connector[HTTP/1.1-8443]
  TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
  TLS_DHE_RSA_WITH_AES_128_CBC_SHA
  TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
  TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
  ...

Server Status

From this link , you can view information about the server.

First, you have the server and JVM version number, JVM provider, OS name and number followed by the architecture type.

Second, there is several information about the memory usage of the JVM (available, total and max memory).

Then, there is information about the Tomcat AJP and HTTP connectors. The same information is available for both of them :

  • Threads information : Max threads, min and max spare threads, current thread count and current thread busy.

  • Request information : Max processing time and processing time, request and error count, bytes received and sent.

  • A table showing Stage, Time, Bytes Sent, Bytes Receive, Client, VHost and Request. All existing threads are listed in the table. Here is the list of the possible thread stages :

    • "Parse and Prepare Request" : The request headers are being parsed or the necessary preparation to read the request body (if a transfer encoding has been specified) is taking place.

    • "Service" : The thread is processing a request and generating the response. This stage follows the "Parse and Prepare Request" stage and precedes the "Finishing" stage. There is always at least one thread in this stage (the server-status page).

    • "Finishing" : The end of the request processing. Any remainder of the response still in the output buffers is sent to the client. This stage is followed by "Keep-Alive" if it is appropriate to keep the connection alive or "Ready" if "Keep-Alive" is not appropriate.

    • "Keep-Alive" : The thread keeps the connection open to the client in case the client sends another request. If another request is received, the next stage will br "Parse and Prepare Requst". If no request is received before the keep alive times out, the connection will be closed and the next stage will be "Ready".

    • "Ready" : The thread is at rest and ready to be used.

Executing Manager Commands With Ant

In addition to the ability to execute Manager commands via HTTP requests, as documented above, Tomcat includes a convenient set of Task definitions for the Ant (version 1.4 or later) build tool. In order to use these commands, you must perform the following setup operations:

  • Download the binary distribution of Ant from http://ant.apache.org. You must use version 1.4 or later.
  • Install the Ant distribution in a convenient directory (called ANT_HOME in the remainder of these instructions).
  • Copy the file server/lib/catalina-ant.jar from your Tomcat installation into Ant's library directory ($ANT_HOME/lib).
  • Add the $ANT_HOME/bin directory to your PATH environment variable.
  • Configure at least one username/password combination in your Tomcat user database that includes the manager-script role.

To use custom tasks within Ant, you must declare them first with a <taskdef> element. Therefore, your build.xml file might look something like this:

<project name="My Application" default="compile" basedir=".">

  <!-- Configure the directory into which the web application is built -->
  <property name="build"    value="${basedir}/build"/>

  <!-- Configure the context path for this application -->
  <property name="path"     value="/myapp"/>

  <!-- Configure properties to access the Manager application -->
  <property name="url"      value="http://localhost:8080/manager/text"/>
  <property name="username" value="myusername"/>
  <property name="password" value="mypassword"/>

  <!-- Configure the custom Ant tasks for the Manager application -->
  <taskdef name="deploy"    classname="org.apache.catalina.ant.DeployTask"/>
  <taskdef name="list"      classname="org.apache.catalina.ant.ListTask"/>
  <taskdef name="reload"    classname="org.apache.catalina.ant.ReloadTask"/>
  <taskdef name="findleaks" classname="org.apache.catalina.ant.FindLeaksTask"/>
  <taskdef name="resources" classname="org.apache.catalina.ant.ResourcesTask"/>
  <taskdef name="start"     classname="org.apache.catalina.ant.StartTask"/>
  <taskdef name="stop"      classname="org.apache.catalina.ant.StopTask"/>
  <taskdef name="undeploy"  classname="org.apache.catalina.ant.UndeployTask"/>

  <!-- Executable Targets -->
  <target name="compile" description="Compile web application">
    <!-- ... construct web application in ${build} subdirectory, and
            generated a ${path}.war ... -->
  </target>

  <target name="deploy" description="Install web application"
          depends="compile">
    <deploy url="${url}" username="${username}" password="${password}"
            path="${path}" war="file:${build}${path}.war"/>
  </target>

  <target name="reload" description="Reload web application"
          depends="compile">
    <reload  url="${url}" username="${username}" password="${password}"
            path="${path}"/>
  </target>

  <target name="undeploy" description="Remove web application">
    <undeploy url="${url}" username="${username}" password="${password}"
            path="${path}"/>
  </target>

</project>

Note: The definition of the resources task above will override the resources datatype added in Ant 1.7. If you wish to use the resources datatype you will need to use Ant's namespace support to assign the Tomcat tasks to their own namespace.

Now, you can execute commands like ant deploy to deploy the application to a running instance of Tomcat, or ant reload to tell Tomcat to reload it. Note also that most of the interesting values in this build.xml file are defined as replaceable properties, so you can override their values from the command line. For example, you might consider it a security risk to include the real manager password in your build.xml file's source code. To avoid this, omit the password property, and specify it from the command line:

ant -Dpassword=secret deploy

Tasks output capture

Using Ant version 1.6.2 or later, the Catalina tasks offer the option to capture their output in properties or external files. They support directly the following subset of the<redirector> type attributes:

Attribute Description Required
output Name of a file to which to write the output. If the error stream is not also redirected to a file or property, it will appear in this output. No
error The file to which the standard error of the command should be redirected. No
logError This attribute is used when you wish to see error output in Ant's log and you are redirecting output to a file/property. The error output will not be included in the output file/property. If you redirect error with the error or errorProperty attributes, this will have no effect. No
append Whether output and error files should be appended to or overwritten. Defaults to false. No
createemptyfiles Whether output and error files should be created even when empty. Defaults to true. No
outputproperty The name of a property in which the output of the command should be stored. Unless the error stream is redirected to a separate file or stream, this property will include the error output. No
errorproperty The name of a property in which the standard error of the command should be stored. No

A couple of additional attributes can also be specified:

Attribute Description Required
alwaysLog This attribute is used when you wish to see the output you are capturing, appearing also in the Ant's log. It must not be used unless you are capturing task output. Defaults to falseThis attribute will be supported directly by <redirector> in Ant 1.6.3 No
failonerror This attribute is used when you wish to avoid that any manager command processing error terminates the ant execution. Defaults to true. It must be set to false, if you want to capture error output, otherwise execution will terminate before anything can be captured. 
This attribute acts only on manager command execution, any wrong or missing command attribute will still cause Ant execution termination.
No

They also support the embedded <redirector> element in which you can specify its full set of attributes, but inputinputstring and inputencoding that, even if accepted, are not used because they have no meaning in this context. Refer to ant manual for details on <redirector> element attributes.

Here is a sample build file extract that shows how this output redirection support can be used:

 <target name="manager.deploy"
        depends="context.status"
        if="context.notInstalled">
        <deploy url="${mgr.url}"
            username="${mgr.username}"
            password="${mgr.password}"
            path="${mgr.context.path}"
            config="${mgr.context.descriptor}"/>
    </target>

    <target name="manager.deploy.war"
        depends="context.status"
        if="context.deployable">
        <deploy url="${mgr.url}"
            username="${mgr.username}"
            password="${mgr.password}"
            update="${mgr.update}"
            path="${mgr.context.path}"
            war="${mgr.war.file}"/>
    </target>

    <target name="context.status">
        <property name="running" value="${mgr.context.path}:running"/>
        <property name="stopped" value="${mgr.context.path}:stopped"/>

        <list url="${mgr.url}"
            outputproperty="ctx.status"
            username="${mgr.username}"
            password="${mgr.password}">
        </list>

        <condition property="context.running">
            <contains string="${ctx.status}" substring="${running}"/>
        </condition>
        <condition property="context.stopped">
            <contains string="${ctx.status}" substring="${stopped}"/>
        </condition>
        <condition property="context.notInstalled">
            <and>
                <isfalse value="${context.running}"/>
                <isfalse value="${context.stopped}"/>
            </and>
        </condition>
        <condition property="context.deployable">
            <or>
                <istrue value="${context.notInstalled}"/>
                <and>
                    <istrue value="${context.running}"/>
                    <istrue value="${mgr.update}"/>
                </and>
                <and>
                    <istrue value="${context.stopped}"/>
                    <istrue value="${mgr.update}"/>
                </and>
            </or>
        </condition>
        <condition property="context.undeployable">
            <or>
                <istrue value="${context.running}"/>
                <istrue value="${context.stopped}"/>
            </or>
        </condition>
    </target>

WARNING: even if it doesn't make many sense, and is always a bad idea, calling a Catalina task more than once, badly set Ant tasks depends chains may cause that a task be called more than once in the same Ant run, even if not intended to. A bit of caution should be exercised when you are capturing output from that task, because this could lead to something unexpected:

  • when capturing in a property you will find in it only the output from the first call, because Ant properties are immutable and once set they cannot be changed,
  • when capturing in a file, each run will overwrite it and you will find in it only the last call output, unless you are using the append="true" attribute, in which case you will see the output of each task call appended to the file.

Using the JMX Proxy Servlet

What is JMX Proxy Servlet

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

This takes the form:

http://webserver/manager/jmxproxy/?qry=STUFF

Where STUFF is the JMX query you wish to perform. For example, here are some queries you might wish to run:

  • qry=*%3Atype%3DRequestProcessor%2C* --> type=RequestProcessor which will locate all workers which can process requests and report their state.
  • qry=*%3Aj2eeType=Servlet%2c* --> j2eeType=Servlet which return all loaded servlets.
  • qry=Catalina%3Atype%3DEnvironment%2Cresourcetype%3DGlobal%2Cname%3DsimpleValue --> Catalina:type=Environment,resourcetype=Global,name=simpleValue which look for a specific MBean by the given name.

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.

JMX Get command

The JXMProxyServlet also supports a "get" command that you can use to fetch the value of a specific MBean's attribute. The general form of the get command is:

http://webserver/manager/jmxproxy/?get=BEANNAME&att=MYATTRIBUTE&key=MYKEY

You must provide the following parameters:

  1. get: The full bean name
  2. att: The attribute you wish to fetch
  3. key: (optional) The key into a CompositeData MBean attribute

If all goes well, then it will say OK, otherwise an error message will be shown. For example, let's say we wish to fetch the current heap memory data:

http://webserver/manager/jmxproxy/?get=java.lang:type=Memory&att=HeapMemoryUsage

Or, if you only want the "used" key:

http://webserver/manager/jmxproxy/
 ?get=java.lang:type=Memory&att=HeapMemoryUsage&key=used

JMX Set command

Now that you can query an MBean, its time to muck with Tomcat's internals! The general form of the set command is :

http://webserver/manager/jmxproxy/?set=BEANNAME&att=MYATTRIBUTE&val=NEWVALUE

So you need to provide 3 request parameters:

  1. set: The full bean name
  2. att: The attribute you wish to alter
  3. val: The new value

If all goes ok, then it will say OK, otherwise an error message will be shown. For example, lets say we wish to turn up debugging on the fly for the ErrorReportValve. The following will set debugging to 10.

http://localhost:8080/manager/jmxproxy/
 ?set=Catalina%3Atype%3DValve%2Cname%3DErrorReportValve%2Chost%3Dlocalhost
 &att=debug&val=10

and my result is (YMMV):

Result: ok

Here is what I see if I pass in a bad value. Here is the URL I used, I try set debugging equal to 'cow':

http://localhost:8080/manager/jmxproxy/
 ?set=Catalina%3Atype%3DValve%2Cname%3DErrorReportValve%2Chost%3Dlocalhost
 &att=debug&val=cow

When I try that, my result is

Error: java.lang.NumberFormatException: For input string: "cow"

JMX Invoke command

The invoke command enables methods to be called on MBeans. The general form of the command is:

http://webserver/manager/jmxproxy/
 ?invoke=BEANNAME&op=METHODNAME&ps=COMMASEPARATEDPARAMETERS

For example, to call the findConnectors() method of the Service use:

http://localhost:8080/manager/jmxproxy/
 ?invoke=Catalina%3Atype%3DService&op=findConnectors&ps=

作者:软件指南针(http://www.softown.cn),转载请保留出处!

用户评论

使用指南 故障排除 0 返回顶部