1
# Copyright 2014-2015 Canonical Limited.
3
# This file is part of charm-helpers.
5
# charm-helpers is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU Lesser General Public License version 3 as
7
# published by the Free Software Foundation.
9
# charm-helpers is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU Lesser General Public License for more details.
14
# You should have received a copy of the GNU Lesser General Public License
15
# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
21
from functools import partial
23
from charmhelpers.core.hookenv import unit_get
24
from charmhelpers.fetch import apt_install
25
from charmhelpers.core.hookenv import (
32
apt_install('python-netifaces')
38
apt_install('python-netaddr')
42
def _validate_cidr(network):
44
netaddr.IPNetwork(network)
45
except (netaddr.core.AddrFormatError, ValueError):
46
raise ValueError("Network (%s) is not in CIDR presentation format" %
50
def no_ip_found_error_out(network):
51
errmsg = ("No IP address found in network: %s" % network)
52
raise ValueError(errmsg)
55
def get_address_in_network(network, fallback=None, fatal=False):
56
"""Get an IPv4 or IPv6 address within the network from the host.
58
:param network (str): CIDR presentation format. For example,
60
:param fallback (str): If no address is found, return fallback.
61
:param fatal (boolean): If no address is found, fallback is not
62
set and fatal is True then exit(1).
65
if fallback is not None:
69
no_ip_found_error_out(network)
73
_validate_cidr(network)
74
network = netaddr.IPNetwork(network)
75
for iface in netifaces.interfaces():
76
addresses = netifaces.ifaddresses(iface)
77
if network.version == 4 and netifaces.AF_INET in addresses:
78
addr = addresses[netifaces.AF_INET][0]['addr']
79
netmask = addresses[netifaces.AF_INET][0]['netmask']
80
cidr = netaddr.IPNetwork("%s/%s" % (addr, netmask))
84
if network.version == 6 and netifaces.AF_INET6 in addresses:
85
for addr in addresses[netifaces.AF_INET6]:
86
if not addr['addr'].startswith('fe80'):
87
cidr = netaddr.IPNetwork("%s/%s" % (addr['addr'],
92
if fallback is not None:
96
no_ip_found_error_out(network)
101
def is_ipv6(address):
102
"""Determine whether provided address is IPv6 or not."""
104
address = netaddr.IPAddress(address)
105
except netaddr.AddrFormatError:
106
# probably a hostname - so not an address at all!
109
return address.version == 6
112
def is_address_in_network(network, address):
114
Determine whether the provided address is within a network range.
116
:param network (str): CIDR presentation format. For example,
118
:param address: An individual IPv4 or IPv6 address without a net
119
mask or subnet prefix. For example, '192.168.1.1'.
120
:returns boolean: Flag indicating whether address is in network.
123
network = netaddr.IPNetwork(network)
124
except (netaddr.core.AddrFormatError, ValueError):
125
raise ValueError("Network (%s) is not in CIDR presentation format" %
129
address = netaddr.IPAddress(address)
130
except (netaddr.core.AddrFormatError, ValueError):
131
raise ValueError("Address (%s) is not in correct presentation format" %
134
if address in network:
140
def _get_for_address(address, key):
141
"""Retrieve an attribute of or the physical interface that
142
the IP address provided could be bound to.
144
:param address (str): An individual IPv4 or IPv6 address without a net
145
mask or subnet prefix. For example, '192.168.1.1'.
146
:param key: 'iface' for the physical interface name or an attribute
147
of the configured interface, for example 'netmask'.
148
:returns str: Requested attribute or None if address is not bindable.
150
address = netaddr.IPAddress(address)
151
for iface in netifaces.interfaces():
152
addresses = netifaces.ifaddresses(iface)
153
if address.version == 4 and netifaces.AF_INET in addresses:
154
addr = addresses[netifaces.AF_INET][0]['addr']
155
netmask = addresses[netifaces.AF_INET][0]['netmask']
156
network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
162
return addresses[netifaces.AF_INET][0][key]
164
if address.version == 6 and netifaces.AF_INET6 in addresses:
165
for addr in addresses[netifaces.AF_INET6]:
166
if not addr['addr'].startswith('fe80'):
167
network = netaddr.IPNetwork("%s/%s" % (addr['addr'],
173
elif key == 'netmask' and cidr:
174
return str(cidr).split('/')[1]
181
get_iface_for_address = partial(_get_for_address, key='iface')
184
get_netmask_for_address = partial(_get_for_address, key='netmask')
187
def format_ipv6_addr(address):
188
"""If address is IPv6, wrap it in '[]' otherwise return None.
190
This is required by most configuration files when specifying IPv6
194
return "[%s]" % address
199
def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False,
200
fatal=True, exc_list=None):
201
"""Return the assigned IP address for a given interface, if any."""
202
# Extract nic if passed /dev/ethX
204
iface = iface.split('/')[-1]
210
inet_num = getattr(netifaces, inet_type)
211
except AttributeError:
212
raise Exception("Unknown inet type '%s'" % str(inet_type))
214
interfaces = netifaces.interfaces()
217
for _iface in interfaces:
218
if iface == _iface or _iface.split(':')[0] == iface:
219
ifaces.append(_iface)
221
if fatal and not ifaces:
222
raise Exception("Invalid interface '%s'" % iface)
226
if iface not in interfaces:
228
raise Exception("Interface '%s' not found " % (iface))
236
for netiface in ifaces:
237
net_info = netifaces.ifaddresses(netiface)
238
if inet_num in net_info:
239
for entry in net_info[inet_num]:
240
if 'addr' in entry and entry['addr'] not in exc_list:
241
addresses.append(entry['addr'])
243
if fatal and not addresses:
244
raise Exception("Interface '%s' doesn't have any %s addresses." %
247
return sorted(addresses)
250
get_ipv4_addr = partial(get_iface_addr, inet_type='AF_INET')
253
def get_iface_from_addr(addr):
254
"""Work out on which interface the provided address is configured."""
255
for iface in netifaces.interfaces():
256
addresses = netifaces.ifaddresses(iface)
257
for inet_type in addresses:
258
for _addr in addresses[inet_type]:
259
_addr = _addr['addr']
261
ll_key = re.compile("(.+)%.*")
262
raw = re.match(ll_key, _addr)
267
log("Address '%s' is configured on iface '%s'" %
271
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
276
"""Ensure decorated function is called with a value for iface.
278
If no iface provided, inject net iface inferred from unit private address.
280
def iface_sniffer(*args, **kwargs):
281
if not kwargs.get('iface', None):
282
kwargs['iface'] = get_iface_from_addr(unit_get('private-address'))
284
return f(*args, **kwargs)
290
def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None,
292
"""Get assigned IPv6 address for a given interface.
294
Returns list of addresses found. If no address found, returns empty list.
296
If iface is None, we infer the current primary interface by doing a reverse
297
lookup on the unit private-address.
299
We currently only support scope global IPv6 addresses i.e. non-temporary
300
addresses. If no global IPv6 address is found, return the first one found
301
in the ipv6 address list.
303
addresses = get_iface_addr(iface=iface, inet_type='AF_INET6',
304
inc_aliases=inc_aliases, fatal=fatal,
309
for addr in addresses:
310
key_scope_link_local = re.compile("^fe80::..(.+)%(.+)")
311
m = re.match(key_scope_link_local, addr)
313
eui_64_mac = m.group(1)
316
global_addrs.append(addr)
319
# Make sure any found global addresses are not temporary
320
cmd = ['ip', 'addr', 'show', iface]
321
out = subprocess.check_output(cmd).decode('UTF-8')
323
key = re.compile("inet6 (.+)/[0-9]+ scope global dynamic.*")
325
key = re.compile("inet6 (.+)/[0-9]+ scope global.*")
328
for line in out.split('\n'):
330
m = re.match(key, line)
331
if m and 'temporary' not in line:
332
# Return the first valid address we find
333
for addr in global_addrs:
334
if m.group(1) == addr:
335
if not dynamic_only or \
336
m.group(1).endswith(eui_64_mac):
343
raise Exception("Interface '%s' does not have a scope global "
344
"non-temporary ipv6 address." % iface)
349
def get_bridges(vnic_dir='/sys/devices/virtual/net'):
350
"""Return a list of bridges on the system."""
351
b_regex = "%s/*/bridge" % vnic_dir
352
return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)]
355
def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'):
356
"""Return a list of nics comprising a given bridge on the system."""
357
brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge)
358
return [x.split('/')[-1] for x in glob.glob(brif_regex)]
361
def is_bridge_member(nic):
362
"""Check if a given nic is a member of a bridge."""
363
for bridge in get_bridges():
364
if nic in get_bridge_nics(bridge):