Debian Codegraph @

lib/ansible/module_utils/facts/network/linux.py

raw
1 # This file is part of Ansible
2 #
3 # Ansible is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # Ansible is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
15
16 from __future__ import annotations
17
18 import glob
19 import os
20 import re
21 import socket
22 import struct
23
24 from ansible.module_utils.facts.network.base import Network, NetworkCollector
25
26 from ansible.module_utils.facts.utils import get_file_content
27
28
29 class LinuxNetwork(Network):
30 """
31 This is a Linux-specific subclass of Network. It defines
32 - interfaces (a list of interface names)
33 - interface_<name> dictionary of ipv4, ipv6, and mac address information.
34 - all_ipv4_addresses and all_ipv6_addresses: lists of all configured addresses.
35 - ipv4_address and ipv6_address: the first non-local address for each family.
36 """
37 platform = 'Linux'
38 INTERFACE_TYPE = {
39 '1': 'ether',
40 '32': 'infiniband',
41 '512': 'ppp',
42 '772': 'loopback',
43 '65534': 'tunnel',
44 }
45
46 def populate(self, collected_facts=None):
47 network_facts = {}
48 ip_path = self.module.get_bin_path('ip')
49 if ip_path is None:
50 return network_facts
51 default_ipv4, default_ipv6 = self.get_default_interfaces(ip_path,
52 collected_facts=collected_facts)
53 interfaces, ips = self.get_interfaces_info(ip_path, default_ipv4, default_ipv6)
54 network_facts['interfaces'] = interfaces.keys()
55 for iface in interfaces:
56 network_facts[iface] = interfaces[iface]
57 network_facts['default_ipv4'] = default_ipv4
58 network_facts['default_ipv6'] = default_ipv6
59 network_facts['all_ipv4_addresses'] = ips['all_ipv4_addresses']
60 network_facts['all_ipv6_addresses'] = ips['all_ipv6_addresses']
61 network_facts['locally_reachable_ips'] = self.get_locally_reachable_ips(ip_path)
62 return network_facts
63
64 # List all `scope host` routes/addresses.
65 # They belong to routes, but it means the whole prefix is reachable
66 # locally, regardless of specific IP addresses.
67 # E.g.: 192.168.0.0/24, any IP address is reachable from this range
68 # if assigned as scope host.
69 def get_locally_reachable_ips(self, ip_path):
70 locally_reachable_ips = dict(
71 ipv4=[],
72 ipv6=[],
73 )
74
75 def parse_locally_reachable_ips(output):
76 for line in output.splitlines():
77 if not line:
78 continue
79 words = line.split()
80 if words[0] != 'local':
81 continue
82 address = words[1]
83 if ":" in address:
84 if address not in locally_reachable_ips['ipv6']:
85 locally_reachable_ips['ipv6'].append(address)
86 else:
87 if address not in locally_reachable_ips['ipv4']:
88 locally_reachable_ips['ipv4'].append(address)
89
90 args = [ip_path, '-4', 'route', 'show', 'table', 'local']
91 rc, routes, dummy = self.module.run_command(args)
92 if rc == 0:
93 parse_locally_reachable_ips(routes)
94 args = [ip_path, '-6', 'route', 'show', 'table', 'local']
95 rc, routes, dummy = self.module.run_command(args)
96 if rc == 0:
97 parse_locally_reachable_ips(routes)
98
99 return locally_reachable_ips
100
101 def get_default_interfaces(self, ip_path, collected_facts=None):
102 collected_facts = collected_facts or {}
103 # Use the commands:
104 # ip -4 route get 8.8.8.8 -> Google public DNS
105 # ip -6 route get 2404:6800:400a:800::1012 -> ipv6.google.com
106 # to find out the default outgoing interface, address, and gateway
107 command = dict(
108 v4=[ip_path, '-4', 'route', 'get', '8.8.8.8'],
109 v6=[ip_path, '-6', 'route', 'get', '2404:6800:400a:800::1012']
110 )
111 interface = dict(v4={}, v6={})
112
113 for v in 'v4', 'v6':
114 if (v == 'v6' and collected_facts.get('ansible_os_family') == 'RedHat' and
115 collected_facts.get('ansible_distribution_version', '').startswith('4.')):
116 continue
117 if v == 'v6' and not socket.has_ipv6:
118 continue
119 rc, out, err = self.module.run_command(command[v], errors='surrogate_then_replace')
120 if not out:
121 # v6 routing may result in
122 # RTNETLINK answers: Invalid argument
123 continue
124 words = out.splitlines()[0].split()
125 # A valid output starts with the queried address on the first line
126 if len(words) > 0 and words[0] == command[v][-1]:
127 for i in range(len(words) - 1):
128 if words[i] == 'dev':
129 interface[v]['interface'] = words[i + 1]
130 elif words[i] == 'src':
131 interface[v]['address'] = words[i + 1]
132 elif words[i] == 'via' and words[i + 1] != command[v][-1]:
133 interface[v]['gateway'] = words[i + 1]
134 return interface['v4'], interface['v6']
135
136 def get_interfaces_info(self, ip_path, default_ipv4, default_ipv6):
137 interfaces = {}
138 ips = dict(
139 all_ipv4_addresses=[],
140 all_ipv6_addresses=[],
141 )
142
143 # FIXME: maybe split into smaller methods?
144 # FIXME: this is pretty much a constructor
145
146 for path in glob.glob('/sys/class/net/*'):
147 if not os.path.isdir(path):
148 continue
149 device = os.path.basename(path)
150 interfaces[device] = {'device': device}
151 if os.path.exists(os.path.join(path, 'address')):
152 macaddress = get_file_content(os.path.join(path, 'address'), default='')
153 if macaddress and macaddress != '00:00:00:00:00:00':
154 interfaces[device]['macaddress'] = macaddress
155 if os.path.exists(os.path.join(path, 'mtu')):
156 interfaces[device]['mtu'] = int(get_file_content(os.path.join(path, 'mtu')))
157 if os.path.exists(os.path.join(path, 'operstate')):
158 interfaces[device]['active'] = get_file_content(os.path.join(path, 'operstate')) != 'down'
159 if os.path.exists(os.path.join(path, 'device', 'driver', 'module')):
160 interfaces[device]['module'] = os.path.basename(os.path.realpath(os.path.join(path, 'device', 'driver', 'module')))
161 if os.path.exists(os.path.join(path, 'type')):
162 _type = get_file_content(os.path.join(path, 'type'))
163 interfaces[device]['type'] = self.INTERFACE_TYPE.get(_type, 'unknown')
164 if os.path.exists(os.path.join(path, 'bridge')):
165 interfaces[device]['type'] = 'bridge'
166 interfaces[device]['interfaces'] = [os.path.basename(b) for b in glob.glob(os.path.join(path, 'brif', '*'))]
167 if os.path.exists(os.path.join(path, 'bridge', 'bridge_id')):
168 interfaces[device]['id'] = get_file_content(os.path.join(path, 'bridge', 'bridge_id'), default='')
169 if os.path.exists(os.path.join(path, 'bridge', 'stp_state')):
170 interfaces[device]['stp'] = get_file_content(os.path.join(path, 'bridge', 'stp_state')) == '1'
171 if os.path.exists(os.path.join(path, 'bonding')):
172 interfaces[device]['type'] = 'bonding'
173 interfaces[device]['slaves'] = get_file_content(os.path.join(path, 'bonding', 'slaves'), default='').split()
174 interfaces[device]['mode'] = get_file_content(os.path.join(path, 'bonding', 'mode'), default='').split()[0]
175 interfaces[device]['miimon'] = get_file_content(os.path.join(path, 'bonding', 'miimon'), default='').split()[0]
176 interfaces[device]['lacp_rate'] = get_file_content(os.path.join(path, 'bonding', 'lacp_rate'), default='').split()[0]
177 primary = get_file_content(os.path.join(path, 'bonding', 'primary'))
178 if primary:
179 interfaces[device]['primary'] = primary
180 path = os.path.join(path, 'bonding', 'all_slaves_active')
181 if os.path.exists(path):
182 interfaces[device]['all_slaves_active'] = get_file_content(path) == '1'
183 if os.path.exists(os.path.join(path, 'bonding_slave')):
184 interfaces[device]['perm_macaddress'] = get_file_content(os.path.join(path, 'bonding_slave', 'perm_hwaddr'), default='')
185 if os.path.exists(os.path.join(path, 'device')):
186 interfaces[device]['pciid'] = os.path.basename(os.readlink(os.path.join(path, 'device')))
187 if os.path.exists(os.path.join(path, 'speed')):
188 speed = get_file_content(os.path.join(path, 'speed'))
189 if speed is not None:
190 interfaces[device]['speed'] = int(speed)
191
192 # Check whether an interface is in promiscuous mode
193 if os.path.exists(os.path.join(path, 'flags')):
194 promisc_mode = False
195 # The second byte indicates whether the interface is in promiscuous mode.
196 # 1 = promisc
197 # 0 = no promisc
198 data = int(get_file_content(os.path.join(path, 'flags')), 16)
199 promisc_mode = (data & 0x0100 > 0)
200 interfaces[device]['promisc'] = promisc_mode
201
202 # TODO: determine if this needs to be in a nested scope/closure
203 def parse_ip_output(output, secondary=False):
204 for line in output.splitlines():
205 if not line:
206 continue
207 words = line.split()
208 broadcast = ''
209 if words[0] == 'inet':
210 if '/' in words[1]:
211 address, netmask_length = words[1].split('/')
212 if len(words) > 3:
213 if words[2] == 'brd':
214 broadcast = words[3]
215 else:
216 # pointopoint interfaces do not have a prefix
217 address = words[1]
218 netmask_length = "32"
219 address_bin = struct.unpack('!L', socket.inet_aton(address))[0]
220 netmask_bin = (1 << 32) - (1 << 32 >> int(netmask_length))
221 netmask = socket.inet_ntoa(struct.pack('!L', netmask_bin))
222 network = socket.inet_ntoa(struct.pack('!L', address_bin & netmask_bin))
223 iface = words[-1]
224 # NOTE: device is ref to outside scope
225 # NOTE: interfaces is also ref to outside scope
226 if iface != device:
227 interfaces[iface] = {}
228 if not secondary and "ipv4" not in interfaces[iface]:
229 interfaces[iface]['ipv4'] = {'address': address,
230 'broadcast': broadcast,
231 'netmask': netmask,
232 'network': network,
233 'prefix': netmask_length,
234 }
235 else:
236 if "ipv4_secondaries" not in interfaces[iface]:
237 interfaces[iface]["ipv4_secondaries"] = []
238 interfaces[iface]["ipv4_secondaries"].append({
239 'address': address,
240 'broadcast': broadcast,
241 'netmask': netmask,
242 'network': network,
243 'prefix': netmask_length,
244 })
245
246 # add this secondary IP to the main device
247 if secondary:
248 if "ipv4_secondaries" not in interfaces[device]:
249 interfaces[device]["ipv4_secondaries"] = []
250 if device != iface:
251 interfaces[device]["ipv4_secondaries"].append({
252 'address': address,
253 'broadcast': broadcast,
254 'netmask': netmask,
255 'network': network,
256 'prefix': netmask_length,
257 })
258
259 # NOTE: default_ipv4 is ref to outside scope
260 # If this is the default address, update default_ipv4
261 if 'address' in default_ipv4 and default_ipv4['address'] == address:
262 default_ipv4['broadcast'] = broadcast
263 default_ipv4['netmask'] = netmask
264 default_ipv4['network'] = network
265 default_ipv4['prefix'] = netmask_length
266 # NOTE: macaddress is ref from outside scope
267 default_ipv4['macaddress'] = macaddress
268 default_ipv4['mtu'] = interfaces[device]['mtu']
269 default_ipv4['type'] = interfaces[device].get("type", "unknown")
270 default_ipv4['alias'] = words[-1]
271 if not address.startswith('127.'):
272 ips['all_ipv4_addresses'].append(address)
273 elif words[0] == 'inet6':
274 if 'peer' == words[2]:
275 address = words[1]
276 dummy, prefix = words[3].split('/')
277 scope = words[5]
278 else:
279 address, prefix = words[1].split('/')
280 scope = words[3]
281 if 'ipv6' not in interfaces[device]:
282 interfaces[device]['ipv6'] = []
283 interfaces[device]['ipv6'].append({
284 'address': address,
285 'prefix': prefix,
286 'scope': scope
287 })
288 # If this is the default address, update default_ipv6
289 if 'address' in default_ipv6 and default_ipv6['address'] == address:
290 default_ipv6['prefix'] = prefix
291 default_ipv6['scope'] = scope
292 default_ipv6['macaddress'] = macaddress
293 default_ipv6['mtu'] = interfaces[device]['mtu']
294 default_ipv6['type'] = interfaces[device].get("type", "unknown")
295 if not address == '::1':
296 ips['all_ipv6_addresses'].append(address)
297
298 args = [ip_path, 'addr', 'show', 'primary', 'dev', device]
299 rc, primary_data, stderr = self.module.run_command(args, errors='surrogate_then_replace')
300 if rc == 0:
301 parse_ip_output(primary_data)
302 else:
303 # possibly busybox, fallback to running without the "primary" arg
304 # https://github.com/ansible/ansible/issues/50871
305 args = [ip_path, 'addr', 'show', 'dev', device]
306 rc, data, stderr = self.module.run_command(args, errors='surrogate_then_replace')
307 if rc == 0:
308 parse_ip_output(data)
309
310 args = [ip_path, 'addr', 'show', 'secondary', 'dev', device]
311 rc, secondary_data, stderr = self.module.run_command(args, errors='surrogate_then_replace')
312 if rc == 0:
313 parse_ip_output(secondary_data, secondary=True)
314
315 interfaces[device].update(self.get_ethtool_data(device))
316
317 # replace : by _ in interface name since they are hard to use in template
318 new_interfaces = {}
319 # i is a dict key (string) not an index int
320 for i in interfaces:
321 if ':' in i:
322 new_interfaces[i.replace(':', '_')] = interfaces[i]
323 else:
324 new_interfaces[i] = interfaces[i]
325 return new_interfaces, ips
326
327 def get_ethtool_data(self, device):
328
329 data = {}
330 ethtool_path = self.module.get_bin_path("ethtool")
331 # FIXME: exit early on falsey ethtool_path and un-indent
332 if ethtool_path:
333 args = [ethtool_path, '-k', device]
334 rc, stdout, stderr = self.module.run_command(args, errors='surrogate_then_replace')
335 # FIXME: exit early on falsey if we can
336 if rc == 0:
337 features = {}
338 for line in stdout.strip().splitlines():
339 if not line or line.endswith(":"):
340 continue
341 key, value = line.split(": ")
342 if not value:
343 continue
344 features[key.strip().replace('-', '_')] = value.strip()
345 data['features'] = features
346
347 args = [ethtool_path, '-T', device]
348 rc, stdout, stderr = self.module.run_command(args, errors='surrogate_then_replace')
349 if rc == 0:
350 data['timestamping'] = [m.lower() for m in re.findall(r'SOF_TIMESTAMPING_(\w+)', stdout)]
351 data['hw_timestamp_filters'] = [m.lower() for m in re.findall(r'HWTSTAMP_FILTER_(\w+)', stdout)]
352 m = re.search(r'PTP Hardware Clock: (\d+)', stdout)
353 if m:
354 data['phc_index'] = int(m.groups()[0])
355
356 return data
357
358
359 class LinuxNetworkCollector(NetworkCollector):
360 _platform = 'Linux'
361 _fact_class = LinuxNetwork
362 required_facts = set(['distribution', 'platform'])