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, apt_update
27
from charmhelpers.core.hookenv import (
35
apt_update(fatal=True)
36
apt_install('python-netifaces', fatal=True)
42
apt_update(fatal=True)
43
apt_install('python-netaddr', fatal=True)
47
def _validate_cidr(network):
49
netaddr.IPNetwork(network)
50
except (netaddr.core.AddrFormatError, ValueError):
51
raise ValueError("Network (%s) is not in CIDR presentation format" %
55
def no_ip_found_error_out(network):
56
errmsg = ("No IP address found in network: %s" % network)
57
raise ValueError(errmsg)
60
def get_address_in_network(network, fallback=None, fatal=False):
61
"""Get an IPv4 or IPv6 address within the network from the host.
63
:param network (str): CIDR presentation format. For example,
65
:param fallback (str): If no address is found, return fallback.
66
:param fatal (boolean): If no address is found, fallback is not
67
set and fatal is True then exit(1).
70
if fallback is not None:
74
no_ip_found_error_out(network)
78
_validate_cidr(network)
79
network = netaddr.IPNetwork(network)
80
for iface in netifaces.interfaces():
81
addresses = netifaces.ifaddresses(iface)
82
if network.version == 4 and netifaces.AF_INET in addresses:
83
addr = addresses[netifaces.AF_INET][0]['addr']
84
netmask = addresses[netifaces.AF_INET][0]['netmask']
85
cidr = netaddr.IPNetwork("%s/%s" % (addr, netmask))
89
if network.version == 6 and netifaces.AF_INET6 in addresses:
90
for addr in addresses[netifaces.AF_INET6]:
91
if not addr['addr'].startswith('fe80'):
92
cidr = netaddr.IPNetwork("%s/%s" % (addr['addr'],
97
if fallback is not None:
101
no_ip_found_error_out(network)
106
def is_ipv6(address):
107
"""Determine whether provided address is IPv6 or not."""
109
address = netaddr.IPAddress(address)
110
except netaddr.AddrFormatError:
111
# probably a hostname - so not an address at all!
114
return address.version == 6
117
def is_address_in_network(network, address):
119
Determine whether the provided address is within a network range.
121
:param network (str): CIDR presentation format. For example,
123
:param address: An individual IPv4 or IPv6 address without a net
124
mask or subnet prefix. For example, '192.168.1.1'.
125
:returns boolean: Flag indicating whether address is in network.
128
network = netaddr.IPNetwork(network)
129
except (netaddr.core.AddrFormatError, ValueError):
130
raise ValueError("Network (%s) is not in CIDR presentation format" %
134
address = netaddr.IPAddress(address)
135
except (netaddr.core.AddrFormatError, ValueError):
136
raise ValueError("Address (%s) is not in correct presentation format" %
139
if address in network:
145
def _get_for_address(address, key):
146
"""Retrieve an attribute of or the physical interface that
147
the IP address provided could be bound to.
149
:param address (str): An individual IPv4 or IPv6 address without a net
150
mask or subnet prefix. For example, '192.168.1.1'.
151
:param key: 'iface' for the physical interface name or an attribute
152
of the configured interface, for example 'netmask'.
153
:returns str: Requested attribute or None if address is not bindable.
155
address = netaddr.IPAddress(address)
156
for iface in netifaces.interfaces():
157
addresses = netifaces.ifaddresses(iface)
158
if address.version == 4 and netifaces.AF_INET in addresses:
159
addr = addresses[netifaces.AF_INET][0]['addr']
160
netmask = addresses[netifaces.AF_INET][0]['netmask']
161
network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
167
return addresses[netifaces.AF_INET][0][key]
169
if address.version == 6 and netifaces.AF_INET6 in addresses:
170
for addr in addresses[netifaces.AF_INET6]:
171
if not addr['addr'].startswith('fe80'):
172
network = netaddr.IPNetwork("%s/%s" % (addr['addr'],
178
elif key == 'netmask' and cidr:
179
return str(cidr).split('/')[1]
186
get_iface_for_address = partial(_get_for_address, key='iface')
189
get_netmask_for_address = partial(_get_for_address, key='netmask')
192
def format_ipv6_addr(address):
193
"""If address is IPv6, wrap it in '[]' otherwise return None.
195
This is required by most configuration files when specifying IPv6
199
return "[%s]" % address
204
def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False,
205
fatal=True, exc_list=None):
206
"""Return the assigned IP address for a given interface, if any."""
207
# Extract nic if passed /dev/ethX
209
iface = iface.split('/')[-1]
215
inet_num = getattr(netifaces, inet_type)
216
except AttributeError:
217
raise Exception("Unknown inet type '%s'" % str(inet_type))
219
interfaces = netifaces.interfaces()
222
for _iface in interfaces:
223
if iface == _iface or _iface.split(':')[0] == iface:
224
ifaces.append(_iface)
226
if fatal and not ifaces:
227
raise Exception("Invalid interface '%s'" % iface)
231
if iface not in interfaces:
233
raise Exception("Interface '%s' not found " % (iface))
241
for netiface in ifaces:
242
net_info = netifaces.ifaddresses(netiface)
243
if inet_num in net_info:
244
for entry in net_info[inet_num]:
245
if 'addr' in entry and entry['addr'] not in exc_list:
246
addresses.append(entry['addr'])
248
if fatal and not addresses:
249
raise Exception("Interface '%s' doesn't have any %s addresses." %
252
return sorted(addresses)
255
get_ipv4_addr = partial(get_iface_addr, inet_type='AF_INET')
258
def get_iface_from_addr(addr):
259
"""Work out on which interface the provided address is configured."""
260
for iface in netifaces.interfaces():
261
addresses = netifaces.ifaddresses(iface)
262
for inet_type in addresses:
263
for _addr in addresses[inet_type]:
264
_addr = _addr['addr']
266
ll_key = re.compile("(.+)%.*")
267
raw = re.match(ll_key, _addr)
272
log("Address '%s' is configured on iface '%s'" %
276
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
281
"""Ensure decorated function is called with a value for iface.
283
If no iface provided, inject net iface inferred from unit private address.
285
def iface_sniffer(*args, **kwargs):
286
if not kwargs.get('iface', None):
287
kwargs['iface'] = get_iface_from_addr(unit_get('private-address'))
289
return f(*args, **kwargs)
295
def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None,
297
"""Get assigned IPv6 address for a given interface.
299
Returns list of addresses found. If no address found, returns empty list.
301
If iface is None, we infer the current primary interface by doing a reverse
302
lookup on the unit private-address.
304
We currently only support scope global IPv6 addresses i.e. non-temporary
305
addresses. If no global IPv6 address is found, return the first one found
306
in the ipv6 address list.
308
addresses = get_iface_addr(iface=iface, inet_type='AF_INET6',
309
inc_aliases=inc_aliases, fatal=fatal,
314
for addr in addresses:
315
key_scope_link_local = re.compile("^fe80::..(.+)%(.+)")
316
m = re.match(key_scope_link_local, addr)
318
eui_64_mac = m.group(1)
321
global_addrs.append(addr)
324
# Make sure any found global addresses are not temporary
325
cmd = ['ip', 'addr', 'show', iface]
326
out = subprocess.check_output(cmd).decode('UTF-8')
328
key = re.compile("inet6 (.+)/[0-9]+ scope global dynamic.*")
330
key = re.compile("inet6 (.+)/[0-9]+ scope global.*")
333
for line in out.split('\n'):
335
m = re.match(key, line)
336
if m and 'temporary' not in line:
337
# Return the first valid address we find
338
for addr in global_addrs:
339
if m.group(1) == addr:
340
if not dynamic_only or \
341
m.group(1).endswith(eui_64_mac):
348
raise Exception("Interface '%s' does not have a scope global "
349
"non-temporary ipv6 address." % iface)
354
def get_bridges(vnic_dir='/sys/devices/virtual/net'):
355
"""Return a list of bridges on the system."""
356
b_regex = "%s/*/bridge" % vnic_dir
357
return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)]
360
def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'):
361
"""Return a list of nics comprising a given bridge on the system."""
362
brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge)
363
return [x.split('/')[-1] for x in glob.glob(brif_regex)]
366
def is_bridge_member(nic):
367
"""Check if a given nic is a member of a bridge."""
368
for bridge in get_bridges():
369
if nic in get_bridge_nics(bridge):
377
Returns True if address is a valid IP address.
380
# Test to see if already an IPv4 address
381
socket.inet_aton(address)
387
def ns_query(address):
391
apt_install('python-dnspython')
394
if isinstance(address, dns.name.Name):
396
elif isinstance(address, six.string_types):
401
answers = dns.resolver.query(address, rtype)
403
return str(answers[0])
407
def get_host_ip(hostname, fallback=None):
409
Resolves the IP for a given hostname, or returns
410
the input if it is already an IP.
415
ip_addr = ns_query(hostname)
418
ip_addr = socket.gethostbyname(hostname)
420
log("Failed to resolve hostname '%s'" % (hostname),
426
def get_hostname(address, fqdn=True):
428
Resolves hostname for given IP, or returns the input
429
if it is already a hostname.
433
import dns.reversename
435
apt_install("python-dnspython")
436
import dns.reversename
438
rev = dns.reversename.from_address(address)
439
result = ns_query(rev)
443
result = socket.gethostbyaddr(address)[0]
451
if result.endswith('.'):
456
return result.split('.')[0]