"""
ResolvConf - file ``/etc/resolv.conf``
======================================
"""
from .. import Parser, parser, get_active_lines, LegacyItemAccess
from insights.specs import Specs
KEYWORD1 = 'search'
KEYWORD2 = 'domain'
[docs]
@parser(Specs.resolv_conf)
class ResolvConf(LegacyItemAccess, Parser):
'''
Parse the ``/etc/resolv.conf`` file into a dictionary of keywords and
their values. This is made available via the ``data`` property but the
object itself can be used as a dictionary thanks to the
:py:class:`insights.core.LegacyItemAccess` mixin class.
Each keyword found in the file is stored as a key in the data dictionary,
storing the list of values given (in order) on all occurrences of that
keyword in the file.
According to the man page, the 'domain' and 'search' keywords are
mutually exclusive. If more than one instance of these keywords is
present, whichever is last becomes the active resolution method. So, the
``active`` key stores which of these keywords was the last present in the
file.
Sample file content::
; generated by /sbin/dhclient-script
# This file is being maintained by Puppet.
# DO NOT EDIT
search a.b.com b.c.com
options timeout:2 attempts:2
nameserver 10.160.224.51
nameserver 10.61.193.11
Examples:
>>> resolv = shared[ResolvConf]
>>> resolv['active']
'search'
>>> resolv['nameserver']
["10.160.224.51", "10.61.193.11" ]
>>> resolv['search']
["a.b.com", "b.c.com"]
>>> resolv.data["options"] # old style access
["timeout:2", "attempts:2"]
'''
[docs]
def parse_content(self, content):
resolv_info = {}
name_info = []
key1_search = key2_domain = False
# According to the man page, the 'domain' and 'search' keywords are
# mutually exclusive. If more than one instance of these keywords is
# present, the last instance wins. So, add a key "active" into
# resolve_info pointing out which keywords is effective.
for line in get_active_lines(content):
# ignore the lines commented by ';'
if line.startswith(';'):
continue
if line.startswith('nameserver'):
name_info.append(line.split()[1])
else:
temp = line.split()
if temp[0] in (KEYWORD1, KEYWORD2):
key1_search = temp[0] == KEYWORD1
key2_domain = temp[0] == KEYWORD2
resolv_info[temp[0]] = temp[1:]
resolv_info['nameserver'] = name_info
resolv_info['active'] = ''
if key1_search and not key2_domain:
resolv_info['active'] = KEYWORD1
elif key2_domain and not key1_search:
resolv_info['active'] = KEYWORD2
self.data = resolv_info