~brad-marshall/charms/trusty/apache2-wsgi/fix-haproxy-relations

« back to all changes in this revision

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

  • Committer: Robin Winslow
  • Date: 2014-05-27 14:00:44 UTC
  • Revision ID: robin.winslow@canonical.com-20140527140044-8rpmb3wx4djzwa83
Add all files

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import sys
 
2
 
 
3
from charmhelpers.fetch import apt_install
 
4
from charmhelpers.core.hookenv import (
 
5
    ERROR, log,
 
6
)
 
7
 
 
8
try:
 
9
    import netifaces
 
10
except ImportError:
 
11
    apt_install('python-netifaces')
 
12
    import netifaces
 
13
 
 
14
try:
 
15
    import netaddr
 
16
except ImportError:
 
17
    apt_install('python-netaddr')
 
18
    import netaddr
 
19
 
 
20
 
 
21
def _validate_cidr(network):
 
22
    try:
 
23
        netaddr.IPNetwork(network)
 
24
    except (netaddr.core.AddrFormatError, ValueError):
 
25
        raise ValueError("Network (%s) is not in CIDR presentation format" %
 
26
                         network)
 
27
 
 
28
 
 
29
def get_address_in_network(network, fallback=None, fatal=False):
 
30
    """
 
31
    Get an IPv4 address within the network from the host.
 
32
 
 
33
    Args:
 
34
        network (str): CIDR presentation format. For example,
 
35
                       '192.168.1.0/24'.
 
36
        fallback (str): If no address is found, return fallback.
 
37
        fatal (boolean): If no address is found, fallback is not
 
38
                         set and fatal is True then exit(1).
 
39
    """
 
40
 
 
41
    def not_found_error_out():
 
42
        log("No IP address found in network: %s" % network,
 
43
            level=ERROR)
 
44
        sys.exit(1)
 
45
 
 
46
    if network is None:
 
47
        if fallback is not None:
 
48
            return fallback
 
49
        else:
 
50
            if fatal:
 
51
                not_found_error_out()
 
52
 
 
53
    _validate_cidr(network)
 
54
    for iface in netifaces.interfaces():
 
55
        addresses = netifaces.ifaddresses(iface)
 
56
        if netifaces.AF_INET in addresses:
 
57
            addr = addresses[netifaces.AF_INET][0]['addr']
 
58
            netmask = addresses[netifaces.AF_INET][0]['netmask']
 
59
            cidr = netaddr.IPNetwork("%s/%s" % (addr, netmask))
 
60
            if cidr in netaddr.IPNetwork(network):
 
61
                return str(cidr.ip)
 
62
 
 
63
    if fallback is not None:
 
64
        return fallback
 
65
 
 
66
    if fatal:
 
67
        not_found_error_out()
 
68
 
 
69
    return None