Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / logic / backend.py @ 3c755209

History | View | Annotate | Download (14 kB)

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

    
34
import json
35

    
36
from logging import getLogger
37

    
38
from django.conf import settings
39
from django.db import transaction
40

    
41
from synnefo.db.models import (VirtualMachine, Network, NetworkLink)
42
from synnefo.logic import utils
43
from synnefo.util.rapi import GanetiRapiClient
44

    
45

    
46
log = getLogger('synnefo.logic')
47

    
48
rapi = GanetiRapiClient(*settings.GANETI_CLUSTER_INFO)
49

    
50
_firewall_tags = {
51
    'ENABLED': settings.GANETI_FIREWALL_ENABLED_TAG,
52
    'DISABLED': settings.GANETI_FIREWALL_DISABLED_TAG,
53
    'PROTECTED': settings.GANETI_FIREWALL_PROTECTED_TAG}
54

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

    
57

    
58
@transaction.commit_on_success
59
def process_op_status(vm, jobid, opcode, status, logmsg):
60
    """Process a job progress notification from the backend
61

62
    Process an incoming message from the backend (currently Ganeti).
63
    Job notifications with a terminating status (sucess, error, or canceled),
64
    also update the operating state of the VM.
65

66
    """
67
    # See #1492, #1031, #1111 why this line has been removed
68
    #if (opcode not in [x[0] for x in VirtualMachine.BACKEND_OPCODES] or
69
    if status not in [x[0] for x in VirtualMachine.BACKEND_STATUSES]:
70
        raise VirtualMachine.InvalidBackendMsgError(opcode, status)
71

    
72
    vm.backendjobid = jobid
73
    vm.backendjobstatus = status
74
    vm.backendopcode = opcode
75
    vm.backendlogmsg = logmsg
76

    
77
    # Notifications of success change the operating state
78
    state_for_success = VirtualMachine.OPER_STATE_FROM_OPCODE.get(opcode, None)
79
    if status == 'success' and state_for_success is not None:
80
        utils.update_state(vm, state_for_success)
81
        # Set the deleted flag explicitly, cater for admin-initiated removals
82
        if opcode == 'OP_INSTANCE_REMOVE':
83
            vm.deleted = True
84
            vm.nics.all().delete()
85

    
86
    # Special case: if OP_INSTANCE_CREATE fails --> ERROR
87
    if status in ('canceled', 'error') and opcode == 'OP_INSTANCE_CREATE':
88
        utils.update_state(vm, 'ERROR')
89

    
90
    # Special case: OP_INSTANCE_REMOVE fails for machines in ERROR,
91
    # when no instance exists at the Ganeti backend.
92
    # See ticket #799 for all the details.
93
    #
94
    if (status == 'error' and opcode == 'OP_INSTANCE_REMOVE' and
95
        vm.operstate == 'ERROR'):
96
        vm.deleted = True
97
        vm.nics.all().delete()
98

    
99
    # Any other notification of failure leaves the operating state unchanged
100

    
101
    vm.save()
102

    
103

    
104
@transaction.commit_on_success
105
def process_net_status(vm, nics):
106
    """Process a net status notification from the backend
107

108
    Process an incoming message from the Ganeti backend,
109
    detailing the NIC configuration of a VM instance.
110

111
    Update the state of the VM in the DB accordingly.
112
    """
113

    
114
    vm.nics.all().delete()
115
    for i, nic in enumerate(nics):
116
        if i == 0:
117
            net = Network.objects.get(public=True)
118
        else:
119
            try:
120
                link = NetworkLink.objects.get(name=nic['link'])
121
            except NetworkLink.DoesNotExist:
122
                # Cannot find an instance of NetworkLink for
123
                # the link attribute specified in the notification
124
                raise NetworkLink.DoesNotExist("Cannot find a NetworkLink "
125
                    "object for link='%s'" % nic['link'])
126
            net = link.network
127
            if net is None:
128
                raise Network.DoesNotExist("NetworkLink for link='%s' not "
129
                    "associated with an existing Network instance." %
130
                    nic['link'])
131

    
132
        firewall = nic.get('firewall', '')
133
        firewall_profile = _reverse_tags.get(firewall, '')
134
        if not firewall_profile and net.public:
135
            firewall_profile = settings.DEFAULT_FIREWALL_PROFILE
136

    
137
        vm.nics.create(
138
            network=net,
139
            index=i,
140
            mac=nic.get('mac', ''),
141
            ipv4=nic.get('ip', ''),
142
            ipv6=nic.get('ipv6', ''),
143
            firewall_profile=firewall_profile)
144

    
145
        # network nics modified, update network object
146
        net.save()
147

    
148
    vm.save()
149

    
150

    
151
@transaction.commit_on_success
152
def process_create_progress(vm, rprogress, wprogress):
153

    
154
    # XXX: This only uses the read progress for now.
155
    #      Explore whether it would make sense to use the value of wprogress
156
    #      somewhere.
157
    percentage = int(rprogress)
158

    
159
    # The percentage may exceed 100%, due to the way
160
    # snf-progress-monitor tracks bytes read by image handling processes
161
    percentage = 100 if percentage > 100 else percentage
162
    if percentage < 0:
163
        raise ValueError("Percentage cannot be negative")
164

    
165
    last_update = vm.buildpercentage
166

    
167
    # FIXME: log a warning here, see #1033
168
#   if last_update > percentage:
169
#       raise ValueError("Build percentage should increase monotonically " \
170
#                        "(old = %d, new = %d)" % (last_update, percentage))
171

    
172
    # This assumes that no message of type 'ganeti-create-progress' is going to
173
    # arrive once OP_INSTANCE_CREATE has succeeded for a Ganeti instance and
174
    # the instance is STARTED.  What if the two messages are processed by two
175
    # separate dispatcher threads, and the 'ganeti-op-status' message for
176
    # successful creation gets processed before the 'ganeti-create-progress'
177
    # message? [vkoukis]
178
    #
179
    #if not vm.operstate == 'BUILD':
180
    #    raise VirtualMachine.IllegalState("VM is not in building state")
181

    
182
    vm.buildpercentage = percentage
183
    vm.save()
184

    
185

    
186
def start_action(vm, action):
187
    """Update the state of a VM when a new action is initiated."""
188
    if not action in [x[0] for x in VirtualMachine.ACTIONS]:
189
        raise VirtualMachine.InvalidActionError(action)
190

    
191
    # No actions to deleted and no actions beside destroy to suspended VMs
192
    if vm.deleted:
193
        raise VirtualMachine.DeletedError
194

    
195
    # No actions to machines being built. They may be destroyed, however.
196
    if vm.operstate == 'BUILD' and action != 'DESTROY':
197
        raise VirtualMachine.BuildingError
198

    
199
    vm.action = action
200
    vm.backendjobid = None
201
    vm.backendopcode = None
202
    vm.backendjobstatus = None
203
    vm.backendlogmsg = None
204

    
205
    # Update the relevant flags if the VM is being suspended or destroyed.
206
    # Do not set the deleted flag here, see ticket #721.
207
    #
208
    # The deleted flag is set asynchronously, when an OP_INSTANCE_REMOVE
209
    # completes successfully. Hence, a server may be visible for some time
210
    # after a DELETE /servers/id returns HTTP 204.
211
    #
212
    if action == "DESTROY":
213
        # vm.deleted = True
214
        pass
215
    elif action == "SUSPEND":
216
        vm.suspended = True
217
    elif action == "START":
218
        vm.suspended = False
219
    vm.save()
220

    
221

    
222
def create_instance(vm, flavor, image, password, personality):
223
    """`image` is a dictionary which should contain the keys:
224
            'backend_id', 'format' and 'metadata'
225

226
        metadata value should be a dictionary.
227
    """
228
    nic = {'ip': 'pool', 'network': settings.GANETI_PUBLIC_NETWORK}
229

    
230
    if settings.IGNORE_FLAVOR_DISK_SIZES:
231
        if image['backend_id'].find("windows") >= 0:
232
            sz = 14000
233
        else:
234
            sz = 4000
235
    else:
236
        sz = flavor.disk * 1024
237

    
238
    # Handle arguments to CreateInstance() as a dictionary,
239
    # initialize it based on a deployment-specific value.
240
    # This enables the administrator to override deployment-specific
241
    # arguments, such as the disk template to use, name of os provider
242
    # and hypervisor-specific parameters at will (see Synnefo #785, #835).
243
    #
244
    kw = settings.GANETI_CREATEINSTANCE_KWARGS
245
    kw['mode'] = 'create'
246
    kw['name'] = vm.backend_id
247
    # Defined in settings.GANETI_CREATEINSTANCE_KWARGS
248
    kw['disk_template'] = flavor.disk_template
249
    kw['disks'] = [{"size": sz}]
250
    kw['nics'] = [nic]
251
    # Defined in settings.GANETI_CREATEINSTANCE_KWARGS
252
    # kw['os'] = settings.GANETI_OS_PROVIDER
253
    kw['ip_check'] = False
254
    kw['name_check'] = False
255
    # Do not specific a node explicitly, have
256
    # Ganeti use an iallocator instead
257
    #
258
    # kw['pnode']=rapi.GetNodes()[0]
259
    kw['dry_run'] = settings.TEST
260

    
261
    kw['beparams'] = {
262
        'auto_balance': True,
263
        'vcpus': flavor.cpu,
264
        'memory': flavor.ram}
265

    
266
    kw['osparams'] = {
267
        'img_id': image['backend_id'],
268
        'img_passwd': password,
269
        'img_format': image['format']}
270
    if personality:
271
        kw['osparams']['img_personality'] = json.dumps(personality)
272

    
273
    kw['osparams']['img_properties'] = json.dumps(image['metadata'])
274

    
275
    # Defined in settings.GANETI_CREATEINSTANCE_KWARGS
276
    # kw['hvparams'] = dict(serial_console=False)
277

    
278
    return rapi.CreateInstance(**kw)
279

    
280

    
281
def delete_instance(vm):
282
    start_action(vm, 'DESTROY')
283
    rapi.DeleteInstance(vm.backend_id, dry_run=settings.TEST)
284

    
285

    
286
def reboot_instance(vm, reboot_type):
287
    assert reboot_type in ('soft', 'hard')
288
    rapi.RebootInstance(vm.backend_id, reboot_type, dry_run=settings.TEST)
289
    log.info('Rebooting instance %s', vm.backend_id)
290

    
291

    
292
def startup_instance(vm):
293
    start_action(vm, 'START')
294
    rapi.StartupInstance(vm.backend_id, dry_run=settings.TEST)
295

    
296

    
297
def shutdown_instance(vm):
298
    start_action(vm, 'STOP')
299
    rapi.ShutdownInstance(vm.backend_id, dry_run=settings.TEST)
300

    
301

    
302
def get_instance_console(vm):
303
    # RAPI GetInstanceConsole() returns endpoints to the vnc_bind_address,
304
    # which is a cluster-wide setting, either 0.0.0.0 or 127.0.0.1, and pretty
305
    # useless (see #783).
306
    #
307
    # Until this is fixed on the Ganeti side, construct a console info reply
308
    # directly.
309
    #
310
    # WARNING: This assumes that VNC runs on port network_port on
311
    #          the instance's primary node, and is probably
312
    #          hypervisor-specific.
313
    #
314
    console = {}
315
    console['kind'] = 'vnc'
316
    i = rapi.GetInstance(vm.backend_id)
317
    if i['hvparams']['serial_console']:
318
        raise Exception("hv parameter serial_console cannot be true")
319
    console['host'] = i['pnode']
320
    console['port'] = i['network_port']
321

    
322
    return console
323
    # return rapi.GetInstanceConsole(vm.backend_id)
324

    
325

    
326
def request_status_update(vm):
327
    return rapi.GetInstanceInfo(vm.backend_id)
328

    
329

    
330
def get_job_status(jobid):
331
    return rapi.GetJobStatus(jobid)
332

    
333

    
334
def update_status(vm, status):
335
    utils.update_state(vm, status)
336

    
337

    
338
def create_network_link():
339
    try:
340
        last = NetworkLink.objects.order_by('-index')[0]
341
        index = last.index + 1
342
    except IndexError:
343
        index = 1
344

    
345
    if index <= settings.GANETI_MAX_LINK_NUMBER:
346
        name = '%s%d' % (settings.GANETI_LINK_PREFIX, index)
347
        return NetworkLink.objects.create(index=index, name=name,
348
                                            available=True)
349
    return None     # All link slots are filled
350

    
351

    
352
@transaction.commit_on_success
353
def create_network(name, user_id):
354
    try:
355
        link = NetworkLink.objects.filter(available=True)[0]
356
    except IndexError:
357
        link = create_network_link()
358
        if not link:
359
            return None
360

    
361
    network = Network.objects.create(
362
        name=name,
363
        userid=user_id,
364
        state='ACTIVE',
365
        link=link)
366

    
367
    link.network = network
368
    link.available = False
369
    link.save()
370

    
371
    return network
372

    
373

    
374
@transaction.commit_on_success
375
def delete_network(net):
376
    link = net.link
377
    if link.name != settings.GANETI_NULL_LINK:
378
        link.available = True
379
        link.network = None
380
        link.save()
381

    
382
    for vm in net.machines.all():
383
        disconnect_from_network(vm, net)
384
        vm.save()
385
    net.state = 'DELETED'
386
    net.save()
387

    
388

    
389
def connect_to_network(vm, net):
390
    nic = {'mode': 'bridged', 'link': net.link.name}
391
    rapi.ModifyInstance(vm.backend_id, nics=[('add', nic)],
392
                        hotplug=True, dry_run=settings.TEST)
393

    
394

    
395
def disconnect_from_network(vm, net):
396
    nics = vm.nics.filter(network__public=False).order_by('index')
397
    ops = [('remove', nic.index, {}) for nic in nics if nic.network == net]
398
    if not ops: # Vm not connected to network
399
        return
400
    rapi.ModifyInstance(vm.backend_id, nics=ops[::-1],
401
                        hotplug=True, dry_run=settings.TEST)
402

    
403

    
404
def set_firewall_profile(vm, profile):
405
    try:
406
        tag = _firewall_tags[profile]
407
    except KeyError:
408
        raise ValueError("Unsopported Firewall Profile: %s" % profile)
409

    
410
    # Delete all firewall tags
411
    for t in _firewall_tags.values():
412
        rapi.DeleteInstanceTags(vm.backend_id, [t], dry_run=settings.TEST)
413

    
414
    rapi.AddInstanceTags(vm.backend_id, [tag], dry_run=settings.TEST)
415

    
416
    # XXX NOP ModifyInstance call to force process_net_status to run
417
    # on the dispatcher
418
    rapi.ModifyInstance(vm.backend_id,
419
                        os_name=settings.GANETI_CREATEINSTANCE_KWARGS['os'])
420

    
421

    
422
def get_ganeti_instances():
423
    return rapi.GetInstances()
424

    
425

    
426
def get_ganeti_nodes():
427
    return rapi.GetNodes()
428

    
429

    
430
def get_ganeti_jobs():
431
    return rapi.GetJobs()