~hopem/charms/trusty/glance/charm-helpers-sync-precise-ipv6-haproxy

« back to all changes in this revision

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

  • Committer: james.page at ubuntu
  • Date: 2014-12-15 09:17:53 UTC
  • mfrom: (82.1.8 glance)
  • Revision ID: james.page@ubuntu.com-20141215091753-23bixw725p75pcdp
[corey.bryant,r=james-page] Sort out charmhelpers issues.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
import glob
2
2
import re
3
3
import subprocess
4
 
import sys
5
4
 
6
5
from functools import partial
7
6
 
8
7
from charmhelpers.core.hookenv import unit_get
9
8
from charmhelpers.fetch import apt_install
10
9
from charmhelpers.core.hookenv import (
11
 
    ERROR,
12
10
    log
13
11
)
14
12
 
33
31
                         network)
34
32
 
35
33
 
 
34
def no_ip_found_error_out(network):
 
35
    errmsg = ("No IP address found in network: %s" % network)
 
36
    raise ValueError(errmsg)
 
37
 
 
38
 
36
39
def get_address_in_network(network, fallback=None, fatal=False):
37
 
    """
38
 
    Get an IPv4 or IPv6 address within the network from the host.
 
40
    """Get an IPv4 or IPv6 address within the network from the host.
39
41
 
40
42
    :param network (str): CIDR presentation format. For example,
41
43
        '192.168.1.0/24'.
42
44
    :param fallback (str): If no address is found, return fallback.
43
45
    :param fatal (boolean): If no address is found, fallback is not
44
46
        set and fatal is True then exit(1).
45
 
 
46
47
    """
47
 
 
48
 
    def not_found_error_out():
49
 
        log("No IP address found in network: %s" % network,
50
 
            level=ERROR)
51
 
        sys.exit(1)
52
 
 
53
48
    if network is None:
54
49
        if fallback is not None:
55
50
            return fallback
 
51
 
 
52
        if fatal:
 
53
            no_ip_found_error_out(network)
56
54
        else:
57
 
            if fatal:
58
 
                not_found_error_out()
59
 
            else:
60
 
                return None
 
55
            return None
61
56
 
62
57
    _validate_cidr(network)
63
58
    network = netaddr.IPNetwork(network)
69
64
            cidr = netaddr.IPNetwork("%s/%s" % (addr, netmask))
70
65
            if cidr in network:
71
66
                return str(cidr.ip)
 
67
 
72
68
        if network.version == 6 and netifaces.AF_INET6 in addresses:
73
69
            for addr in addresses[netifaces.AF_INET6]:
74
70
                if not addr['addr'].startswith('fe80'):
81
77
        return fallback
82
78
 
83
79
    if fatal:
84
 
        not_found_error_out()
 
80
        no_ip_found_error_out(network)
85
81
 
86
82
    return None
87
83
 
88
84
 
89
85
def is_ipv6(address):
90
 
    '''Determine whether provided address is IPv6 or not'''
 
86
    """Determine whether provided address is IPv6 or not."""
91
87
    try:
92
88
        address = netaddr.IPAddress(address)
93
89
    except netaddr.AddrFormatError:
94
90
        # probably a hostname - so not an address at all!
95
91
        return False
96
 
    else:
97
 
        return address.version == 6
 
92
 
 
93
    return address.version == 6
98
94
 
99
95
 
100
96
def is_address_in_network(network, address):
112
108
    except (netaddr.core.AddrFormatError, ValueError):
113
109
        raise ValueError("Network (%s) is not in CIDR presentation format" %
114
110
                         network)
 
111
 
115
112
    try:
116
113
        address = netaddr.IPAddress(address)
117
114
    except (netaddr.core.AddrFormatError, ValueError):
118
115
        raise ValueError("Address (%s) is not in correct presentation format" %
119
116
                         address)
 
117
 
120
118
    if address in network:
121
119
        return True
122
120
    else:
146
144
                    return iface
147
145
                else:
148
146
                    return addresses[netifaces.AF_INET][0][key]
 
147
 
149
148
        if address.version == 6 and netifaces.AF_INET6 in addresses:
150
149
            for addr in addresses[netifaces.AF_INET6]:
151
150
                if not addr['addr'].startswith('fe80'):
159
158
                            return str(cidr).split('/')[1]
160
159
                        else:
161
160
                            return addr[key]
 
161
 
162
162
    return None
163
163
 
164
164
 
165
165
get_iface_for_address = partial(_get_for_address, key='iface')
166
166
 
 
167
 
167
168
get_netmask_for_address = partial(_get_for_address, key='netmask')
168
169
 
169
170
 
170
171
def format_ipv6_addr(address):
171
 
    """
172
 
    IPv6 needs to be wrapped with [] in url link to parse correctly.
 
172
    """If address is IPv6, wrap it in '[]' otherwise return None.
 
173
 
 
174
    This is required by most configuration files when specifying IPv6
 
175
    addresses.
173
176
    """
174
177
    if is_ipv6(address):
175
 
        address = "[%s]" % address
176
 
    else:
177
 
        address = None
 
178
        return "[%s]" % address
178
179
 
179
 
    return address
 
180
    return None
180
181
 
181
182
 
182
183
def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False,
183
184
                   fatal=True, exc_list=None):
184
 
    """
185
 
    Return the assigned IP address for a given interface, if any, or [].
186
 
    """
 
185
    """Return the assigned IP address for a given interface, if any."""
187
186
    # Extract nic if passed /dev/ethX
188
187
    if '/' in iface:
189
188
        iface = iface.split('/')[-1]
 
189
 
190
190
    if not exc_list:
191
191
        exc_list = []
 
192
 
192
193
    try:
193
194
        inet_num = getattr(netifaces, inet_type)
194
195
    except AttributeError:
195
 
        raise Exception('Unknown inet type ' + str(inet_type))
 
196
        raise Exception("Unknown inet type '%s'" % str(inet_type))
196
197
 
197
198
    interfaces = netifaces.interfaces()
198
199
    if inc_aliases:
200
201
        for _iface in interfaces:
201
202
            if iface == _iface or _iface.split(':')[0] == iface:
202
203
                ifaces.append(_iface)
 
204
 
203
205
        if fatal and not ifaces:
204
206
            raise Exception("Invalid interface '%s'" % iface)
 
207
 
205
208
        ifaces.sort()
206
209
    else:
207
210
        if iface not in interfaces:
208
211
            if fatal:
209
 
                raise Exception("%s not found " % (iface))
 
212
                raise Exception("Interface '%s' not found " % (iface))
210
213
            else:
211
214
                return []
 
215
 
212
216
        else:
213
217
            ifaces = [iface]
214
218
 
219
223
            for entry in net_info[inet_num]:
220
224
                if 'addr' in entry and entry['addr'] not in exc_list:
221
225
                    addresses.append(entry['addr'])
 
226
 
222
227
    if fatal and not addresses:
223
228
        raise Exception("Interface '%s' doesn't have any %s addresses." %
224
229
                        (iface, inet_type))
225
 
    return addresses
 
230
 
 
231
    return sorted(addresses)
 
232
 
226
233
 
227
234
get_ipv4_addr = partial(get_iface_addr, inet_type='AF_INET')
228
235
 
239
246
                raw = re.match(ll_key, _addr)
240
247
                if raw:
241
248
                    _addr = raw.group(1)
 
249
 
242
250
                if _addr == addr:
243
251
                    log("Address '%s' is configured on iface '%s'" %
244
252
                        (addr, iface))
249
257
 
250
258
 
251
259
def sniff_iface(f):
252
 
    """If no iface provided, inject net iface inferred from unit private
253
 
    address.
 
260
    """Ensure decorated function is called with a value for iface.
 
261
 
 
262
    If no iface provided, inject net iface inferred from unit private address.
254
263
    """
255
264
    def iface_sniffer(*args, **kwargs):
256
265
        if not kwargs.get('iface', None):
293
302
        if global_addrs:
294
303
            # Make sure any found global addresses are not temporary
295
304
            cmd = ['ip', 'addr', 'show', iface]
296
 
            out = subprocess.check_output(cmd)
 
305
            out = subprocess.check_output(cmd).decode('UTF-8')
297
306
            if dynamic_only:
298
307
                key = re.compile("inet6 (.+)/[0-9]+ scope global dynamic.*")
299
308
            else:
315
324
                return addrs
316
325
 
317
326
    if fatal:
318
 
        raise Exception("Interface '%s' doesn't have a scope global "
 
327
        raise Exception("Interface '%s' does not have a scope global "
319
328
                        "non-temporary ipv6 address." % iface)
320
329
 
321
330
    return []
322
331
 
323
332
 
324
333
def get_bridges(vnic_dir='/sys/devices/virtual/net'):
325
 
    """
326
 
    Return a list of bridges on the system or []
327
 
    """
328
 
    b_rgex = vnic_dir + '/*/bridge'
329
 
    return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_rgex)]
 
334
    """Return a list of bridges on the system."""
 
335
    b_regex = "%s/*/bridge" % vnic_dir
 
336
    return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)]
330
337
 
331
338
 
332
339
def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'):
333
 
    """
334
 
    Return a list of nics comprising a given bridge on the system or []
335
 
    """
336
 
    brif_rgex = "%s/%s/brif/*" % (vnic_dir, bridge)
337
 
    return [x.split('/')[-1] for x in glob.glob(brif_rgex)]
 
340
    """Return a list of nics comprising a given bridge on the system."""
 
341
    brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge)
 
342
    return [x.split('/')[-1] for x in glob.glob(brif_regex)]
338
343
 
339
344
 
340
345
def is_bridge_member(nic):
341
 
    """
342
 
    Check if a given nic is a member of a bridge
343
 
    """
 
346
    """Check if a given nic is a member of a bridge."""
344
347
    for bridge in get_bridges():
345
348
        if nic in get_bridge_nics(bridge):
346
349
            return True
 
350
 
347
351
    return False