logparse / util.pyon commit new parser class structure (4da08ff)
   1#
   2#   utilities.py
   3#
   4#   Commonly used general functions
   5#
   6
   7import re
   8import os
   9import socket
  10import inspect
  11from systemd import journal
  12from datetime import datetime, timedelta
  13
  14import logging
  15logger = logging.getLogger(__name__)
  16
  17from pkg_resources import Requirement, resource_filename
  18
  19from logparse import config
  20
  21def hostname(path): # get the hostname of current server
  22    hnfile = open(path, 'r')
  23    hn = re.search('^(\w*)\n*', hnfile.read()).group(1)
  24    return hn
  25
  26def getlocaldomain(): # get the parent fqdn of current server
  27    domain = socket.getfqdn().split('.', 1) # Note: if socket.fetfqdn() returns localhost, make sure the first entry in /etc/hosts contains the fqdn
  28    if len(domain) != 2:
  29        logger.warning('Could not get domain of this server, only hostname. Please consider updating /etc/hosts')
  30        return 'localdomain'
  31    else:
  32        return domain[-1]
  33
  34def resolve(ip, fqdn=None):        # try to resolve an ip to hostname
  35    # Possible values for fqdn:
  36    #   fqdn            show full hostname and domain
  37    #   fqdn-implicit   show hostname and domain unless local
  38    #   host-only       only show hostname
  39    #   ip              never resolve anything
  40    # resolve-domains defined in individual sections of the config take priority over global config
  41    
  42    if not fqdn:
  43        fqdn = config.prefs.get("logparse", "resolve-domains")
  44
  45    if fqdn == 'ip':
  46        return(ip)
  47
  48    try:
  49        socket.inet_aton(ip)  # succeeds if text contains ip
  50        hn = socket.gethostbyaddr(ip)[0] # resolve ip to hostname
  51        if fqdn == 'fqdn-implicit' and hn.split('.', 1)[1] == getlocaldomain():
  52            return(hn.split('.')[0])
  53        elif fqdn == 'fqdn' or fqdn == 'fqdn-implicit':
  54            return(hn)
  55        elif fqdn == 'host-only':
  56            return(hn.split('.')[0])
  57        else:
  58            logger.warning("invalid value for fqdn config")
  59            return(hn)
  60    except socket.herror:
  61        # cannot resolve ip
  62        logger.debug(ip + " cannot be found, might not exist anymore")
  63        return(ip)
  64    except (OSError, socket.error): # socket.error for Python 2 compatibility
  65        # already a hostname
  66        logger.debug(ip + " is already a hostname")
  67        return(ip)
  68    except Exception as err:
  69        logger.warning("failed to resolve hostname for " + ip + ": " + str(err))
  70        return(ip)  # return ip if no hostname exists
  71
  72def readlog(path = None, mode = 'r'):   # read file
  73    if (path == None):
  74        logger.error("no path provided")
  75        return
  76    else:
  77        if (os.path.isfile(path) is False):
  78            logger.error("Log at {0} was requested but does not exist".format(path))
  79            return ''
  80        else:
  81            try:
  82                return open(path, mode).read()
  83            except IOError or OSError as e:
  84                logger.warning("Error reading log at {0}: {1}".format(path, e.strerror))
  85                return 1