WIP: Remove netifaces usage

Change-Id: I1a7c01d16eb8d2a2e372bd0d2474a601d3d2c1f4
This commit is contained in:
Julia Kreger 2023-04-10 08:47:06 -07:00
parent 0304c73c0e
commit 50adec0fc1
1 changed files with 34 additions and 15 deletions

View File

@ -19,7 +19,6 @@ import socket
import struct
import sys
import netifaces
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import netutils
@ -213,31 +212,51 @@ def _get_lldp_info(interfaces):
return lldp_info
def get_default_ip_addr(type, interface_id):
"""Retrieve default IPv4 or IPv6 address."""
try:
addrs = netifaces.ifaddresses(interface_id)
return addrs[type][0]['addr']
except (ValueError, IndexError, KeyError):
# No default IP address found
return None
def _extract_address(lines):
"""Extract an usable IP address from the supplied lines.
:param lines: The split lines of an "ip addr show $interface" command.
:returns: The first found global/non-temporary IP address.
"""
for line in lines:
# Get a global, non-temporary (i.e. v6 privacy) address
if 'global' in line and 'temporary' not in line
line = line.lstrip()
# line is the list of addresses
address = line.split('/')[1]
# strip tailing / off of the result, as v4 and v6 addresses
return address[0]
def get_ipv4_addr(interface_id):
return get_default_ip_addr(netifaces.AF_INET, interface_id)
try:
out, _ = utils.execute('ip', '-4', 'addr', 'show', interface_id)
except OSError:
LOG.error('The IP command is required. Could not get IPv4 address.')
return None
return _extract_address(out.splitlines())
def get_ipv6_addr(interface_id):
return get_default_ip_addr(netifaces.AF_INET6, interface_id)
try:
out, _ = utils.execute('ip', '-6', 'addr', 'show', interface_id)
except OSError:
LOG.error('The IP command is required. Could not get IPv4 address.')
return None
return _extract_address(out.splitlines())
def get_mac_addr(interface_id):
path = '/sys/class/net/{}/address'.format(interface_id)
try:
addrs = netifaces.ifaddresses(interface_id)
return addrs[netifaces.AF_LINK][0]['addr']
except (ValueError, IndexError, KeyError):
# No mac address found
with open(path, 'rt') as fp:
return fp.read().strip()
except OSError as e:
LOG.debug('Encountered error while attempting to access the address '
'for %s. Error: %s', interface_id, e))
return None
LOG.debug('No MAC Address found for interface %s.', interface_id)
return None
# Other options...