Use from Python¶
Connect to the server¶
Before you can do anything useful, you need to create a TomcatManager
object
and connect to a server.
-
TomcatManager.
connect
(url: str, user: str = '', password: str = '') → tomcatmanager.models.TomcatManagerResponse Connect to a Tomcat Manager server.
Parameters: url – url where the Tomcat Manager web application is deployed :param user: (optional) user to authenticate with :param password: (optional) password to authenticate with :return: TomcatManagerResponse()
objectYou don’t have to connect before using any other commands. If you initialized the object with credentials you can call any other method. This method:
- give you a way to change the credentials on an existing object
- provide a convenient mechanism to validate you can actually connect to the server
- allow you to inspect the response so you can see why you can’t connect
Usage:
>>> import tomcatmanager as tm >>> url = 'http://localhost:8080/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
The only way to validate whether we are connected is to make an HTTP request to the server and see if it returns successfully. Internally this method tries to retrieve
/manager/text/serverinfo
.Requesting url’s via http can raise all kinds of exceptions. For example, if you give a URL where no web server is listening, you’ll get a
requests.connections.ConnectionError
. However, this method won’t raise exceptions for everything. If the credentials are incorrect, you won’t get an exception unless you ask for it.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.
You can also use
TomcatManager.is_connected()
to check if you are connected.If you want to raise more exceptions see
TomcatManagerResponse.raise_for_status()
.
Responses from the server¶
All the methods of TomcatManager
which interact with the server
return a response in the form of a TomcatManagerResponse
object.
Use this object to check whether the command completed successfully, and to
get any results generated by the command.
-
class
tomcatmanager.models.
TomcatManagerResponse
(response=None) Returned as the response for
TomcatManager
commands.After running a command, it’s a good idea to check and make sure that the command completed succesfully before relying on the results:
>>> import tomcatmanager as tm >>> tomcat = getfixture('tomcat') >>> try: ... r = tomcat.server_info() ... r.raise_for_status() ... if r.ok: ... print(r.server_info.os_name) ... else: ... print('Error: {}'.format(r.status_message)) ... except Exception as err: ... # handle exception ... pass Linux
-
ok
Returns: True if the request completed with no errors. For this property to return True:
- The HTTP request must return a status code of
200 OK
- The first line of the response from the Tomcat Server must begin with
OK
.
- The HTTP request must return a status code of
-
raise_for_status
() Raise exceptions for server errors.
First this method calls
requests.Response.raise_for_status()
which raises exceptions if a 4xx or 5xx response is received from the server.If that doesn’t raise anything, then it raises a
TomcatError
if there is not anOK
response from the first line of text back from the Tomcat Manager web app.
-
status_code
Status of the Tomcat Manager command from the first line of text.
The preferred way to check for success is to use the
ok()
method, because it checks for http errors as well as tomcat errors. However, if you want specific access to the status of the tomcat command, use this method.There are three status codes:
OK
FAIL
NOTFOUND
tomcatmanager.status_codes
is a dictionary which makes it easy to check this code against known values. It also has attributes with friendly names, as shown here:>>> import tomcatmanager as tm >>> tomcat = getfixture('tomcat') >>> r = tomcat.server_info() >>> r.status_code == tm.status_codes.ok True
-
status_message
The message on the first line of the response from the Tomcat Server.
-
result
The text of the response from the Tomcat server, without the first line (which contains the status code and message).
-
response
The server’s response to an HTTP request.
TomcatManager
uses the excellent Requests package for HTTP communication. This property returns therequests.models.Response
object which contains the server’s response to the HTTP request.Of particular use is
requests.models.Response.text
which contains the content of the response in unicode. If you want raw access to the content returned by the Tomcat Server, this is where you can get it.
-
Deploying applications¶
There are three methods you can use to deploy applications to a Tomcat server.
-
TomcatManager.
deploy_localwar
(path: str, warfile: str, version: str = None, update: bool = False) → tomcatmanager.models.TomcatManagerResponse Deploy a warfile on 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
objectRaises: ValueError – if no path is specified; if no warfile is specified
-
TomcatManager.
deploy_serverwar
(path: str, warfile: str, version: str = None, update: bool = False) → tomcatmanager.models.TomcatManagerResponse Deploy a warfile on 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 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
objectRaises: ValueError – if no path is given; if no warfile is given
-
TomcatManager.
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.
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
objectRaises: ValueError – if no path is given; if no contextfile is given
You can also undeploy applications. This removes the WAR file from the Tomcat server.
-
TomcatManager.
undeploy
(path: str, version: str = None) → tomcatmanager.models.TomcatManagerResponse Undeploy the application at a given path.
Parameters: - path – The path of the application to undeploy
- version – (optional) The version string of the app to undeploy
Returns: TomcatManagerResponse
objectRaises: 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.
Other application commands¶
-
TomcatManager.
start
(path: str, version: str = None) → tomcatmanager.models.TomcatManagerResponse Start the application at a given path.
Parameters: - path – The path of the application to start
- version – (optional) The version string of the app to start
Returns: TomcatManagerResponse
objectRaises: 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.
-
TomcatManager.
stop
(path: str, version: str = None) → tomcatmanager.models.TomcatManagerResponse Stop the application at a given path.
Parameters: - path – The path of the application to stop
- version – (optional) The version string of the app to stop
Returns: TomcatManagerResponse
objectRaises: 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.
-
TomcatManager.
reload
(path: str, version: str = None) → tomcatmanager.models.TomcatManagerResponse Reload (stop and start) the application at a given path.
Parameters: - path – The path of the application to reload
- version – (optional) The version string of the app to reload
Returns: TomcatManagerResponse
objectRaises: 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.
-
TomcatManager.
sessions
(path: str, version: str = None) → tomcatmanager.models.TomcatManagerResponse Get the age of the sessions in 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
attributeRaises: ValueError – if no path is specified
Usage:
>>> tomcat = getfixture('tomcat') >>> r = tomcat.sessions('/manager') >>> if r.ok: ... session_data = r.sessions
-
TomcatManager.
expire
(path: str, version: str = None, idle: Any = None) → tomcatmanager.models.TomcatManagerResponse Expire sessions idle for longer than idle minutes.
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
attributeRaises: ValueError – if no path is specified
Usage:
>>> tomcat = getfixture('tomcat') >>> r = tomcat.expire('/manager', idle=15) >>> if r.ok: ... expiration_data = r.sessions
-
TomcatManager.
list
() → tomcatmanager.models.TomcatManagerResponse Get a list of all applications currently installed.
Returns: TomcatManagerResponse
object with an additionalapps
attribute which contains a list ofTomcatApplication
objectsUsage:
>>> import tomcatmanager as tm >>> tomcat = getfixture('tomcat') >>> r = tomcat.list() >>> if r.ok: ... running = filter(lambda app: app.state == tm.application_states.running, r.apps)
Parallel Deployment¶
Tomcat supports a parallel deployment feature which allows multiple versions of the same WAR to be deployed simultaneously at the same URL. To utilize this feature, you need to deploy an application with a version string. The combination of path and version string uniquely identify the application:
>>> tomcat = getfixture('tomcat')
>>> safe_path = getfixture('safe_path')
>>> localwar_file = getfixture('localwar_file')
>>> with open(localwar_file, 'rb') as localwar_fileobj:
... r = tomcat.deploy_localwar(safe_path, localwar_fileobj, version='42')
... r.ok
True
>>> with open(localwar_file, 'rb') as localwar_fileobj:
... r = tomcat.deploy_localwar(safe_path, localwar_fileobj, version='43')
... r.ok
True
We now have two instances of the same application, deployed at the same location, but with different version strings. To do anything to either of those applications, you must supply both the path and the version string:
>>> r = tomcat.stop(path=safe_path, version='42')
>>> r.ok
True
>>> r = tomcat.undeploy(path=safe_path, version='42')
>>> r.ok
True
>>> r = tomcat.undeploy(path=safe_path, version='43')
>>> r.ok
True
The following methods include an optional version parameter to support parallel deployments:
Information about Tomcat¶
There are a number of methods which just return information about the Tomcat
server. With the exception of find_leakers()
(which
triggers garbage collection), these methods don’t effect any change on the
server.
-
TomcatManager.
server_info
() → tomcatmanager.models.TomcatManagerResponse Get information about the Tomcat server.
Returns: TomcatManagerResponse
object with an additionalserver_info
attributeThe
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
-
TomcatManager.
status_xml
() → tomcatmanager.models.TomcatManagerResponse Get server status information in XML format.
Returns: TomcatManagerResponse
object with an additionalstatus_xml
attributeUsage:
>>> 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.
-
TomcatManager.
vm_info
() → tomcatmanager.models.TomcatManagerResponse Get diagnostic information about the JVM.
Returns: TomcatManagerResponse
object with an additionalvm_info
attribute
-
TomcatManager.
ssl_connector_ciphers
() → tomcatmanager.models.TomcatManagerResponse Get SSL/TLS ciphers configured for each connector.
Returns: TomcatManagerResponse
object with an additionalssl_connector_ciphers
attribute
-
TomcatManager.
thread_dump
() → tomcatmanager.models.TomcatManagerResponse Get a jvm thread dump.
Returns: TomcatManagerResponse
object with an additionalthread_dump
attribute
-
TomcatManager.
resources
(type_: str = None) → tomcatmanager.models.TomcatManagerResponse Get the global JNDI resources available for use in resource links for context config files
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.
-
TomcatManager.
find_leakers
() → tomcatmanager.models.TomcatManagerResponse Get apps that leak memory.
Returns: TomcatManagerResponse
object with an additionalleakers
attributeThe
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