#!/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.

# Based on check from  Darin Perusich <darin@darins.net>
#
# /usr/sbin/zpool status -x
#
# Example output of a healthy spool
# ---------------------------------
# all pools are healthy
# ---------------------------------
#
# Example output with no poole
# ---------------------------------
# no pools available
# ---------------------------------
#
# Example output of a pool with a error
# ---------------------------------
# pool: snapshots
#  state: ONLINE
# status: One or more devices has experienced an unrecoverable error.  An
#         attempt was made to correct the error.  Applications are unaffected.
# action: Determine if the device needs to be replaced, and clear the errors
#         using 'zpool clear' or replace the device with 'zpool replace'.
#    see: http://www.sun.com/msg/ZFS-8000-9P
#  scrub: none requested
# config:
#
#         NAME        STATE     READ WRITE CKSUM
#         snapshots   ONLINE       0     0     0
#           raidz1    ONLINE       0     0     0
#             c0d0s7  ONLINE       0     0     0
#             c0d1s7  ONLINE       0     0     0
#             c1d0s7  ONLINE       0     0     0
#             c1d1s7  ONLINE       0     0     1
#
# errors: No known data errors
# ---------------------------------


def inventory_zpool_status(info):
    if not info or " ".join(info[0]) == "no pools available":
        return []
    return [(None, None)]


def check_zpool_status(_no_item, _no_params, info):
    if " ".join(info[0]) == "all pools are healthy":
        return 0, "All pools are healthy"

    start_pool    = False
    multiline     = False
    last_pool     = None
    error_pools   = {}
    warning_pools = {}
    pool_messages = {}
    message = []
    state   = 0

    for line in info:
        if line[0] == "pool:":
            last_pool = line[1]
            pool_messages.setdefault(last_pool, [])
            continue

        if line[0] == "state:":
            if   line[1] == "ONLINE":
                 state = 0
            elif line[1] == "DEGRADED":
                 state = 1
                 message.append("DEGRADED State")
            elif line[1] == "FAULTED":
                 state = 2
                 message.append("FAULTED State")
            elif line[1] == "UNAVIL":
                 state = 2
                 message.append("UNAVIL State")
            elif line[1] == "REMOVED":
                 state = 2
                 message.append("REMOVED State")
            elif line[1] == "OFFLINE":
                 state = 0
            else:
                 message.append("Unknown State")
                 state = 1
            continue

        if line[0] in ["status:", "action:"]:
            pool_messages[last_pool].append(" ".join(line[1:]))
            multiline = True
            continue

        if line[0] in ["scrub:", "see:", "scan:", "config:"]:
            multiline = False
            continue

        if line[0] == "NAME":
            multiline  = False
            start_pool = True
            continue

        if line[0] == "errors:":
            multiline  = False
            start_pool = False
            msg = " ".join(line[1:])
            if msg != 'No known data errors':
                pool_messages[last_pool].append(msg)
            continue

        if line[0] in ["spares", "logs", "cache"]:
            start_pool = False
            continue

        if start_pool == True:
            if line[1] != "ONLINE":
                error_pools[line[0]] = tuple(line[1:])
                continue

            if saveint(line[4]) != 0:
                warning_pools[line[0]] = tuple(line[1:])
                continue

        if multiline:
            pool_messages[last_pool].append(" ".join(line))
            continue

    for pool in pool_messages.keys():
        state = 1
        message.append("%s: %s" % (pool, " ".join(pool_messages[pool])))

    for pool in warning_pools.keys():
        state = 1
        message.append("%s CKSUM: %d" % (pool, saveint(warning_pools[pool][3])))

    for pool in error_pools.keys():
        state = 2
        message.append("%s state: %s" % (pool, error_pools[pool][0]))

    if len(message) == 0:
        message = ['No critical errors']

    return state, ", ".join(message)


check_info["zpool_status"] = {
    'check_function'      : check_zpool_status,
    'inventory_function'  : inventory_zpool_status,
    'service_description' : 'zpool status',
}
