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