~openstack-charmers/charms/trusty/glance-simplestreams-sync/next

« back to all changes in this revision

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

[freyes,r=billy-olsen]

Refactor config-changed hook to ensure that cron jobs are installed
properly.

Closes-Bug: #1434356

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
import six
 
21
import socket
 
22
 
 
23
from functools import partial
 
24
 
 
25
from charmhelpers.core.hookenv import unit_get
 
26
from charmhelpers.fetch import apt_install, apt_update
 
27
from charmhelpers.core.hookenv import (
 
28
    log,
 
29
    WARNING,
 
30
)
 
31
 
 
32
try:
 
33
    import netifaces
 
34
except ImportError:
 
35
    apt_update(fatal=True)
 
36
    apt_install('python-netifaces', fatal=True)
 
37
    import netifaces
 
38
 
 
39
try:
 
40
    import netaddr
 
41
except ImportError:
 
42
    apt_update(fatal=True)
 
43
    apt_install('python-netaddr', fatal=True)
 
44
    import netaddr
 
45
 
 
46
 
 
47
def _validate_cidr(network):
 
48
    try:
 
49
        netaddr.IPNetwork(network)
 
50
    except (netaddr.core.AddrFormatError, ValueError):
 
51
        raise ValueError("Network (%s) is not in CIDR presentation format" %
 
52
                         network)
 
53
 
 
54
 
 
55
def no_ip_found_error_out(network):
 
56
    errmsg = ("No IP address found in network: %s" % network)
 
57
    raise ValueError(errmsg)
 
58
 
 
59
 
 
60
def get_address_in_network(network, fallback=None, fatal=False):
 
61
    """Get an IPv4 or IPv6 address within the network from the host.
 
62
 
 
63
    :param network (str): CIDR presentation format. For example,
 
64
        '192.168.1.0/24'.
 
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).
 
68
    """
 
69
    if network is None:
 
70
        if fallback is not None:
 
71
            return fallback
 
72
 
 
73
        if fatal:
 
74
            no_ip_found_error_out(network)
 
75
        else:
 
76
            return None
 
77
 
 
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))
 
86
            if cidr in network:
 
87
                return str(cidr.ip)
 
88
 
 
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'],
 
93
                                                        addr['netmask']))
 
94
                    if cidr in network:
 
95
                        return str(cidr.ip)
 
96
 
 
97
    if fallback is not None:
 
98
        return fallback
 
99
 
 
100
    if fatal:
 
101
        no_ip_found_error_out(network)
 
102
 
 
103
    return None
 
104
 
 
105
 
 
106
def is_ipv6(address):
 
107
    """Determine whether provided address is IPv6 or not."""
 
108
    try:
 
109
        address = netaddr.IPAddress(address)
 
110
    except netaddr.AddrFormatError:
 
111
        # probably a hostname - so not an address at all!
 
112
        return False
 
113
 
 
114
    return address.version == 6
 
115
 
 
116
 
 
117
def is_address_in_network(network, address):
 
118
    """
 
119
    Determine whether the provided address is within a network range.
 
120
 
 
121
    :param network (str): CIDR presentation format. For example,
 
122
        '192.168.1.0/24'.
 
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.
 
126
    """
 
127
    try:
 
128
        network = netaddr.IPNetwork(network)
 
129
    except (netaddr.core.AddrFormatError, ValueError):
 
130
        raise ValueError("Network (%s) is not in CIDR presentation format" %
 
131
                         network)
 
132
 
 
133
    try:
 
134
        address = netaddr.IPAddress(address)
 
135
    except (netaddr.core.AddrFormatError, ValueError):
 
136
        raise ValueError("Address (%s) is not in correct presentation format" %
 
137
                         address)
 
138
 
 
139
    if address in network:
 
140
        return True
 
141
    else:
 
142
        return False
 
143
 
 
144
 
 
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.
 
148
 
 
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.
 
154
    """
 
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))
 
162
            cidr = network.cidr
 
163
            if address in cidr:
 
164
                if key == 'iface':
 
165
                    return iface
 
166
                else:
 
167
                    return addresses[netifaces.AF_INET][0][key]
 
168
 
 
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'],
 
173
                                                           addr['netmask']))
 
174
                    cidr = network.cidr
 
175
                    if address in cidr:
 
176
                        if key == 'iface':
 
177
                            return iface
 
178
                        elif key == 'netmask' and cidr:
 
179
                            return str(cidr).split('/')[1]
 
180
                        else:
 
181
                            return addr[key]
 
182
 
 
183
    return None
 
184
 
 
185
 
 
186
get_iface_for_address = partial(_get_for_address, key='iface')
 
187
 
 
188
 
 
189
get_netmask_for_address = partial(_get_for_address, key='netmask')
 
190
 
 
191
 
 
192
def format_ipv6_addr(address):
 
193
    """If address is IPv6, wrap it in '[]' otherwise return None.
 
194
 
 
195
    This is required by most configuration files when specifying IPv6
 
196
    addresses.
 
197
    """
 
198
    if is_ipv6(address):
 
199
        return "[%s]" % address
 
200
 
 
201
    return None
 
202
 
 
203
 
 
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
 
208
    if '/' in iface:
 
209
        iface = iface.split('/')[-1]
 
210
 
 
211
    if not exc_list:
 
212
        exc_list = []
 
213
 
 
214
    try:
 
215
        inet_num = getattr(netifaces, inet_type)
 
216
    except AttributeError:
 
217
        raise Exception("Unknown inet type '%s'" % str(inet_type))
 
218
 
 
219
    interfaces = netifaces.interfaces()
 
220
    if inc_aliases:
 
221
        ifaces = []
 
222
        for _iface in interfaces:
 
223
            if iface == _iface or _iface.split(':')[0] == iface:
 
224
                ifaces.append(_iface)
 
225
 
 
226
        if fatal and not ifaces:
 
227
            raise Exception("Invalid interface '%s'" % iface)
 
228
 
 
229
        ifaces.sort()
 
230
    else:
 
231
        if iface not in interfaces:
 
232
            if fatal:
 
233
                raise Exception("Interface '%s' not found " % (iface))
 
234
            else:
 
235
                return []
 
236
 
 
237
        else:
 
238
            ifaces = [iface]
 
239
 
 
240
    addresses = []
 
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'])
 
247
 
 
248
    if fatal and not addresses:
 
249
        raise Exception("Interface '%s' doesn't have any %s addresses." %
 
250
                        (iface, inet_type))
 
251
 
 
252
    return sorted(addresses)
 
253
 
 
254
 
 
255
get_ipv4_addr = partial(get_iface_addr, inet_type='AF_INET')
 
256
 
 
257
 
 
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']
 
265
                # link local
 
266
                ll_key = re.compile("(.+)%.*")
 
267
                raw = re.match(ll_key, _addr)
 
268
                if raw:
 
269
                    _addr = raw.group(1)
 
270
 
 
271
                if _addr == addr:
 
272
                    log("Address '%s' is configured on iface '%s'" %
 
273
                        (addr, iface))
 
274
                    return iface
 
275
 
 
276
    msg = "Unable to infer net iface on which '%s' is configured" % (addr)
 
277
    raise Exception(msg)
 
278
 
 
279
 
 
280
def sniff_iface(f):
 
281
    """Ensure decorated function is called with a value for iface.
 
282
 
 
283
    If no iface provided, inject net iface inferred from unit private address.
 
284
    """
 
285
    def iface_sniffer(*args, **kwargs):
 
286
        if not kwargs.get('iface', None):
 
287
            kwargs['iface'] = get_iface_from_addr(unit_get('private-address'))
 
288
 
 
289
        return f(*args, **kwargs)
 
290
 
 
291
    return iface_sniffer
 
292
 
 
293
 
 
294
@sniff_iface
 
295
def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None,
 
296
                  dynamic_only=True):
 
297
    """Get assigned IPv6 address for a given interface.
 
298
 
 
299
    Returns list of addresses found. If no address found, returns empty list.
 
300
 
 
301
    If iface is None, we infer the current primary interface by doing a reverse
 
302
    lookup on the unit private-address.
 
303
 
 
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.
 
307
    """
 
308
    addresses = get_iface_addr(iface=iface, inet_type='AF_INET6',
 
309
                               inc_aliases=inc_aliases, fatal=fatal,
 
310
                               exc_list=exc_list)
 
311
 
 
312
    if addresses:
 
313
        global_addrs = []
 
314
        for addr in addresses:
 
315
            key_scope_link_local = re.compile("^fe80::..(.+)%(.+)")
 
316
            m = re.match(key_scope_link_local, addr)
 
317
            if m:
 
318
                eui_64_mac = m.group(1)
 
319
                iface = m.group(2)
 
320
            else:
 
321
                global_addrs.append(addr)
 
322
 
 
323
        if global_addrs:
 
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')
 
327
            if dynamic_only:
 
328
                key = re.compile("inet6 (.+)/[0-9]+ scope global dynamic.*")
 
329
            else:
 
330
                key = re.compile("inet6 (.+)/[0-9]+ scope global.*")
 
331
 
 
332
            addrs = []
 
333
            for line in out.split('\n'):
 
334
                line = line.strip()
 
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):
 
342
                                addrs.append(addr)
 
343
 
 
344
            if addrs:
 
345
                return addrs
 
346
 
 
347
    if fatal:
 
348
        raise Exception("Interface '%s' does not have a scope global "
 
349
                        "non-temporary ipv6 address." % iface)
 
350
 
 
351
    return []
 
352
 
 
353
 
 
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)]
 
358
 
 
359
 
 
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)]
 
364
 
 
365
 
 
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):
 
370
            return True
 
371
 
 
372
    return False
 
373
 
 
374
 
 
375
def is_ip(address):
 
376
    """
 
377
    Returns True if address is a valid IP address.
 
378
    """
 
379
    try:
 
380
        # Test to see if already an IPv4 address
 
381
        socket.inet_aton(address)
 
382
        return True
 
383
    except socket.error:
 
384
        return False
 
385
 
 
386
 
 
387
def ns_query(address):
 
388
    try:
 
389
        import dns.resolver
 
390
    except ImportError:
 
391
        apt_install('python-dnspython')
 
392
        import dns.resolver
 
393
 
 
394
    if isinstance(address, dns.name.Name):
 
395
        rtype = 'PTR'
 
396
    elif isinstance(address, six.string_types):
 
397
        rtype = 'A'
 
398
    else:
 
399
        return None
 
400
 
 
401
    answers = dns.resolver.query(address, rtype)
 
402
    if answers:
 
403
        return str(answers[0])
 
404
    return None
 
405
 
 
406
 
 
407
def get_host_ip(hostname, fallback=None):
 
408
    """
 
409
    Resolves the IP for a given hostname, or returns
 
410
    the input if it is already an IP.
 
411
    """
 
412
    if is_ip(hostname):
 
413
        return hostname
 
414
 
 
415
    ip_addr = ns_query(hostname)
 
416
    if not ip_addr:
 
417
        try:
 
418
            ip_addr = socket.gethostbyname(hostname)
 
419
        except:
 
420
            log("Failed to resolve hostname '%s'" % (hostname),
 
421
                level=WARNING)
 
422
            return fallback
 
423
    return ip_addr
 
424
 
 
425
 
 
426
def get_hostname(address, fqdn=True):
 
427
    """
 
428
    Resolves hostname for given IP, or returns the input
 
429
    if it is already a hostname.
 
430
    """
 
431
    if is_ip(address):
 
432
        try:
 
433
            import dns.reversename
 
434
        except ImportError:
 
435
            apt_install("python-dnspython")
 
436
            import dns.reversename
 
437
 
 
438
        rev = dns.reversename.from_address(address)
 
439
        result = ns_query(rev)
 
440
 
 
441
        if not result:
 
442
            try:
 
443
                result = socket.gethostbyaddr(address)[0]
 
444
            except:
 
445
                return None
 
446
    else:
 
447
        result = address
 
448
 
 
449
    if fqdn:
 
450
        # strip trailing .
 
451
        if result.endswith('.'):
 
452
            return result[:-1]
 
453
        else:
 
454
            return result
 
455
    else:
 
456
        return result.split('.')[0]