Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (35.6 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, remove_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 or remove_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
        if remove_reserved_ips:
434
            for ip in remove_reserved_ips:
435
                pool.put(ip, external=True)
436
        pool.save()
437

    
438
    if status == 'success':
439
        back_network.backendtime = etime
440
    back_network.save()
441

    
442

    
443
@transaction.commit_on_success
444
def process_create_progress(vm, etime, progress):
445

    
446
    percentage = int(progress)
447

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

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

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

    
469
    vm.buildpercentage = percentage
470
    vm.backendtime = etime
471
    vm.save()
472

    
473

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

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

    
492

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

497
        metadata value should be a dictionary.
498
    """
499

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

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

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

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

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

    
551
    kw['dry_run'] = settings.TEST
552

    
553
    kw['beparams'] = {
554
        'auto_balance': True,
555
        'vcpus': flavor.cpu,
556
        'memory': flavor.ram}
557

    
558
    kw['osparams'] = {
559
        'config_url': vm.config_url,
560
        # Store image id and format to Ganeti
561
        'img_id': image['backend_id'],
562
        'img_format': image['format']}
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
    network_type = network.public and 'public' or 'private'
687

    
688
    tags = network.backend_tag
689
    if network.dhcp:
690
        tags.append('nfdhcpd')
691

    
692
    if network.public:
693
        conflicts_check = True
694
    else:
695
        conflicts_check = False
696

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

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

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

    
723

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

    
728
    if network.public:
729
        conflicts_check = True
730
    else:
731
        conflicts_check = False
732

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

    
745

    
746
def delete_network(network, backend, disconnect=True):
747
    log.debug("Deleting network %s from backend %s", network, backend)
748

    
749
    depends = []
750
    if disconnect:
751
        depends = disconnect_network(network, backend)
752
    _delete_network(network, backend, depends=depends)
753

    
754

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

    
760

    
761
def disconnect_network(network, backend, group=None):
762
    log.debug("Disconnecting network %s to backend %s", network, backend)
763

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

    
772

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

    
783
    depends = [[job, ["success", "error", "canceled"]] for job in depend_jobs]
784

    
785
    nic = {'ip': nic.ipv4, 'network': network.backend_id}
786

    
787
    log.debug("Connecting NIC %s to VM %s", nic, vm)
788

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

    
799
    with pooled_rapi_client(vm) as client:
800
        return client.ModifyInstance(**kwargs)
801

    
802

    
803
def disconnect_from_network(vm, nic):
804
    log.debug("Removing nic of VM %s, with index %s", vm, str(nic.index))
805

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

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

    
829
        return jobID
830

    
831

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

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

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

    
849
        if profile != "DISABLED":
850
            client.AddInstanceTags(vm.backend_vm_id, [tag],
851
                                   dry_run=settings.TEST)
852

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

    
860

    
861
def get_instances(backend, bulk=True):
862
    with pooled_rapi_client(backend) as c:
863
        return c.GetInstances(bulk=bulk)
864

    
865

    
866
def get_nodes(backend, bulk=True):
867
    with pooled_rapi_client(backend) as c:
868
        return c.GetNodes(bulk=bulk)
869

    
870

    
871
def get_jobs(backend, bulk=True):
872
    with pooled_rapi_client(backend) as c:
873
        return c.GetJobs(bulk=bulk)
874

    
875

    
876
def get_physical_resources(backend):
877
    """ Get the physical resources of a backend.
878

879
    Get the resources of a backend as reported by the backend (not the db).
880

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

    
896

    
897
def update_backend_resources(backend, resources=None):
898
    """ Update the state of the backend resources in db.
899

900
    """
901

    
902
    if not resources:
903
        resources = get_physical_resources(backend)
904

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

    
914

    
915
def get_memory_from_instances(backend):
916
    """ Get the memory that is used from instances.
917

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

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

    
929

    
930
def get_available_disk_templates(backend):
931
    """Get the list of available disk templates of a Ganeti backend.
932

933
    The list contains the disk templates that are enabled in the Ganeti backend
934
    and also included in ipolicy-disk-templates.
935

936
    """
937
    with pooled_rapi_client(backend) as c:
938
        info = c.GetInfo()
939
    enabled_disk_templates = info["enabled_disk_templates"]
940
    ipolicy_disk_templates = info["ipolicy"]["disk-templates"]
941
    return [dp for dp in enabled_disk_templates
942
            if dp in ipolicy_disk_templates]
943

    
944

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

    
950

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

    
955

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

    
963

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

    
970

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

    
980
    return result
981

    
982

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

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