Debian Codegraph @

ansible_collections/community/dns/plugins/modules/wait_for_txt.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2021, Felix Fontein <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: wait_for_txt
10 short_description: Wait for TXT entries to be available on all authoritative nameservers
11 version_added: 0.1.0
12 description:
13 - Wait for TXT entries with specific values to show up on B(all) authoritative nameservers for the DNS name.
14 extends_documentation_fragment:
15 - community.dns._attributes
16 - community.dns._attributes.idempotent_not_modify_state
17 attributes:
18 check_mode:
19 support: full
20 details:
21 - This action does not modify state.
22 version_added: 2.4.0
23 diff_mode:
24 support: N/A
25 details:
26 - This action does not modify state.
27 author:
28 - Felix Fontein (@felixfontein)
29 options:
30 records:
31 description:
32 - A list of DNS names with TXT entries to look out for.
33 required: true
34 type: list
35 elements: dict
36 suboptions:
37 name:
38 description:
39 - A DNS name, like V(www.example.com).
40 type: str
41 required: true
42 values:
43 description:
44 - The TXT values to look for.
45 - The alias O(records[].entries) has been added in community.dns 3.4.0.
46 aliases:
47 - entries
48 type: list
49 elements: str
50 required: true
51 mode:
52 description:
53 - Comparison modes for the values in O(records[].values).
54 - If V(subset), O(records[].values) should be a (not necessarily proper) subset of the TXT values set for the DNS
55 name.
56 - If V(superset), O(records[].values) should be a (not necessarily proper) superset of the TXT values set for the
57 DNS name. This includes the case that no TXT entries are set.
58 - If V(superset_not_empty), O(records[].values) should be a (not necessarily proper) superset of the TXT values
59 set for the DNS name, assuming at least one TXT record is present.
60 - If V(equals), O(records[].values) should be the same set of strings as the TXT values for the DNS name (up to
61 order).
62 - If V(equals_ordered), O(records[].values) should be the same ordered list of strings as the TXT values for the
63 DNS name.
64 type: str
65 default: subset
66 choices:
67 - subset
68 - superset
69 - superset_not_empty
70 - equals
71 - equals_ordered
72 query_retry:
73 description:
74 - Number of retries for DNS query timeouts.
75 type: int
76 default: 3
77 query_timeout:
78 description:
79 - Timeout per DNS query in seconds.
80 type: float
81 default: 10
82 timeout:
83 description:
84 - Global timeout for waiting for all records in seconds.
85 - If not set, will wait indefinitely.
86 type: float
87 max_sleep:
88 description:
89 - Maximal amount of seconds to sleep between two rounds of probing the TXT records.
90 type: float
91 default: 10
92 always_ask_default_resolver:
93 description:
94 - When set to V(true) (default), will use the default resolver to find the authoritative nameservers of a subzone. See
95 O(server) for how to configure the default resolver.
96 - When set to V(false), will use the authoritative nameservers of the parent zone to find the authoritative nameservers
97 of a subzone. This only makes sense when the nameservers were recently changed and have not yet propagated.
98 type: bool
99 default: true
100 servfail_retries:
101 description:
102 - How often to retry on SERVFAIL errors.
103 type: int
104 default: 0
105 version_added: 2.6.0
106 server:
107 description:
108 - The DNS server(s) to use to look up the result. Must be a list of one or more IP addresses.
109 - By default, the system's standard resolver is used.
110 type: list
111 elements: str
112 version_added: 2.7.0
113 requirements:
114 - dnspython >= 2.0.0
115 """
116
117 EXAMPLES = r"""
118 - name: Wait for a TXT entry to appear
119 community.dns.wait_for_txt:
120 records:
121 # We want that www.example.com has a single TXT record with value 'Hello world!'.
122 # There should not be any other TXT record for www.example.com.
123 - name: www.example.com
124 values: "Hello world!"
125 mode: equals
126 # We want that example.com has a specific SPF record set.
127 # We do not care about other TXT records.
128 - name: www.example.com
129 values: "v=spf1 a mx -all"
130 mode: subset
131 """
132
133 RETURN = r"""
134 records:
135 description:
136 - Results on the TXT records queried.
137 - The entries are in a 1:1 correspondence to the entries of the O(records) parameter, in exactly the same order.
138 returned: always
139 type: list
140 elements: dict
141 contains:
142 name:
143 description:
144 - The DNS name this check is for.
145 returned: always
146 type: str
147 sample: example.com
148 done:
149 description:
150 - Whether the check completed.
151 returned: always
152 type: bool
153 sample: false
154 values:
155 description:
156 - For every authoritative nameserver for the DNS name, lists the TXT records retrieved during the last lookup made.
157 - Once the check completed for all TXT records retrieved, the TXT records for this DNS name are no longer checked.
158 - If these are multiple TXT entries for a nameserver, the order is as it was received from that nameserver. This might
159 not be the same order provided in the check.
160 - B(The field has been renamed) to RV(records[].entries) in community.dns 3.4.0.
161 While the old name will be around for a longer time, prefer using the new one.
162 returned: lookup was done at least once
163 type: dict
164 elements: list
165 entries:
166 description:
167 - For every authoritative nameserver for the DNS name, lists the TXT records retrieved during the last lookup made.
168 - Once the check completed for all TXT records retrieved, the TXT records for this DNS name are no longer checked.
169 - If these are multiple TXT entries for a nameserver, the order is as it was received from that nameserver. This might
170 not be the same order provided in the check.
171 - This field has been called RV(records[].values) before.
172 returned: lookup was done at least once
173 type: dict
174 elements: list
175 sample:
176 ns1.example.com:
177 - TXT value 1
178 - TXT value 2
179 ns2.example.com:
180 - TXT value 2
181 version_added: 3.4.0
182 check_count:
183 description:
184 - How often the TXT records for this DNS name were checked.
185 returned: always
186 type: int
187 sample: 3
188 sample:
189 - name: example.com
190 done: true
191 entries: [a, b, c]
192 check_count: 1
193 - name: foo.example.org
194 done: false
195 check_count: 0
196 completed:
197 description:
198 - How many of the checks were completed.
199 returned: always
200 type: int
201 sample: 3
202 """
203
204 import time
205 import typing as t
206 from time import monotonic
207
208 from ansible.module_utils.basic import AnsibleModule
209 from ansible.module_utils.common.text.converters import to_text
210
211 from ansible_collections.community.dns.plugins.module_utils._resolver import (
212 ResolveDirectlyFromNameServers,
213 assert_requirements_present,
214 guarded_run,
215 )
216
217 try:
218 import dns.rdatatype
219 except ImportError:
220 pass # handled in assert_requirements_present()
221
222 if t.TYPE_CHECKING:
223 import dns.rdtypes.ANY.TXT # pragma: no cover
224
225
226 def lookup(resolver: ResolveDirectlyFromNameServers, name: str) -> dict[str, list[str]]:
227 result = {}
228 txts = resolver.resolve(name, rdtype=dns.rdatatype.TXT)
229 for key, txt in txts.items():
230 res = []
231 if txt is not None:
232 for data in txt:
233 line = []
234 for txtstring in data.strings:
235 line.append(to_text(txtstring))
236 res.append("".join(line))
237 result[key] = res
238 return result
239
240
241 def validate_check(
242 record_values: list[str],
243 expected_values: list[str],
244 comparison_mode: t.Literal[
245 "subset", "superset", "superset_not_empty", "equals", "equals_ordered"
246 ],
247 ) -> bool:
248 if comparison_mode == "subset":
249 return set(expected_values) <= set(record_values)
250
251 if comparison_mode == "superset":
252 return set(expected_values) >= set(record_values)
253
254 if comparison_mode == "superset_not_empty":
255 return bool(record_values) and set(expected_values) >= set(record_values)
256
257 if comparison_mode == "equals":
258 return sorted(record_values) == sorted(expected_values)
259
260 if comparison_mode == "equals_ordered":
261 return record_values == expected_values
262
263 raise AssertionError("Internal error!") # pragma: no cover
264
265
266 class Waiter:
267 def __init__(self, module: AnsibleModule) -> None:
268 self.module = module
269
270 self.resolver = ResolveDirectlyFromNameServers(
271 timeout=self.module.params["query_timeout"],
272 timeout_retries=self.module.params["query_retry"],
273 servfail_retries=self.module.params["servfail_retries"],
274 always_ask_default_resolver=self.module.params[
275 "always_ask_default_resolver"
276 ],
277 server_addresses=self.module.params["server"],
278 )
279 self.records: list[dict[str, t.Any]] = self.module.params["records"]
280 self.timeout: float | None = self.module.params["timeout"]
281 self.max_sleep: float = self.module.params["max_sleep"]
282
283 self.results = [
284 {
285 "name": record["name"],
286 "done": False,
287 "check_count": 0,
288 }
289 for record in self.records
290 ]
291 self.finished_checks = 0
292
293 def _run(self) -> None:
294 start_time = monotonic()
295
296 step = 0
297 while True:
298 has_timeout = False
299 if self.timeout is not None:
300 expired = monotonic() - start_time
301 has_timeout = expired > self.timeout
302
303 done = True
304 for index, record in enumerate(self.records):
305 if self.results[index]["done"]:
306 continue
307 txts = lookup(self.resolver, record["name"])
308 self.results[index]["values"] = txts
309 self.results[index]["entries"] = txts
310 self.results[index]["check_count"] += 1
311 if txts and all(
312 validate_check(txt, record["values"], record["mode"])
313 for txt in txts.values()
314 ):
315 self.results[index]["done"] = True
316 self.finished_checks += 1
317 else:
318 done = False
319
320 if done:
321 self.module.exit_json(
322 msg="All checks passed", **self._generate_additional_results()
323 )
324
325 if has_timeout:
326 self.module.fail_json(
327 msg=f"Timeout ({self.finished_checks} out of {len(self.records)} check(s) passed).",
328 **self._generate_additional_results(),
329 )
330
331 # Simple quadratic sleep with maximum wait of max_sleep seconds
332 wait = min(2 + step * 0.5, self.max_sleep)
333 if self.timeout is not None:
334 # Make sure we do not exceed the timeout by much by waiting
335 expired = monotonic() - start_time
336 wait = max(min(wait, self.timeout - expired + 0.1), 0.1)
337
338 time.sleep(wait)
339 step += 1
340
341 def _generate_additional_results(self) -> dict[str, t.Any]:
342 return {
343 "records": self.results,
344 "completed": self.finished_checks,
345 }
346
347 def run(self) -> None:
348 guarded_run(
349 self._run,
350 self.module,
351 generate_additional_results=self._generate_additional_results,
352 )
353
354
355 def main() -> None:
356 module = AnsibleModule(
357 argument_spec={
358 "records": {
359 "required": True,
360 "type": "list",
361 "elements": "dict",
362 "options": {
363 "name": {"required": True, "type": "str"},
364 "values": {
365 "required": True,
366 "type": "list",
367 "elements": "str",
368 "aliases": ["entries"],
369 },
370 "mode": {
371 "type": "str",
372 "default": "subset",
373 "choices": [
374 "subset",
375 "superset",
376 "superset_not_empty",
377 "equals",
378 "equals_ordered",
379 ],
380 },
381 },
382 },
383 "query_retry": {"type": "int", "default": 3},
384 "query_timeout": {"type": "float", "default": 10},
385 "timeout": {"type": "float"},
386 "max_sleep": {"type": "float", "default": 10},
387 "always_ask_default_resolver": {"type": "bool", "default": True},
388 "servfail_retries": {"type": "int", "default": 0},
389 "server": {"type": "list", "elements": "str"},
390 },
391 supports_check_mode=True,
392 )
393 assert_requirements_present(module)
394
395 waiter = Waiter(module)
396 waiter.run()
397
398
399 if __name__ == "__main__":
400 main()