File: models.py

package info (click to toggle)
openstack-trove 2014.1.3-8
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 10,752 kB
  • ctags: 6,663
  • sloc: python: 37,317; xml: 1,485; sh: 281; makefile: 49
file content (280 lines) | stat: -rw-r--r-- 10,537 bytes parent folder | download
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
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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.
#

"""
Model classes for Security Groups and Security Group Rules on instances.
"""
import trove.common.remote
from trove.common import cfg
from trove.common import exception
from trove.db.models import DatabaseModelBase
from trove.common.models import NovaRemoteModelBase
from trove.openstack.common import log as logging
from trove.openstack.common.gettextutils import _

from novaclient import exceptions as nova_exceptions

CONF = cfg.CONF
LOG = logging.getLogger(__name__)


def persisted_models():
    return {
        'security_group': SecurityGroup,
        'security_group_rule': SecurityGroupRule,
        'security_group_instance_association':
        SecurityGroupInstanceAssociation,
    }


class SecurityGroup(DatabaseModelBase):
    _data_fields = ['id', 'name', 'description', 'user', 'tenant_id',
                    'created', 'updated', 'deleted', 'deleted_at']

    @property
    def instance_id(self):
        return SecurityGroupInstanceAssociation\
            .get_instance_id_by_security_group_id(self.id)

    @classmethod
    def create_sec_group(cls, name, description, context):
        try:
            remote_sec_group = RemoteSecurityGroup.create(name,
                                                          description,
                                                          context)

            if not remote_sec_group:
                raise exception.SecurityGroupCreationError(
                    "Failed to create Security Group")
            else:
                return cls.create(
                    id=remote_sec_group.data()['id'],
                    name=name,
                    description=description,
                    user=context.user,
                    tenant_id=context.tenant)

        except exception.SecurityGroupCreationError as e:
            LOG.exception("Failed to create remote security group")
            raise e

    @classmethod
    def create_for_instance(cls, instance_id, context):
        # Create a new security group
        name = "%s_%s" % (CONF.trove_security_group_name_prefix, instance_id)
        description = _("Security Group for %s") % instance_id
        sec_group = cls.create_sec_group(name, description, context)

        # Currently this locked down by default, since we don't create any
        # default security group rules for the security group.

        # Create security group instance association
        SecurityGroupInstanceAssociation.create(
            security_group_id=sec_group["id"],
            instance_id=instance_id)

        return sec_group

    @classmethod
    def get_security_group_by_id_or_instance_id(self, id, tenant_id):
        try:
            return SecurityGroup.find_by(id=id,
                                         tenant_id=tenant_id,
                                         deleted=False)
        except exception.ModelNotFoundError:
            return SecurityGroupInstanceAssociation.\
                get_security_group_by_instance_id(id)

    def get_rules(self):
        return SecurityGroupRule.find_all(group_id=self.id,
                                          deleted=False)

    def delete(self, context):
        try:
            sec_group_rules = self.get_rules()
            if sec_group_rules:
                for rule in sec_group_rules:
                    rule.delete(context)

            RemoteSecurityGroup.delete(self.id, context)
            super(SecurityGroup, self).delete()

        except exception.TroveError:
            LOG.exception('Failed to delete security group')
            raise exception.TroveError("Failed to delete Security Group")

    @classmethod
    def delete_for_instance(cls, instance_id, context):
        try:
            association = SecurityGroupInstanceAssociation.find_by(
                instance_id=instance_id,
                deleted=False)
            if association:
                sec_group = association.get_security_group()
                if sec_group:
                    sec_group.delete(context)
                association.delete()
        except (exception.ModelNotFoundError,
                exception.TroveError):
            LOG.info(_('Security Group with id: %(id)s '
                       'already had been deleted')
                     % {'id': instance_id})


class SecurityGroupRule(DatabaseModelBase):
    _data_fields = ['id', 'parent_group_id', 'protocol', 'from_port',
                    'to_port', 'cidr', 'group_id', 'created', 'updated',
                    'deleted', 'deleted_at']

    @classmethod
    def create_sec_group_rule(cls, sec_group, protocol, from_port,
                              to_port, cidr, context):
        try:
            remote_rule_id = RemoteSecurityGroup.add_rule(
                sec_group_id=sec_group['id'],
                protocol=protocol,
                from_port=from_port,
                to_port=to_port,
                cidr=cidr,
                context=context)

            if not remote_rule_id:
                raise exception.SecurityGroupRuleCreationError(
                    "Failed to create Security Group Rule")
            else:
                # Create db record
                return cls.create(
                    id=remote_rule_id,
                    protocol=protocol,
                    from_port=from_port,
                    to_port=to_port,
                    cidr=cidr,
                    group_id=sec_group['id'])

        except exception.SecurityGroupRuleCreationError as e:
            LOG.exception("Failed to create remote security group")
            raise e

    def get_security_group(self, tenant_id):
        return SecurityGroup.find_by(id=self.group_id,
                                     tenant_id=tenant_id,
                                     deleted=False)

    def delete(self, context):
        try:
            # Delete Remote Security Group Rule
            RemoteSecurityGroup.delete_rule(self.id, context)
            super(SecurityGroupRule, self).delete()
        except exception.TroveError:
            LOG.exception('Failed to delete security group')
            raise exception.SecurityGroupRuleDeletionError(
                "Failed to delete Security Group")


class SecurityGroupInstanceAssociation(DatabaseModelBase):
    _data_fields = ['id', 'security_group_id', 'instance_id',
                    'created', 'updated', 'deleted', 'deleted_at']

    def get_security_group(self):
        return SecurityGroup.find_by(id=self.security_group_id,
                                     deleted=False)

    @classmethod
    def get_security_group_by_instance_id(cls, id):
        association = SecurityGroupInstanceAssociation.find_by(
            instance_id=id,
            deleted=False)
        return association.get_security_group()

    @classmethod
    def get_instance_id_by_security_group_id(cls, secgroup_id):
        association = SecurityGroupInstanceAssociation.find_by(
            security_group_id=secgroup_id,
            deleted=False)
        return association.instance_id


class RemoteSecurityGroup(NovaRemoteModelBase):

    _data_fields = ['id', 'name', 'description', 'rules']

    def __init__(self, security_group=None, id=None, context=None):
        if id is None and security_group is None:
            msg = "Security Group does not have id defined!"
            raise exception.InvalidModelError(msg)
        elif security_group is None:
            try:
                client = trove.common.remote.create_nova_client(context)
                self._data_object = client.security_groups.get(id)
            except nova_exceptions.NotFound as e:
                raise exception.NotFound(id=id)
            except nova_exceptions.ClientException as e:
                raise exception.TroveError(str(e))
        else:
            self._data_object = security_group

    @classmethod
    def create(cls, name, description, context):
        """Creates a new Security Group"""
        client = trove.common.remote.create_nova_client(context)
        try:
            sec_group = client.security_groups.create(name=name,
                                                      description=description)
        except nova_exceptions.ClientException as e:
            LOG.exception('Failed to create remote security group')
            raise exception.SecurityGroupCreationError(str(e))

        return RemoteSecurityGroup(security_group=sec_group)

    @classmethod
    def delete(cls, sec_group_id, context):
        client = trove.common.remote.create_nova_client(context)

        try:
            client.security_groups.delete(sec_group_id)
        except nova_exceptions.ClientException as e:
            LOG.exception('Failed to delete remote security group')
            raise exception.SecurityGroupDeletionError(str(e))

    @classmethod
    def add_rule(cls, sec_group_id, protocol, from_port,
                 to_port, cidr, context):

        client = trove.common.remote.create_nova_client(context)

        try:
            sec_group_rule = client.security_group_rules.create(
                parent_group_id=sec_group_id,
                ip_protocol=protocol,
                from_port=from_port,
                to_port=to_port,
                cidr=cidr)

            return sec_group_rule.id
        except nova_exceptions.ClientException as e:
            LOG.exception('Failed to add rule to remote security group')
            raise exception.SecurityGroupRuleCreationError(str(e))

    @classmethod
    def delete_rule(cls, sec_group_rule_id, context):
        client = trove.common.remote.create_nova_client(context)

        try:
            client.security_group_rules.delete(sec_group_rule_id)

        except nova_exceptions.ClientException as e:
            LOG.exception('Failed to delete rule to remote security group')
            raise exception.SecurityGroupRuleDeletionError(str(e))