~canonical-ci-engineering/charms/trusty/core-image-publisher/trunk

« back to all changes in this revision

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

  • Committer: Celso Providelo
  • Date: 2015-03-25 04:13:43 UTC
  • Revision ID: celso.providelo@canonical.com-20150325041343-jw05jaz6jscs3c8f
fork of core-image-watcher

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2014-2015 Canonical Limited.
 
2
#
 
3
# This file is part of charm-helpers.
 
4
#
 
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.
 
8
#
 
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.
 
13
#
 
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/>.
 
16
 
 
17
import glob
 
18
import re
 
19
import subprocess
 
20
 
 
21
from functools import partial
 
22
 
 
23
from charmhelpers.core.hookenv import unit_get
 
24
from charmhelpers.fetch import apt_install
 
25
from charmhelpers.core.hookenv import (
 
26
    log
 
27
)
 
28
 
 
29
try:
 
30
    import netifaces
 
31
except ImportError:
 
32
    apt_install('python-netifaces')
 
33
    import netifaces
 
34
 
 
35
try:
 
36
    import netaddr
 
37
except ImportError:
 
38
    apt_install('python-netaddr')
 
39
    import netaddr
 
40
 
 
41
 
 
42
def _validate_cidr(network):
 
43
    try:
 
44
        netaddr.IPNetwork(network)
 
45
    except (netaddr.core.AddrFormatError, ValueError):
 
46
        raise ValueError("Network (%s) is not in CIDR presentation format" %
 
47
                         network)
 
48
 
 
49
 
 
50
def no_ip_found_error_out(network):
 
51
    errmsg = ("No IP address found in network: %s" % network)
 
52
    raise ValueError(errmsg)
 
53
 
 
54
 
 
55
def get_address_in_network(network, fallback=None, fatal=False):
 
56
    """Get an IPv4 or IPv6 address within the network from the host.
 
57
 
 
58
    :param network (str): CIDR presentation format. For example,
 
59
        '192.168.1.0/24'.
 
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).
 
63
    """
 
64
    if network is None:
 
65
        if fallback is not None:
 
66
            return fallback
 
67
 
 
68
        if fatal:
 
69
            no_ip_found_error_out(network)
 
70
        else:
 
71
            return None
 
72
 
 
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))
 
81
            if cidr in network:
 
82
                return str(cidr.ip)
 
83
 
 
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'],
 
88
                                                        addr['netmask']))
 
89
                    if cidr in network:
 
90
                        return str(cidr.ip)
 
91
 
 
92
    if fallback is not None:
 
93
        return fallback
 
94
 
 
95
    if fatal:
 
96
        no_ip_found_error_out(network)
 
97
 
 
98
    return None
 
99
 
 
100
 
 
101
def is_ipv6(address):
 
102
    """Determine whether provided address is IPv6 or not."""
 
103
    try:
 
104
        address = netaddr.IPAddress(address)
 
105
    except netaddr.AddrFormatError:
 
106
        # probably a hostname - so not an address at all!
 
107
        return False
 
108
 
 
109
    return address.version == 6
 
110
 
 
111
 
 
112
def is_address_in_network(network, address):
 
113
    """
 
114
    Determine whether the provided address is within a network range.
 
115
 
 
116
    :param network (str): CIDR presentation format. For example,
 
117
        '192.168.1.0/24'.
 
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.
 
121
    """
 
122
    try:
 
123
        network = netaddr.IPNetwork(network)
 
124
    except (netaddr.core.AddrFormatError, ValueError):
 
125
        raise ValueError("Network (%s) is not in CIDR presentation format" %
 
126
                         network)
 
127
 
 
128
    try:
 
129
        address = netaddr.IPAddress(address)
 
130
    except (netaddr.core.AddrFormatError, ValueError):
 
131
        raise ValueError("Address (%s) is not in correct presentation format" %
 
132
                         address)
 
133
 
 
134
    if address in network:
 
135
        return True
 
136
    else:
 
137
        return False
 
138
 
 
139
 
 
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.
 
143
 
 
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.
 
149
    """
 
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))
 
157
            cidr = network.cidr
 
158
            if address in cidr:
 
159
                if key == 'iface':
 
160
                    return iface
 
161
                else:
 
162
                    return addresses[netifaces.AF_INET][0][key]
 
163
 
 
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'],
 
168
                                                           addr['netmask']))
 
169
                    cidr = network.cidr
 
170
                    if address in cidr:
 
171
                        if key == 'iface':
 
172
                            return iface
 
173
                        elif key == 'netmask' and cidr:
 
174
                            return str(cidr).split('/')[1]
 
175
                        else:
 
176
                            return addr[key]
 
177
 
 
178
    return None
 
179
 
 
180
 
 
181
get_iface_for_address = partial(_get_for_address, key='iface')
 
182
 
 
183
 
 
184
get_netmask_for_address = partial(_get_for_address, key='netmask')
 
185
 
 
186
 
 
187
def format_ipv6_addr(address):
 
188
    """If address is IPv6, wrap it in '[]' otherwise return None.
 
189
 
 
190
    This is required by most configuration files when specifying IPv6
 
191
    addresses.
 
192
    """
 
193
    if is_ipv6(address):
 
194
        return "[%s]" % address
 
195
 
 
196
    return None
 
197
 
 
198
 
 
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
 
203
    if '/' in iface:
 
204
        iface = iface.split('/')[-1]
 
205
 
 
206
    if not exc_list:
 
207
        exc_list = []
 
208
 
 
209
    try:
 
210
        inet_num = getattr(netifaces, inet_type)
 
211
    except AttributeError:
 
212
        raise Exception("Unknown inet type '%s'" % str(inet_type))
 
213
 
 
214
    interfaces = netifaces.interfaces()
 
215
    if inc_aliases:
 
216
        ifaces = []
 
217
        for _iface in interfaces:
 
218
            if iface == _iface or _iface.split(':')[0] == iface:
 
219
                ifaces.append(_iface)
 
220
 
 
221
        if fatal and not ifaces:
 
222
            raise Exception("Invalid interface '%s'" % iface)
 
223
 
 
224
        ifaces.sort()
 
225
    else:
 
226
        if iface not in interfaces:
 
227
            if fatal:
 
228
                raise Exception("Interface '%s' not found " % (iface))
 
229
            else:
 
230
                return []
 
231
 
 
232
        else:
 
233
            ifaces = [iface]
 
234
 
 
235
    addresses = []
 
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'])
 
242
 
 
243
    if fatal and not addresses:
 
244
        raise Exception("Interface '%s' doesn't have any %s addresses." %
 
245
                        (iface, inet_type))
 
246
 
 
247
    return sorted(addresses)
 
248
 
 
249
 
 
250
get_ipv4_addr = partial(get_iface_addr, inet_type='AF_INET')
 
251
 
 
252
 
 
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']
 
260
                # link local
 
261
                ll_key = re.compile("(.+)%.*")
 
262
                raw = re.match(ll_key, _addr)
 
263
                if raw:
 
264
                    _addr = raw.group(1)
 
265
 
 
266
                if _addr == addr:
 
267
                    log("Address '%s' is configured on iface '%s'" %
 
268
                        (addr, iface))
 
269
                    return iface
 
270
 
 
271
    msg = "Unable to infer net iface on which '%s' is configured" % (addr)
 
272
    raise Exception(msg)
 
273
 
 
274
 
 
275
def sniff_iface(f):
 
276
    """Ensure decorated function is called with a value for iface.
 
277
 
 
278
    If no iface provided, inject net iface inferred from unit private address.
 
279
    """
 
280
    def iface_sniffer(*args, **kwargs):
 
281
        if not kwargs.get('iface', None):
 
282
            kwargs['iface'] = get_iface_from_addr(unit_get('private-address'))
 
283
 
 
284
        return f(*args, **kwargs)
 
285
 
 
286
    return iface_sniffer
 
287
 
 
288
 
 
289
@sniff_iface
 
290
def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None,
 
291
                  dynamic_only=True):
 
292
    """Get assigned IPv6 address for a given interface.
 
293
 
 
294
    Returns list of addresses found. If no address found, returns empty list.
 
295
 
 
296
    If iface is None, we infer the current primary interface by doing a reverse
 
297
    lookup on the unit private-address.
 
298
 
 
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.
 
302
    """
 
303
    addresses = get_iface_addr(iface=iface, inet_type='AF_INET6',
 
304
                               inc_aliases=inc_aliases, fatal=fatal,
 
305
                               exc_list=exc_list)
 
306
 
 
307
    if addresses:
 
308
        global_addrs = []
 
309
        for addr in addresses:
 
310
            key_scope_link_local = re.compile("^fe80::..(.+)%(.+)")
 
311
            m = re.match(key_scope_link_local, addr)
 
312
            if m:
 
313
                eui_64_mac = m.group(1)
 
314
                iface = m.group(2)
 
315
            else:
 
316
                global_addrs.append(addr)
 
317
 
 
318
        if global_addrs:
 
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')
 
322
            if dynamic_only:
 
323
                key = re.compile("inet6 (.+)/[0-9]+ scope global dynamic.*")
 
324
            else:
 
325
                key = re.compile("inet6 (.+)/[0-9]+ scope global.*")
 
326
 
 
327
            addrs = []
 
328
            for line in out.split('\n'):
 
329
                line = line.strip()
 
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):
 
337
                                addrs.append(addr)
 
338
 
 
339
            if addrs:
 
340
                return addrs
 
341
 
 
342
    if fatal:
 
343
        raise Exception("Interface '%s' does not have a scope global "
 
344
                        "non-temporary ipv6 address." % iface)
 
345
 
 
346
    return []
 
347
 
 
348
 
 
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)]
 
353
 
 
354
 
 
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)]
 
359
 
 
360
 
 
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):
 
365
            return True
 
366
 
 
367
    return False