#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8
#
# Munin plugin to monitor lighttpd web-server.
#
# Copyright Igor Borodikhin
#
# License : GPLv3
#
# Configuration parameters:
# env.status_url - url of lighty's server-status (optional, default is http://127.0.0.1/server-status)
# env.username - username to provide if status_url requires authentication (optional, default - no authentication)
# env.password - password to provide if status_url requires authentication (optional, default - no authentication)
# env.auth_type - the authentication mechanism to use -- either 'basic' (default) or 'digest'.
#
# Note: If HTTP authentication is required you should specify both username and password.
#
# ## Installation
# Copy file to directory /usr/share/munin/plugins/
# Because this plugin has suggest capability the last step is to run
#     # munin-node-configure --suggest --shell | sh -x
#
#%# family=contrib
#%# capabilities=autoconf suggest

import os, sys, urllib2

program = sys.argv[0]
graph_type = program[program.rfind("_")+1:]
graph_types = {
    "accesses" : [
        {
            "title" : "Total accesses",
            "type" : "COUNTER",
            "args" : "--base 1000 -l 0",
            "fields" : ["accesses"]
        }
    ],
    "kbytes" : [
        {
            "title" : "Total kBytes",
            "type" : "COUNTER",
            "args" : "--base 1024 -l 0",
            "fields" : ["kbytes"]
        }
    ],
    "uptime" : [
        {
            "title" : "Uptime",
            "type" : "GAUGE",
            "args" : "--base 1000 -l 0",
            "fields" : ["uptime"]
        }
    ],
    "status" : [
        {
            "title" : "Status",
            "type" : "GAUGE",
            "args" : "--base 1000 -l 0",
            "fields" : ["busy", "idle"]
        }
    ]
}

if len(sys.argv) == 2 and sys.argv[1] == "autoconf":
    print "yes"
elif len(sys.argv) == 2 and sys.argv[1] == "config":
    if graph_type not in graph_types.keys():
        raise Exception("Unknown graph type '%s'"%graph_type)
    params = graph_types[graph_type]
    for item in params:
        print "graph_title %s" % item["title"]
        print "graph_category lighttpd"
        for field in item["fields"]:
            print "%s.label %s" % (field, field)
            print "%s.type %s" % (field, item["type"])
        print "graph_args %s" % item["args"]
elif len(sys.argv) == 2 and sys.argv[1] == "suggest":
    for item in graph_types.keys():
        print item
else:
    status_url = os.environ.get('status_url', 'http://127.0.0.1/server-status')

    request = urllib2.Request("%s?auto" % status_url)
    if "username" in os.environ and "password" in os.environ:
        mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
        mgr.add_password(None, status_url, os.environ["username"], os.environ["password"])
        if os.environ.get("auth_type", "basic") == "digest":
            auth = urllib2.HTTPDigestAuthHandler(mgr)
        else:
            auth = urllib2.HTTPBasicAuthHandler(mgr)
        opener = urllib2.build_opener(auth)
        urllib2.install_opener(opener)
    info = urllib2.urlopen(request).read()
    data = {}
    for line in info.split("\n"):
        try:
           (title, value) = line.split(": ")
           data[title] = value
        except Exception:
           pass

    if graph_type == "accesses":
        print "accesses.value %s" % data["Total Accesses"]
    elif graph_type == "kbytes":
        print "kbytes.value %s" % data["Total kBytes"]
    elif graph_type == "uptime":
        print "uptime.value %s" % str(float(data["Uptime"])/86400)
    elif graph_type == "status":
        print "busy.value %s" % data["BusyServers"]
        print "idle.value %s" % data["IdleServers"]
