1"""
2Commonly used general functions.
34
This module provides the following methods:
5- `hostname`: get the current machine's hostname
6- `getlocaldomain`: get the current machine's domain name
7- `resolve`: attempt to convert a local/public IP to hostname
8- `readlog`: read contents of a log file from disk
9"""
1011
from datetime import datetime, timedelta
12import copy
13import ipaddress
14import logging
15import os
16from pkg_resources import Requirement, resource_filename
17import re
18import socket
19from systemd import journal
2021
from logparse import config, formatting
22from logparse.timeparse import timeparse
2324
25
logger = logging.getLogger(__name__)
2627
28
def hostname(path): # get the hostname of current server
29"""
30Get the hostname of the current machine using the file supplied in the
31`hostname-path` config option.
32"""
3334
hnfile = open(path, 'r')
35hn = re.search('^(\w*)\n*', hnfile.read()).group(1)
36return hn
3738
39
def getlocaldomain(): # get the parent fqdn of current server
40"""
41Get parent domain name (possibly FQDN) of the current machine. Note: if
42`socket.fetfqdn()` returns localhost, make sure the first entry in the
43hostname file includes the FQDN.
44"""
4546
domain = socket.getfqdn().split('.', 1)
47if len(domain) != 2:
48logger.warning("Could not get domain of this server, only hostname. "
49"Please consider updating the hostname file at {0}".format(
50config.prefs.get("logparse", "hostname-path")))
51return 'localdomain'
52else:
53return domain[-1]
5455
56
def resolve(ip, fqdn=None): # try to resolve an ip to hostname
57"""
58Attempt to resolve an IP into a hostname or FQDN.
59Possible values for fqdn:
60- fqdn show full hostname and domain
61- fqdn-implicit show hostname and domain unless local
62- host-only only show hostname
63- ip never resolve anything
64Note resolve-domains settings defined in individual sections of the config
65take priority over the global config (this is enforced in parser modules)
66"""
6768
if not fqdn:
69fqdn = config.prefs.get("logparse", "resolve-domains")
7071
if fqdn == 'ip':
72return(ip)
7374
try:
75ip_obj = ipaddress.ip_address(ip)
76except ValueError as err:
77logger.debug("Invalid format: " + str(err))
78return ip
7980
try:
81hn = socket.gethostbyaddr(ip)[0] # resolve ip to hostname
82except socket.herror:
83# cannot resolve ip
84logger.debug(ip + " cannot be found, might not exist anymore")
85return(ip)
86except Exception as err:
87logger.warning("Failed to resolve hostname for " + ip + ": " + str(err))
88return(ip) # return ip if no hostname exists
8990
if (fqdn == "host-only") or (fqdn == "fqdn-implicit" and ip_obj.is_private):
91return hn.split('.')[0]
92if fqdn == 'fqdn' or fqdn == 'fqdn-implicit':
93return hn
94return hn
9596
97
98
def readlog(path = None, mode = 'r'):
99"""
100Read a logfile from disk and return string
101"""
102103
if (path == None):
104logger.error("No path provided")
105return 1
106else:
107if (os.path.isfile(path) is False):
108logger.error("Log at {0} was requested but does not exist"
109.format(path))
110return ''
111else:
112try:
113return open(path, mode).read()
114except IOError or OSError as e:
115logger.warning("Error reading log at {0}: {1}"
116.format(path, e.strerror))
117return 1
118119
class LogPeriod:
120121
def __init__(self, section):
122if config.prefs.get(section.split("_")[0], "period"):
123self.startdate = datetime.now() \
124- timeparse(config.prefs.get(section.split("_")[0], "period"))
125logger.debug("Parsing logs for {0} since {1}".format(
126section, self.startdate.strftime(formatting.DATEFMT
127+ " " + formatting.TIMEFMT)))
128self.unique = True
129else:
130self.startdate = datetime.now() \
131- timeparse(config.prefs.get("logparse", "period"))
132self.unique = False