# # utilities.py # # Commonly used general functions # import re import os import socket import inspect from systemd import journal from datetime import datetime, timedelta import logging logger = logging.getLogger(__name__) from pkg_resources import Requirement, resource_filename from . import config def hostname(path): # get the hostname of current server hnfile = open(path, 'r') hn = re.search('^(\w*)\n*', hnfile.read()).group(1) return hn def getlocaldomain(): # get the parent fqdn of current server domain = socket.getfqdn().split('.', 1) # Note: if socket.fetfqdn() returns localhost, make sure the first entry in /etc/hosts contains the fqdn if len(domain) != 2: logger.warning('Could not get domain of this server, only hostname. Please consider updating /etc/hosts') return 'localdomain' else: return domain[-1] def resolve(ip, fqdn=None): # try to resolve an ip to hostname # Possible values for fqdn: # fqdn show full hostname and domain # fqdn-implicit show hostname and domain unless local # host-only only show hostname # ip never resolve anything # resolve-domains defined in individual sections of the config take priority over global config if not fqdn: fqdn = config.prefs['resolve-domains'] if fqdn == 'ip': return(ip) try: socket.inet_aton(ip) # succeeds if text contains ip hn = socket.gethostbyaddr(ip)[0] # resolve ip to hostname if fqdn == 'fqdn-implicit' and hn.split('.', 1)[1] == getlocaldomain(): return(hn.split('.')[0]) elif fqdn == 'fqdn' or fqdn == 'fqdn-implicit': return(hn) elif fqdn == 'host-only': return(hn.split('.')[0]) else: logger.warning("invalid value for fqdn config") return(hn) except socket.herror: # cannot resolve ip logger.debug(ip + " cannot be found, might not exist anymore") return(ip) except (OSError, socket.error): # socket.error for Python 2 compatibility # already a hostname logger.debug(ip + " is already a hostname") return(ip) except Exception as err: logger.warning("failed to resolve hostname for " + ip + ": " + str(err)) return(ip) # return ip if no hostname exists def readlog(path = None, mode = 'r'): # read file if (path == None): logger.error("no path provided") return else: if (os.path.isfile(path) is False): logger.error("Log at {0} was requested but does not exist".format(path)) return '' else: try: return open(path, mode).read() except IOError or OSError as e: logger.warning("Error reading log at {0}: {1}".format(path, e.strerror)) return 1