April 10, 2018

[原创]获取tomcat status信息的统计脚本

Filed under: 技术话题 — hunter @ 9:12 pm

网上找了一上午,没有合用的脚本,花半天用python写了一个简单的脚本,用来获取tomcat status信息,计划上报到ganglia中

# -*- coding: utf-8 -*-
import urllib2
import sys
import base64
import xml.parsers.expat

#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 be "Parse and Prepare Request". 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.

class TomcatStatusParser:
  def __init__(self, is_detail):
    self.is_detail = is_detail
    self.value = {}
    self.connector_name = None
    self.inXml = 0
    self.inconnector = 0
  def parse(self, xmlString):
    p = xml.parsers.expat.ParserCreate()
    p.StartElementHandler = parser.start_element
    p.EndElementHandler = parser.end_element
    if self.value == None:
      raise Exception("can't parse xml")
    return self.value

  def set_memory_pool(self, poolname, attrs):
    memoryPoolDict["init"] = attrs["usageInit"]
    memoryPoolDict["committed"] = attrs["usageCommitted"]
    memoryPoolDict["max"]   = attrs["usageMax"]
    memoryPoolDict["used"]  = attrs["usageUsed"]
    self.value[poolname]   = memoryPoolDict
  def set_thread_info(self, attrs):
    thread_info["max"] = attrs["maxThreads"]
    thread_info["count"] = attrs["currentThreadCount"]
    thread_info["busy"] = attrs["currentThreadsBusy"]
    self.value[self.connector_name]["threadInfo"] = thread_info 
  def set_request_info(self, attrs):
    request_info["max"] = attrs["maxTime"]
    request_info["process"] = attrs["processingTime"]
    request_info["requests"] = attrs["requestCount"]
    request_info["errors"] = attrs["errorCount"]
    request_info["received"] = attrs["bytesReceived"]
    request_info["sent"] = attrs["bytesSent"]
    self.value[self.connector_name]["requestInfo"] = request_info
  def add_worker(self, attrs):
    work_info["stage"]    = attrs["stage"]
    work_info["process"]  = attrs["requestProcessingTime"]
    work_info["remote_addr"] = attrs["remoteAddr"]
    work_info["vhost"]       = attrs["virtualHost"]
    work_info["received"]    = attrs["requestBytesReceived"]
    work_info["sent"]        = attrs["requestBytesSent"]
    work_info["method"]      = attrs["method"]
    work_info["url"]         = attrs["currentUri"]

  def start_element(self, name, attrs):
    if name == "status" and self.inXml == 0:
        self.inXml = 1
    elif self.inXml == 1:
        if name == "memory":
            self.value["mem_free"]  = attrs["free"]
            self.value["mem_total"] = attrs["total"]
            self.value["mem_max"]   = attrs["max"]
        elif name == "memorypool":
            if   attrs["name"] == "PS Eden Space":
                 self.set_memory_pool("pool_eden", attrs)
            elif attrs["name"] == "PS Old Gen":
                 self.set_memory_pool("pool_old", attrs)
            elif attrs["name"] == "PS Survivor Space":
                 self.set_memory_pool("pool_survivor", attrs)
            elif attrs["name"] == "Code Cache":
                 self.set_memory_pool("pool_code", attrs)
            elif attrs["name"] == "PS Perm Gen":
                 self.set_memory_pool("pool_perm", attrs)
        elif name == "connector":
            self.connector_name = attrs["name"].replace('"','')
            self.inconnector    = 1
            self.value[self.connector_name] = {}
            self.value[self.connector_name]["works"] = []
        elif self.inconnector == 1:
            if name == "threadInfo":
            elif name == "requestInfo":
            elif name == "workers":
                self.inconnector = 2
                self.works_num = 0
        elif self.inconnector == 2:
            if name == "worker":

  def end_element(self, name):
    if name == "status" and self.inXml==1:
      self.inXml = 0
def httpget(url, authorUser, authPass):
    authorStr    = authorUser + ":" + authPass
    authorEncStr = base64.standard_b64encode(authorStr)

        req = urllib2.Request(url)
        req.add_header('Authorization',"Basic " + authorEncStr)
        r = urllib2.urlopen(req)
        #receive_header =
        #print receive_header
        if r.getcode() == 200:
            html =
            return html
            return ""

    except Exception, e:
        print e

def httpget2(url, authorUser, authPass):
        password_mgr.add_password(None, url, authorUser, authPass)
        handler = urllib2.HTTPBasicAuthHandler(password_mgr)
        opener  = urllib2.build_opener(handler)
        r = urllib2.urlopen(url)

        if r.getcode() == 200:
            html =
            return html
            return ""

    except Exception, e:
        print e

authUser="your user"
authPass="your pass"

xmlStr = httpget(tomcatUrl,authUser,authPass)

print '#####################################'
if len(xmlStr)>0 :
    parser = TomcatStatusParser(1)
    jsonStr = parser.parse(xmlStr)
    print jsonStr

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress