summaryrefslogtreecommitdiff
path: root/nova/scheduler/weights/affinity.py
blob: 2b5179aebc7ccaf629425cf32ce66fdb88eaba08 (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
# Copyright (c) 2015 Ericsson AB
# 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.
"""
Affinity Weighers.  Weigh hosts by the number of instances from a given host.

AffinityWeigher implements the soft-affinity policy for server groups by
preferring the hosts that has more instances from the given group.

AntiAffinityWeigher implements the soft-anti-affinity policy for server groups
by preferring the hosts that has less instances from the given group.

"""
from oslo_config import cfg
from oslo_log import log as logging

from nova.scheduler import utils
from nova.scheduler import weights

CONF = cfg.CONF

LOG = logging.getLogger(__name__)


class _SoftAffinityWeigherBase(weights.BaseHostWeigher):
    policy_name = None

    def _weigh_object(self, host_state, request_spec):
        """Higher weights win."""
        if not request_spec.instance_group:
            return 0

        policy = request_spec.instance_group.policy

        if self.policy_name != policy:
            return 0

        instances = set(host_state.instances.keys())
        members = set(request_spec.instance_group.members)
        member_on_host = instances.intersection(members)

        return len(member_on_host)


class ServerGroupSoftAffinityWeigher(_SoftAffinityWeigherBase):
    policy_name = 'soft-affinity'

    def weight_multiplier(self, host_state):
        return utils.get_weight_multiplier(
            host_state, 'soft_affinity_weight_multiplier',
            CONF.filter_scheduler.soft_affinity_weight_multiplier)


class ServerGroupSoftAntiAffinityWeigher(_SoftAffinityWeigherBase):
    policy_name = 'soft-anti-affinity'

    def weight_multiplier(self, host_state):
        return utils.get_weight_multiplier(
            host_state, 'soft_anti_affinity_weight_multiplier',
            CONF.filter_scheduler.soft_anti_affinity_weight_multiplier)

    def _weigh_object(self, host_state, request_spec):
        weight = super(ServerGroupSoftAntiAffinityWeigher, self)._weigh_object(
            host_state, request_spec)
        return -1 * weight