Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / logic / servers.py @ 92d2d1ce

History | View | Annotate | Download (18.4 kB)

1
import logging
2

    
3
from socket import getfqdn
4
from functools import wraps
5
from django import dispatch
6
from django.db import transaction
7
from django.utils import simplejson as json
8

    
9
from snf_django.lib.api import faults
10
from django.conf import settings
11
from synnefo import quotas
12
from synnefo.api import util
13
from synnefo.logic import backend
14
from synnefo.logic.backend_allocator import BackendAllocator
15
from synnefo.db.models import (NetworkInterface, VirtualMachine, Network,
16
                               VirtualMachineMetadata, IPAddress, Subnet)
17
from synnefo.db import query as db_query
18

    
19
from vncauthproxy.client import request_forwarding as request_vnc_forwarding
20

    
21
log = logging.getLogger(__name__)
22

    
23
# server creation signal
24
server_created = dispatch.Signal(providing_args=["created_vm_params"])
25

    
26

    
27
def validate_server_action(vm, action):
28
    if vm.deleted:
29
        raise faults.BadRequest("Server '%s' has been deleted." % vm.id)
30

    
31
    # Destroyin a server should always be permitted
32
    if action == "DESTROY":
33
        return
34

    
35
    # Check that there is no pending action
36
    pending_action = vm.task
37
    if pending_action:
38
        if pending_action == "BUILD":
39
            raise faults.BuildInProgress("Server '%s' is being build." % vm.id)
40
        raise faults.BadRequest("Can not perform '%s' action while there is a"
41
                                " pending '%s'." % (action, pending_action))
42

    
43
    # Check if action can be performed to VM's operstate
44
    operstate = vm.operstate
45
    if operstate == "BUILD" and action != "BUILD":
46
        raise faults.BuildInProgress("Server '%s' is being build." % vm.id)
47
    elif (action == "START" and operstate != "STOPPED") or\
48
         (action == "STOP" and operstate != "STARTED") or\
49
         (action == "RESIZE" and operstate != "STOPPED") or\
50
         (action in ["CONNECT", "DISCONNECT"] and operstate != "STOPPED"
51
          and not settings.GANETI_USE_HOTPLUG):
52
        raise faults.BadRequest("Can not perform '%s' action while server is"
53
                                " in '%s' state." % (action, operstate))
54
    return
55

    
56

    
57
def server_command(action):
58
    """Handle execution of a server action.
59

60
    Helper function to validate and execute a server action, handle quota
61
    commission and update the 'task' of the VM in the DB.
62

63
    1) Check if action can be performed. If it can, then there must be no
64
       pending task (with the exception of DESTROY).
65
    2) Handle previous commission if unresolved:
66
       * If it is not pending and it to accept, then accept
67
       * If it is not pending and to reject or is pending then reject it. Since
68
       the action can be performed only if there is no pending task, then there
69
       can be no pending commission. The exception is DESTROY, but in this case
70
       the commission can safely be rejected, and the dispatcher will generate
71
       the correct ones!
72
    3) Issue new commission and associate it with the VM. Also clear the task.
73
    4) Send job to ganeti
74
    5) Update task and commit
75
    """
76
    def decorator(func):
77
        @wraps(func)
78
        @transaction.commit_on_success
79
        def wrapper(vm, *args, **kwargs):
80
            user_id = vm.userid
81
            validate_server_action(vm, action)
82
            vm.action = action
83

    
84
            commission_name = "client: api, resource: %s" % vm
85
            quotas.handle_resource_commission(vm, action=action,
86
                                              commission_name=commission_name)
87
            vm.save()
88

    
89
            # XXX: Special case for server creation!
90
            if action == "BUILD":
91
                # Perform a commit, because the VirtualMachine must be saved to
92
                # DB before the OP_INSTANCE_CREATE job in enqueued in Ganeti.
93
                # Otherwise, messages will arrive from snf-dispatcher about
94
                # this instance, before the VM is stored in DB.
95
                transaction.commit()
96
                # After committing the locks are released. Refetch the instance
97
                # to guarantee x-lock.
98
                vm = VirtualMachine.objects.select_for_update().get(id=vm.id)
99

    
100
            # Send the job to Ganeti and get the associated jobID
101
            try:
102
                job_id = func(vm, *args, **kwargs)
103
            except Exception as e:
104
                if vm.serial is not None:
105
                    # Since the job never reached Ganeti, reject the commission
106
                    log.debug("Rejecting commission: '%s', could not perform"
107
                              " action '%s': %s" % (vm.serial,  action, e))
108
                    transaction.rollback()
109
                    quotas.reject_serial(vm.serial)
110
                    transaction.commit()
111
                raise
112

    
113
            if action == "BUILD" and vm.serial is not None:
114
                # XXX: Special case for server creation: we must accept the
115
                # commission because the VM has been stored in DB. Also, if
116
                # communication with Ganeti fails, the job will never reach
117
                # Ganeti, and the commission will never be resolved.
118
                quotas.accept_serial(vm.serial)
119

    
120
            log.info("user: %s, vm: %s, action: %s, job_id: %s, serial: %s",
121
                     user_id, vm.id, action, job_id, vm.serial)
122

    
123
            # store the new task in the VM
124
            if job_id is not None:
125
                vm.task = action
126
                vm.task_job_id = job_id
127
            vm.save()
128

    
129
            return vm
130
        return wrapper
131
    return decorator
132

    
133

    
134
@transaction.commit_on_success
135
def create(userid, name, password, flavor, image, metadata={},
136
           personality=[], private_networks=None, floating_ips=None,
137
           use_backend=None):
138
    if use_backend is None:
139
        # Allocate server to a Ganeti backend
140
        use_backend = allocate_new_server(userid, flavor)
141

    
142
    if private_networks is None:
143
        private_networks = []
144
    if floating_ips is None:
145
        floating_ips = []
146

    
147
    # Fix flavor for archipelago
148
    disk_template, provider = util.get_flavor_provider(flavor)
149
    if provider:
150
        flavor.disk_template = disk_template
151
        flavor.disk_provider = provider
152
        flavor.disk_origin = None
153
        if provider == 'vlmc':
154
            flavor.disk_origin = image['checksum']
155
            image['backend_id'] = 'null'
156
    else:
157
        flavor.disk_provider = None
158

    
159
    # We must save the VM instance now, so that it gets a valid
160
    # vm.backend_vm_id.
161
    vm = VirtualMachine.objects.create(name=name,
162
                                       backend=use_backend,
163
                                       userid=userid,
164
                                       imageid=image["id"],
165
                                       flavor=flavor,
166
                                       operstate="BUILD")
167
    log.info("Created entry in DB for VM '%s'", vm)
168

    
169
    nics = create_instance_nics(vm, userid, private_networks, floating_ips)
170

    
171
    for key, val in metadata.items():
172
        VirtualMachineMetadata.objects.create(
173
            meta_key=key,
174
            meta_value=val,
175
            vm=vm)
176

    
177
    # Create the server in Ganeti.
178
    vm = create_server(vm, nics, flavor, image, personality, password)
179

    
180
    return vm
181

    
182

    
183
@transaction.commit_on_success
184
def allocate_new_server(userid, flavor):
185
    """Allocate a new server to a Ganeti backend.
186

187
    Allocation is performed based on the owner of the server and the specified
188
    flavor. Also, backends that do not have a public IPv4 address are excluded
189
    from server allocation.
190

191
    This function runs inside a transaction, because after allocating the
192
    instance a commit must be performed in order to release all locks.
193

194
    """
195
    backend_allocator = BackendAllocator()
196
    use_backend = backend_allocator.allocate(userid, flavor)
197
    if use_backend is None:
198
        log.error("No available backend for VM with flavor %s", flavor)
199
        raise faults.ServiceUnavailable("No available backends")
200
    return use_backend
201

    
202

    
203
@server_command("BUILD")
204
def create_server(vm, nics, flavor, image, personality, password):
205
    # dispatch server created signal needed to trigger the 'vmapi', which
206
    # enriches the vm object with the 'config_url' attribute which must be
207
    # passed to the Ganeti job.
208
    server_created.send(sender=vm, created_vm_params={
209
        'img_id': image['backend_id'],
210
        'img_passwd': password,
211
        'img_format': str(image['format']),
212
        'img_personality': json.dumps(personality),
213
        'img_properties': json.dumps(image['metadata']),
214
    })
215
    # send job to Ganeti
216
    try:
217
        jobID = backend.create_instance(vm, nics, flavor, image)
218
    except:
219
        log.exception("Failed create instance '%s'", vm)
220
        jobID = None
221
        vm.operstate = "ERROR"
222
        vm.backendlogmsg = "Failed to send job to Ganeti."
223
        vm.save()
224
        vm.nics.all().update(state="ERROR")
225

    
226
    # At this point the job is enqueued in the Ganeti backend
227
    vm.backendjobid = jobID
228
    vm.save()
229
    log.info("User %s created VM %s, NICs %s, Backend %s, JobID %s",
230
             vm.userid, vm, nics, backend, str(jobID))
231

    
232
    return jobID
233

    
234

    
235
def create_instance_nics(vm, userid, private_networks=[], floating_ips=[]):
236
    """Create NICs for VirtualMachine.
237

238
    Helper function for allocating IP addresses and creating NICs in the DB
239
    for a VirtualMachine. Created NICs are the combination of the default
240
    network policy (defined by administration settings) and the private
241
    networks defined by the user.
242

243
    """
244
    attachments = []
245
    for network_id in settings.DEFAULT_INSTANCE_NETWORKS:
246
        network, ipaddress = None, None
247
        if network_id == "SNF:ANY_PUBLIC":
248
            ipaddress = util.allocate_public_address(backend=vm.backend,
249
                                                     userid=userid)
250
            network = ipaddress.network
251
        else:
252
            try:
253
                network = Network.objects.get(id=network_id, deleted=False)
254
            except Network.DoesNotExist:
255
                msg = "Invalid configuration. Setting"\
256
                      " 'DEFAULT_INSTANCE_NETWORKS' contains invalid"\
257
                      " network '%s'" % network_id
258
                log.error(msg)
259
                raise Exception(msg)
260
            try:
261
                subnet = network.subnets.get(ipversion=4, dhcp=True)
262
                ipaddress = util.get_network_free_address(subnet, userid)
263
            except Subnet.DoesNotExist:
264
                ipaddress = None
265
        attachments.append((network, ipaddress))
266
    for address in floating_ips:
267
        floating_ip = get_floating_ip(userid=vm.userid, address=address)
268
        attachments.append((floating_ip.network, floating_ip))
269
    for network_id in private_networks:
270
        network = util.get_network(network_id, userid, non_deleted=True)
271
        if network.public:
272
            raise faults.Forbidden("Can not connect to public network")
273
        attachments.append((network, ipaddress))
274

    
275
    nics = []
276
    for index, (network, ipaddress) in enumerate(attachments):
277
        # Create VM's public NIC. Do not wait notification form ganeti
278
        # hooks to create this NIC, because if the hooks never run (e.g.
279
        # building error) the VM's public IP address will never be
280
        # released!
281
        nic = NetworkInterface.objects.create(userid=userid, machine=vm,
282
                                              network=network, index=index,
283
                                              state="BUILDING")
284
        if ipaddress is not None:
285
            ipaddress.nic = nic
286
            ipaddress.save()
287
        nics.append(nic)
288
    return nics
289

    
290

    
291
@server_command("DESTROY")
292
def destroy(vm):
293
    log.info("Deleting VM %s", vm)
294
    return backend.delete_instance(vm)
295

    
296

    
297
@server_command("START")
298
def start(vm):
299
    log.info("Starting VM %s", vm)
300
    return backend.startup_instance(vm)
301

    
302

    
303
@server_command("STOP")
304
def stop(vm):
305
    log.info("Stopping VM %s", vm)
306
    return backend.shutdown_instance(vm)
307

    
308

    
309
@server_command("REBOOT")
310
def reboot(vm, reboot_type):
311
    if reboot_type not in ("SOFT", "HARD"):
312
        raise faults.BadRequest("Malformed request. Invalid reboot"
313
                                " type %s" % reboot_type)
314
    log.info("Rebooting VM %s. Type %s", vm, reboot_type)
315

    
316
    return backend.reboot_instance(vm, reboot_type.lower())
317

    
318

    
319
@server_command("RESIZE")
320
def resize(vm, flavor):
321
    old_flavor = vm.flavor
322
    # User requested the same flavor
323
    if old_flavor.id == flavor.id:
324
        raise faults.BadRequest("Server '%s' flavor is already '%s'."
325
                                % (vm, flavor))
326
        return None
327
    # Check that resize can be performed
328
    if old_flavor.disk != flavor.disk:
329
        raise faults.BadRequest("Can not resize instance disk.")
330
    if old_flavor.disk_template != flavor.disk_template:
331
        raise faults.BadRequest("Can not change instance disk template.")
332

    
333
    log.info("Resizing VM from flavor '%s' to '%s", old_flavor, flavor)
334
    commission_info = {"cyclades.cpu": flavor.cpu - old_flavor.cpu,
335
                       "cyclades.ram": 1048576 * (flavor.ram - old_flavor.ram)}
336
    # Save serial to VM, since it is needed by server_command decorator
337
    vm.serial = quotas.issue_commission(user=vm.userid,
338
                                        source=quotas.DEFAULT_SOURCE,
339
                                        provisions=commission_info,
340
                                        name="resource: %s. resize" % vm)
341
    return backend.resize_instance(vm, vcpus=flavor.cpu, memory=flavor.ram)
342

    
343

    
344
@server_command("SET_FIREWALL_PROFILE")
345
def set_firewall_profile(vm, profile, nic):
346
    log.info("Setting VM %s, NIC %s, firewall %s", vm, nic, profile)
347

    
348
    if profile not in [x[0] for x in NetworkInterface.FIREWALL_PROFILES]:
349
        raise faults.BadRequest("Unsupported firewall profile")
350
    backend.set_firewall_profile(vm, profile=profile, nic=nic)
351
    return None
352

    
353

    
354
@server_command("CONNECT")
355
def connect(vm, network):
356
    if network.state != 'ACTIVE':
357
        raise faults.BuildInProgress('Network not active yet')
358

    
359
    address = None
360
    if network.subnet is not None and network.dhcp:
361
        # Get a free IP from the address pool.
362
        address = util.get_network_free_address(network)
363
    nic = NetworkInterface.objects.create(machine=vm, network=network,
364
                                          ip_type="STATIC", ipv4=address,
365
                                          state="BUILDING")
366
    log.info("Connecting VM %s to Network %s. NIC: %s", vm, network, nic)
367

    
368
    return backend.connect_to_network(vm, nic)
369

    
370

    
371
@server_command("DISCONNECT")
372
def disconnect(vm, nic):
373
    log.info("Removing NIC %s from VM %s", nic, vm)
374
    return backend.disconnect_from_network(vm, nic)
375

    
376

    
377
def console(vm, console_type):
378
    """Arrange for an OOB console of the specified type
379

380
    This method arranges for an OOB console of the specified type.
381
    Only consoles of type "vnc" are supported for now.
382

383
    It uses a running instance of vncauthproxy to setup proper
384
    VNC forwarding with a random password, then returns the necessary
385
    VNC connection info to the caller.
386

387
    """
388
    log.info("Get console  VM %s, type %s", vm, console_type)
389

    
390
    # Use RAPI to get VNC console information for this instance
391
    if vm.operstate != "STARTED":
392
        raise faults.BadRequest('Server not in ACTIVE state.')
393

    
394
    if settings.TEST:
395
        console_data = {'kind': 'vnc', 'host': 'ganeti_node', 'port': 1000}
396
    else:
397
        console_data = backend.get_instance_console(vm)
398

    
399
    if console_data['kind'] != 'vnc':
400
        message = 'got console of kind %s, not "vnc"' % console_data['kind']
401
        raise faults.ServiceUnavailable(message)
402

    
403
    # Let vncauthproxy decide on the source port.
404
    # The alternative: static allocation, e.g.
405
    # sport = console_data['port'] - 1000
406
    sport = 0
407
    daddr = console_data['host']
408
    dport = console_data['port']
409
    password = util.random_password()
410

    
411
    if settings.TEST:
412
        fwd = {'source_port': 1234, 'status': 'OK'}
413
    else:
414
        fwd = request_vnc_forwarding(sport, daddr, dport, password)
415

    
416
    if fwd['status'] != "OK":
417
        raise faults.ServiceUnavailable('vncauthproxy returned error status')
418

    
419
    # Verify that the VNC server settings haven't changed
420
    if not settings.TEST:
421
        if console_data != backend.get_instance_console(vm):
422
            raise faults.ServiceUnavailable('VNC Server settings changed.')
423

    
424
    console = {
425
        'type': 'vnc',
426
        'host': getfqdn(),
427
        'port': fwd['source_port'],
428
        'password': password}
429

    
430
    return console
431

    
432

    
433
@server_command("CONNECT")
434
def add_floating_ip(vm, address):
435
    floating_ip = get_floating_ip(userid=vm.userid, address=address)
436
    nic = NetworkInterface.objects.create(machine=vm,
437
                                          network=floating_ip.network,
438
                                          ipv4=floating_ip.ipv4,
439
                                          ip_type="FLOATING",
440
                                          state="BUILDING")
441
    log.info("Connecting VM %s to floating IP %s. NIC: %s", vm, floating_ip,
442
             nic)
443
    return backend.connect_to_network(vm, nic)
444

    
445

    
446
def get_floating_ip(userid, address):
447
    """Get a floating IP by it's address.
448

449
    Helper function for looking up a IPAddress by it's address. This function
450
    also checks if the floating IP is currently used by any instance.
451

452
    """
453
    try:
454
        # Get lock in VM, to guarantee that floating IP will only by assigned
455
        # once
456
        floating_ip = db_query.get_user_floating_ip(userid=userid,
457
                                                    address=address,
458
                                                    for_update=True)
459
    except IPAddress.DoesNotExist:
460
        raise faults.ItemNotFound("Floating IP with address '%s' does not"
461
                                  " exist" % address)
462

    
463
    if floating_ip.nic is not None:
464
        raise faults.Conflict("Floating IP '%s' already in use" %
465
                              floating_ip.id)
466

    
467
    return floating_ip
468

    
469

    
470
@server_command("DISCONNECT")
471
def remove_floating_ip(vm, address):
472
    try:
473
        floating_ip = db_query.get_server_floating_ip(server=vm,
474
                                                      address=address,
475
                                                      for_update=True)
476
    except IPAddress.DoesNotExist:
477
        raise faults.BadRequest("Server '%s' has no floating ip with"
478
                                " address '%s'" % (vm, address))
479

    
480
    nic = floating_ip.nic
481
    log.info("Removing NIC %s from VM %s. Floating IP '%s'", str(nic.index),
482
             vm, floating_ip)
483

    
484
    return backend.disconnect_from_network(vm, nic)
485

    
486

    
487
def rename(server, new_name):
488
    """Rename a VirtualMachine."""
489
    old_name = server.name
490
    server.name = new_name
491
    server.save()
492
    log.info("Renamed server '%s' from '%s' to '%s'", server, old_name,
493
             new_name)
494
    return server