forked from bn222/cluster-deployment-automation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdnsutil.py
294 lines (232 loc) · 9.51 KB
/
dnsutil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import dataclasses
import os
import threading
import common
import host
from logger import logger
from typing import Optional
RESOLVCONF = "/etc/resolv.conf"
RESOLVCONF_ORIG = "/etc/resolv.conf.cda-orig"
RESOLVCONF_LOCAL = "/etc/resolv.conf.cda-local"
DNSMASQ_SERVERS_FILE = "/etc/dnsmasq.d/servers/cda-servers.conf"
_lock = threading.Lock()
def resolvconf_dont_touch() -> bool:
# The user can disable touching /etc/resolv.conf by
#
# $ sudo touch /etc/.resolv.conf.cda-dont-touch
#
# We will still write our "/etc/resolv.conf.cda*" files, but
# it's up to the user to redirect symlinks accordingly.
return os.path.exists("/etc/.resolv.conf.cda-dont-touch")
@dataclasses.dataclass
class ResolvConfData:
nameservers: list[str]
searches: list[str]
def _resolvconf_parse_file(rc_file: str) -> ResolvConfData:
try:
with open(rc_file, "rb") as f:
rc_content = f.read()
except IOError:
return ResolvConfData([], [])
def _startswith(line: bytes, prefix: bytes) -> Optional[str]:
if not line.startswith(prefix):
return None
length = len(prefix)
if len(line) <= length:
return None
if line[length] not in (32, 9):
return None
s = line[length + 1 :].strip()
try:
return s.decode()
except ValueError:
return None
nameservers = []
searches = []
for line in rc_content.split(b'\n'):
line = line.strip()
if (val := _startswith(line, b"nameserver")) is not None:
addr = common.ipaddr_norm(val)
if not addr:
continue
if addr not in nameservers:
nameservers.append(addr)
elif (val := _startswith(line, b"search")) is not None:
# Keep the last occurrence. `man resolv.conf` says "If there are
# multiple search directives, only the search list from the last
# instance is used".
searches = val.split()
return ResolvConfData(nameservers, searches)
def _resolvconf_ensure_orig() -> None:
if os.path.exists(RESOLVCONF_ORIG):
return
rc_content_orig = b""
try:
with open(RESOLVCONF, "rb") as f:
rc_content_orig = f.read()
except IOError:
pass
# Backup the original resolv.conf file to "RESOLVCONF_ORIG"
if rc_content_orig == b"":
pass
elif b"Written by cluster-deployment-automation" in rc_content_orig:
rc_content_orig = b""
elif b"Generated by NetworkManager" in rc_content_orig and os.path.exists("/run/NetworkManager/resolv.conf"):
# This file seems to be written by NetworkManager. Symlink there.
logger.info(f"resolv.conf: point {RESOLVCONF_ORIG} to /run/NetworkManager/resolv.conf")
lh = host.LocalHost()
lh.run_or_die(f"ln -snf /run/NetworkManager/resolv.conf {RESOLVCONF_ORIG}")
else:
logger.info(f"resolv.conf: write {RESOLVCONF_ORIG}")
with common.atomic_write(RESOLVCONF_ORIG, text=False) as f:
f.write(rc_content_orig)
def resolvconf_ensure_orig() -> bool:
if resolvconf_dont_touch():
return False
with _lock:
_resolvconf_ensure_orig()
return True
def _resolvconf_update(setup: bool = True, searches: Optional[list[str]] = None) -> None:
lh = host.LocalHost()
# The user can disable touching /etc/resolv.conf by
#
# $ sudo touch /etc/.resolv.conf.cda-dont-touch
#
# We will still write our "/etc/resolv.conf.cda*" files, but
# it's up to the user to redirect symlinks accordingly.
dont_touch = resolvconf_dont_touch()
if not setup:
if dont_touch:
return
if not os.path.exists(RESOLVCONF_ORIG):
return
try:
lnk = os.readlink(RESOLVCONF)
except Exception:
return
if not os.path.basename(lnk).startswith("resolv.conf.cda."):
# We only restore, if /etc/resolv.conf is a symlink to "resolv.conf-cda.*"
# which indicates that the file was created by us.
return
dst = os.path.basename(RESOLVCONF_ORIG)
if lnk == dst:
return
logger.info(f"resolv.conf: restore /etc/resolv.conf to link to original {RESOLVCONF_ORIG}")
lh.run_or_die(f"ln -snf {dst} {RESOLVCONF}")
return
searches_str = ""
if searches:
searches_str = f"search {' '.join(searches)}\n"
with common.atomic_write(RESOLVCONF_LOCAL) as file:
file.write(
f"""# Written by cluster-deployment-automation.
#
# A local dnsmasq instance is configured (`systemctl status dnsmasq.service`).
# Original file is at "{RESOLVCONF_ORIG}".
#
# Set: `sudo ln -snf {os.path.basename(RESOLVCONF_LOCAL)} /etc/resolv.conf`
# Restore: `sudo ln -snf {os.path.basename(RESOLVCONF_ORIG)} /etc/resolv.conf`
# Alternatively, restore by deleting "/etc/resolv.conf" and let NetworkManager
# write anew with `systemctl reload NetworkManager.service`.
#
# Prevent touching "/etc/resolv.conf" with a file "/etc/.resolv.conf.cda-dont-touch"
{searches_str}nameserver 127.0.0.1
"""
)
# We only point a symlink to the correct file. This indicates that
# somebody is handling the file and NetworkManager leaves the symlink
# alone.
# It's also easy to restore the previous file with
# `ln -snf resolv.conf.cda-orig /etc/resolv.conf`.
if not dont_touch:
lh.run_or_die(f"ln -snf {os.path.basename(RESOLVCONF_LOCAL)} {RESOLVCONF}")
def dnsmasq_update(cluster_name: str, api_vip: Optional[str] = None) -> None:
# Cleanup old files that we wrote (but no longer).
try:
os.remove(f"/etc/dnsmasq.d/cda-cluster-{cluster_name}.conf")
except FileNotFoundError:
pass
try:
os.remove("/etc/dnsmasq.d/cda-orig.conf")
except FileNotFoundError:
pass
lh = host.LocalHost()
dmasqconf_cda = "/etc/dnsmasq.d/cda.conf"
with _lock:
_resolvconf_ensure_orig()
servers_changed = _dnsmasq_servers_update(cluster_name, api_vip)
rcdata = _resolvconf_parse_file(RESOLVCONF_ORIG)
if api_vip is None:
# We don't reset. That's because we might have multiple clusters. If
# you want to reset /etc/resolv.conf, see comments in
# "/etc/resolv.conf.cda-local".
pass
else:
_resolvconf_update(searches=rcdata.searches)
with common.atomic_write(dmasqconf_cda) as file:
content = "# Written by cluster-deployment-automation.\n"
content += "listen-address=127.0.0.1\n"
content += "bind-interfaces\n"
content += f"resolv-file={RESOLVCONF_ORIG}\n"
content += f"servers-file={DNSMASQ_SERVERS_FILE}\n"
file.write(content)
ret = lh.run("systemctl unmask dnsmasq.service")
ret = lh.run("systemctl enable dnsmasq.service")
if servers_changed or not lh.run("systemctl is-active --quiet dnsmasq.service").success():
ret = lh.run("systemctl restart dnsmasq.service")
if not ret.success():
logger.warning(f"dnsmasq: failure to start dnsmasq service: {ret}")
else:
logger.debug("dnsmasq: service was restarted")
else:
logger.debug("dnsmasq: service was not restarted")
def _dnsmasq_servers_content_parse(content: bytes) -> list[bytes]:
result: list[bytes] = []
if content:
for line in content.split(b'\n'):
line = line.strip()
if line.startswith(b"server=/"):
result.append(line)
return result
def _dnsmasq_servers_content_update(old_content: bytes, cluster_name: Optional[str], api_vip: Optional[str] = None) -> tuple[bytes, list[bytes]]:
old_entries = _dnsmasq_servers_content_parse(old_content)
new_entries = list(old_entries)
if cluster_name is None:
pass
else:
prefix1 = f"server=/*.api.{cluster_name}.redhat.com/*.api-int.{cluster_name}.redhat.com/#".encode()
prefix2 = f"server=/apps.{cluster_name}.redhat.com/api.{cluster_name}.redhat.com/api-int.{cluster_name}.redhat.com/".encode()
# Remove all entires for our cluster name.
for entry in list(new_entries):
if entry == prefix1 or entry.startswith(prefix2):
new_entries.remove(entry)
if api_vip is not None:
new_entries.append(prefix1)
new_entries.append(prefix2 + f"{api_vip}".encode())
new_entries.sort()
new_content = (
b"""# Written by cluster-deployment-automation for resolving cluster names.
# This file is passed to dnsmasq via the --servers-file= option
#
# You can reload after changes with
# systemctl restart dnsmasq.service
# systemctl kill -s SIGHUP dnsmasq.service
"""
+ b"\n".join(new_entries)
+ b"\n"
)
return new_content, new_entries
def _dnsmasq_servers_update(cluster_name: Optional[str], api_vip: Optional[str] = None) -> bool:
try:
with open(DNSMASQ_SERVERS_FILE, "rb") as f:
old_content = f.read()
except Exception:
old_content = b""
new_content, new_entries = _dnsmasq_servers_content_update(old_content, cluster_name, api_vip)
if new_content == old_content:
return False
logger.debug(f"dnsmasq: update {DNSMASQ_SERVERS_FILE} (content: {[s.decode('utf-8', errors='replace') for s in new_entries]})")
os.makedirs(os.path.dirname(DNSMASQ_SERVERS_FILE), exist_ok=True)
with common.atomic_write(DNSMASQ_SERVERS_FILE, text=False) as f:
f.write(new_content)
return True