summaryrefslogtreecommitdiffstats
path: root/snaps/openstack/create_security_group.py
blob: 52ea9dc894839512b03b06aad1ab7ed349590980 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
#                    and others.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging

import enum
from neutronclient.common.exceptions import NotFound, Conflict

from snaps.config.security_group import (
    SecurityGroupConfig, SecurityGroupRuleConfig)
from snaps.openstack.openstack_creator import OpenStackNetworkObject
from snaps.openstack.utils import keystone_utils
from snaps.openstack.utils import neutron_utils

__author__ = 'spisarski'

logger = logging.getLogger('OpenStackSecurityGroup')


class OpenStackSecurityGroup(OpenStackNetworkObject):
    """
    Class responsible for managing a Security Group in OpenStack
    """

    def __init__(self, os_creds, sec_grp_settings):
        """
        Constructor - all parameters are required
        :param os_creds: The credentials to connect with OpenStack
        :param sec_grp_settings: The settings used to create a security group
        """
        super(self.__class__, self).__init__(os_creds)

        self.sec_grp_settings = sec_grp_settings

        # Attributes instantiated on create()
        self.__security_group = None

        # dict where the rule settings object is the key
        self.__rules = dict()

    def initialize(self):
        """
        Loads existing security group.
        :return: the security group domain object
        """
        super(self.__class__, self).initialize()

        self.__security_group = neutron_utils.get_security_group(
            self._neutron, sec_grp_settings=self.sec_grp_settings,
            project_id=self.project_id)
        if self.__security_group:
            # Populate rules
            existing_rules = neutron_utils.get_rules_by_security_group(
                self._neutron, self.__security_group)

            for existing_rule in existing_rules:
                # For Custom Rules
                rule_setting = self.__get_setting_from_rule(existing_rule)
                self.__rules[rule_setting] = existing_rule

            self.__security_group = neutron_utils.get_security_group_by_id(
                self._neutron, self.__security_group.id)

        return self.__security_group

    def create(self):
        """
        Responsible for creating the security group.
        :return: the security group domain object
        """
        self.initialize()

        if not self.__security_group:
            logger.info(
                'Creating security group %s...' % self.sec_grp_settings.name)

            keystone = keystone_utils.keystone_client(self._os_creds)
            self.__security_group = neutron_utils.create_security_group(
                self._neutron, keystone, self.sec_grp_settings,
                project_id=self.project_id)

            # Get the rules added for free
            auto_rules = neutron_utils.get_rules_by_security_group(
                self._neutron, self.__security_group)

            ctr = 0
            for auto_rule in auto_rules:
                auto_rule_setting = self.__generate_rule_setting(auto_rule)
                self.__rules[auto_rule_setting] = auto_rule
                ctr += 1

            # Create the custom rules
            for sec_grp_rule_setting in self.sec_grp_settings.rule_settings:
                try:
                    custom_rule = neutron_utils.create_security_group_rule(
                        self._neutron, sec_grp_rule_setting, self.project_id)
                    self.__rules[sec_grp_rule_setting] = custom_rule
                except Conflict as e:
                    logger.warn('Unable to create rule due to conflict - %s',
                                e)

            # Refresh security group object to reflect the new rules added
            self.__security_group = neutron_utils.get_security_group_by_id(
                self._neutron, self.__security_group.id)

        return self.__security_group

    def __generate_rule_setting(self, rule):
        """
        Creates a SecurityGroupRuleConfig object for a given rule
        :param rule: the rule from which to create the
                    SecurityGroupRuleConfig object
        :return: the newly instantiated SecurityGroupRuleConfig object
        """
        sec_grp = neutron_utils.get_security_group_by_id(
            self._neutron, rule.security_group_id)

        setting = SecurityGroupRuleConfig(
            description=rule.description,
            direction=rule.direction,
            ethertype=rule.ethertype,
            port_range_min=rule.port_range_min,
            port_range_max=rule.port_range_max,
            protocol=rule.protocol,
            remote_group_id=rule.remote_group_id,
            remote_ip_prefix=rule.remote_ip_prefix,
            sec_grp_name=sec_grp.name)
        return setting

    def clean(self):
        """
        Removes and deletes the rules then the security group.
        """
        for setting, rule in self.__rules.items():
            try:
                neutron_utils.delete_security_group_rule(self._neutron, rule)
            except NotFound as e:
                logger.warning('Rule not found, cannot delete - ' + str(e))
                pass
        self.__rules = dict()

        if self.__security_group:
            try:
                neutron_utils.delete_security_group(self._neutron,
                                                    self.__security_group)
            except NotFound as e:
                logger.warning(
                    'Security Group not found, cannot delete - ' + str(e))

            self.__security_group = None

    def get_security_group(self):
        """
        Returns the OpenStack security group object
        :return:
        """
        return self.__security_group

    def get_rules(self):
        """
        Returns the associated rules
        :return:
        """
        return self.__rules

    def add_rule(self, rule_setting):
        """
        Adds a rule to this security group
        :param rule_setting: the rule configuration
        """
        rule_setting.sec_grp_name = self.sec_grp_settings.name
        new_rule = neutron_utils.create_security_group_rule(
            self._neutron, rule_setting, self.project_id)
        self.__rules[rule_setting] = new_rule
        self.sec_grp_settings.rule_settings.append(rule_setting)

    def remove_rule(self, rule_id=None, rule_setting=None):
        """
        Removes a rule to this security group by id, name, or rule_setting
        object
        :param rule_id: the rule's id
        :param rule_setting: the rule's setting object
        """
        rule_to_remove = None
        if rule_id or rule_setting:
            if rule_id:
                rule_to_remove = neutron_utils.get_rule_by_id(
                    self._neutron, self.__security_group, rule_id)
            elif rule_setting:
                rule_to_remove = self.__rules.get(rule_setting)

        if rule_to_remove:
            neutron_utils.delete_security_group_rule(self._neutron,
                                                     rule_to_remove)
            rule_setting = self.__get_setting_from_rule(rule_to_remove)
            if rule_setting:
                self.__rules.pop(rule_setting)
            else:
                logger.warning('Rule setting is None, cannot remove rule')

    def __get_setting_from_rule(self, rule):
        """
        Returns the associated RuleSetting object for a given rule
        :param rule: the Rule object
        :return: the associated RuleSetting object or None
        """
        for rule_setting in self.sec_grp_settings.rule_settings:
            if rule_setting.rule_eq(rule):
                return rule_setting
        return None


class SecurityGroupSettings(SecurityGroupConfig):
    """
    Class to hold the configuration settings required for creating OpenStack
    SecurityGroup objects
    deprecated - use snaps.config.security_group.SecurityGroupConfig instead
    """

    def __init__(self, **kwargs):
        from warnings import warn
        warn('Use snaps.config.security_group.SecurityGroupConfig instead',
             DeprecationWarning)
        super(self.__class__, self).__init__(**kwargs)


class Direction(enum.Enum):
    """
    A rule's direction
    deprecated - use snaps.config.security_group.Direction
    """
    ingress = 'ingress'
    egress = 'egress'


class Protocol(enum.Enum):
    """
    A rule's protocol
    deprecated - use snaps.config.security_group.Protocol
    """
    ah = 51
    dccp = 33
    egp = 8
    esp = 50
    gre = 47
    icmp = 1
    icmpv6 = 58
    igmp = 2
    ipv6_encap = 41
    ipv6_frag = 44
    ipv6_icmp = 58
    ipv6_nonxt = 59
    ipv6_opts = 60
    ipv6_route = 43
    ospf = 89
    pgm = 113
    rsvp = 46
    sctp = 132
    tcp = 6
    udp = 17
    udplite = 136
    vrrp = 112
    any = 'any'
    null = 'null'


class Ethertype(enum.Enum):
    """
    A rule's ethertype
    deprecated - use snaps.config.security_group.Ethertype
    """
    IPv4 = 4
    IPv6 = 6


class SecurityGroupRuleSettings(SecurityGroupRuleConfig):
    """
    Class to hold the configuration settings required for creating OpenStack
    SecurityGroupRule objects
    deprecated - use snaps.config.security_group.SecurityGroupRuleConfig
    instead
    """

    def __init__(self, **kwargs):
        from warnings import warn
        warn('Use snaps.config.security_group.SecurityGroupRuleConfig instead',
             DeprecationWarning)
        super(self.__class__, self).__init__(**kwargs)