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