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 21defhostname(path):# get the hostname of current server 22 hnfile =open(path,'r') 23 hn = re.search('^(\w*)\n*', hnfile.read()).group(1) 24return hn 25 26defgetlocaldomain():# 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 28iflen(domain) !=2: 29 logger.warning('Could not get domain of this server, only hostname. Please consider updating /etc/hosts') 30return'localdomain' 31else: 32return domain[-1] 33 34defresolve(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 42if not fqdn: 43 fqdn = config.prefs.get("logparse","resolve-domains") 44 45if fqdn =='ip': 46return(ip) 47 48try: 49 socket.inet_aton(ip)# succeeds if text contains ip 50 hn = socket.gethostbyaddr(ip)[0]# resolve ip to hostname 51if fqdn =='fqdn-implicit'and hn.split('.',1)[1] ==getlocaldomain(): 52return(hn.split('.')[0]) 53elif fqdn =='fqdn'or fqdn =='fqdn-implicit': 54return(hn) 55elif fqdn =='host-only': 56return(hn.split('.')[0]) 57else: 58 logger.warning("invalid value for fqdn config") 59return(hn) 60except socket.herror: 61# cannot resolve ip 62 logger.debug(ip +" cannot be found, might not exist anymore") 63return(ip) 64except(OSError, socket.error):# socket.error for Python 2 compatibility 65# already a hostname 66 logger.debug(ip +" is already a hostname") 67return(ip) 68exceptExceptionas err: 69 logger.warning("failed to resolve hostname for "+ ip +": "+str(err)) 70return(ip)# return ip if no hostname exists 71 72defreadlog(path =None, mode ='r'):# read file 73if(path ==None): 74 logger.error("no path provided") 75return 76else: 77if(os.path.isfile(path)is False): 78 logger.error("Log at{0}was requested but does not exist".format(path)) 79return'' 80else: 81try: 82returnopen(path, mode).read() 83exceptIOErrororOSErroras e: 84 logger.warning("Error reading log at{0}:{1}".format(path, e.strerror)) 85return1