TomcatManager
- class tomcatmanager.tomcat_manager.TomcatManager
A class for interacting with the Tomcat Manager web application.
Here’s a summary of the recommended way to use this class with proper exception and error handling. For this example, we’ll use the
server_info()
method.import tomcatmanager as tm url = "http://localhost:808099/manager" user = "ace" password = "newenglandclamchowder" tomcat = tm.TomcatManager() try: r = tomcat.connect(url, user, password) if r.ok: r = tomcat.server_info() if r.ok: print(r.server_info) else: print("Error: {}".format(r.status_message)) else: print("not connected") except Exception as err: # handle exception print("not connected")
Attributes:
Seconds to wait before giving up on network operations.
Url of the Tomcat Manager web application we are connected to.
User we successfully authenticated to the Tomcat Manager web application with.
Client side SSL/TLS certificates we authenticated to the Tomcat Manager web application with.
The certificate authority directory or bundle to use to verify server SSL/TLS certificates.
If connected to a server, this contains an instance of
TomcatMajorMinor
describing the major version of Tomcat we are connected to.Does the url point to an actual tomcat server and are the credentials valid?
Methods:
implements
(method)Is a method implemented on the tomcat server we are connected to?
implemented_by
(method, tomcat_major_minor)Check whether a method is implemented by any version of Tomcat.
connect
(url[, user, password, cert, verify, ...])Connect to the manager application running in a Tomcat server.
deploy_localwar
(path, warfile[, version, update])Deploy a warfile from the local file system to the Tomcat server.
deploy_serverwar
(path, warfile[, version, ...])Deploy a warfile from the server file system to the Tomcat server.
deploy_servercontext
(path, contextfile[, ...])Deploy a Tomcat application defined by a context file from the server filesystem to the Tomcat server.
undeploy
(path[, version])Undeploy an application in the Tomcat server.
start
(path[, version])Start an application already deployed in the Tomcat server.
stop
(path[, version])Stop an application already deployed in the Tomcat server.
reload
(path[, version])Stop and start a Tomcat application.
sessions
(path[, version])Get the age of the sessions for an application.
expire
(path[, version, idle])Expire idle sessions.
list
()Get a list of all applications currently installed.
Get information about the Tomcat server.
Get server status information in XML format.
vm_info
()Get diagnostic information about the JVM.
Get a JVM thread dump.
resources
([type_])Get the global JNDI resources
Get apps that leak memory.
Get SSL/TLS ciphers configured for each connector.
Get the SSL certificate chain currently configured for each virtual host
Get the trusted certificates currently configured for each virtual host
ssl_reload
([host])Reload TLS certificates and keys (but not server.xml) for a specified or all virtual hosts
- timeout
Seconds to wait before giving up on network operations. Can be a
float
or anint
. Default is10
. I surely don’t want to wait forever, but if you do, set to0
.Usage:
>>> import tomcatmanager as tm >>> tomcat = tm.TomcatManager() >>> tomcat.timeout = 3.5
Changed in version 3.0.0: Can be a
float
orint
instead of just anint
- property url: str
Url of the Tomcat Manager web application we are connected to.
This attribute is set by the
connect()
method. Look there for more info.Changed in version 3.0.0: Now a read-only property instead of a read-write attribute.
- property user: str
User we successfully authenticated to the Tomcat Manager web application with.
This attribute is set by the
connect()
method. Look there for more info.Changed in version 3.0.0: Now a read-only property instead of a read-write attribute.
- property cert: Union[str, Tuple[str, str]]
Client side SSL/TLS certificates we authenticated to the Tomcat Manager web application with.
This attribute is set by the
connect()
method. Look there for more info.New in version 3.0.0.
- property verify: Union[str, bool]
The certificate authority directory or bundle to use to verify server SSL/TLS certificates. If
False
no verification is performed.This attribute is set by the
connect()
method. Look there for more info.New in version 3.0.0.
- property tomcat_major_minor: tomcatmanager.models.TomcatMajorMinor
If connected to a server, this contains an instance of
TomcatMajorMinor
describing the major version of Tomcat we are connected to.This attribute is set by the
connect()
method. Look there for more info.New in version 3.0.0.
- implements(method: Union[Callable, str]) bool
Is a method implemented on the tomcat server we are connected to?
- Parameters
method – a method on
TomcatManager
to check if is implemented- Returns
True
if the method is implemented,False
otherwise- Raises
TomcatNotConnected – if we are not currently connected to a tomcat server
Not all versions of Tomcat implement all of the methods of
TomcatManager
. Use this to check whether a method on this class is implemented by the version of the Tomcat server we are connected to. The method parameter accepts a string containing the method name or the method itself.Usage:
import tomcatmanager as tm tomcat = tm.TomcatManager() tomcat.connect("http://localhost:8080", "ace", "newenglandclamchowder") print(tomcat.implements(tomcat.deploy_localwar))
or:
import tomcatmanager as tm tomcat = tm.TomcatManager() tomcat.connect("http://localhost:8080", "ace", "newenglandclamchowder") print(tomcat.implements(tomcat.deploy_localwar))
New in version 3.0.0.
- classmethod implemented_by(method: Union[Callable, str], tomcat_major_minor: tomcatmanager.models.TomcatMajorMinor) bool
Check whether a method is implemented by any version of Tomcat.
- Parameters
method – a method on
TomcatManager
to checktomcat_major_minor – the version of Tomcat to check
- Returns
True
if the method is implemented on the given tomcat version.
This method does not require prior connection to a Tomcat server.
New in version 3.0.0.
- property is_connected: bool
Does the url point to an actual tomcat server and are the credentials valid?
- Returns
True
if connected to a tomcat server, otherwise,False
.
- connect(url: str, user: str = '', password: str = '', *, cert: Optional[Union[str, Tuple[str, str]]] = None, verify: Union[str, bool] = True, timeout: Optional[float] = None) tomcatmanager.models.TomcatManagerResponse
Connect to the manager application running in a Tomcat server.
- Parameters
url – url where the Tomcat Manager web application is deployed
user – (optional) user to authenticate with
password – (optional) password to authenticate with
cert – client side certificates to use for SSL/TLS authentication
verify – verify server SSL/TLS certificates
timeout – timeout in seconds for network operations
- Returns
TomcatManagerResponse
object with an additionalserver_info
attribute
The
server_info
attribute of the returned object contains aServerInfo
object, which is a dictionary with some added properties for well-known values returned from the Tomcat server.This method:
sets or changes the url, credentials, and certificates on an existing object
provides a convenient mechanism to validate you can actually connect to the server
returns a response object that includes information about the server you are connected to
allows you to inspect the response so you can see why you can’t connect
Usage
>>> import tomcatmanager as tm >>> url = "http://localhost:808099/manager" >>> user = "ace" >>> password = "newenglandclamchowder" >>> tomcat = tm.TomcatManager() >>> try: ... r = tomcat.connect(url, user, password) ... if r.ok: ... print("connected") ... else: ... print("not connected") ... except Exception as err: ... # handle exception ... print("not connected") not connected
Many things can go wrong when requesting url’s via http. tomcatmanager uses the requests library for all network communication, and follows that library’s approach for raising exceptions and checking the response to your request. Therefore:
Some exceptions will always be raised by this method. If you give a URL where no web server is listening,
requests.connections.ConnectionError
will be raised.Other exceptions will only be raised if you call
TomcatManagerResponse.raise_for_status()
. For example, if the credentials are incorrect, you won’t get an exception unless you ask for it.The
TomcatManagerResponse.ok
attribute is the easiest and most rigerous way to check whether you connected successfully. However, as the example usage above shows, you still have to catch exceptions because requests can raise exceptions from inside theconnect()
method and this library doesn’t attempt to catch them so that you can do specific error handling if you want to.
All communications between this library and a Tomcat server happen over HTTP, which means there isn’t a persistent connection. A new HTTP GET request is issued for each method call on this object (i.e.
deploy_localwar()
,stop()
). However, the mental model for this library is connection based: use theconnect()
method to establish the URL and authentication credentials, then call other methods to perform actions on the server you are connected to. If you try and call other methods before you callconnect()
,TomcatNotConnected
will be raised. Because there is no persistent connection of any kind, there is no disconnect method and no cleanup to perform when you are done using a server.If you discard or don’t save the return object from this method, you can call
is_connected()
to check if you are connected.Authentication
The only way to validate the URL and authentication credentials is to make an HTTP request to the server and see if it returns successfully. Internally this method tries to retrieve
/manager/text/serverinfo
.Typically authentication is done via user and password. Pass those parameters to utilize HTTP Basic authentication.
To authenticate with a SSL/TLS server using a client certificate and key, pass the path to a single file containing the private key and certificate in the
cert
parameter. As an alternative, you can pass a tuple containing the path to the certificate, and the path to the key.Warning
The private key for your local certificate must be unencrypted. The Requests library used for network communication does not support using encrypted keys.
If the URL uses the
https
protocol, the default behavior is to validate the server SSL/TLS certificate chain.To validate with your own certificate authority bundle, set the
verify
parameter to the path to a certificate authority bundle file or a directory of certificates of trusted certificate authorities. You can disable server certificate validation by settingverify
toFalse
.See Authentication for more details.
Side Effects
Passing a
timeout
parameter to this method has the side effect of setting thetimeout
attribute on this object.Requesting url’s via http can also result in redirection to another url. If that occurs, the new url, not the one you passed, will be stored in the
url
attribute.If you pass user and password credentials and the connection is successful, the user will be stored in the
user
attribute.If you pass an authentication key and certificate in the
cert
parameter and the connection is successful, the information will be stored in thecert
attribute.Upon successful connection, an instance of
TomcatMajorMinor
will be stored intomcat_major_minor
indicating the major version of Tomcat running on the server. Further details about the server are available in theserver_info
attribute of the returned response.Changed in version 3.0.0:
Returned
TomcatManagerResponse
now includes aserver_info
attribute containing aServerInfo
object describing the server we are connected toSets
tomcat_major_minor
attributetimeout
is now a keyword only argument
- deploy_localwar(path: str, warfile: str, version: str = None, update: bool = False) tomcatmanager.models.TomcatManagerResponse
Deploy a warfile from the local file system to the Tomcat server.
- Parameters
path – The path on the server to deploy this war to, i.e. /sampleapp
warfile – The path (specified using your local operating system convention) to a war file on the local file system. You can also pass a stream or file-like object. This will be sent to the server for deployment.
version – (optional) For tomcat parallel deployments, the version string to associate with this deployment
update – (optional) Whether to undeploy the existing path first (default False)
- Returns
TomcatManagerResponse
object- Raises
ValueError – if no path is specified or if no warfile is specified
- deploy_serverwar(path: str, warfile: str, version: str = None, update: bool = False) tomcatmanager.models.TomcatManagerResponse
Deploy a warfile from the server file system to the Tomcat server.
- Parameters
path – The path on the server to deploy this war to, i.e. /sampleapp
warfile – The java-style path (use slashes not backslashes) to the war file on the server. Don’t include
file:
at the beginning.version – (optional) For tomcat parallel deployments, the version string to associate with this deployment
update – (optional) Whether to undeploy the existing path first (default False)
- Returns
TomcatManagerResponse
object- Raises
ValueError – if no path is given or if no warfile is given
- deploy_servercontext(path: str, contextfile: str, warfile: str = None, version: str = None, update: bool = False) tomcatmanager.models.TomcatManagerResponse
Deploy a Tomcat application defined by a context file from the server filesystem to the Tomcat server.
- Parameters
path – The path on the server to deploy this war to, i.e. /sampleapp
contextfile – The java-style path (use slashes not backslashes) to the context file on the server. Don’t include
file:
at the beginning.warfile – (optional) The java-style path (use slashes not backslashes) to the war file on the server. Don’t include
file:
at the beginning.version – (optional) For tomcat parallel deployments, the version string to associate with this deployment
update – (optional) Whether to undeploy the existing path first (default False)
- Returns
TomcatManagerResponse
object- Raises
ValueError – if no path is given or if no contextfile is given
- undeploy(path: str, version: str = None) tomcatmanager.models.TomcatManagerResponse
Undeploy an application in the Tomcat server.
- Parameters
path – The path of the application to undeploy
version – (optional) The version string of the app to undeploy
- Returns
TomcatManagerResponse
object- Raises
ValueError – if no path is specified
If the application was deployed with a version string, it must be specified in order to undeploy the application.
- start(path: str, version: str = None) tomcatmanager.models.TomcatManagerResponse
Start an application already deployed in the Tomcat server.
- Parameters
path – The path of the application to start
version – (optional) The version string of the app to start
- Returns
TomcatManagerResponse
object- Raises
ValueError – if no path is specified
If the application was deployed with a version string, it must be specified in order to start the application.
- stop(path: str, version: str = None) tomcatmanager.models.TomcatManagerResponse
Stop an application already deployed in the Tomcat server.
- Parameters
path – The path of the application to stop
version – (optional) The version string of the app to stop
- Returns
TomcatManagerResponse
object- Raises
ValueError – if no path is specified
If the application was deployed with a version string, it must be specified in order to stop the application.
- reload(path: str, version: str = None) tomcatmanager.models.TomcatManagerResponse
Stop and start a Tomcat application.
- Parameters
path – The path of the application to reload
version – (optional) The version string of the app to reload
- Returns
TomcatManagerResponse
object- Raises
ValueError – if no path is specified
If the application was deployed with a version string, it must be specified in order to reload the application.
- sessions(path: str, version: str = None) tomcatmanager.models.TomcatManagerResponse
Get the age of the sessions for an application.
- Parameters
path – The path of the application to get session information about
version – (optional) The version string of the app to get session information about
- Returns
TomcatManagerResponse
object with the session summary in both theresult
attribute and thesessions
attribute- Raises
ValueError – if no path is specified
Usage:
>>> tomcat = getfixture("tomcat") >>> r = tomcat.sessions("/manager") >>> if r.ok: ... session_data = r.sessions
- expire(path: str, version: str = None, idle: Any = None) tomcatmanager.models.TomcatManagerResponse
Expire idle sessions.
- Parameters
path – the path to the app on the server whose sessions you want to expire
idle – sessions idle for more than this number of minutes will be expired. Use idle=0 to expire all sessions.
- Returns
TomcatManagerResponse
object with the session summary in both theresult
attribute and thesessions
attribute- Raises
ValueError – if no path is specified
Usage:
>>> tomcat = getfixture("tomcat") >>> r = tomcat.expire("/manager", idle=15) >>> if r.ok: ... expiration_data = r.sessions
- list() tomcatmanager.models.TomcatManagerResponse
Get a list of all applications currently installed.
- Returns
TomcatManagerResponse
object with an additionalapps
attribute which contains a list ofTomcatApplication
objects
Usage:
>>> import tomcatmanager as tm >>> tomcat = getfixture("tomcat") >>> r = tomcat.list() >>> if r.ok: ... running = filter(lambda app: app.state == tm.ApplicationState.RUNNING, r.apps)
- server_info() tomcatmanager.models.TomcatManagerResponse
Get information about the Tomcat server.
- Returns
TomcatManagerResponse
object with an additionalserver_info
attribute
The
server_info
attribute contains aServerInfo
object, which is a dictionary with some added properties for well-known values returned from the Tomcat server.Usage:
>>> tomcat = getfixture("tomcat") >>> r = tomcat.server_info() >>> if r.ok: ... r.server_info["OS Name"] == r.server_info.os_name True
- status_xml() tomcatmanager.models.TomcatManagerResponse
Get server status information in XML format.
- Returns
TomcatManagerResponse
object with an additionalstatus_xml
attribute
Usage:
>>> import xml.etree.ElementTree as ET >>> tomcat = getfixture("tomcat") >>> r = tomcat.status_xml() >>> if r.ok: ... root = ET.fromstring(r.status_xml) ... mem = root.find("jvm/memory") ... print("Free Memory = {}".format(mem.attrib["free"])) Free Memory ...
Tomcat 8.0 doesn’t include application info in the XML, even though the docs say it does.
- vm_info() tomcatmanager.models.TomcatManagerResponse
Get diagnostic information about the JVM.
- Returns
TomcatManagerResponse
object with an additionalvm_info
attribute
- thread_dump() tomcatmanager.models.TomcatManagerResponse
Get a JVM thread dump.
- Returns
TomcatManagerResponse
object with an additionalthread_dump
attribute
- resources(type_: str = None) tomcatmanager.models.TomcatManagerResponse
Get the global JNDI resources
- Parameters
type – (optional) Fully qualified java class name of the resource type you are interested in. For example, pass
javax.sql.DataSource
to acquire the names of all available JDBC data sources.- Returns
TomcatManagerResponse
object with an additionalresources
attribute.
Usage:
>>> tomcat = getfixture("tomcat") >>> r = tomcat.resources() >>> if r.ok: ... print(r.resources) {'UserDatabase': 'org.apache.catalina.users.MemoryUserDatabase'}
resources
is a dictionary with the resource name as the key and the class name as the value.
- find_leakers() tomcatmanager.models.TomcatManagerResponse
Get apps that leak memory.
- Returns
TomcatManagerResponse
object with an additionalleakers
attribute
The
leakers
attribute contains a list of paths of applications which leak memory.This command triggers a full garbage collection on the server. Use with extreme caution on production systems.
Explicity triggering a full garbage collection from code is documented to be unreliable. Furthermore, depending on the jvm, there are options to disable explicit GC triggering, like
-XX:+DisableExplicitGC
. If you want to make sure this command triggered a full GC, you will have to verify using something like GC logging or JConsole.The Tomcat Manager documentation says the server can return duplicates in this list if the app has been reloaded and was leaking both before and after the reload. The list returned by the
leakers
attribute will have no duplicates in it.Usage:
>>> tomcat = getfixture("tomcat") >>> r = tomcat.find_leakers() >>> if r.ok: ... cnt = len(r.leakers) ... else: ... cnt = 0
- ssl_connector_ciphers() tomcatmanager.models.TomcatManagerResponse
Get SSL/TLS ciphers configured for each connector.
- Returns
TomcatManagerResponse
object with an additionalssl_connector_ciphers
attribute
- ssl_connector_certs() tomcatmanager.models.TomcatManagerResponse
Get the SSL certificate chain currently configured for each virtual host
- Returns
TomcatManagerResponse
object with an additionalssl_connector_certs
attribute
- ssl_connector_trusted_certs() tomcatmanager.models.TomcatManagerResponse
Get the trusted certificates currently configured for each virtual host
- Returns
TomcatManagerResponse
object with an additionalssl_connector_trusted_certs
attribute
- ssl_reload(host: str = None) tomcatmanager.models.TomcatManagerResponse
Reload TLS certificates and keys (but not server.xml) for a specified or all virtual hosts
- Parameters
host – (optional) Host name to reload, if omitted, reload all virtual hosts
- Returns
TomcatManagerResponse
object