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