#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2013             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# ails.  You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

# WARNING: This plugin is deprecated and will be removed soon.
# Please use mk_jolokia instead

import urllib2, sys, os

server   = "localhost"
port     = 8080
user     = "monitoring"
password = "foobar"
mode     = "digest"
suburi   = "jolokia"
instance = None

vars = [
 ( "java.lang:type=Memory/NonHeapMemoryUsage/used",     "NonHeapMemoryUsage" ),
 ( "java.lang:type=Memory/HeapMemoryUsage/used",        "HeapMemoryUsage" ),
 ( "java.lang:type=Threading/ThreadCount",              "ThreadCount" ),
 ( "java.lang:type=Threading/DaemonThreadCount",        "DeamonThreadCount" ),
 ( "java.lang:type=Threading/PeakThreadCount",          "PeakThreadCount" ),
 ( "java.lang:type=Threading/TotalStartedThreadCount",  "TotalStartedThreadCount" ),
 ( "java.lang:type=Runtime/Uptime",                     "Uptime" ),
]

app_vars = [
 ('*:j2eeType=WebModule,name=/--/localhost/-/%(app)s,*/state', 'Running'),
 ('*:path=/-/%(app)s,type=Manager,*/activeSessions',           'Sessions'),
]

servlet_vars = [
 ('*:j2eeType=Servlet,WebModule=/--/localhost/-/%(app)s,name=%(servlet)s,*/requestCount', 'Requests')
]

# The servlets dictionary keys represent an application (webmodule) which holds a
# list of servlets which are available within this application
servlets = {}

conffile = os.getenv("MK_CONFDIR", "/etc/check_mk") + "/j4p.conf"

if instance == None:
    instance = str(port)

if os.path.exists(conffile):
    execfile(conffile)

# We have to deal with socket timeouts. Python > 2.6
# supports timeout parameter for the urllib2.urlopen method
# but we are on a python 2.5 system here which seem to use the
# default socket timeout. We are local here so  set it to 1 second.
import socket
socket.setdefaulttimeout(1.0)

# Convert servlet config definitions and append it to the vars definitions
for app, servlets  in servlets.iteritems():
    # Add application specific vars
    for var in app_vars:
        vars.append(((app, None), var[0] % {'app': app}, var[1]))

    # Add servlet specific checks
    for servlet in servlets:
        for var in servlet_vars:
            vars.append(((app, servlet), var[0] % {'app': app, 'servlet': servlet}, var[1]))


def init_auth():
    if user and password:
        passwdmngr = urllib2.HTTPPasswordMgrWithDefaultRealm()
        passwdmngr.add_password(None, "http://%s:%d/" % (server, port), user, password)
        if mode == 'digest':
            authhandler = urllib2.HTTPDigestAuthHandler(passwdmngr)
        else:
            authhandler = urllib2.HTTPBasicAuthHandler(passwdmngr)
        opener = urllib2.build_opener(authhandler)
        urllib2.install_opener(opener)


def fetch_var(server, port, path, suburi):
    url = "http://%s:%d/%s/read/%s" % (server, port, suburi, path)
    json = urllib2.urlopen(url).read()

    try:
        obj = eval(json)
    except Exception, e:
        sys.stderr.write('ERROR: Invalid json code (%s)\n' % e)
        sys.stderr.write('       Response %s\n' % json)
        return None

    if obj.get('status', 200) == 404:
        sys.stderr.write('ERROR: Invalid response when fetching url %s\n' % url)
        sys.stderr.write('       Response: %s\n' % json)

    # Only take the value of the object. If the value is an object
    # take the first items first value.
    # {'Catalina:host=localhost,path=\\/test,type=Manager': {'activeSessions': 0}}
    val = obj.get('value', None)
    if isinstance(val, dict):
        item = val[val.keys()[0]]
        return item[item.keys()[0]]
    else:
        return val


init_auth()

# Fetch the general information first
first = True
for var in vars:
    app, servlet = None, None
    if len(var) == 2:
        path, title = var
    else:
        (app, servlet), path, title = var

    if servlet:
        item = [instance, app, servlet]
    elif app:
        item = [instance, app]
    else:
        item = [instance]

    try:
        value = fetch_var(server, port, path, suburi)
    except IOError:
        sys.exit(1)
    except socket.timeout:
        sys.exit(1)
    except:
        # Simply ignore exceptions. Need to be removed for debugging
        continue

    if first:
        first = False
        sys.stdout.write("<<<j4p_performance>>>\n")

    sys.stdout.write("%s %s %s\n" % (','.join(item), title, value))
sys.exit(0)
