Merge branch 'network-facts' of https://github.com/akhayyat/ansible into devel

This commit is contained in:
Michael DeHaan 2012-08-11 12:02:52 -04:00
commit 08ce3692b2

View file

@ -426,6 +426,8 @@ class LinuxNetwork(Network):
This is a Linux-specific subclass of Network. It defines This is a Linux-specific subclass of Network. It defines
- interfaces (a list of interface names) - interfaces (a list of interface names)
- interface_<name> dictionary of ipv4, ipv6, and mac address information. - interface_<name> dictionary of ipv4, ipv6, and mac address information.
- all_ipv4_addresses and all_ipv6_addresses: lists of all configured addresses.
- ipv4_address and ipv6_address: the first non-local address for each family.
""" """
platform = 'Linux' platform = 'Linux'
@ -433,94 +435,88 @@ class LinuxNetwork(Network):
Network.__init__(self) Network.__init__(self)
def populate(self): def populate(self):
self.facts['interfaces'] = self.get_interfaces() interfaces, ips = self.parse_ip_addr()
self.get_interface_facts()
self.get_ipv4_facts() self.facts['interfaces'] = interfaces.keys()
self.get_ipv6_facts() for iface in interfaces:
self.facts[iface] = interfaces[iface]
for key in ips:
self.facts[key] = ips[key]
return self.facts return self.facts
# get list of interfaces def parse_ip_addr(self):
def get_interfaces(self): interfaces = {}
names = [] ips = {'all_ipv4_addresses': [], 'all_ipv6_addresses': [],
data = get_file_content('/proc/net/dev') 'ipv4_address': None, 'ipv6_address': None}
# Format of /proc/net/dev is:
# Inter-| Receive ...
# face |bytes ...
# lo: 595059
for line in data.split('\n'):
if ':' in line:
names.append(line.split(':')[0].strip())
return names
def get_iface_hwaddr(self, iface): output = subprocess.Popen(['ip','addr'], stdout=subprocess.PIPE).communicate()[0]
data = get_file_content('/sys/class/net/%s/address' % iface) for line in output.split('\n'):
if data is None: if line:
return 'unknown' words = line.split()
if not line.startswith(' '):
device = words[1][0:-1]
mtu = words[4]
elif words[0].startswith('link/'):
iface_type = words[0].split('/')[1]
if iface_type == 'void':
macaddress = 'unknown'
else: else:
return data.strip() macaddress = words[1]
elif words[0] == 'inet':
address, netmask_length = words[1].split('/')
address_bin = struct.unpack('!L', socket.inet_aton(address))[0]
def get_interface_facts(self): netmask_bin = (1<<32) - (1<<32>>int(netmask_length))
for iface in self.facts['interfaces']: netmask = socket.inet_ntoa(struct.pack('!L', netmask_bin))
if iface not in self.facts:
self.facts[iface] = {}
self.facts[iface] = { 'macaddress': self.get_iface_hwaddr(iface) }
if os.path.exists('/sys/class/net/%s/mtu' % iface):
mtu = get_file_content('/sys/class/net/%s/mtu' % iface)
self.facts[iface]['mtu'] = mtu.strip()
def get_ipv4_facts(self): network = socket.inet_ntoa(struct.pack('!L', address_bin & netmask_bin))
for iface in self.facts['interfaces']:
# This is lame, but there doesn't appear to be a good way
# to get all addresses for both IPv4 and IPv6.
cmd = subprocess.Popen("env LANG=\"\" /sbin/ifconfig %s" % iface, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate()
for line in out.split('\n'):
is_ipv4 = False
data = line.split()
if 'inet addr' in line:
if 'ipv4' not in self.facts[iface]:
self.facts[iface]['ipv4'] = {}
is_ipv4 = True
self.facts[iface]['ipv4'] = { 'address': data[1].split(':')[1],
'netmask': data[-1].split(':')[1] }
# Slightly different output in net-tools-1.60-134.20120127git
# Looks like
# inet 192.168.1.2 netmask 255.255.255.0 broadcast 192.168.1.255
elif 'inet ' in line:
is_ipv4 = True
if 'ipv4' not in self.facts[iface]:
self.facts[iface]['ipv4'] = {}
self.facts[iface]['ipv4'] = { 'address': data[1],
'netmask': data[3] }
if is_ipv4:
ip = struct.unpack("!L", socket.inet_aton(self.facts[iface]['ipv4']['address']))[0]
mask = struct.unpack("!L", socket.inet_aton(self.facts[iface]['ipv4']['netmask']))[0]
self.facts[iface]['ipv4']['network'] = socket.inet_ntoa(struct.pack("!L", ip & mask))
def get_ipv6_facts(self): iface = words[-1]
if not socket.has_ipv6: # If an interface has multiple IPv4 addresses, make up an
return # interface name for each address
data = get_file_content('/proc/net/if_inet6') if iface in interfaces:
if data is None: i = 0
return while '{0}:{1}'.format(iface, i) in interfaces:
for line in data.split('\n'): i += 1
l = line.split() iface = '{0}:{1}'.format(iface, i)
iface = l[5]
if 'ipv6' not in self.facts[iface]: interfaces[iface] = {}
self.facts[iface]['ipv6'] = [] interfaces[iface]['macaddress'] = macaddress
scope = l[3] interfaces[iface]['mtu'] = mtu
if Network.IPV6_SCOPE.has_key(l[3]): interfaces[iface]['device'] = device
scope = Network.IPV6_SCOPE[l[3]] interfaces[iface]['ipv4'] = {'address': address,
prefix = int(l[2], 16) 'netmask': netmask,
str_addr = ':'.join( [ l[0][i:i+4] for i in range(0, len(l[0]), 4) ] ) 'network': network}
# Normalize ipv6 address from format in /proc/net/if_inet6
addr = socket.inet_ntop(socket.AF_INET6, ips['all_ipv4_addresses'].append(address)
socket.inet_pton(socket.AF_INET6, str_addr)) if not ips['ipv4_address'] or ips['ipv4_address'].startswith('127'):
self.facts[iface]['ipv6'].append( { 'address': addr, ips['ipv4_address'] = address
elif words[0] == 'inet6':
address, prefix = words[1].split('/')
scope = words[3]
iface = device
if iface not in interfaces:
interfaces[iface] = {}
interfaces[iface]['macaddress'] = macaddress
interfaces[iface]['mtu'] = mtu
interfaces[iface]['device'] = device
if 'ipv6' not in interfaces[iface]:
interfaces[iface]['ipv6'] = []
interfaces[iface]['ipv6'].append( {
'address': address,
'prefix': prefix, 'prefix': prefix,
'scope': scope} ) 'scope': scope} )
ips['all_ipv6_addresses'].append(address)
if not ips['ipv6_address'] or ips['ipv6_address'] == '::1':
ips['ipv6_address'] = address
return interfaces, ips
class Virtual(Facts): class Virtual(Facts):
""" """
This is a generic Virtual subclass of Facts. This should be further This is a generic Virtual subclass of Facts. This should be further