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