f2d5c7f79a033ae35835245fc46d15b87e7dd47e
   1#
   2#   __main__.py
   3#
   4#   This module is the entrypoint of the `logparse` shell command and also
   5#   contains single-use functions which don't fit elsewhere.
   6#
   7
   8import logging, logging.handlers
   9import argparse
  10import os
  11import glob
  12import sys
  13from datetime import datetime
  14
  15import logparse
  16from .config import *
  17from logparse import formatting, mail, config
  18from .parsers import load_parsers
  19
  20def rotate():   
  21    # rotate logs using systemd logrotate
  22    if argparser.parse_args().function is None:
  23        if (prefs['rotate'] == 'y'):
  24            subprocess.call("/usr/sbin/logrotate -f /etc/logrotate.conf", shell=True)
  25            logger.info("rotated logfiles")
  26        else:
  27            logger.debug("user doesn't want to rotate logs")
  28            if (prefs['rotate'] == 's'):
  29                logger.debug("Here is the output of `logrotate -d /etc/logrotate.conf` (simulated):")
  30                sim = subprocess.check_output("/usr/sbin/logrotate -d /etc/logrotate.conf", shell=True)
  31                logger.debug(sim)
  32
  33
  34
  35def main():
  36    # Get arguments
  37    argparser = argparse.ArgumentParser(description='grab logs of some common services and send them by email')
  38    argparser.add_argument('-t','--to', help='mail recipient (\"to\" address)', required=False)
  39    argparser.add_argument('-c', '--config', help='path to config file', required=False)
  40    argparser.add_argument('-p', '--print', help='print HTML to stdout', required=False, dest='printout', action='store_true', default=False)
  41    argparser.add_argument('-d', '--destination', help='file to output HTML', required=False)
  42    argparser.add_argument('-f', '--overwrite', help='force overwrite an existing output file', required=False, action='store_true', default=False)
  43    argparser.add_argument('-v', '--verbose', help='verbose console/syslog output (for debugging)', required=False, default=False, action='store_true')
  44    argparser.add_argument('-r', '--rotate', help='force rotate log files using systemd logrotate', required=False, default=False, action='store_true')
  45    argparser.add_argument('-nr', '--no-rotate', help='do not rotate logfiles (overrides logparse.conf)', required=False, default=False, action='store_true')
  46    argparser.add_argument('-l', '--logs', help='services to analyse', required=False)
  47    argparser.add_argument('-nl', '--ignore-logs', help='skip these services (takes precedence over -l)', required=False)
  48    argparser.add_argument('-es', '--embed-styles', help='make CSS rules inline rather than linking the file', required=False, default=False, action='store_true')
  49
  50    # Load config
  51    if argparser.parse_args().config:
  52        config.prefs = config.loadconf(argparser.parse_args().config, argparser)
  53    else:
  54        config.prefs = config.loadconf(argparser=argparser)
  55    prefs = config.prefs
  56    
  57    # Set up logging
  58    logger = logging.getLogger(__name__)
  59    loghandler = logging.handlers.SysLogHandler(address = '/dev/log')
  60    loghandler.setFormatter(logging.Formatter(fmt='logparse.py[' + str(os.getpid()) + ']: %(message)s'))
  61    loghandler.setLevel(logging.WARNING)   # don't spam syslog with debug messages
  62    if argparser.parse_args().verbose or (config.prefs['verbose'] == 'y' or config.prefs['verbose'] == 'yes'):
  63        logging.basicConfig(level=logging.DEBUG)
  64        logger.debug("Verbose mode turned on")
  65    else:
  66        logging.basicConfig(level=logging.INFO)
  67    logger.addHandler(loghandler)
  68
  69    logger.debug("Finished loading config")
  70
  71    # Time analysis
  72    global start
  73    start = datetime.now()
  74    logger.info("Beginning log analysis at {0} {1}".format(start.strftime(formatting.DATEFMT), start.strftime(formatting.TIMEFMT)))
  75    logger.debug("This is {0} version {1}, running on Python {2}".format(logparse.__name__, logparse.__version__, sys.version.replace('\n', '')))
  76     
  77    # Write HTML header
  78
  79    global output_html
  80    output_html = formatting.header(prefs['header'])
  81    output_html += formatting.opentag('div', id='main')
  82
  83    # Find parsers
  84    
  85    parser_providers = []
  86    if argparser.parse_args().logs:
  87        log_src = argparser.parse_args().logs.split()
  88    elif len(prefs['parsers']) > 0:
  89        log_src = prefs['parsers']
  90    else:
  91        log_src = load_parsers.default_parsers
  92
  93    for parser_name in log_src:
  94        parser = load_parsers.search(parser_name)
  95        if parser == None:
  96            logger.warning("Can't find parser {0}".format(parser_name))
  97            continue
  98        else:
  99            parser_providers.append(load_parsers.load(parser))
 100
 101    if argparser.parse_args().ignore_logs or len(prefs['ignore-parsers']) > 0:
 102        if argparser.parse_args().ignore_logs:
 103            ignore_src = argparser.parse_args().ignore_logs.split()
 104        else:
 105            ignore_src = prefs['ignore-parsers']
 106        for parser_name in ignore_src:
 107            if parser_name in [x.__name__.rpartition('.')[2] for x in parser_providers]:
 108                logger.info("Ignoring default parser {0}".format(parser_name))
 109                parser_providers_new = []
 110                for p in parser_providers:
 111                    if p.__name__.rpartition('.')[2] != parser_name:
 112                        parser_providers_new.append(p)
 113                parser_providers = parser_providers_new
 114                continue
 115
 116    # Execute parsers
 117
 118    logger.debug(str(parser_providers))
 119    for parser in parser_providers:
 120        output_html += parser.parse_log()
 121
 122    # Write HTML footer
 123
 124    output_html += formatting.closetag('div') + formatting.closetag('body') + formatting.closetag('html')
 125
 126    if argparser.parse_args().printout:
 127        print(output_html)
 128    if argparser.parse_args().destination or prefs['output']:
 129        if argparser.parse_args().destination:
 130            dest_path = argparser.parse_args().destination
 131        else:
 132            dest_path = prefs['output']
 133        logger.debug("Outputting to {0}".format(dest_path))
 134        if argparser.parse_args().embed_styles or prefs['embed-styles']:
 135            output_html = mail.mailprep(output_html, prefs['css'])
 136        if not os.path.isfile(dest_path) and not (argparser.parse_args().overwrite or config['overwrite']):
 137            with open(dest_path, 'w') as f:
 138                f.write(output_html)
 139                logger.info("Written output to {}".format(dest_path))
 140        else:
 141            logger.warning("Destination file already exists")
 142            if input("Would you like to overwrite {0}? (y/n) [n] ".format(dest_path)) == 'y':
 143                with open(dest_path, 'w') as f:
 144                    f.write(output_html)
 145                logger.debug("Written output to {}".format(dest_path))
 146            else:
 147                logger.warning("No output written")
 148
 149    if argparser.parse_args().to:
 150       mail.sendmail(mailbin=prefs['mail']['mailbin'], body=mail.mailprep(output_html, prefs['css']), recipient=argparser.parse_args().to, subject=formatting.fsubject(config.prefs['mail']['subject']))
 151    
 152    # Print end message
 153    finish = datetime.now()
 154    logger.info("Finished parsing logs at {0} {1} (total time: {2})".format(finish.strftime(formatting.DATEFMT), finish.strftime(formatting.TIMEFMT), finish - start))
 155
 156    return