Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / logic / backend_allocator.py @ adc46059

History | View | Annotate | Download (4.4 kB)

1
# Copyright 2011 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or without
4
# modification, are permitted provided that the following conditions
5
# are met:
6
#
7
#   1. Redistributions of source code must retain the above copyright
8
#      notice, this list of conditions and the following disclaimer.
9
#
10
#  2. Redistributions in binary form must reproduce the above copyright
11
#     notice, this list of conditions and the following disclaimer in the
12
#     documentation and/or other materials provided with the distribution.
13
#
14
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
15
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24
# SUCH DAMAGE.
25
#
26
# The views and conclusions contained in the software and documentation are
27
# those of the authors and should not be interpreted as representing official
28
# policies, either expressed or implied, of GRNET S.A.
29

    
30
import logging
31
import datetime
32
from django.utils import importlib
33

    
34
from synnefo import settings
35
from synnefo.db.models import Backend
36
from synnefo.logic.backend import update_resources
37

    
38
log = logging.getLogger(__name__)
39

    
40

    
41
class BackendAllocator():
42
    """Wrapper class for instance allocation.
43

44
    """
45
    def __init__(self):
46
        self.strategy_mod =\
47
            importlib.import_module(settings.BACKEND_ALLOCATOR_MODULE)
48

    
49
    def allocate(self, flavor):
50
        """Allocate a vm of the specified flavor to a backend.
51

52
        Warning!!: An explicit commit is required after calling this function,
53
        in order to release the locks acquired by the get_available_backends
54
        function.
55

56
        """
57
        # Get the size of the vm
58
        disk = flavor_disk(flavor)
59
        ram = flavor.ram
60
        cpu = flavor.cpu
61
        vm = {'ram': ram, 'disk': disk, 'cpu': cpu}
62

    
63
        log.debug("Allocating VM: %r", vm)
64

    
65
        # Refresh backends, if needed
66
        refresh_backends_stats()
67

    
68
        # Get available backends
69
        available_backends = get_available_backends()
70

    
71
        if not available_backends:
72
            return None
73

    
74
        # Find the best backend to host the vm, based on the allocation
75
        # strategy
76
        backend = self.strategy_mod.allocate(available_backends, vm)
77

    
78
        log.info("Allocated VM %r, in backend %s", vm, backend)
79

    
80
        # Reduce the free resources of the selected backend by the size of
81
        # the vm
82
        reduce_backend_resources(backend, vm)
83

    
84
        return backend
85

    
86

    
87
def get_available_backends():
88
    """Get available backends from db.
89

90
    """
91
    return list(Backend.objects.select_for_update().filter(drained=False,
92
                                                           offline=False))
93

    
94

    
95
def flavor_disk(flavor):
96
    """ Get flavor's 'real' disk size
97

98
    """
99
    if flavor.disk_template == 'drbd':
100
        return flavor.disk * 1024 * 2
101
    else:
102
        return flavor.disk * 1024
103

    
104

    
105
def reduce_backend_resources(backend, vm):
106
    """ Conservatively update the resources of a backend.
107

108
    Reduce the free resources of the backend by the size of the of the vm that
109
    will host. This is an underestimation of the backend capabilities.
110

111
    """
112

    
113
    new_mfree = backend.mfree - vm['ram']
114
    new_dfree = backend.dfree - vm['disk']
115
    backend.mfree = 0 if new_mfree < 0 else new_mfree
116
    backend.dfree = 0 if new_dfree < 0 else new_dfree
117
    backend.pinst_cnt += 1
118

    
119
    backend.save()
120

    
121

    
122
def refresh_backends_stats():
123
    """ Refresh the statistics of the backends.
124

125
    Set db backend state to the actual state of the backend, if
126
    BACKEND_REFRESH_MIN time has passed.
127

128
    """
129

    
130
    now = datetime.datetime.now()
131
    delta = datetime.timedelta(minutes=settings.BACKEND_REFRESH_MIN)
132
    for b in Backend.objects.filter(drained=False, offline=False):
133
        if now > b.updated + delta:
134
            log.debug("Updating resources of backend %r", b)
135
            update_resources(b)