summaryrefslogtreecommitdiff
path: root/nova/objects/instance_group.py
blob: f9fc7c7d45a6c4347f55967af14717072c2a52ee (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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# Copyright (c) 2013 OpenStack Foundation
#
#    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 copy

from oslo_db import exception as db_exc
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import uuidutils
from oslo_utils import versionutils
from sqlalchemy import orm

from nova.compute import utils as compute_utils
from nova.db.api import api as api_db_api
from nova.db.api import models as api_models
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields


LAZY_LOAD_FIELDS = ['hosts']
LOG = logging.getLogger(__name__)


def _instance_group_get_query(context, id_field=None, id=None):
    query = context.session.query(api_models.InstanceGroup).\
        options(orm.joinedload(api_models.InstanceGroup._policies)).\
        options(orm.joinedload(api_models.InstanceGroup._members))
    if not context.is_admin:
        query = query.filter_by(project_id=context.project_id)
    if id and id_field:
        query = query.filter(id_field == id)
    return query


def _instance_group_model_get_query(context, model_class, group_id):
    return context.session.query(model_class).filter_by(group_id=group_id)


def _instance_group_model_add(context, model_class, items, item_models, field,
                              group_id, append_to_models=None):
    models = []
    already_existing = set()
    for db_item in item_models:
        already_existing.add(getattr(db_item, field))
        models.append(db_item)
    for item in items:
        if item in already_existing:
            continue
        model = model_class()
        values = {'group_id': group_id}
        values[field] = item
        model.update(values)
        context.session.add(model)
        if append_to_models:
            append_to_models.append(model)
        models.append(model)
    return models


def _instance_group_members_add(context, group, members):
    query = _instance_group_model_get_query(context,
                                            api_models.InstanceGroupMember,
                                            group.id)
    query = query.filter(
                api_models.InstanceGroupMember.instance_uuid.in_(set(members)))
    return _instance_group_model_add(context, api_models.InstanceGroupMember,
                                     members, query.all(), 'instance_uuid',
                                     group.id, append_to_models=group._members)


def _instance_group_members_add_by_uuid(context, group_uuid, members):
    # NOTE(melwitt): The condition on the join limits the number of members
    # returned to only those we wish to check as already existing.
    group = context.session.query(api_models.InstanceGroup).outerjoin(
        api_models.InstanceGroupMember,
        api_models.InstanceGroupMember.instance_uuid.in_(set(members))
    ).filter(
        api_models.InstanceGroup.uuid == group_uuid
    ).options(orm.contains_eager(api_models.InstanceGroup._members)).first()
    if not group:
        raise exception.InstanceGroupNotFound(group_uuid=group_uuid)
    return _instance_group_model_add(
        context,
        api_models.InstanceGroupMember,
        members,
        group._members,
        'instance_uuid',
        group.id,
    )


# TODO(berrange): Remove NovaObjectDictCompat
# TODO(mriedem): Replace NovaPersistentObject with TimestampedObject in v2.0.
@base.NovaObjectRegistry.register
class InstanceGroup(base.NovaPersistentObject, base.NovaObject,
                    base.NovaObjectDictCompat):
    # Version 1.0: Initial version
    # Version 1.1: String attributes updated to support unicode
    # Version 1.2: Use list/dict helpers for policies, metadetails, members
    # Version 1.3: Make uuid a non-None real string
    # Version 1.4: Add add_members()
    # Version 1.5: Add get_hosts()
    # Version 1.6: Add get_by_name()
    # Version 1.7: Deprecate metadetails
    # Version 1.8: Add count_members_by_user()
    # Version 1.9: Add get_by_instance_uuid()
    # Version 1.10: Add hosts field
    # Version 1.11: Add policy and deprecate policies, add _rules
    VERSION = '1.11'

    fields = {
        'id': fields.IntegerField(),

        'user_id': fields.StringField(nullable=True),
        'project_id': fields.StringField(nullable=True),

        'uuid': fields.UUIDField(),
        'name': fields.StringField(nullable=True),

        'policies': fields.ListOfStringsField(nullable=True, read_only=True),
        'members': fields.ListOfStringsField(nullable=True),
        'hosts': fields.ListOfStringsField(nullable=True),
        'policy': fields.StringField(nullable=True),
        # NOTE(danms): Use rules not _rules for general access
        '_rules': fields.DictOfStringsField(),
        }

    def __init__(self, *args, **kwargs):
        if 'rules' in kwargs:
            kwargs['_rules'] = kwargs.pop('rules')
        super(InstanceGroup, self).__init__(*args, **kwargs)

    @property
    def rules(self):
        if '_rules' not in self:
            return {}
        # NOTE(danms): Coerce our rules into a typed dict for convenience
        rules = {}
        if 'max_server_per_host' in self._rules:
            rules['max_server_per_host'] = \
                    int(self._rules['max_server_per_host'])
        return rules

    def obj_make_compatible(self, primitive, target_version):
        target_version = versionutils.convert_version_to_tuple(target_version)
        if target_version < (1, 11):
            # NOTE(yikun): Before 1.11, we had a policies property which is
            # the list of policy name, even though it was a list, there was
            # ever only one entry in the list.
            policy = primitive.pop('policy', None)
            if policy:
                primitive['policies'] = [policy]
            else:
                primitive['policies'] = []
            primitive.pop('rules', None)
        if target_version < (1, 7):
            # NOTE(danms): Before 1.7, we had an always-empty
            # metadetails property
            primitive['metadetails'] = {}

    @staticmethod
    def _from_db_object(context, instance_group, db_inst):
        """Method to help with migration to objects.

        Converts a database entity to a formal object.
        """
        # Most of the field names match right now, so be quick
        for field in instance_group.fields:
            if field in LAZY_LOAD_FIELDS:
                continue
            # This is needed to handle db models from both the api
            # database and the main database. In the migration to
            # the api database, we have removed soft-delete, so
            # the object fields for delete must be filled in with
            # default values for db models from the api database.
            # TODO(mriedem): Remove this when NovaPersistentObject is removed.
            ignore = {'deleted': False,
                      'deleted_at': None}
            if '_rules' == field:
                db_policy = db_inst['policy']
                instance_group._rules = (
                    jsonutils.loads(db_policy['rules'])
                    if db_policy and db_policy['rules']
                    else {})
            elif field in ignore and not hasattr(db_inst, field):
                instance_group[field] = ignore[field]
            elif 'policies' == field:
                continue
            # NOTE(yikun): The obj.policies is deprecated and marked as
            # read_only in version 1.11, and there is no "policies" property
            # in InstanceGroup model anymore, so we just skip to set
            # "policies" and then load the "policies" when "policy" is set.
            elif 'policy' == field:
                db_policy = db_inst['policy']
                if db_policy:
                    instance_group.policy = db_policy['policy']
                    instance_group.policies = [instance_group.policy]
                else:
                    instance_group.policy = None
                    instance_group.policies = []
            else:
                instance_group[field] = db_inst[field]

        instance_group._context = context
        instance_group.obj_reset_changes()
        return instance_group

    @staticmethod
    @api_db_api.context_manager.reader
    def _get_from_db_by_uuid(context, uuid):
        grp = _instance_group_get_query(context,
                                        id_field=api_models.InstanceGroup.uuid,
                                        id=uuid).first()
        if not grp:
            raise exception.InstanceGroupNotFound(group_uuid=uuid)
        return grp

    @staticmethod
    @api_db_api.context_manager.reader
    def _get_from_db_by_id(context, id):
        grp = _instance_group_get_query(context,
                                        id_field=api_models.InstanceGroup.id,
                                        id=id).first()
        if not grp:
            raise exception.InstanceGroupNotFound(group_uuid=id)
        return grp

    @staticmethod
    @api_db_api.context_manager.reader
    def _get_from_db_by_name(context, name):
        grp = _instance_group_get_query(context).filter_by(name=name).first()
        if not grp:
            raise exception.InstanceGroupNotFound(group_uuid=name)
        return grp

    @staticmethod
    @api_db_api.context_manager.reader
    def _get_from_db_by_instance(context, instance_uuid):
        grp_member = context.session.query(api_models.InstanceGroupMember).\
                     filter_by(instance_uuid=instance_uuid).first()
        if not grp_member:
            raise exception.InstanceGroupNotFound(group_uuid='')
        grp = InstanceGroup._get_from_db_by_id(context, grp_member.group_id)
        return grp

    @staticmethod
    @api_db_api.context_manager.writer
    def _save_in_db(context, group_uuid, values):
        grp = InstanceGroup._get_from_db_by_uuid(context, group_uuid)
        values_copy = copy.copy(values)
        members = values_copy.pop('members', None)

        grp.update(values_copy)

        if members is not None:
            _instance_group_members_add(context, grp, members)

        return grp

    @staticmethod
    @api_db_api.context_manager.writer
    def _create_in_db(context, values, policies=None, members=None,
                      policy=None, rules=None):
        try:
            group = api_models.InstanceGroup()
            group.update(values)
            group.save(context.session)
        except db_exc.DBDuplicateEntry:
            raise exception.InstanceGroupIdExists(group_uuid=values['uuid'])

        if policies:
            db_policy = api_models.InstanceGroupPolicy(
                group_id=group['id'], policy=policies[0], rules=None)
            group._policies = [db_policy]
            group.rules = None
        elif policy:
            db_rules = jsonutils.dumps(rules or {})
            db_policy = api_models.InstanceGroupPolicy(
                group_id=group['id'], policy=policy,
                rules=db_rules)
            group._policies = [db_policy]
        else:
            group._policies = []

        if group._policies:
            group.save(context.session)

        if members:
            group._members = _instance_group_members_add(context, group,
                                                         members)
        else:
            group._members = []

        return group

    @staticmethod
    @api_db_api.context_manager.writer
    def _destroy_in_db(context, group_uuid):
        qry = _instance_group_get_query(context,
                                        id_field=api_models.InstanceGroup.uuid,
                                        id=group_uuid)
        if qry.count() == 0:
            raise exception.InstanceGroupNotFound(group_uuid=group_uuid)

        # Delete policies and members
        group_id = qry.first().id
        instance_models = [api_models.InstanceGroupPolicy,
                           api_models.InstanceGroupMember]
        for model in instance_models:
            context.session.query(model).filter_by(group_id=group_id).delete()

        qry.delete()

    @staticmethod
    @api_db_api.context_manager.writer
    def _add_members_in_db(context, group_uuid, members):
        return _instance_group_members_add_by_uuid(context, group_uuid,
                                                   members)

    @staticmethod
    @api_db_api.context_manager.writer
    def _remove_members_in_db(context, group_id, instance_uuids):
        # There is no public method provided for removing members because the
        # user-facing API doesn't allow removal of instance group members. We
        # need to be able to remove members to address quota races.
        context.session.query(api_models.InstanceGroupMember).\
            filter_by(group_id=group_id).\
            filter(api_models.InstanceGroupMember.instance_uuid.
                   in_(set(instance_uuids))).\
            delete(synchronize_session=False)

    @staticmethod
    @api_db_api.context_manager.writer
    def _destroy_members_bulk_in_db(context, instance_uuids):
        return context.session.query(api_models.InstanceGroupMember).filter(
            api_models.InstanceGroupMember.instance_uuid.in_(instance_uuids)).\
            delete(synchronize_session=False)

    @classmethod
    def destroy_members_bulk(cls, context, instance_uuids):
        return cls._destroy_members_bulk_in_db(context, instance_uuids)

    def obj_load_attr(self, attrname):
        # NOTE(sbauza): Only hosts could be lazy-loaded right now
        if attrname != 'hosts':
            raise exception.ObjectActionError(
                action='obj_load_attr', reason='unable to load %s' % attrname)

        LOG.debug("Lazy-loading '%(attr)s' on %(name)s uuid %(uuid)s",
                  {'attr': attrname,
                   'name': self.obj_name(),
                   'uuid': self.uuid,
                   })

        self.hosts = self.get_hosts()
        self.obj_reset_changes(['hosts'])

    @base.remotable_classmethod
    def get_by_uuid(cls, context, uuid):
        db_group = cls._get_from_db_by_uuid(context, uuid)
        return cls._from_db_object(context, cls(), db_group)

    @base.remotable_classmethod
    def get_by_name(cls, context, name):
        db_group = cls._get_from_db_by_name(context, name)
        return cls._from_db_object(context, cls(), db_group)

    @base.remotable_classmethod
    def get_by_instance_uuid(cls, context, instance_uuid):
        db_group = cls._get_from_db_by_instance(context, instance_uuid)
        return cls._from_db_object(context, cls(), db_group)

    @classmethod
    def get_by_hint(cls, context, hint):
        if uuidutils.is_uuid_like(hint):
            return cls.get_by_uuid(context, hint)
        else:
            return cls.get_by_name(context, hint)

    @base.remotable
    def save(self):
        """Save updates to this instance group."""

        updates = self.obj_get_changes()

        # NOTE(sbauza): We do NOT save the set of compute nodes that an
        # instance group is connected to in this method. Instance groups are
        # implicitly connected to compute nodes when the
        # InstanceGroup.add_members() method is called, which adds the mapping
        # table entries.
        # So, since the only way to have hosts in the updates is to set that
        # field explicitly, we prefer to raise an Exception so the developer
        # knows he has to call obj_reset_changes(['hosts']) right after setting
        # the field.
        if 'hosts' in updates:
            raise exception.InstanceGroupSaveException(field='hosts')

        # NOTE(yikun): You have to provide exactly one policy on group create,
        # and also there are no group update APIs, so we do NOT support
        # policies update.
        if 'policies' in updates:
            raise exception.InstanceGroupSaveException(field='policies')

        if not updates:
            return

        payload = dict(updates)
        payload['server_group_id'] = self.uuid

        db_group = self._save_in_db(self._context, self.uuid, updates)
        self._from_db_object(self._context, self, db_group)
        compute_utils.notify_about_server_group_update(self._context,
                                                       "update", payload)

    @base.remotable
    def refresh(self):
        """Refreshes the instance group."""
        current = self.__class__.get_by_uuid(self._context, self.uuid)
        for field in self.fields:
            if self.obj_attr_is_set(field) and self[field] != current[field]:
                self[field] = current[field]
        self.obj_reset_changes()

    @base.remotable
    def create(self):
        if self.obj_attr_is_set('id'):
            raise exception.ObjectActionError(action='create',
                                              reason='already created')
        updates = self.obj_get_changes()
        payload = dict(updates)
        updates.pop('id', None)
        policies = updates.pop('policies', None)
        policy = updates.pop('policy', None)
        rules = updates.pop('_rules', None)
        members = updates.pop('members', None)

        if 'uuid' not in updates:
            self.uuid = uuidutils.generate_uuid()
            updates['uuid'] = self.uuid

        db_group = self._create_in_db(self._context, updates,
                                      policies=policies,
                                      members=members,
                                      policy=policy,
                                      rules=rules)
        self._from_db_object(self._context, self, db_group)
        payload['server_group_id'] = self.uuid
        compute_utils.notify_about_server_group_update(self._context,
                                                       "create", payload)
        compute_utils.notify_about_server_group_action(
            context=self._context,
            group=self,
            action=fields.NotificationAction.CREATE)

    @base.remotable
    def destroy(self):
        payload = {'server_group_id': self.uuid}
        self._destroy_in_db(self._context, self.uuid)
        self.obj_reset_changes()
        compute_utils.notify_about_server_group_update(self._context,
                                                       "delete", payload)
        compute_utils.notify_about_server_group_action(
            context=self._context,
            group=self,
            action=fields.NotificationAction.DELETE)

    @base.remotable_classmethod
    def add_members(cls, context, group_uuid, instance_uuids):
        payload = {'server_group_id': group_uuid,
                   'instance_uuids': instance_uuids}
        members = cls._add_members_in_db(context, group_uuid,
                                         instance_uuids)
        members = [member['instance_uuid'] for member in members]
        compute_utils.notify_about_server_group_update(context,
                                                       "addmember", payload)
        compute_utils.notify_about_server_group_add_member(context, group_uuid)
        return list(members)

    @base.remotable
    def get_hosts(self, exclude=None):
        """Get a list of hosts for non-deleted instances in the group

        This method allows you to get a list of the hosts where instances in
        this group are currently running.  There's also an option to exclude
        certain instance UUIDs from this calculation.

        """
        filter_uuids = self.members
        if exclude:
            filter_uuids = set(filter_uuids) - set(exclude)
        filters = {'uuid': filter_uuids, 'deleted': False}
        # Pass expected_attrs=[] to avoid unnecessary joins.
        # TODO(mriedem): This is pretty inefficient since all we care about
        # are the hosts. We could optimize this with a single-purpose SQL query
        # like:
        #   SELECT host FROM instances WHERE deleted=0 AND host IS NOT NULL
        #       AND uuid IN ($filter_uuids) GROUP BY host;
        instances = objects.InstanceList.get_by_filters(self._context,
                                                        filters=filters,
                                                        expected_attrs=[])
        return list(set([instance.host for instance in instances
                         if instance.host]))

    @base.remotable
    def count_members_by_user(self, user_id):
        """Count the number of instances in a group belonging to a user."""
        filter_uuids = self.members
        filters = {'uuid': filter_uuids, 'user_id': user_id, 'deleted': False}
        instances = objects.InstanceList.get_by_filters(self._context,
                                                        filters=filters)
        return len(instances)


@base.NovaObjectRegistry.register
class InstanceGroupList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    #              InstanceGroup <= version 1.3
    # Version 1.1: InstanceGroup <= version 1.4
    # Version 1.2: InstanceGroup <= version 1.5
    # Version 1.3: InstanceGroup <= version 1.6
    # Version 1.4: InstanceGroup <= version 1.7
    # Version 1.5: InstanceGroup <= version 1.8
    # Version 1.6: InstanceGroup <= version 1.9
    # Version 1.7: InstanceGroup <= version 1.10
    # Version 1.8: Added get_counts() for quotas
    VERSION = '1.8'

    fields = {
        'objects': fields.ListOfObjectsField('InstanceGroup'),
        }

    @staticmethod
    @api_db_api.context_manager.reader
    def _get_from_db(context, project_id=None):
        query = _instance_group_get_query(context)
        if project_id is not None:
            query = query.filter_by(project_id=project_id)
        return query.all()

    @staticmethod
    @api_db_api.context_manager.reader
    def _get_counts_from_db(context, project_id, user_id=None):
        query = context.session.query(api_models.InstanceGroup.id).\
                filter_by(project_id=project_id)
        counts = {}
        counts['project'] = {'server_groups': query.count()}
        if user_id:
            query = query.filter_by(user_id=user_id)
            counts['user'] = {'server_groups': query.count()}
        return counts

    @base.remotable_classmethod
    def get_by_project_id(cls, context, project_id):
        api_db_groups = cls._get_from_db(context, project_id=project_id)
        return base.obj_make_list(context, cls(context), objects.InstanceGroup,
                                  api_db_groups)

    @base.remotable_classmethod
    def get_all(cls, context):
        api_db_groups = cls._get_from_db(context)
        return base.obj_make_list(context, cls(context), objects.InstanceGroup,
                                  api_db_groups)

    @base.remotable_classmethod
    def get_counts(cls, context, project_id, user_id=None):
        """Get the counts of InstanceGroup objects in the database.

        :param context: The request context for database access
        :param project_id: The project_id to count across
        :param user_id: The user_id to count across
        :returns: A dict containing the project-scoped counts and user-scoped
                  counts if user_id is specified. For example:

                    {'project': {'server_groups': <count across project>},
                     'user': {'server_groups': <count across user>}}
        """
        return cls._get_counts_from_db(context, project_id, user_id=user_id)