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/>.
23
from functools import partial
25
from charmhelpers.core.hookenv import unit_get
26
from charmhelpers.fetch import apt_install
27
from charmhelpers.core.hookenv import (
35
apt_install('python-netifaces')
41
apt_install('python-netaddr')
45
def _validate_cidr(network):
47
netaddr.IPNetwork(network)
48
except (netaddr.core.AddrFormatError, ValueError):
49
raise ValueError("Network (%s) is not in CIDR presentation format" %
53
def no_ip_found_error_out(network):
54
errmsg = ("No IP address found in network: %s" % network)
55
raise ValueError(errmsg)
58
def get_address_in_network(network, fallback=None, fatal=False):
59
"""Get an IPv4 or IPv6 address within the network from the host.
61
:param network (str): CIDR presentation format. For example,
63
:param fallback (str): If no address is found, return fallback.
64
:param fatal (boolean): If no address is found, fallback is not
65
set and fatal is True then exit(1).
68
if fallback is not None:
72
no_ip_found_error_out(network)
76
_validate_cidr(network)
77
network = netaddr.IPNetwork(network)
78
for iface in netifaces.interfaces():
79
addresses = netifaces.ifaddresses(iface)
80
if network.version == 4 and netifaces.AF_INET in addresses:
81
addr = addresses[netifaces.AF_INET][0]['addr']
82
netmask = addresses[netifaces.AF_INET][0]['netmask']
83
cidr = netaddr.IPNetwork("%s/%s" % (addr, netmask))
87
if network.version == 6 and netifaces.AF_INET6 in addresses:
88
for addr in addresses[netifaces.AF_INET6]:
89
if not addr['addr'].startswith('fe80'):
90
cidr = netaddr.IPNetwork("%s/%s" % (addr['addr'],
95
if fallback is not None:
99
no_ip_found_error_out(network)
104
def is_ipv6(address):
105
"""Determine whether provided address is IPv6 or not."""
107
address = netaddr.IPAddress(address)
108
except netaddr.AddrFormatError:
109
# probably a hostname - so not an address at all!
112
return address.version == 6
115
def is_address_in_network(network, address):
117
Determine whether the provided address is within a network range.
119
:param network (str): CIDR presentation format. For example,
121
:param address: An individual IPv4 or IPv6 address without a net
122
mask or subnet prefix. For example, '192.168.1.1'.
123
:returns boolean: Flag indicating whether address is in network.
126
network = netaddr.IPNetwork(network)
127
except (netaddr.core.AddrFormatError, ValueError):
128
raise ValueError("Network (%s) is not in CIDR presentation format" %
132
address = netaddr.IPAddress(address)
133
except (netaddr.core.AddrFormatError, ValueError):
134
raise ValueError("Address (%s) is not in correct presentation format" %
137
if address in network:
143
def _get_for_address(address, key):
144
"""Retrieve an attribute of or the physical interface that
145
the IP address provided could be bound to.
147
:param address (str): An individual IPv4 or IPv6 address without a net
148
mask or subnet prefix. For example, '192.168.1.1'.
149
:param key: 'iface' for the physical interface name or an attribute
150
of the configured interface, for example 'netmask'.
151
:returns str: Requested attribute or None if address is not bindable.
153
address = netaddr.IPAddress(address)
154
for iface in netifaces.interfaces():
155
addresses = netifaces.ifaddresses(iface)
156
if address.version == 4 and netifaces.AF_INET in addresses:
157
addr = addresses[netifaces.AF_INET][0]['addr']
158
netmask = addresses[netifaces.AF_INET][0]['netmask']
159
network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
165
return addresses[netifaces.AF_INET][0][key]
167
if address.version == 6 and netifaces.AF_INET6 in addresses:
168
for addr in addresses[netifaces.AF_INET6]:
169
if not addr['addr'].startswith('fe80'):
170
network = netaddr.IPNetwork("%s/%s" % (addr['addr'],
176
elif key == 'netmask' and cidr:
177
return str(cidr).split('/')[1]
184
get_iface_for_address = partial(_get_for_address, key='iface')
187
get_netmask_for_address = partial(_get_for_address, key='netmask')
190
def format_ipv6_addr(address):
191
"""If address is IPv6, wrap it in '[]' otherwise return None.
193
This is required by most configuration files when specifying IPv6
197
return "[%s]" % address
202
def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False,
203
fatal=True, exc_list=None):
204
"""Return the assigned IP address for a given interface, if any."""
205
# Extract nic if passed /dev/ethX
207
iface = iface.split('/')[-1]
213
inet_num = getattr(netifaces, inet_type)
214
except AttributeError:
215
raise Exception("Unknown inet type '%s'" % str(inet_type))
217
interfaces = netifaces.interfaces()
220
for _iface in interfaces:
221
if iface == _iface or _iface.split(':')[0] == iface:
222
ifaces.append(_iface)
224
if fatal and not ifaces:
225
raise Exception("Invalid interface '%s'" % iface)
229
if iface not in interfaces:
231
raise Exception("Interface '%s' not found " % (iface))
239
for netiface in ifaces:
240
net_info = netifaces.ifaddresses(netiface)
241
if inet_num in net_info:
242
for entry in net_info[inet_num]:
243
if 'addr' in entry and entry['addr'] not in exc_list:
244
addresses.append(entry['addr'])
246
if fatal and not addresses:
247
raise Exception("Interface '%s' doesn't have any %s addresses." %
250
return sorted(addresses)
253
get_ipv4_addr = partial(get_iface_addr, inet_type='AF_INET')
256
def get_iface_from_addr(addr):
257
"""Work out on which interface the provided address is configured."""
258
for iface in netifaces.interfaces():
259
addresses = netifaces.ifaddresses(iface)
260
for inet_type in addresses:
261
for _addr in addresses[inet_type]:
262
_addr = _addr['addr']
264
ll_key = re.compile("(.+)%.*")
265
raw = re.match(ll_key, _addr)
270
log("Address '%s' is configured on iface '%s'" %
274
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
279
"""Ensure decorated function is called with a value for iface.
281
If no iface provided, inject net iface inferred from unit private address.
283
def iface_sniffer(*args, **kwargs):
284
if not kwargs.get('iface', None):
285
kwargs['iface'] = get_iface_from_addr(unit_get('private-address'))
287
return f(*args, **kwargs)
293
def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None,
295
"""Get assigned IPv6 address for a given interface.
297
Returns list of addresses found. If no address found, returns empty list.
299
If iface is None, we infer the current primary interface by doing a reverse
300
lookup on the unit private-address.
302
We currently only support scope global IPv6 addresses i.e. non-temporary
303
addresses. If no global IPv6 address is found, return the first one found
304
in the ipv6 address list.
306
addresses = get_iface_addr(iface=iface, inet_type='AF_INET6',
307
inc_aliases=inc_aliases, fatal=fatal,
312
for addr in addresses:
313
key_scope_link_local = re.compile("^fe80::..(.+)%(.+)")
314
m = re.match(key_scope_link_local, addr)
316
eui_64_mac = m.group(1)
319
global_addrs.append(addr)
322
# Make sure any found global addresses are not temporary
323
cmd = ['ip', 'addr', 'show', iface]
324
out = subprocess.check_output(cmd).decode('UTF-8')
326
key = re.compile("inet6 (.+)/[0-9]+ scope global dynamic.*")
328
key = re.compile("inet6 (.+)/[0-9]+ scope global.*")
331
for line in out.split('\n'):
333
m = re.match(key, line)
334
if m and 'temporary' not in line:
335
# Return the first valid address we find
336
for addr in global_addrs:
337
if m.group(1) == addr:
338
if not dynamic_only or \
339
m.group(1).endswith(eui_64_mac):
346
raise Exception("Interface '%s' does not have a scope global "
347
"non-temporary ipv6 address." % iface)
352
def get_bridges(vnic_dir='/sys/devices/virtual/net'):
353
"""Return a list of bridges on the system."""
354
b_regex = "%s/*/bridge" % vnic_dir
355
return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)]
358
def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'):
359
"""Return a list of nics comprising a given bridge on the system."""
360
brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge)
361
return [x.split('/')[-1] for x in glob.glob(brif_regex)]
364
def is_bridge_member(nic):
365
"""Check if a given nic is a member of a bridge."""
366
for bridge in get_bridges():
367
if nic in get_bridge_nics(bridge):
375
Returns True if address is a valid IP address.
378
# Test to see if already an IPv4 address
379
socket.inet_aton(address)
385
def ns_query(address):
389
apt_install('python-dnspython')
392
if isinstance(address, dns.name.Name):
394
elif isinstance(address, six.string_types):
399
answers = dns.resolver.query(address, rtype)
401
return str(answers[0])
405
def get_host_ip(hostname, fallback=None):
407
Resolves the IP for a given hostname, or returns
408
the input if it is already an IP.
413
ip_addr = ns_query(hostname)
416
ip_addr = socket.gethostbyname(hostname)
418
log("Failed to resolve hostname '%s'" % (hostname),
424
def get_hostname(address, fqdn=True):
426
Resolves hostname for given IP, or returns the input
427
if it is already a hostname.
431
import dns.reversename
433
apt_install("python-dnspython")
434
import dns.reversename
436
rev = dns.reversename.from_address(address)
437
result = ns_query(rev)
445
if result.endswith('.'):
450
return result.split('.')[0]