Statistics
| Branch: | Tag: | Revision:

root / logic / backend.py @ e6209aa2

History | View | Annotate | Download (9.9 kB)

1
# Copyright 2011 GRNET S.A. All rights reserved.
2

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

    
35
from django.conf import settings
36
from django.db import transaction
37

    
38
from synnefo.db.models import (VirtualMachine, Network, NetworkInterface,
39
                                NetworkLink)
40
from synnefo.logic import utils
41
from synnefo.util.rapi import GanetiRapiClient
42

    
43

    
44
rapi = GanetiRapiClient(*settings.GANETI_CLUSTER_INFO)
45

    
46
_firewall_tags = {
47
    'ENABLED': settings.GANETI_FIREWALL_ENABLED_TAG,
48
    'DISABLED': settings.GANETI_FIREWALL_DISABLED_TAG,
49
    'PROTECTED': settings.GANETI_FIREWALL_PROTECTED_TAG}
50

    
51
_reverse_tags = dict((v.split(':')[3], k) for k, v in _firewall_tags.items())
52

    
53

    
54
def process_op_status(vm, jobid, opcode, status, logmsg):
55
    """Process a job progress notification from the backend
56

57
    Process an incoming message from the backend (currently Ganeti).
58
    Job notifications with a terminating status (sucess, error, or canceled),
59
    also update the operating state of the VM.
60

61
    """
62
    if (opcode not in [x[0] for x in VirtualMachine.BACKEND_OPCODES] or
63
       status not in [x[0] for x in VirtualMachine.BACKEND_STATUSES]):
64
        raise VirtualMachine.InvalidBackendMsgError(opcode, status)
65

    
66
    vm.backendjobid = jobid
67
    vm.backendjobstatus = status
68
    vm.backendopcode = opcode
69
    vm.backendlogmsg = logmsg
70

    
71
    # Notifications of success change the operating state
72
    if status == 'success' and VirtualMachine.OPER_STATE_FROM_OPCODE[opcode] is not None:
73
        utils.update_state(vm, VirtualMachine.OPER_STATE_FROM_OPCODE[opcode])
74
        # Set the deleted flag explicitly, to cater for admin-initiated removals
75
        if opcode == 'OP_INSTANCE_REMOVE':
76
            vm.deleted = True
77

    
78
    # Special case: if OP_INSTANCE_CREATE fails --> ERROR
79
    if status in ('canceled', 'error') and opcode == 'OP_INSTANCE_CREATE':
80
        utils.update_state(vm, 'ERROR')
81
    # Any other notification of failure leaves the operating state unchanged
82

    
83
    vm.save()
84

    
85

    
86
@transaction.commit_on_success
87
def process_net_status(vm, nics):
88
    """Process a net status notification from the backend
89

90
    Process an incoming message from the Ganeti backend,
91
    detailing the NIC configuration of a VM instance.
92

93
    Update the state of the VM in the DB accordingly.
94
    """
95

    
96
    vm.nics.all().delete()
97
    for i, nic in enumerate(nics):
98
        if i == 0:
99
            net = Network.objects.get(public=True)
100
        else:
101
            try:
102
                link = NetworkLink.objects.get(name=nic['link'])
103
            except NetworkLink.DoesNotExist:
104
                # Cannot find an instance of NetworkLink for
105
                # the link attribute specified in the notification
106
                raise NetworkLink.DoesNotExist("Cannot find a NetworkLink "
107
                    "object for link='%s'" % nic['link'])
108
            net = link.network
109
            if net is None:
110
                raise Network.DoesNotExist("NetworkLink for link='%s' not "
111
                    "associated with an existing Network instance." %
112
                    nic['link'])
113
    
114
        firewall = nic.get('firewall', '')
115
        firewall_profile = _reverse_tags.get(firewall, '')
116
        if not firewall_profile and net.public:
117
            firewall_profile = settings.DEFAULT_FIREWALL_PROFILE
118
    
119
        vm.nics.create(
120
            network=net,
121
            index=i,
122
            mac=nic.get('mac', ''),
123
            ipv4=nic.get('ip', ''),
124
            ipv6=nic.get('ipv6',''),
125
            firewall_profile=firewall_profile)
126
    vm.save()
127

    
128

    
129
def start_action(vm, action):
130
    """Update the state of a VM when a new action is initiated."""
131
    if not action in [x[0] for x in VirtualMachine.ACTIONS]:
132
        raise VirtualMachine.InvalidActionError(action)
133

    
134
    # No actions to deleted and no actions beside destroy to suspended VMs
135
    if vm.deleted:
136
        raise VirtualMachine.DeletedError
137

    
138
    # No actions to machines being built. They may be destroyed, however.
139
    if vm.operstate == 'BUILD' and action != 'DESTROY':
140
        raise VirtualMachine.BuildingError
141

    
142
    vm.action = action
143
    vm.backendjobid = None
144
    vm.backendopcode = None
145
    vm.backendjobstatus = None
146
    vm.backendlogmsg = None
147

    
148
    # Update the relevant flags if the VM is being suspended or destroyed
149
    if action == "DESTROY":
150
        vm.deleted = True
151
    elif action == "SUSPEND":
152
        vm.suspended = True
153
    elif action == "START":
154
        vm.suspended = False
155
    vm.save()
156

    
157

    
158
def create_instance(vm, flavor, image, password):
159

    
160
    nic = {'ip': 'pool', 'mode': 'routed', 'link': settings.GANETI_PUBLIC_LINK}
161
    
162
    if image.backend_id.find("windows") >= 0:
163
        sz = 14000
164
    else:
165
        sz = 4000
166

    
167
    return rapi.CreateInstance(
168
        mode='create',
169
        name=vm.backend_id,
170
        disk_template='plain',
171
        disks=[{"size": sz}],     #FIXME: Always ask for a 4GB disk for now
172
        nics=[nic],
173
        os=settings.GANETI_OS_PROVIDER,
174
        ip_check=False,
175
        name_check=False,
176
        # Do not specific a node explicitly, have
177
        # Ganeti use an iallocator instead
178
        #
179
        # pnode=rapi.GetNodes()[0]
180
        dry_run=settings.TEST,
181
        beparams=dict(auto_balance=True, vcpus=flavor.cpu, memory=flavor.ram),
182
        osparams=dict(img_id=image.backend_id, img_passwd=password,
183
                      img_format=image.format))
184

    
185

    
186
def delete_instance(vm):
187
    start_action(vm, 'DESTROY')
188
    rapi.DeleteInstance(vm.backend_id, dry_run=settings.TEST)
189
    vm.nics.all().delete()
190

    
191

    
192
def reboot_instance(vm, reboot_type):
193
    assert reboot_type in ('soft', 'hard')
194
    rapi.RebootInstance(vm.backend_id, reboot_type, dry_run=settings.TEST)
195

    
196

    
197
def startup_instance(vm):
198
    start_action(vm, 'START')
199
    rapi.StartupInstance(vm.backend_id, dry_run=settings.TEST)
200

    
201

    
202
def shutdown_instance(vm):
203
    start_action(vm, 'STOP')
204
    rapi.ShutdownInstance(vm.backend_id, dry_run=settings.TEST)
205

    
206

    
207
def get_instance_console(vm):
208
    return rapi.GetInstanceConsole(vm.backend_id)
209

    
210

    
211
def request_status_update(vm):
212
    return rapi.GetInstanceInfo(vm.backend_id)
213

    
214

    
215
def get_job_status(jobid):
216
    return rapi.GetJobStatus(jobid)
217

    
218

    
219
def update_status(vm, status):
220
    utils.update_state(vm, status)
221

    
222
def create_network_link():
223
    try:
224
        last = NetworkLink.objects.order_by('-index')[0]
225
        index = last.index + 1
226
    except IndexError:
227
        index = 1
228

    
229
    if index <= settings.GANETI_MAX_LINK_NUMBER:
230
        name = '%s%d' % (settings.GANETI_LINK_PREFIX, index)
231
        return NetworkLink.objects.create(index=index, name=name,
232
                                            available=True)
233
    return None     # All link slots are filled
234

    
235
@transaction.commit_on_success
236
def create_network(name, owner):
237
    try:
238
        link = NetworkLink.objects.filter(available=True)[0]
239
    except IndexError:
240
        link = create_network_link()
241
        if not link:
242
            return None
243

    
244
    network = Network.objects.create(
245
        name=name,
246
        owner=owner,
247
        state='ACTIVE',
248
        link=link)
249

    
250
    link.network = network
251
    link.available = False
252
    link.save()
253

    
254
    return network
255

    
256
@transaction.commit_on_success
257
def delete_network(net):
258
    link = net.link
259
    if link.name != settings.GANETI_NULL_LINK:
260
        link.available = True
261
        link.network = None
262
        link.save()
263

    
264
    for vm in net.machines.all():
265
        disconnect_from_network(vm, net)
266
        vm.save()
267
    net.state = 'DELETED'
268
    net.save()
269

    
270
def connect_to_network(vm, net):
271
    nic = {'mode': 'bridged', 'link': net.link.name}
272
    rapi.ModifyInstance(vm.backend_id,
273
        nics=[('add', nic)],
274
        dry_run=settings.TEST)
275

    
276
def disconnect_from_network(vm, net):
277
    nics = vm.nics.filter(network__public=False).order_by('index')
278
    new_nics = [nic for nic in nics if nic.network != net]
279
    if new_nics == nics:
280
        return      # Nothing to remove
281
    ops = [('remove', {})]
282
    for i, nic in enumerate(new_nics):
283
        ops.append((i + 1, {
284
            'mode': 'bridged',
285
            'link': nic.network.link.name}))
286
    rapi.ModifyInstance(vm.backend_id, nics=ops, dry_run=settings.TEST)
287

    
288
def set_firewall_profile(vm, profile):
289
    try:
290
        tag = _firewall_tags[profile]
291
    except KeyError:
292
        raise ValueError("Unsopported Firewall Profile: %s" % profile)
293

    
294
    # Delete all firewall tags
295
    for t in _firewall_tags.values():
296
        rapi.DeleteInstanceTags(vm.backend_id, [t], dry_run=settings.TEST)
297

    
298
    rapi.AddInstanceTags(vm.backend_id, [tag], dry_run=settings.TEST)
299
    
300
    # XXX NOP ModifyInstance call to force process_net_status to run
301
    # on the dispatcher
302
    rapi.ModifyInstance(vm.backend_id, os_name=settings.GANETI_OS_PROVIDER)