#!/usr/bin/env python
# -*- coding: utf-8 -*-

# /* vim: set filetype=python : */

"""Wildcard-plugin to monitor http response time.

To monitor a website, link response_time_<server address|fqdn> to this file.

E.g.

   ln -s /usr/share/node/node/plugins-auto/response_time_http_ \
        /etc/munin/node.d/response_time_http_192.168.0.10

... will monitor http response times to http://192.168.0.10/

If you wish to monitor the http response time to a particular page, use the
/etc/munin/plugin-conf.d/munin-node CONFIGuration file and add the following 
section:

[response_time_http*]
       env.url keepalived.php

You may add as many urls as you wish to, separated by colons:

[response_time_http_192.168.0.10]
    env.url index.html:keepalived.php:testslowpage.html

"""

import sys
import os
from urllib2 import URLError
from timeit import Timer


USAGE = """\
To use this plugin, you must create a symbolic link to it,
with the ip address or fqdn of the web server to monitor.

E.g.

ln -s /usr/share/node/node/plugins-auto/response_time_http_ \
/etc/munin/node.d/response_time_http_192.168.0.10"""

CONFIG = """\
graph_title HTTP GET response time for %s
graph_vlabel seconds
ping_http.label response time
graph_info The response time for a GET to complete on the given server.
response_time_http.info Response time for a GET request to complete."""


def main(argv=None):
    """Main program.

    If called with the "config" parameter, output munin configuration for this
    graph.

    """

    if argv is None:
        argv = sys.argv

    address = os.path.basename(argv[0]).replace('response_time_http_', '')

    if not address:
        print(USAGE)
        return 1

    if 'config' in sys.argv:
        print(CONFIG % address)
    else:
        runs = 10
        if 'runs' in os.environ:
            runs = os.environ['runs']
        runs = int(runs)

        timeout = 5
        if 'timeout' in os.environ:
            timeout = os.environ['timeout']

        try:
            timer = Timer('urlopen("http://%s", None, %s)' % (address, timeout),
                          'from urllib2 import urlopen')
            res = timer.timeit(runs)
            print("response_time.value %s" % (res / runs))
        except URLError:
            print("response_time.value U")
    return 0


if __name__ == '__main__':
    sys.exit(main())
