1"""2Commonly used general functions.34This module provides the following methods:5- `hostname`: get the current machine's hostname6- `getlocaldomain`: get the current machine's domain name7- `resolve`: attempt to convert a local/public IP to hostname8- `readlog`: read contents of a log file from disk9"""1011from datetime import datetime, timedelta12import copy13import ipaddress14import logging15import os16from pkg_resources import Requirement, resource_filename17import re18import socket19from systemd import journal2021from logparse import config, formatting22from logparse.timeparse import timeparse232425logger = logging.getLogger(__name__)262728def hostname(path): # get the hostname of current server29"""30Get the hostname of the current machine using the file supplied in the31`hostname-path` config option.32"""3334hnfile = open(path, 'r')35hn = re.search('^(\w*)\n*', hnfile.read()).group(1)36return hn373839def getlocaldomain(): # get the parent fqdn of current server40"""41Get parent domain name (possibly FQDN) of the current machine. Note: if42`socket.fetfqdn()` returns localhost, make sure the first entry in the43hostname file includes the FQDN.44"""4546domain = socket.getfqdn().split('.', 1)47if len(domain) != 2:48logger.warning("Could not get domain of this server, only hostname. "49"Please consider updating the hostname file at {0}".format(50config.prefs.get("logparse", "hostname-path")))51return 'localdomain'52else:53return domain[-1]545556def resolve(ip, fqdn=None): # try to resolve an ip to hostname57"""58Attempt to resolve an IP into a hostname or FQDN.59Possible values for fqdn:60- fqdn show full hostname and domain61- fqdn-implicit show hostname and domain unless local62- host-only only show hostname63- ip never resolve anything64Note resolve-domains settings defined in individual sections of the config65take priority over the global config (this is enforced in parser modules)66"""6768if not fqdn:69fqdn = config.prefs.get("logparse", "resolve-domains")7071if fqdn == 'ip':72return(ip)7374try:75ip_obj = ipaddress.ip_address(ip)76except ValueError as err:77logger.debug("Invalid format: " + str(err))78return ip7980try:81hn = socket.gethostbyaddr(ip)[0] # resolve ip to hostname82except socket.herror:83# cannot resolve ip84logger.debug(ip + " cannot be found, might not exist anymore")85return(ip)86except Exception as err:87logger.warning("Failed to resolve hostname for " + ip + ": " + str(err))88return(ip) # return ip if no hostname exists8990if (fqdn == "host-only") or (fqdn == "fqdn-implicit" and ip_obj.is_private):91return hn.split('.')[0]92if fqdn == 'fqdn' or fqdn == 'fqdn-implicit':93return hn94return hn95969798def readlog(path = None, mode = 'r'):99"""100Read a logfile from disk and return string101"""102103if (path == None):104logger.error("No path provided")105return 1106else:107if (os.path.isfile(path) is False):108logger.error("Log at {0} was requested but does not exist"109.format(path))110return ''111else:112try:113return open(path, mode).read()114except IOError or OSError as e:115logger.warning("Error reading log at {0}: {1}"116.format(path, e.strerror))117return 1118119class LogPeriod:120121def __init__(self, section):122if config.prefs.get(section.split("_")[0], "period"):123self.startdate = datetime.now() \124- timeparse(config.prefs.get(section.split("_")[0], "period"))125logger.debug("Parsing logs for {0} since {1}".format(126section, self.startdate.strftime(formatting.DATEFMT127+ " " + formatting.TIMEFMT)))128self.unique = True129else:130self.startdate = datetime.now() \131- timeparse(config.prefs.get("logparse", "period"))132self.unique = False