#!/usr/bin/env python3
#
# Script to monitor mdadm based RAID devices.
#
# Parameters understood:
#
#    config   (required)
#    autoconf (optional - used by munin-config)
#
# Configuration:
#
# This script supports one environment variable:
#    DEVICES        - The devices to monitor. If not set, the plugin will
#              monitor all devices found in /proc/mdstat.
#
# Note that the script has to be run as user root to get access to all relevant
# information.
#
# Log:
#
# Revision 1.0:
# Initial version
#
#%# family=auto
#%# capabilities=autoconf

import os
import sys

# handle autoconf
if len(sys.argv) > 1 and sys.argv[1] == 'autoconf':
    if os.path.exists('/proc/mdstat'):
        print('yes')
    else:
        print('no')
    sys.exit(0)

# get devices:
if 'DEVICES' in os.environ:
    devs = os.environ['DEVICES'].split()
else:
    lines = open('/proc/mdstat', 'r').readlines()
    devs = [line.split()[0] for line in lines if line.startswith('md')]


# handle config
if len(sys.argv) > 1 and sys.argv[1] == 'config':
    print("""graph_title Status of RAID arrays
graph_args -l 0
graph_vlabel no. of failed devices
graph_category disk
graph_info This graph shows disk usage on the machine.""")
    for dev in devs:
        print("""%s.label /dev/%s
%s.critical :1""" % (dev, dev, dev))

    sys.exit(0)

# get value
from subprocess import PIPE, Popen
for dev in devs:
    device = '/dev/%s' % dev
    if not os.path.exists(device):
        print('%s.value -1' % dev)
        continue

    p = Popen(['mdadm', '-D', device], text=True, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()

    if p.returncode != 0:
        print('Error: %s: %s' % (device, stderr))
        continue

    lines = stdout.split("\n")
    line = [line for line in lines if 'Failed Devices :' in line]
    failed = int(line[0].split(': ')[1].strip())
    print('%s.value %s' % (dev, failed))
