Debian Codegraph @

lib/jnpr/junos/facts/domain.py

raw
1 from lxml import etree
2 from jnpr.junos.exception import PermissionError
3 from jnpr.junos.utils.fs import FS
4
5
6 def provides_facts():
7 """
8 Returns a dictionary keyed on the facts provided by this module. The value
9 of each key is the doc string describing the fact.
10 """
11 return {
12 "domain": "The domain name configured at the [edit system "
13 "domain-name] configuration hierarchy.",
14 "fqdn": "The device's hostname + domain",
15 }
16
17
18 def get_facts(device):
19 """
20 Gathers domain facts from the configuration or /etc/resolv.conf.
21 """
22 domain_config = """
23 <configuration>
24 <system>
25 <domain-name/>
26 </system>
27 </configuration>
28 """
29 domain = None
30 fqdn = None
31 # Try to read the domain-name from the config.
32 # This might fail due to lack of permissions.
33 try:
34 rsp = device.rpc.get_config(
35 filter_xml=etree.XML(domain_config),
36 options={
37 "database": "committed",
38 "inherit": "inherit",
39 "commit-scripts": "apply",
40 },
41 )
42 domain = rsp.findtext(".//domain-name")
43 # Ignore if user can't view the configuration.
44 except PermissionError:
45 pass
46
47 # Try to read the domain from the resolv.conf file. This only requires
48 # view permissions.
49 if domain is None:
50 fs = FS(device)
51 file_content = fs.cat("/etc/resolv.conf") or fs.cat("/var/etc/resolv.conf")
52 words = file_content.split() if file_content is not None else []
53 if "domain" in words:
54 idx = words.index("domain") + 1
55 domain = words[idx]
56
57 # Set the fqdn
58 fqdn = device.facts["hostname"]
59 if fqdn is not None and domain is not None:
60 fqdn = fqdn + "." + domain
61
62 return {
63 "domain": domain,
64 "fqdn": fqdn,
65 }