Skip to content
Snippets Groups Projects
test_monitoring.py 2.10 KiB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Criticality: Low
Check that the monitoring graphs work.
'''
import os
from datetime import datetime
import sys
import imp

YELLOW = '\033[93m'
GREEN = '\033[92m'
RED = '\033[91m'
DEF = '\033[0m'

os.chdir(os.path.dirname(__file__))
if not os.path.isfile('../utils.py'):
    print('The envsetup configuration was not found.')
    sys.exit(1)
else:
    es_utils = imp.load_source('es_utils', '../utils.py')
    conf = es_utils.load_conf()


def print_color(txt, col):
    print('%s%s%s' % (col, txt, DEF))


def print_yellow(txt):
    print_color(txt, YELLOW)


def print_red(txt):
    print_color(txt, RED)


def print_green(txt):
    print_color(txt, GREEN)


MUNIN_WWW_PATH = '/var/cache/munin/www/'


def check_munin():
    print('Checking if monitoring works...')
    if not os.path.exists(MUNIN_WWW_PATH):
        print_red('Munin directory "%s" not found.' % MUNIN_WWW_PATH)
        return 1

    # get cpu day graph of each host
    paths = list()
    for name in os.listdir(MUNIN_WWW_PATH):
        if not name.endswith('.html') and name != 'static' and os.path.isfile(os.path.join(MUNIN_WWW_PATH, name, 'index.html')):
            for sub_name in os.listdir(os.path.join(MUNIN_WWW_PATH, name)):
                path = os.path.join(MUNIN_WWW_PATH, name, sub_name, 'cpu-day.png')
                if sub_name != 'index.html' and os.path.exists(path):
                    paths.append(path)
    if not paths:
        print_red('No Munin host directory was found in "%s".' % MUNIN_WWW_PATH)
        return 1

    # check graph mtime
    error = False
    for path in paths:
        print('Checking graph "%s" modification date...' % path)
        mtime = os.path.getmtime(path)
        d = datetime.fromtimestamp(mtime)
        now = datetime.now()
        diff_seconds = (now - d).total_seconds()
        if diff_seconds > 3600:
            print_red('The graph is older than 1 hour. The monitoring is probably not working.')
            error = True
        else:
            print_green('The graph is not older than 1 hour.')
    return 1 if error else 0


rc = check_munin()
sys.exit(rc)