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