Debian Codegraph @

tests/util.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
4 #
5 # Permission to use, copy, modify, and distribute this software and its
6 # documentation for any purpose with or without fee is hereby granted,
7 # provided that the above copyright notice and this permission notice
8 # appear in all copies.
9 #
10 # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
11 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
13 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
16 # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18 import enum
19 import functools
20 import inspect
21 import os
22
23 import dns.exception
24 import dns.message
25 import dns.name
26 import dns.query
27 import dns.rdataclass
28 import dns.rdatatype
29
30 # Cache for is_internet_reachable()
31 _internet_reachable = None
32 _have_ipv4 = False
33 _have_ipv6 = False
34
35
36 def here(filename):
37 return os.path.join(os.path.dirname(__file__), filename)
38
39
40 def check_networking(addresses):
41 """Can we do a DNS resolution via UDP and TCP to at least one of the addresses?"""
42 for address in addresses:
43 try:
44 q = dns.message.make_query(dns.name.root, dns.rdatatype.NS)
45 ok = False
46 # We try UDP a few times in case we get unlucky and a packet is lost.
47 for i in range(5):
48 # We don't check the answer other than make sure there is one.
49 try:
50 r = dns.query.udp(q, address, timeout=4)
51 ns = r.find_rrset(
52 r.answer, dns.name.root, dns.rdataclass.IN, dns.rdatatype.NS
53 )
54 ok = True
55 break
56 except Exception:
57 continue # UDP try loop
58 if not ok:
59 continue # addresses loop
60 try:
61 r = dns.query.tcp(q, address, timeout=4)
62 ns = r.find_rrset(
63 r.answer, dns.name.root, dns.rdataclass.IN, dns.rdatatype.NS
64 )
65 # UDP and TCP both work!
66 return True
67 except Exception:
68 continue
69 except Exception as e:
70 pass
71 return False
72
73
74 def is_internet_reachable():
75 """Check if the Internet is reachable.
76
77 Setting the environment variable `NO_INTERNET` will let this
78 function always return False. The result is cached.
79
80 We check using the Google and Cloudflare public resolvers as they are highly
81 available and have well-known stable addresses.
82 """
83 global _internet_reachable
84 if _internet_reachable is None:
85 if os.environ.get("NO_INTERNET"):
86 _internet_reachable = False
87 else:
88 global _have_ipv4
89 _have_ipv4 = check_networking(["8.8.8.8", "1.1.1.1"])
90 global _have_ipv6
91 _have_ipv6 = check_networking(
92 ["2001:4860:4860::8888", "2606:4700:4700::1111"]
93 )
94 _internet_reachable = _have_ipv4 or _have_ipv6
95 return _internet_reachable
96
97
98 def have_ipv4():
99 if not is_internet_reachable():
100 return False
101 return _have_ipv4
102
103
104 def have_ipv6():
105 if not is_internet_reachable():
106 return False
107 return _have_ipv6
108
109
110 def enumerate_module(module, super_class):
111 """Yield module attributes which are subclasses of given class"""
112 for attr_name in dir(module):
113 attr = getattr(module, attr_name)
114 if inspect.isclass(attr) and issubclass(attr, super_class):
115 yield attr
116
117
118 def check_enum_exports(module, eq_callback, only=None):
119 """Make sure module exports all mnemonics from enums"""
120 for attr in enumerate_module(module, enum.Enum):
121 if only is not None and attr not in only:
122 # print('SKIP', attr)
123 continue
124 for flag, value in attr.__members__.items():
125 # print(module, flag, value)
126 eq_callback(getattr(module, flag), value)
127
128
129 def is_docker() -> bool:
130 # There are a lot of answers to "am I runnning in a container" and none appear
131 # to work reliably, so we're settling for "am I running in docker?"
132 try:
133 return os.path.isfile("/.dockerenv")
134 except Exception:
135 return False
136
137
138 def retry_on_timeout(f):
139 @functools.wraps(f)
140 def wrapper(*args, **kwargs):
141 bad = True
142 for i in range(3):
143 try:
144 f(*args, **kwargs)
145 bad = False
146 break
147 except dns.exception.Timeout:
148 pass
149 if bad:
150 raise dns.exception.Timeout
151
152 return wrapper