logparse / interface.pyon commit new parser class structure (4da08ff)
   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 subprocess import check_output
  14from datetime import datetime
  15
  16import logparse
  17import logparse.config
  18from logparse.config import prefs, loadconf
  19from logparse import formatting, mail, config, load_parsers
  20
  21global argparser
  22
  23def rotate():       # Rotate logs using systemd logrotate
  24    try:
  25        if not os.geteuid() == 0:
  26            if sys.stdin.isatty():
  27                logger.warning("Not running as root, using sudo (may require password to be entered)")
  28                rotate_shell = check_output("sudo logrotate /etc/logrotate.conf", shell=True)
  29            else:
  30                raise PermissionError("Root priviliges are required to run logrotate but are not provided")
  31        else:
  32            rotate_shell = check_output("/usr/sbin/logrotate /etc/logrotate.conf", shell=True)
  33        logger.info("Rotated logfiles")
  34        logger.debug("logrotate output: " + rotate_shell)
  35    except Exception as e:
  36        logger.warning("Failed to rotate log files: " + str(e))
  37
  38def rotate_sim():   # Simulate log rotation
  39    try:
  40        if not os.geteuid() == 0:
  41            logger.warning("Cannot run logrotate as root - you will see permission errors in the output below")
  42        sim_cmd = "logrotate -d /etc/logrotate.conf"
  43        logger.debug("Here is the output of `{0}` (simulated):".format(sim_cmd))
  44        sim = check_output(sim_cmd, shell=True)
  45        logger.debug(sim)
  46    except Exception as e:
  47        logger.warning("Failed to get logrotate simulation: " + str(e))
  48
  49
  50def main():
  51    # Get arguments
  52    global argparser
  53    argparser = argparse.ArgumentParser(description='grab logs of some common services and send them by email')
  54    argparser.add_argument('-t','--to', help='mail recipient (\"to\" address)', required=False)
  55    argparser.add_argument('-c', '--config', help='path to config file', required=False, default="/etc/logparse/logparse.conf")
  56    argparser.add_argument('-p', '--print', help='print HTML to stdout', required=False, dest='printout', action='store_true', default=False)
  57    argparser.add_argument('-d', '--destination', help='file to output HTML', required=False)
  58    argparser.add_argument('-f', '--overwrite', help='force overwrite an existing output file', required=False, action='store_true', default=False)
  59    argparser.add_argument('-v', '--verbose', help='verbose console/syslog output (for debugging)', required=False, default=False, action='store_true')
  60    argparser.add_argument('-r', '--rotate', help='force rotate log files using systemd logrotate (overrides --rotate and "rotate" in logparse.conf)', required=False, default=False, action='store_true')
  61    argparser.add_argument('-nr', '--no-rotate', help='do not rotate logfiles (overrides --rotate and logparse.conf)', required=False, default=False, action='store_true')
  62    argparser.add_argument('-s', '--simulate', help="test run logrotate (do not actually change files)", required=False, default=False, action="store_true")
  63    argparser.add_argument('-l', '--logs', help='services to analyse', required=False)
  64    argparser.add_argument('-nl', '--ignore-logs', help='skip these services (takes precedence over -l)', required=False)
  65    argparser.add_argument('-es', '--embed-styles', help='make CSS rules inline rather than linking the file', required=False, default=False, action='store_true')
  66    argparser.add_argument('-nh', '--plain', help='write/send plain text rather than HTML', required=False, default=False, action='store_true')
  67    argparser.add_argument('-q', '--quiet', help='no output to stdout', required=False, default=False, action='store_true')
  68    argparser.add_argument('-nm', '--no-mail', help="do not send email (overrides config file)", required=False, default=False, action="store_true")
  69    argparser.add_argument('-nw', '--no-write', help="do not write output file (overrides config file)", required=False, default=False, action="store_true")
  70
  71    # Load config
  72    config.prefs = loadconf(argparser.parse_args().config)
  73    
  74    # Set up logging
  75    logger = logging.getLogger(__name__)
  76    loghandler = logging.handlers.SysLogHandler(address = '/dev/log')
  77    loghandler.setFormatter(logging.Formatter(fmt='logparse[' + str(os.getpid()) + ']: %(message)s'))
  78    loghandler.setLevel(logging.INFO)   # don't spam syslog with debug messages
  79    if argparser.parse_args().quiet or config.prefs.getboolean("logparse", "quiet"):
  80        logging.basicConfig(level=logging.CRITICAL)
  81    elif argparser.parse_args().verbose or config.prefs.getboolean("logparse", "verbose"):
  82        logging.basicConfig(level=logging.DEBUG)
  83        logger.debug("Verbose mode turned on")
  84    else:
  85        logging.basicConfig(level=logging.INFO)
  86    logger.addHandler(loghandler)
  87
  88    logger.debug([x for x in config.prefs.sections()])
  89    logger.debug(config.prefs.get("logparse", "output"))
  90    logger.debug("Config test: " + config.prefs.get("logparse", "output"))
  91
  92    # Time analysis
  93    global start
  94    start = datetime.now()
  95    logger.info("Beginning log analysis at {0} {1}".format(start.strftime(formatting.DATEFMT), start.strftime(formatting.TIMEFMT)))
  96    logger.debug("This is {0} version {1}, running on Python {2}".format(logparse.__name__, logparse.__version__, sys.version.replace('\n', '')))
  97     
  98    # Write header
  99
 100    formatting.init_var()
 101
 102    if argparser.parse_args().plain:
 103        output = formatting.PlaintextOutput(linewidth=config.prefs.getint("plain", "linewidth"))
 104        output.append_header()
 105    else:
 106        output = formatting.HtmlOutput()
 107        output.append_header(config.prefs.get("html", "header"))
 108
 109
 110    # Find parsers
 111    
 112    loader = load_parsers.ParserLoader("logparse.parsers") 
 113    parser_names = set([x.name for x in loader.parsers])
 114
 115    if argparser.parse_args().logs:
 116        parser_names = parser_names.intersection(set(argparser.parse_args().logs.split()))
 117    elif config.prefs.get("logparse", "parsers"):
 118        parser_names = parser_names.intersection(set(config.prefs.get("logparse", "parsers").split()))
 119
 120    if argparser.parse_args().ignore_logs:
 121        parser_names = parser_names.difference(set(argparser.parse_args().ignore_logs.split()))
 122    elif config.prefs.get("logparse", "ignore-parsers"):
 123        parser_names = parser_names.difference(set(config.prefs.get("logparse", "ignore-parsers").split()))
 124
 125    # Execute parsers
 126
 127    logger.debug("Queued the following parsers: " + str(loader.parsers))
 128    for parser in loader.parsers:
 129        if parser.name in parser_names:
 130            output.append_section(parser.parse_log())
 131
 132    # Write HTML footer
 133    output.append_footer()
 134
 135    if (argparser.parse_args().destination or config.prefs.get("logparse", "output")) and not argparser.parse_args().no_write:
 136        if argparser.parse_args().destination:
 137            dest_path = argparser.parse_args().destination
 138        else:
 139            dest_path = config.prefs.get("logparse", "output")
 140        logger.debug("Outputting to {0}".format(dest_path))
 141        if (argparser.parse_args().embed_styles or config.prefs.getboolean("html", "embed-styles")) and not (argparser.parse_args().plain or config.prefs.getboolean("plain", "plain")):
 142            output.embed_css(config.prefs.get("html", "css"))
 143        if (not os.path.isfile(dest_path)) and not (argparser.parse_args().overwrite or config.prefs.getboolean("logparse", "overwrite")):
 144            output.write(dest_path)
 145        elif logging.root.level == logging.CRITICAL:
 146            pass
 147        else:
 148            logger.warning("Destination file already exists")
 149            if input("Would you like to overwrite {0}? (y/n) [n] ".format(dest_path)) == 'y':
 150                output.write(dest_path)
 151            else:
 152                logger.warning("No output written")
 153
 154    if (str(argparser.parse_args().to) or str(config.prefs.get("mail", "to"))) and not argparser.parse_args().no_mail:
 155        if str(argparser.parse_args().to):
 156            to = argparser.parse_args().to
 157        else:
 158            to = config.prefs.get("mail", "to")
 159        mail.sendmail(
 160            mailbin=config.prefs.get("mail", "mailbin"),
 161            body=(output.embed_css(config.prefs.get("html", "css")) if isinstance(output, formatting.HtmlOutput) else output.content),
 162            recipient=to,
 163            subject=formatting.fsubject(config.prefs.get("mail", "subject")),
 164            html=isinstance(output, formatting.HtmlOutput),
 165            sender=config.prefs.get("mail", "from"))
 166
 167    if not argparser.parse_args().no_rotate:
 168        if argparser.parse_args().simulate or config.prefs.getboolean("logparse", "rotate"):
 169            rotate_sim()
 170        elif config.prefs.getboolean("logparse", "rotate") or argparser.parse_args().rotate:
 171            rotate()
 172        else:
 173            logger.debug("User doesn't want to rotate logs")
 174    else:
 175        logger.debug("User doesn't want to rotate logs")
 176
 177    # Print end message
 178    finish = datetime.now()
 179    logger.info("Finished parsing logs at {0} {1} (total time: {2})".format(finish.strftime(formatting.DATEFMT), finish.strftime(formatting.TIMEFMT), finish - start))
 180
 181    if argparser.parse_args().printout:
 182        output.print_stdout()
 183
 184    return