13d6d07099759e82c168304acb92aca437096404
   1#
   2#   config.py
   3#
   4#   Default config values and basic wrapper for PyYaml. New config options
   5#   should be added to the dictionary below, along with appropriate defaults.
   6#
   7
   8import yaml
   9import types
  10import os
  11from pkg_resources import Requirement, resource_filename
  12from types import SimpleNamespace
  13
  14import logparse
  15import logging
  16logger = logging.getLogger(__name__)
  17
  18def locate(filename):
  19    logger.debug("Searching for {0}".format(filename))
  20    loc = resource_filename(Requirement.parse(__package__), filename)
  21    logger.debug("Found {0}".format(loc))
  22    return loc
  23
  24class Configuration(dict):
  25
  26    def __init__(self, *arg, **kw):
  27        super(Configuration, self).__init__(*arg, **kw)
  28    
  29    def _str2bool(x):
  30        positives = ["yes", "true", "1", "y"]
  31        negatives = ["no", "false", "0", "n"]
  32        x = x.lower()
  33        if x in positives:
  34            return True
  35        elif x in negatives:
  36            return False
  37        else:
  38            raise ValueError("Unknown option %s" % x)
  39
  40defaults = Configuration({
  41    'output': '/var/www/logparse/summary.html',
  42    'header':  '/etc/logparse/header.html',
  43    'css': '/etc/logparse/main.css',
  44    'title': logparse.__name__,
  45    'maxlist': 10,
  46    'maxcmd': 3,
  47    'resolve-domains': 'fqdn',
  48    'mail': {
  49        'to': '',
  50        'from': '',
  51        'subject': 'logparse from $hostname$',
  52        'mailbin': '/usr/bin/mail',
  53    },
  54    'rotate': 'n',
  55    'verbose': 'n',
  56    'hddtemp': {
  57        'drives': ['/dev/sda'],
  58        'host': '127.0.0.1',
  59        'separator': '|',
  60        'timeout': 10,
  61        'port': 7634,
  62        'show-model': False, 
  63    },
  64    'apache': {
  65        'resolve-domains': '',
  66    },
  67    'sshd': {
  68        'resolve-domains': '',
  69    },
  70    'smbd': {
  71        'resolve-domains': '',
  72    },
  73    'httpd': {
  74        'resolve-domains': '',
  75    },
  76    'du': {
  77        'paths': ['/', '/etc', '/home'],
  78        'force-write': 'n',
  79    },
  80    'hostname-path': '/etc/hostname',
  81    'logs': {
  82        'auth': '/var/log/auth.log',
  83        'cron': '/var/log/cron.log',
  84        'sys': '/var/log/syslog',
  85        'smb': '/var/log/samba',
  86        'zfs': '/var/log/zpool.log',
  87        'alloc': '/var/log/du.log',
  88        'postfix': '/var/log/mail.log',
  89        'httpd': '/var/log/apache2'
  90    }
  91})
  92
  93def verify(raw_dict, defaults):
  94    for key, value in raw_dict.items():
  95        if key in defaults: # valid key
  96            logger.debug("Found valid key {0} with value {1}".format(key, value))
  97            if (isinstance(value, dict)):
  98                verify(value, defaults[key])   # recurse nested dictionaries
  99
 100        else:               # invalid key
 101            logger.warning("Invalid key {0} with value {1}".format(key, value))
 102
 103def loadconf(argparser, configfile = "/etc/logparse/logparse.conf"):
 104    logger.debug("Getting config from {0}".format(configfile))
 105    try:
 106        raw_dict = yaml.safe_load(open(configfile))
 107        # verify fields
 108        verify(raw_dict, defaults)
 109        prefs = defaults
 110        for value in raw_dict:
 111            if(isinstance(raw_dict[value], dict)):
 112                for key in raw_dict[value].items():
 113                    logger.debug("Inserting key {0} with value {1}".format(key[0], key[1]))
 114                    if not value in prefs:
 115                        prefs[value] = {}
 116                    prefs[value][key[0]] = key[1]
 117            else:
 118                prefs[value] = raw_dict[value]
 119        if argparser.parse_args().to is not None:
 120            prefs['mail']['to'] = argparser.parse_args().to
 121        if not prefs['mail']['to']:
 122            logger.info("No recipient address provided, outputting to stdout")
 123        else:
 124            logger.info("Email will be sent to " + prefs['mail']['to'])
 125        return prefs 
 126    except Exception as e:
 127        logger.warning("Error processing config: " + str(e))