~james-page/charms/trusty/cinder/https-multi-network

« back to all changes in this revision

Viewing changes to hooks/charmhelpers/contrib/network/ip.py

  • Committer: james.page at ubuntu
  • Date: 2014-10-01 22:07:44 UTC
  • mfrom: (45.1.1 cinder)
  • Revision ID: james.page@ubuntu.com-20141001220744-v35hu9iblt15phc7
Rebase and resync

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
import glob
 
2
import re
 
3
import subprocess
2
4
import sys
3
5
 
4
6
from functools import partial
5
7
 
 
8
from charmhelpers.core.hookenv import unit_get
6
9
from charmhelpers.fetch import apt_install
7
10
from charmhelpers.core.hookenv import (
8
 
    ERROR, log,
 
11
    WARNING,
 
12
    ERROR,
 
13
    log
9
14
)
10
15
 
11
16
try:
164
169
    if is_ipv6(address):
165
170
        address = "[%s]" % address
166
171
    else:
167
 
        log("Not an valid ipv6 address: %s" % address,
168
 
            level=ERROR)
 
172
        log("Not a valid ipv6 address: %s" % address, level=WARNING)
169
173
        address = None
 
174
 
170
175
    return address
171
176
 
172
177
 
173
 
def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False, fatal=True, exc_list=None):
 
178
def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False,
 
179
                   fatal=True, exc_list=None):
174
180
    """
175
181
    Return the assigned IP address for a given interface, if any, or [].
176
182
    """
210
216
                if 'addr' in entry and entry['addr'] not in exc_list:
211
217
                    addresses.append(entry['addr'])
212
218
    if fatal and not addresses:
213
 
        raise Exception("Interface '%s' doesn't have any %s addresses." % (iface, inet_type))
 
219
        raise Exception("Interface '%s' doesn't have any %s addresses." %
 
220
                        (iface, inet_type))
214
221
    return addresses
215
222
 
216
223
get_ipv4_addr = partial(get_iface_addr, inet_type='AF_INET')
217
224
 
218
225
 
219
 
def get_ipv6_addr(iface='eth0', inc_aliases=False, fatal=True, exc_list=None):
 
226
def get_iface_from_addr(addr):
 
227
    """Work out on which interface the provided address is configured."""
 
228
    for iface in netifaces.interfaces():
 
229
        addresses = netifaces.ifaddresses(iface)
 
230
        for inet_type in addresses:
 
231
            for _addr in addresses[inet_type]:
 
232
                _addr = _addr['addr']
 
233
                # link local
 
234
                ll_key = re.compile("(.+)%.*")
 
235
                raw = re.match(ll_key, _addr)
 
236
                if raw:
 
237
                    _addr = raw.group(1)
 
238
                if _addr == addr:
 
239
                    log("Address '%s' is configured on iface '%s'" %
 
240
                        (addr, iface))
 
241
                    return iface
 
242
 
 
243
    msg = "Unable to infer net iface on which '%s' is configured" % (addr)
 
244
    raise Exception(msg)
 
245
 
 
246
 
 
247
def sniff_iface(f):
 
248
    """If no iface provided, inject net iface inferred from unit private
 
249
    address.
220
250
    """
221
 
    Return the assigned IPv6 address for a given interface, if any, or [].
 
251
    def iface_sniffer(*args, **kwargs):
 
252
        if not kwargs.get('iface', None):
 
253
            kwargs['iface'] = get_iface_from_addr(unit_get('private-address'))
 
254
 
 
255
        return f(*args, **kwargs)
 
256
 
 
257
    return iface_sniffer
 
258
 
 
259
 
 
260
@sniff_iface
 
261
def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None,
 
262
                  dynamic_only=True):
 
263
    """Get assigned IPv6 address for a given interface.
 
264
 
 
265
    Returns list of addresses found. If no address found, returns empty list.
 
266
 
 
267
    If iface is None, we infer the current primary interface by doing a reverse
 
268
    lookup on the unit private-address.
 
269
 
 
270
    We currently only support scope global IPv6 addresses i.e. non-temporary
 
271
    addresses. If no global IPv6 address is found, return the first one found
 
272
    in the ipv6 address list.
222
273
    """
223
274
    addresses = get_iface_addr(iface=iface, inet_type='AF_INET6',
224
275
                               inc_aliases=inc_aliases, fatal=fatal,
225
276
                               exc_list=exc_list)
226
 
    remotly_addressable = []
227
 
    for address in addresses:
228
 
        if not address.startswith('fe80'):
229
 
            remotly_addressable.append(address)
230
 
    if fatal and not remotly_addressable:
231
 
        raise Exception("Interface '%s' doesn't have global ipv6 address." % iface)
232
 
    return remotly_addressable
 
277
 
 
278
    if addresses:
 
279
        global_addrs = []
 
280
        for addr in addresses:
 
281
            key_scope_link_local = re.compile("^fe80::..(.+)%(.+)")
 
282
            m = re.match(key_scope_link_local, addr)
 
283
            if m:
 
284
                eui_64_mac = m.group(1)
 
285
                iface = m.group(2)
 
286
            else:
 
287
                global_addrs.append(addr)
 
288
 
 
289
        if global_addrs:
 
290
            # Make sure any found global addresses are not temporary
 
291
            cmd = ['ip', 'addr', 'show', iface]
 
292
            out = subprocess.check_output(cmd)
 
293
            if dynamic_only:
 
294
                key = re.compile("inet6 (.+)/[0-9]+ scope global dynamic.*")
 
295
            else:
 
296
                key = re.compile("inet6 (.+)/[0-9]+ scope global.*")
 
297
 
 
298
            addrs = []
 
299
            for line in out.split('\n'):
 
300
                line = line.strip()
 
301
                m = re.match(key, line)
 
302
                if m and 'temporary' not in line:
 
303
                    # Return the first valid address we find
 
304
                    for addr in global_addrs:
 
305
                        if m.group(1) == addr:
 
306
                            if not dynamic_only or \
 
307
                                    m.group(1).endswith(eui_64_mac):
 
308
                                addrs.append(addr)
 
309
 
 
310
            if addrs:
 
311
                return addrs
 
312
 
 
313
    if fatal:
 
314
        raise Exception("Interface '%s' doesn't have a scope global "
 
315
                        "non-temporary ipv6 address." % iface)
 
316
 
 
317
    return []
233
318
 
234
319
 
235
320
def get_bridges(vnic_dir='/sys/devices/virtual/net'):