~openstack-charmers/charms/trusty/quantum-gateway/next

« back to all changes in this revision

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

  • Committer: Edward Hope-Morley
  • Date: 2015-02-11 18:40:18 UTC
  • mfrom: (85.1.1 quantum-gateway)
  • Revision ID: edward.hope-morley@canonical.com-20150211184018-3s2ah3b5j95jk43j
[trivial] synced charm-helpers

Show diffs side-by-side

added added

removed removed

Lines of Context:
46
46
from charmhelpers.core import hookenv
47
47
 
48
48
 
 
49
class UFWError(Exception):
 
50
    pass
 
51
 
 
52
 
49
53
def is_enabled():
50
54
    """
51
55
    Check if `ufw` is enabled
53
57
    :returns: True if ufw is enabled
54
58
    """
55
59
    output = subprocess.check_output(['ufw', 'status'],
 
60
                                     universal_newlines=True,
56
61
                                     env={'LANG': 'en_US',
57
62
                                          'PATH': os.environ['PATH']})
58
63
 
61
66
    return len(m) >= 1
62
67
 
63
68
 
 
69
def is_ipv6_ok():
 
70
    """
 
71
    Check if IPv6 support is present and ip6tables functional
 
72
 
 
73
    :returns: True if IPv6 is working, False otherwise
 
74
    """
 
75
 
 
76
    # do we have IPv6 in the machine?
 
77
    if os.path.isdir('/proc/sys/net/ipv6'):
 
78
        # is ip6tables kernel module loaded?
 
79
        lsmod = subprocess.check_output(['lsmod'], universal_newlines=True)
 
80
        matches = re.findall('^ip6_tables[ ]+', lsmod, re.M)
 
81
        if len(matches) == 0:
 
82
            # ip6tables support isn't complete, let's try to load it
 
83
            try:
 
84
                subprocess.check_output(['modprobe', 'ip6_tables'],
 
85
                                        universal_newlines=True)
 
86
                # great, we could load the module
 
87
                return True
 
88
            except subprocess.CalledProcessError as ex:
 
89
                hookenv.log("Couldn't load ip6_tables module: %s" % ex.output,
 
90
                            level="WARN")
 
91
                # we are in a world where ip6tables isn't working
 
92
                # so we inform that the machine doesn't have IPv6
 
93
                return False
 
94
        else:
 
95
            # the module is present :)
 
96
            return True
 
97
 
 
98
    else:
 
99
        # the system doesn't have IPv6
 
100
        return False
 
101
 
 
102
 
 
103
def disable_ipv6():
 
104
    """
 
105
    Disable ufw IPv6 support in /etc/default/ufw
 
106
    """
 
107
    exit_code = subprocess.call(['sed', '-i', 's/IPV6=.*/IPV6=no/g',
 
108
                                 '/etc/default/ufw'])
 
109
    if exit_code == 0:
 
110
        hookenv.log('IPv6 support in ufw disabled', level='INFO')
 
111
    else:
 
112
        hookenv.log("Couldn't disable IPv6 support in ufw", level="ERROR")
 
113
        raise UFWError("Couldn't disable IPv6 support in ufw")
 
114
 
 
115
 
64
116
def enable():
65
117
    """
66
118
    Enable ufw
70
122
    if is_enabled():
71
123
        return True
72
124
 
73
 
    if not os.path.isdir('/proc/sys/net/ipv6'):
74
 
        # disable IPv6 support in ufw
75
 
        hookenv.log("This machine doesn't have IPv6 enabled", level="INFO")
76
 
        exit_code = subprocess.call(['sed', '-i', 's/IPV6=yes/IPV6=no/g',
77
 
                                     '/etc/default/ufw'])
78
 
        if exit_code == 0:
79
 
            hookenv.log('IPv6 support in ufw disabled', level='INFO')
80
 
        else:
81
 
            hookenv.log("Couldn't disable IPv6 support in ufw", level="ERROR")
82
 
            raise Exception("Couldn't disable IPv6 support in ufw")
 
125
    if not is_ipv6_ok():
 
126
        disable_ipv6()
83
127
 
84
128
    output = subprocess.check_output(['ufw', 'enable'],
 
129
                                     universal_newlines=True,
85
130
                                     env={'LANG': 'en_US',
86
131
                                          'PATH': os.environ['PATH']})
87
132
 
107
152
        return True
108
153
 
109
154
    output = subprocess.check_output(['ufw', 'disable'],
 
155
                                     universal_newlines=True,
110
156
                                     env={'LANG': 'en_US',
111
157
                                          'PATH': os.environ['PATH']})
112
158
 
151
197
        cmd += ['to', dst]
152
198
 
153
199
    if port is not None:
154
 
        cmd += ['port', port]
 
200
        cmd += ['port', str(port)]
155
201
 
156
202
    if proto is not None:
157
203
        cmd += ['proto', proto]
208
254
    :param action: `open` or `close`
209
255
    """
210
256
    if action == 'open':
211
 
        subprocess.check_output(['ufw', 'allow', name])
 
257
        subprocess.check_output(['ufw', 'allow', str(name)],
 
258
                                universal_newlines=True)
212
259
    elif action == 'close':
213
 
        subprocess.check_output(['ufw', 'delete', 'allow', name])
 
260
        subprocess.check_output(['ufw', 'delete', 'allow', str(name)],
 
261
                                universal_newlines=True)
214
262
    else:
215
 
        raise Exception(("'{}' not supported, use 'allow' "
216
 
                         "or 'delete'").format(action))
 
263
        raise UFWError(("'{}' not supported, use 'allow' "
 
264
                        "or 'delete'").format(action))