#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2014             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-
# tails. 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.

# Example output:
# <<<nginx_status>>>
# 127.0.0.1 80 Active connections: 1
# 127.0.0.1 80 server accepts handled requests
# 127.0.0.1 80  12 12 12
# 127.0.0.1 80 Reading: 0 Writing: 1 Waiting: 0


def parse_nginx_status(info):
    if len(info) % 4 != 0:
        # Every instance block consists of four lines
        # Multiple block may occur.
        return {}

    data = {}
    for i, line in enumerate(info):
        address, port = line[:2]
        if len(line) < 3:
            continue  # Skip unexpected lines
        item = '%s:%s' % (address, port)

        if item not in data:
            # new server block start
            data[item] = {
                'active': int(info[i + 0][4]),
                'accepted': int(info[i + 2][2]),
                'handled': int(info[i + 2][3]),
                'requests': int(info[i + 2][4]),
                'reading': int(info[i + 3][3]),
                'writing': int(info[i + 3][5]),
                'waiting': int(info[i + 3][7]),
            }

    return data


@get_parsed_item_data
def check_nginx_status(item, params, data):
    if params is None:
        params = {}

    # Add some more values, derived from the raw ones...
    computed_values = {}
    computed_values['requests_per_conn'] = data['requests'] / data['handled']

    this_time = int(time.time())
    for key in ['accepted', 'handled', 'requests']:
        per_sec = get_rate("nginx_status.%s" % key, this_time, data[key])
        computed_values['%s_per_sec' % key] = per_sec

    perfdata = data.items()
    perfdata.sort()

    worst_state = 0

    conn_warn, conn_crit = params.get('active_connections', (None, None))
    conn_txt = ''
    if conn_crit is not None and data['active'] > conn_crit:
        worst_state = max(worst_state, 2)
        conn_txt = ' (!!)'
    elif conn_warn is not None and data['active'] > conn_warn:
        worst_state = max(worst_state, 1)
        conn_txt = ' (!)'

    output = [
        'Active: %d%s (%d reading, %d writing, %d waiting)' %
        (data['active'], conn_txt, data['reading'], data['writing'], data['waiting']),
        'Requests: %0.2f/s (%0.2f/Connection)' % (computed_values['requests_per_sec'],
                                                  computed_values['requests_per_conn']),
    ]

    if data['accepted'] == data['handled']:
        output.append('Accepted/Handled: %0.2f/s' % computed_values['accepted_per_sec'])
    else:
        output.append('Accepted: %0.2f/s, Handled: %0.2f/s' % (computed_values['accepted_per_sec'],
                                                               computed_values['handled_per_sec']))

    return worst_state, ', '.join(output), perfdata


check_info['nginx_status'] = {
    "parse_function": parse_nginx_status,
    "check_function": check_nginx_status,
    "inventory_function": discover(),
    "service_description": "Nginx %s Status",
    "has_perfdata": True,
    "group": "nginx_status"
}
