Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (35.5 kB)

1
# Copyright 2011-2013 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
from django.conf import settings
34
from django.db import transaction
35
from datetime import datetime
36

    
37
from synnefo.db.models import (Backend, VirtualMachine, Network,
38
                               FloatingIP,
39
                               BackendNetwork, BACKEND_STATUSES,
40
                               pooled_rapi_client, VirtualMachineDiagnostic,
41
                               Flavor)
42
from synnefo.logic import utils
43
from synnefo import quotas
44
from synnefo.api.util import release_resource
45
from synnefo.util.mac2eui64 import mac2eui64
46
from synnefo.logic.rapi import GanetiApiError
47

    
48
from logging import getLogger
49
log = getLogger(__name__)
50

    
51

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

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

    
59

    
60
def handle_vm_quotas(vm, job_id, job_opcode, job_status, job_fields):
61
    """Handle quotas for updated VirtualMachine.
62

63
    Update quotas for the updated VirtualMachine based on the job that run on
64
    the Ganeti backend. If a commission has been already issued for this job,
65
    then this commission is just accepted or rejected based on the job status.
66
    Otherwise, a new commission for the given change is issued, that is also in
67
    force and auto-accept mode. In this case, previous commissions are
68
    rejected, since they reflect a previous state of the VM.
69

70
    """
71
    if job_status not in ["success", "error", "canceled"]:
72
        return vm
73

    
74
    # Check successful completion of a job will trigger any quotable change in
75
    # the VM state.
76
    action = utils.get_action_from_opcode(job_opcode, job_fields)
77
    if action == "BUILD":
78
        # Quotas for new VMs are automatically accepted by the API
79
        return vm
80
    commission_info = quotas.get_commission_info(vm, action=action,
81
                                                 action_fields=job_fields)
82

    
83
    if vm.task_job_id == job_id and vm.serial is not None:
84
        # Commission for this change has already been issued. So just
85
        # accept/reject it. Special case is OP_INSTANCE_CREATE, which even
86
        # if fails, must be accepted, as the user must manually remove the
87
        # failed server
88
        serial = vm.serial
89
        if job_status == "success":
90
            quotas.accept_serial(serial)
91
        elif job_status in ["error", "canceled"]:
92
            log.debug("Job %s failed. Rejecting related serial %s", job_id,
93
                      serial)
94
            quotas.reject_serial(serial)
95
        vm.serial = None
96
    elif job_status == "success" and commission_info is not None:
97
        log.debug("Expected job was %s. Processing job %s. Commission for"
98
                  " this job: %s", vm.task_job_id, job_id, commission_info)
99
        # Commission for this change has not been issued, or the issued
100
        # commission was unaware of the current change. Reject all previous
101
        # commissions and create a new one in forced mode!
102
        commission_name = ("client: dispatcher, resource: %s, ganeti_job: %s"
103
                           % (vm, job_id))
104
        quotas.handle_resource_commission(vm, action,
105
                                          commission_info=commission_info,
106
                                          commission_name=commission_name,
107
                                          force=True,
108
                                          auto_accept=True)
109
        log.debug("Issued new commission: %s", vm.serial)
110

    
111
    return vm
112

    
113

    
114
@transaction.commit_on_success
115
def process_op_status(vm, etime, jobid, opcode, status, logmsg, nics=None,
116
                      beparams=None):
117
    """Process a job progress notification from the backend
118

119
    Process an incoming message from the backend (currently Ganeti).
120
    Job notifications with a terminating status (sucess, error, or canceled),
121
    also update the operating state of the VM.
122

123
    """
124
    # See #1492, #1031, #1111 why this line has been removed
125
    #if (opcode not in [x[0] for x in VirtualMachine.BACKEND_OPCODES] or
126
    if status not in [x[0] for x in BACKEND_STATUSES]:
127
        raise VirtualMachine.InvalidBackendMsgError(opcode, status)
128

    
129
    vm.backendjobid = jobid
130
    vm.backendjobstatus = status
131
    vm.backendopcode = opcode
132
    vm.backendlogmsg = logmsg
133

    
134
    if status in ["queued", "waiting", "running"]:
135
        vm.save()
136
        return
137

    
138
    state_for_success = VirtualMachine.OPER_STATE_FROM_OPCODE.get(opcode)
139

    
140
    # Notifications of success change the operating state
141
    if status == "success":
142
        if state_for_success is not None:
143
            vm.operstate = state_for_success
144
        if beparams:
145
            # Change the flavor of the VM
146
            _process_resize(vm, beparams)
147
        # Update backendtime only for jobs that have been successfully
148
        # completed, since only these jobs update the state of the VM. Else a
149
        # "race condition" may occur when a successful job (e.g.
150
        # OP_INSTANCE_REMOVE) completes before an error job and messages arrive
151
        # in reversed order.
152
        vm.backendtime = etime
153

    
154
    if status in ["success", "error", "canceled"] and nics is not None:
155
        # Update the NICs of the VM
156
        _process_net_status(vm, etime, nics)
157

    
158
    # Special case: if OP_INSTANCE_CREATE fails --> ERROR
159
    if opcode == 'OP_INSTANCE_CREATE' and status in ('canceled', 'error'):
160
        vm.operstate = 'ERROR'
161
        vm.backendtime = etime
162
    elif opcode == 'OP_INSTANCE_REMOVE':
163
        # Special case: OP_INSTANCE_REMOVE fails for machines in ERROR,
164
        # when no instance exists at the Ganeti backend.
165
        # See ticket #799 for all the details.
166
        if status == 'success' or (status == 'error' and
167
                                   not vm_exists_in_backend(vm)):
168
            # VM has been deleted. Release the instance IPs
169
            release_instance_ips(vm, [])
170
            # And delete the releated NICs (must be performed after release!)
171
            vm.nics.all().delete()
172
            vm.deleted = True
173
            vm.operstate = state_for_success
174
            vm.backendtime = etime
175
            status = "success"
176

    
177
    if status in ["success", "error", "canceled"]:
178
        # Job is finalized: Handle quotas/commissioning
179
        job_fields = {"nics": nics, "beparams": beparams}
180
        vm = handle_vm_quotas(vm, job_id=jobid, job_opcode=opcode,
181
                              job_status=status, job_fields=job_fields)
182
        # and clear task fields
183
        if vm.task_job_id == jobid:
184
            vm.task = None
185
            vm.task_job_id = None
186

    
187
    vm.save()
188

    
189

    
190
def _process_resize(vm, beparams):
191
    """Change flavor of a VirtualMachine based on new beparams."""
192
    old_flavor = vm.flavor
193
    vcpus = beparams.get("vcpus", old_flavor.cpu)
194
    ram = beparams.get("maxmem", old_flavor.ram)
195
    if vcpus == old_flavor.cpu and ram == old_flavor.ram:
196
        return
197
    try:
198
        new_flavor = Flavor.objects.get(cpu=vcpus, ram=ram,
199
                                        disk=old_flavor.disk,
200
                                        disk_template=old_flavor.disk_template)
201
    except Flavor.DoesNotExist:
202
        raise Exception("Can not find flavor for VM")
203
    vm.flavor = new_flavor
204
    vm.save()
205

    
206

    
207
@transaction.commit_on_success
208
def process_net_status(vm, etime, nics):
209
    """Wrap _process_net_status inside transaction."""
210
    _process_net_status(vm, etime, nics)
211

    
212

    
213
def _process_net_status(vm, etime, nics):
214
    """Process a net status notification from the backend
215

216
    Process an incoming message from the Ganeti backend,
217
    detailing the NIC configuration of a VM instance.
218

219
    Update the state of the VM in the DB accordingly.
220
    """
221

    
222
    ganeti_nics = process_ganeti_nics(nics)
223
    if not nics_changed(vm.nics.order_by('index'), ganeti_nics):
224
        log.debug("NICs for VM %s have not changed", vm)
225
        return
226

    
227
    # Get X-Lock on backend before getting X-Lock on network IP pools, to
228
    # guarantee that no deadlock will occur with Backend allocator.
229
    Backend.objects.select_for_update().get(id=vm.backend_id)
230

    
231
    # NICs have changed. Release the instance IPs
232
    release_instance_ips(vm, ganeti_nics)
233
    # And delete the releated NICs (must be performed after release!)
234
    vm.nics.all().delete()
235

    
236
    for nic in ganeti_nics:
237
        ipv4 = nic["ipv4"]
238
        net = nic['network']
239
        if ipv4:
240
            net.reserve_address(ipv4)
241

    
242
        nic['dirty'] = False
243
        vm.nics.create(**nic)
244
        # Dummy save the network, because UI uses changed-since for VMs
245
        # and Networks in order to show the VM NICs
246
        net.save()
247

    
248
    vm.backendtime = etime
249
    vm.save()
250

    
251

    
252
def process_ganeti_nics(ganeti_nics):
253
    """Process NIC dict from ganeti hooks."""
254
    new_nics = []
255
    for i, new_nic in enumerate(ganeti_nics):
256
        network = new_nic.get('network', '')
257
        n = str(network)
258
        pk = utils.id_from_network_name(n)
259

    
260
        net = Network.objects.get(pk=pk)
261

    
262
        # Get the new nic info
263
        mac = new_nic.get('mac')
264
        ipv4 = new_nic.get('ip')
265
        ipv6 = mac2eui64(mac, net.subnet6) if net.subnet6 is not None else None
266

    
267
        firewall = new_nic.get('firewall')
268
        firewall_profile = _reverse_tags.get(firewall)
269
        if not firewall_profile and net.public:
270
            firewall_profile = settings.DEFAULT_FIREWALL_PROFILE
271

    
272
        nic = {
273
            'index': i,
274
            'network': net,
275
            'mac': mac,
276
            'ipv4': ipv4,
277
            'ipv6': ipv6,
278
            'firewall_profile': firewall_profile,
279
            'state': 'ACTIVE'}
280

    
281
        new_nics.append(nic)
282
    return new_nics
283

    
284

    
285
def nics_changed(old_nics, new_nics):
286
    """Return True if NICs have changed in any way."""
287
    if len(old_nics) != len(new_nics):
288
        return True
289
    fields = ["ipv4", "ipv6", "mac", "firewall_profile", "index", "network"]
290
    for old_nic, new_nic in zip(old_nics, new_nics):
291
        for field in fields:
292
            if getattr(old_nic, field) != new_nic[field]:
293
                return True
294
    return False
295

    
296

    
297
def release_instance_ips(vm, ganeti_nics):
298
    old_addresses = set(vm.nics.values_list("network", "ipv4"))
299
    new_addresses = set(map(lambda nic: (nic["network"].id, nic["ipv4"]),
300
                            ganeti_nics))
301
    to_release = old_addresses - new_addresses
302
    for (network_id, ipv4) in to_release:
303
        if ipv4:
304
            # Get X-Lock before searching floating IP, to exclusively search
305
            # and release floating IP. Otherwise you may release a floating IP
306
            # that has been just reserved.
307
            net = Network.objects.select_for_update().get(id=network_id)
308
            if net.floating_ip_pool:
309
                try:
310
                    floating_ip = net.floating_ips.select_for_update()\
311
                                                  .get(ipv4=ipv4, machine=vm,
312
                                                       deleted=False)
313
                    floating_ip.machine = None
314
                    floating_ip.save()
315
                except FloatingIP.DoesNotExist:
316
                    net.release_address(ipv4)
317
            else:
318
                net.release_address(ipv4)
319

    
320

    
321
@transaction.commit_on_success
322
def process_network_status(back_network, etime, jobid, opcode, status, logmsg):
323
    if status not in [x[0] for x in BACKEND_STATUSES]:
324
        raise Network.InvalidBackendMsgError(opcode, status)
325

    
326
    back_network.backendjobid = jobid
327
    back_network.backendjobstatus = status
328
    back_network.backendopcode = opcode
329
    back_network.backendlogmsg = logmsg
330

    
331
    network = back_network.network
332

    
333
    # Notifications of success change the operating state
334
    state_for_success = BackendNetwork.OPER_STATE_FROM_OPCODE.get(opcode, None)
335
    if status == 'success' and state_for_success is not None:
336
        back_network.operstate = state_for_success
337

    
338
    if status in ('canceled', 'error') and opcode == 'OP_NETWORK_ADD':
339
        back_network.operstate = 'ERROR'
340
        back_network.backendtime = etime
341

    
342
    if opcode == 'OP_NETWORK_REMOVE':
343
        network_is_deleted = (status == "success")
344
        if network_is_deleted or (status == "error" and not
345
                                  network_exists_in_backend(back_network)):
346
            back_network.operstate = state_for_success
347
            back_network.deleted = True
348
            back_network.backendtime = etime
349

    
350
    if status == 'success':
351
        back_network.backendtime = etime
352
    back_network.save()
353
    # Also you must update the state of the Network!!
354
    update_network_state(network)
355

    
356

    
357
def update_network_state(network):
358
    """Update the state of a Network based on BackendNetwork states.
359

360
    Update the state of a Network based on the operstate of the networks in the
361
    backends that network exists.
362

363
    The state of the network is:
364
    * ACTIVE: If it is 'ACTIVE' in at least one backend.
365
    * DELETED: If it is is 'DELETED' in all backends that have been created.
366

367
    This function also releases the resources (MAC prefix or Bridge) and the
368
    quotas for the network.
369

370
    """
371
    if network.deleted:
372
        # Network has already been deleted. Just assert that state is also
373
        # DELETED
374
        if not network.state == "DELETED":
375
            network.state = "DELETED"
376
            network.save()
377
        return
378

    
379
    backend_states = [s.operstate for s in network.backend_networks.all()]
380
    if not backend_states and network.action != "DESTROY":
381
        if network.state != "ACTIVE":
382
            network.state = "ACTIVE"
383
            network.save()
384
            return
385

    
386
    # Network is deleted when all BackendNetworks go to "DELETED" operstate
387
    deleted = reduce(lambda x, y: x == y and "DELETED", backend_states,
388
                     "DELETED")
389

    
390
    # Release the resources on the deletion of the Network
391
    if deleted:
392
        log.info("Network %r deleted. Releasing link %r mac_prefix %r",
393
                 network.id, network.mac_prefix, network.link)
394
        network.deleted = True
395
        network.state = "DELETED"
396
        if network.mac_prefix:
397
            if network.FLAVORS[network.flavor]["mac_prefix"] == "pool":
398
                release_resource(res_type="mac_prefix",
399
                                 value=network.mac_prefix)
400
        if network.link:
401
            if network.FLAVORS[network.flavor]["link"] == "pool":
402
                release_resource(res_type="bridge", value=network.link)
403

    
404
        # Issue commission
405
        if network.userid:
406
            quotas.issue_and_accept_commission(network, delete=True)
407
            # the above has already saved the object and committed;
408
            # a second save would override others' changes, since the
409
            # object is now unlocked
410
            return
411
        elif not network.public:
412
            log.warning("Network %s does not have an owner!", network.id)
413
    network.save()
414

    
415

    
416
@transaction.commit_on_success
417
def process_network_modify(back_network, etime, jobid, opcode, status,
418
                           add_reserved_ips):
419
    assert (opcode == "OP_NETWORK_SET_PARAMS")
420
    if status not in [x[0] for x in BACKEND_STATUSES]:
421
        raise Network.InvalidBackendMsgError(opcode, status)
422

    
423
    back_network.backendjobid = jobid
424
    back_network.backendjobstatus = status
425
    back_network.opcode = opcode
426

    
427
    if add_reserved_ips:
428
        net = back_network.network
429
        pool = net.get_pool()
430
        if add_reserved_ips:
431
            for ip in add_reserved_ips:
432
                pool.reserve(ip, external=True)
433
        pool.save()
434

    
435
    if status == 'success':
436
        back_network.backendtime = etime
437
    back_network.save()
438

    
439

    
440
@transaction.commit_on_success
441
def process_create_progress(vm, etime, progress):
442

    
443
    percentage = int(progress)
444

    
445
    # The percentage may exceed 100%, due to the way
446
    # snf-image:copy-progress tracks bytes read by image handling processes
447
    percentage = 100 if percentage > 100 else percentage
448
    if percentage < 0:
449
        raise ValueError("Percentage cannot be negative")
450

    
451
    # FIXME: log a warning here, see #1033
452
#   if last_update > percentage:
453
#       raise ValueError("Build percentage should increase monotonically " \
454
#                        "(old = %d, new = %d)" % (last_update, percentage))
455

    
456
    # This assumes that no message of type 'ganeti-create-progress' is going to
457
    # arrive once OP_INSTANCE_CREATE has succeeded for a Ganeti instance and
458
    # the instance is STARTED.  What if the two messages are processed by two
459
    # separate dispatcher threads, and the 'ganeti-op-status' message for
460
    # successful creation gets processed before the 'ganeti-create-progress'
461
    # message? [vkoukis]
462
    #
463
    #if not vm.operstate == 'BUILD':
464
    #    raise VirtualMachine.IllegalState("VM is not in building state")
465

    
466
    vm.buildpercentage = percentage
467
    vm.backendtime = etime
468
    vm.save()
469

    
470

    
471
@transaction.commit_on_success
472
def create_instance_diagnostic(vm, message, source, level="DEBUG", etime=None,
473
                               details=None):
474
    """
475
    Create virtual machine instance diagnostic entry.
476

477
    :param vm: VirtualMachine instance to create diagnostic for.
478
    :param message: Diagnostic message.
479
    :param source: Diagnostic source identifier (e.g. image-helper).
480
    :param level: Diagnostic level (`DEBUG`, `INFO`, `WARNING`, `ERROR`).
481
    :param etime: The time the message occured (if available).
482
    :param details: Additional details or debug information.
483
    """
484
    VirtualMachineDiagnostic.objects.create_for_vm(vm, level, source=source,
485
                                                   source_date=etime,
486
                                                   message=message,
487
                                                   details=details)
488

    
489

    
490
def create_instance(vm, nics, flavor, image):
491
    """`image` is a dictionary which should contain the keys:
492
            'backend_id', 'format' and 'metadata'
493

494
        metadata value should be a dictionary.
495
    """
496

    
497
    # Handle arguments to CreateInstance() as a dictionary,
498
    # initialize it based on a deployment-specific value.
499
    # This enables the administrator to override deployment-specific
500
    # arguments, such as the disk template to use, name of os provider
501
    # and hypervisor-specific parameters at will (see Synnefo #785, #835).
502
    #
503
    kw = vm.backend.get_create_params()
504
    kw['mode'] = 'create'
505
    kw['name'] = vm.backend_vm_id
506
    # Defined in settings.GANETI_CREATEINSTANCE_KWARGS
507

    
508
    kw['disk_template'] = flavor.disk_template
509
    kw['disks'] = [{"size": flavor.disk * 1024}]
510
    provider = flavor.disk_provider
511
    if provider:
512
        kw['disks'][0]['provider'] = provider
513
        kw['disks'][0]['origin'] = flavor.disk_origin
514

    
515
    kw['nics'] = [{"network": nic.network.backend_id, "ip": nic.ipv4}
516
                  for nic in nics]
517
    backend = vm.backend
518
    depend_jobs = []
519
    for nic in nics:
520
        network = Network.objects.select_for_update().get(id=nic.network.id)
521
        bnet, created = BackendNetwork.objects.get_or_create(backend=backend,
522
                                                             network=network)
523
        if bnet.operstate != "ACTIVE":
524
            if network.public:
525
                msg = "Can not connect instance to network %s. Network is not"\
526
                      " ACTIVE in backend %s." % (network, backend)
527
                raise Exception(msg)
528
            else:
529
                jobs = create_network(network, backend, connect=True)
530
                if isinstance(jobs, list):
531
                    depend_jobs.extend(jobs)
532
                else:
533
                    depend_jobs.append(jobs)
534
    kw["depends"] = [[job, ["success", "error", "canceled"]]
535
                     for job in depend_jobs]
536

    
537
    if vm.backend.use_hotplug():
538
        kw['hotplug'] = True
539
    # Defined in settings.GANETI_CREATEINSTANCE_KWARGS
540
    # kw['os'] = settings.GANETI_OS_PROVIDER
541
    kw['ip_check'] = False
542
    kw['name_check'] = False
543

    
544
    # Do not specific a node explicitly, have
545
    # Ganeti use an iallocator instead
546
    #kw['pnode'] = rapi.GetNodes()[0]
547

    
548
    kw['dry_run'] = settings.TEST
549

    
550
    kw['beparams'] = {
551
        'auto_balance': True,
552
        'vcpus': flavor.cpu,
553
        'memory': flavor.ram}
554

    
555
    kw['osparams'] = {
556
        'config_url': vm.config_url,
557
        # Store image id and format to Ganeti
558
        'img_id': image['backend_id'],
559
        'img_format': image['format']}
560

    
561
    # Use opportunistic locking
562
    kw['opportunistic_locking'] = True
563

    
564
    # Defined in settings.GANETI_CREATEINSTANCE_KWARGS
565
    # kw['hvparams'] = dict(serial_console=False)
566

    
567
    log.debug("Creating instance %s", utils.hide_pass(kw))
568
    with pooled_rapi_client(vm) as client:
569
        return client.CreateInstance(**kw)
570

    
571

    
572
def delete_instance(vm):
573
    with pooled_rapi_client(vm) as client:
574
        return client.DeleteInstance(vm.backend_vm_id, dry_run=settings.TEST)
575

    
576

    
577
def reboot_instance(vm, reboot_type):
578
    assert reboot_type in ('soft', 'hard')
579
    kwargs = {"instance": vm.backend_vm_id,
580
              "reboot_type": "hard"}
581
    # XXX: Currently shutdown_timeout parameter is not supported from the
582
    # Ganeti RAPI. Until supported, we will fallback for both reboot types
583
    # to the default shutdown timeout of Ganeti (120s). Note that reboot
584
    # type of Ganeti job must be always hard. The 'soft' and 'hard' type
585
    # of OS API is different from the one in Ganeti, and maps to
586
    # 'shutdown_timeout'.
587
    #if reboot_type == "hard":
588
    #    kwargs["shutdown_timeout"] = 0
589
    if settings.TEST:
590
        kwargs["dry_run"] = True
591
    with pooled_rapi_client(vm) as client:
592
        return client.RebootInstance(**kwargs)
593

    
594

    
595
def startup_instance(vm):
596
    with pooled_rapi_client(vm) as client:
597
        return client.StartupInstance(vm.backend_vm_id, dry_run=settings.TEST)
598

    
599

    
600
def shutdown_instance(vm):
601
    with pooled_rapi_client(vm) as client:
602
        return client.ShutdownInstance(vm.backend_vm_id, dry_run=settings.TEST)
603

    
604

    
605
def resize_instance(vm, vcpus, memory):
606
    beparams = {"vcpus": int(vcpus),
607
                "minmem": int(memory),
608
                "maxmem": int(memory)}
609
    with pooled_rapi_client(vm) as client:
610
        return client.ModifyInstance(vm.backend_vm_id, beparams=beparams)
611

    
612

    
613
def get_instance_console(vm):
614
    # RAPI GetInstanceConsole() returns endpoints to the vnc_bind_address,
615
    # which is a cluster-wide setting, either 0.0.0.0 or 127.0.0.1, and pretty
616
    # useless (see #783).
617
    #
618
    # Until this is fixed on the Ganeti side, construct a console info reply
619
    # directly.
620
    #
621
    # WARNING: This assumes that VNC runs on port network_port on
622
    #          the instance's primary node, and is probably
623
    #          hypervisor-specific.
624
    #
625
    log.debug("Getting console for vm %s", vm)
626

    
627
    console = {}
628
    console['kind'] = 'vnc'
629

    
630
    with pooled_rapi_client(vm) as client:
631
        i = client.GetInstance(vm.backend_vm_id)
632

    
633
    if vm.backend.hypervisor == "kvm" and i['hvparams']['serial_console']:
634
        raise Exception("hv parameter serial_console cannot be true")
635
    console['host'] = i['pnode']
636
    console['port'] = i['network_port']
637

    
638
    return console
639

    
640

    
641
def get_instance_info(vm):
642
    with pooled_rapi_client(vm) as client:
643
        return client.GetInstance(vm.backend_vm_id)
644

    
645

    
646
def vm_exists_in_backend(vm):
647
    try:
648
        get_instance_info(vm)
649
        return True
650
    except GanetiApiError as e:
651
        if e.code == 404:
652
            return False
653
        raise e
654

    
655

    
656
def get_network_info(backend_network):
657
    with pooled_rapi_client(backend_network) as client:
658
        return client.GetNetwork(backend_network.network.backend_id)
659

    
660

    
661
def network_exists_in_backend(backend_network):
662
    try:
663
        get_network_info(backend_network)
664
        return True
665
    except GanetiApiError as e:
666
        if e.code == 404:
667
            return False
668

    
669

    
670
def create_network(network, backend, connect=True):
671
    """Create a network in a Ganeti backend"""
672
    log.debug("Creating network %s in backend %s", network, backend)
673

    
674
    job_id = _create_network(network, backend)
675

    
676
    if connect:
677
        job_ids = connect_network(network, backend, depends=[job_id])
678
        return job_ids
679
    else:
680
        return [job_id]
681

    
682

    
683
def _create_network(network, backend):
684
    """Create a network."""
685

    
686
    tags = network.backend_tag
687
    if network.dhcp:
688
        tags.append('nfdhcpd')
689

    
690
    if network.public:
691
        conflicts_check = True
692
    else:
693
        conflicts_check = False
694

    
695
    # Use a dummy network subnet for IPv6 only networks. Currently Ganeti does
696
    # not support IPv6 only networks. To bypass this limitation, we create the
697
    # network with a dummy network subnet, and make Cyclades connect instances
698
    # to such networks, with address=None.
699
    subnet = network.subnet
700
    if subnet is None:
701
        subnet = "10.0.0.0/24"
702

    
703
    try:
704
        bn = BackendNetwork.objects.get(network=network, backend=backend)
705
        mac_prefix = bn.mac_prefix
706
    except BackendNetwork.DoesNotExist:
707
        raise Exception("BackendNetwork for network '%s' in backend '%s'"
708
                        " does not exist" % (network.id, backend.id))
709

    
710
    with pooled_rapi_client(backend) as client:
711
        return client.CreateNetwork(network_name=network.backend_id,
712
                                    network=subnet,
713
                                    network6=network.subnet6,
714
                                    gateway=network.gateway,
715
                                    gateway6=network.gateway6,
716
                                    mac_prefix=mac_prefix,
717
                                    conflicts_check=conflicts_check,
718
                                    tags=tags)
719

    
720

    
721
def connect_network(network, backend, depends=[], group=None):
722
    """Connect a network to nodegroups."""
723
    log.debug("Connecting network %s to backend %s", network, backend)
724

    
725
    if network.public:
726
        conflicts_check = True
727
    else:
728
        conflicts_check = False
729

    
730
    depends = [[job, ["success", "error", "canceled"]] for job in depends]
731
    with pooled_rapi_client(backend) as client:
732
        groups = [group] if group is not None else client.GetGroups()
733
        job_ids = []
734
        for group in groups:
735
            job_id = client.ConnectNetwork(network.backend_id, group,
736
                                           network.mode, network.link,
737
                                           conflicts_check,
738
                                           depends=depends)
739
            job_ids.append(job_id)
740
    return job_ids
741

    
742

    
743
def delete_network(network, backend, disconnect=True):
744
    log.debug("Deleting network %s from backend %s", network, backend)
745

    
746
    depends = []
747
    if disconnect:
748
        depends = disconnect_network(network, backend)
749
    _delete_network(network, backend, depends=depends)
750

    
751

    
752
def _delete_network(network, backend, depends=[]):
753
    depends = [[job, ["success", "error", "canceled"]] for job in depends]
754
    with pooled_rapi_client(backend) as client:
755
        return client.DeleteNetwork(network.backend_id, depends)
756

    
757

    
758
def disconnect_network(network, backend, group=None):
759
    log.debug("Disconnecting network %s to backend %s", network, backend)
760

    
761
    with pooled_rapi_client(backend) as client:
762
        groups = [group] if group is not None else client.GetGroups()
763
        job_ids = []
764
        for group in groups:
765
            job_id = client.DisconnectNetwork(network.backend_id, group)
766
            job_ids.append(job_id)
767
    return job_ids
768

    
769

    
770
def connect_to_network(vm, nic):
771
    network = nic.network
772
    backend = vm.backend
773
    network = Network.objects.select_for_update().get(id=network.id)
774
    bnet, created = BackendNetwork.objects.get_or_create(backend=backend,
775
                                                         network=network)
776
    depend_jobs = []
777
    if bnet.operstate != "ACTIVE":
778
        depend_jobs = create_network(network, backend, connect=True)
779

    
780
    depends = [[job, ["success", "error", "canceled"]] for job in depend_jobs]
781

    
782
    nic = {'ip': nic.ipv4, 'network': network.backend_id}
783

    
784
    log.debug("Connecting NIC %s to VM %s", nic, vm)
785

    
786
    kwargs = {
787
        "instance": vm.backend_vm_id,
788
        "nics": [("add", nic)],
789
        "depends": depends,
790
    }
791
    if vm.backend.use_hotplug():
792
        kwargs["hotplug"] = True
793
    if settings.TEST:
794
        kwargs["dry_run"] = True
795

    
796
    with pooled_rapi_client(vm) as client:
797
        return client.ModifyInstance(**kwargs)
798

    
799

    
800
def disconnect_from_network(vm, nic):
801
    log.debug("Removing nic of VM %s, with index %s", vm, str(nic.index))
802

    
803
    kwargs = {
804
        "instance": vm.backend_vm_id,
805
        "nics": [("remove", nic.index, {})],
806
    }
807
    if vm.backend.use_hotplug():
808
        kwargs["hotplug"] = True
809
    if settings.TEST:
810
        kwargs["dry_run"] = True
811

    
812
    with pooled_rapi_client(vm) as client:
813
        jobID = client.ModifyInstance(**kwargs)
814
        # If the NIC has a tag for a firewall profile it must be deleted,
815
        # otherwise it may affect another NIC. XXX: Deleting the tag should
816
        # depend on the removing the NIC, but currently RAPI client does not
817
        # support this, this may result in clearing the firewall profile
818
        # without successfully removing the NIC. This issue will be fixed with
819
        # use of NIC UUIDs.
820
        firewall_profile = nic.firewall_profile
821
        if firewall_profile and firewall_profile != "DISABLED":
822
            tag = _firewall_tags[firewall_profile] % nic.index
823
            client.DeleteInstanceTags(vm.backend_vm_id, [tag],
824
                                      dry_run=settings.TEST)
825

    
826
        return jobID
827

    
828

    
829
def set_firewall_profile(vm, profile, index=0):
830
    try:
831
        tag = _firewall_tags[profile] % index
832
    except KeyError:
833
        raise ValueError("Unsopported Firewall Profile: %s" % profile)
834

    
835
    log.debug("Setting tag of VM %s, NIC index %d, to %s", vm, index, profile)
836

    
837
    with pooled_rapi_client(vm) as client:
838
        # Delete previous firewall tags
839
        old_tags = client.GetInstanceTags(vm.backend_vm_id)
840
        delete_tags = [(t % index) for t in _firewall_tags.values()
841
                       if (t % index) in old_tags]
842
        if delete_tags:
843
            client.DeleteInstanceTags(vm.backend_vm_id, delete_tags,
844
                                      dry_run=settings.TEST)
845

    
846
        if profile != "DISABLED":
847
            client.AddInstanceTags(vm.backend_vm_id, [tag],
848
                                   dry_run=settings.TEST)
849

    
850
        # XXX NOP ModifyInstance call to force process_net_status to run
851
        # on the dispatcher
852
        os_name = settings.GANETI_CREATEINSTANCE_KWARGS['os']
853
        client.ModifyInstance(vm.backend_vm_id,
854
                              os_name=os_name)
855
    return None
856

    
857

    
858
def get_instances(backend, bulk=True):
859
    with pooled_rapi_client(backend) as c:
860
        return c.GetInstances(bulk=bulk)
861

    
862

    
863
def get_nodes(backend, bulk=True):
864
    with pooled_rapi_client(backend) as c:
865
        return c.GetNodes(bulk=bulk)
866

    
867

    
868
def get_jobs(backend, bulk=True):
869
    with pooled_rapi_client(backend) as c:
870
        return c.GetJobs(bulk=bulk)
871

    
872

    
873
def get_physical_resources(backend):
874
    """ Get the physical resources of a backend.
875

876
    Get the resources of a backend as reported by the backend (not the db).
877

878
    """
879
    nodes = get_nodes(backend, bulk=True)
880
    attr = ['mfree', 'mtotal', 'dfree', 'dtotal', 'pinst_cnt', 'ctotal']
881
    res = {}
882
    for a in attr:
883
        res[a] = 0
884
    for n in nodes:
885
        # Filter out drained, offline and not vm_capable nodes since they will
886
        # not take part in the vm allocation process
887
        can_host_vms = n['vm_capable'] and not (n['drained'] or n['offline'])
888
        if can_host_vms and n['cnodes']:
889
            for a in attr:
890
                res[a] += int(n[a])
891
    return res
892

    
893

    
894
def update_backend_resources(backend, resources=None):
895
    """ Update the state of the backend resources in db.
896

897
    """
898

    
899
    if not resources:
900
        resources = get_physical_resources(backend)
901

    
902
    backend.mfree = resources['mfree']
903
    backend.mtotal = resources['mtotal']
904
    backend.dfree = resources['dfree']
905
    backend.dtotal = resources['dtotal']
906
    backend.pinst_cnt = resources['pinst_cnt']
907
    backend.ctotal = resources['ctotal']
908
    backend.updated = datetime.now()
909
    backend.save()
910

    
911

    
912
def get_memory_from_instances(backend):
913
    """ Get the memory that is used from instances.
914

915
    Get the used memory of a backend. Note: This is different for
916
    the real memory used, due to kvm's memory de-duplication.
917

918
    """
919
    with pooled_rapi_client(backend) as client:
920
        instances = client.GetInstances(bulk=True)
921
    mem = 0
922
    for i in instances:
923
        mem += i['oper_ram']
924
    return mem
925

    
926

    
927
def get_available_disk_templates(backend):
928
    """Get the list of available disk templates of a Ganeti backend.
929

930
    The list contains the disk templates that are enabled in the Ganeti backend
931
    and also included in ipolicy-disk-templates.
932

933
    """
934
    with pooled_rapi_client(backend) as c:
935
        info = c.GetInfo()
936
    ipolicy_disk_templates = info["ipolicy"]["disk-templates"]
937
    try:
938
        enabled_disk_templates = info["enabled_disk_templates"]
939
        return [dp for dp in enabled_disk_templates
940
                if dp in ipolicy_disk_templates]
941
    except KeyError:
942
        # Ganeti < 2.8 does not have 'enabled_disk_templates'
943
        return ipolicy_disk_templates
944

    
945

    
946
def update_backend_disk_templates(backend):
947
    disk_templates = get_available_disk_templates(backend)
948
    backend.disk_templates = disk_templates
949
    backend.save()
950

    
951

    
952
##
953
## Synchronized operations for reconciliation
954
##
955

    
956

    
957
def create_network_synced(network, backend):
958
    result = _create_network_synced(network, backend)
959
    if result[0] != 'success':
960
        return result
961
    result = connect_network_synced(network, backend)
962
    return result
963

    
964

    
965
def _create_network_synced(network, backend):
966
    with pooled_rapi_client(backend) as client:
967
        job = _create_network(network, backend)
968
        result = wait_for_job(client, job)
969
    return result
970

    
971

    
972
def connect_network_synced(network, backend):
973
    with pooled_rapi_client(backend) as client:
974
        for group in client.GetGroups():
975
            job = client.ConnectNetwork(network.backend_id, group,
976
                                        network.mode, network.link)
977
            result = wait_for_job(client, job)
978
            if result[0] != 'success':
979
                return result
980

    
981
    return result
982

    
983

    
984
def wait_for_job(client, jobid):
985
    result = client.WaitForJobChange(jobid, ['status', 'opresult'], None, None)
986
    status = result['job_info'][0]
987
    while status not in ['success', 'error', 'cancel']:
988
        result = client.WaitForJobChange(jobid, ['status', 'opresult'],
989
                                         [result], None)
990
        status = result['job_info'][0]
991

    
992
    if status == 'success':
993
        return (status, None)
994
    else:
995
        error = result['job_info'][1]
996
        return (status, error)