Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / logic / servers.py @ 2fa6faca

History | View | Annotate | Download (27.4 kB)

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

    
30
import logging
31

    
32
from socket import getfqdn
33
from functools import wraps
34
from django import dispatch
35
from django.db import transaction
36
from django.utils import simplejson as json
37

    
38
from snf_django.lib.api import faults
39
from django.conf import settings
40
from synnefo import quotas
41
from synnefo.api import util
42
from synnefo.logic import backend, ips
43
from synnefo.logic.backend_allocator import BackendAllocator
44
from synnefo.db.models import (NetworkInterface, VirtualMachine,
45
                               VirtualMachineMetadata, IPAddressLog, Network)
46
from vncauthproxy.client import request_forwarding as request_vnc_forwarding
47
from synnefo.logic import rapi
48

    
49
log = logging.getLogger(__name__)
50

    
51
# server creation signal
52
server_created = dispatch.Signal(providing_args=["created_vm_params"])
53

    
54

    
55
def validate_server_action(vm, action):
56
    if vm.deleted:
57
        raise faults.BadRequest("Server '%s' has been deleted." % vm.id)
58

    
59
    # Destroyin a server should always be permitted
60
    if action == "DESTROY":
61
        return
62

    
63
    # Check that there is no pending action
64
    pending_action = vm.task
65
    if pending_action:
66
        if pending_action == "BUILD":
67
            raise faults.BuildInProgress("Server '%s' is being build." % vm.id)
68
        raise faults.BadRequest("Cannot perform '%s' action while there is a"
69
                                " pending '%s'." % (action, pending_action))
70

    
71
    # Check if action can be performed to VM's operstate
72
    operstate = vm.operstate
73
    if operstate == "ERROR":
74
        raise faults.BadRequest("Cannot perform '%s' action while server is"
75
                                " in 'ERROR' state." % action)
76
    elif operstate == "BUILD" and action != "BUILD":
77
        raise faults.BuildInProgress("Server '%s' is being build." % vm.id)
78
    elif (action == "START" and operstate != "STOPPED") or\
79
         (action == "STOP" and operstate != "STARTED") or\
80
         (action == "RESIZE" and operstate != "STOPPED") or\
81
         (action in ["CONNECT", "DISCONNECT"] and operstate != "STOPPED"
82
          and not settings.GANETI_USE_HOTPLUG):
83
        raise faults.BadRequest("Cannot perform '%s' action while server is"
84
                                " in '%s' state." % (action, operstate))
85
    return
86

    
87

    
88
def server_command(action, action_fields=None):
89
    """Handle execution of a server action.
90

91
    Helper function to validate and execute a server action, handle quota
92
    commission and update the 'task' of the VM in the DB.
93

94
    1) Check if action can be performed. If it can, then there must be no
95
       pending task (with the exception of DESTROY).
96
    2) Handle previous commission if unresolved:
97
       * If it is not pending and it to accept, then accept
98
       * If it is not pending and to reject or is pending then reject it. Since
99
       the action can be performed only if there is no pending task, then there
100
       can be no pending commission. The exception is DESTROY, but in this case
101
       the commission can safely be rejected, and the dispatcher will generate
102
       the correct ones!
103
    3) Issue new commission and associate it with the VM. Also clear the task.
104
    4) Send job to ganeti
105
    5) Update task and commit
106
    """
107
    def decorator(func):
108
        @wraps(func)
109
        @transaction.commit_on_success
110
        def wrapper(vm, *args, **kwargs):
111
            user_id = vm.userid
112
            validate_server_action(vm, action)
113
            vm.action = action
114

    
115
            commission_name = "client: api, resource: %s" % vm
116
            quotas.handle_resource_commission(vm, action=action,
117
                                              action_fields=action_fields,
118
                                              commission_name=commission_name)
119
            vm.save()
120

    
121
            # XXX: Special case for server creation!
122
            if action == "BUILD":
123
                # Perform a commit, because the VirtualMachine must be saved to
124
                # DB before the OP_INSTANCE_CREATE job in enqueued in Ganeti.
125
                # Otherwise, messages will arrive from snf-dispatcher about
126
                # this instance, before the VM is stored in DB.
127
                transaction.commit()
128
                # After committing the locks are released. Refetch the instance
129
                # to guarantee x-lock.
130
                vm = VirtualMachine.objects.select_for_update().get(id=vm.id)
131

    
132
            # Send the job to Ganeti and get the associated jobID
133
            try:
134
                job_id = func(vm, *args, **kwargs)
135
            except Exception as e:
136
                if vm.serial is not None:
137
                    # Since the job never reached Ganeti, reject the commission
138
                    log.debug("Rejecting commission: '%s', could not perform"
139
                              " action '%s': %s" % (vm.serial,  action, e))
140
                    transaction.rollback()
141
                    quotas.reject_serial(vm.serial)
142
                    transaction.commit()
143
                raise
144

    
145
            if action == "BUILD" and vm.serial is not None:
146
                # XXX: Special case for server creation: we must accept the
147
                # commission because the VM has been stored in DB. Also, if
148
                # communication with Ganeti fails, the job will never reach
149
                # Ganeti, and the commission will never be resolved.
150
                quotas.accept_serial(vm.serial)
151

    
152
            log.info("user: %s, vm: %s, action: %s, job_id: %s, serial: %s",
153
                     user_id, vm.id, action, job_id, vm.serial)
154

    
155
            # store the new task in the VM
156
            if job_id is not None:
157
                vm.task = action
158
                vm.task_job_id = job_id
159
            vm.save()
160

    
161
            return vm
162
        return wrapper
163
    return decorator
164

    
165

    
166
@transaction.commit_on_success
167
def create(userid, name, password, flavor, image, metadata={},
168
           personality=[], networks=None, use_backend=None):
169
    if use_backend is None:
170
        # Allocate server to a Ganeti backend
171
        use_backend = allocate_new_server(userid, flavor)
172

    
173
    # Create the ports for the server
174
    try:
175
        ports = create_instance_ports(userid, networks)
176
    except Exception as e:
177
        raise e
178

    
179
    # Fix flavor for archipelago
180
    disk_template, provider = util.get_flavor_provider(flavor)
181
    if provider:
182
        flavor.disk_template = disk_template
183
        flavor.disk_provider = provider
184
        flavor.disk_origin = None
185
        if provider in ['vlmc', 'archipelago']:
186
            flavor.disk_origin = image['checksum']
187
            image['backend_id'] = 'null'
188
    else:
189
        flavor.disk_provider = None
190

    
191
    # We must save the VM instance now, so that it gets a valid
192
    # vm.backend_vm_id.
193
    vm = VirtualMachine.objects.create(name=name,
194
                                       backend=use_backend,
195
                                       userid=userid,
196
                                       imageid=image["id"],
197
                                       flavor=flavor,
198
                                       operstate="BUILD")
199
    log.info("Created entry in DB for VM '%s'", vm)
200

    
201
    # Associate the ports with the server
202
    for index, port in enumerate(ports):
203
        associate_port_with_machine(port, vm)
204
        port.index = index
205
        port.save()
206

    
207
    for key, val in metadata.items():
208
        VirtualMachineMetadata.objects.create(
209
            meta_key=key,
210
            meta_value=val,
211
            vm=vm)
212

    
213
    # Create the server in Ganeti.
214
    vm = create_server(vm, ports, flavor, image, personality, password)
215

    
216
    return vm
217

    
218

    
219
@transaction.commit_on_success
220
def allocate_new_server(userid, flavor):
221
    """Allocate a new server to a Ganeti backend.
222

223
    Allocation is performed based on the owner of the server and the specified
224
    flavor. Also, backends that do not have a public IPv4 address are excluded
225
    from server allocation.
226

227
    This function runs inside a transaction, because after allocating the
228
    instance a commit must be performed in order to release all locks.
229

230
    """
231
    backend_allocator = BackendAllocator()
232
    use_backend = backend_allocator.allocate(userid, flavor)
233
    if use_backend is None:
234
        log.error("No available backend for VM with flavor %s", flavor)
235
        raise faults.ServiceUnavailable("No available backends")
236
    return use_backend
237

    
238

    
239
@server_command("BUILD")
240
def create_server(vm, nics, flavor, image, personality, password):
241
    # dispatch server created signal needed to trigger the 'vmapi', which
242
    # enriches the vm object with the 'config_url' attribute which must be
243
    # passed to the Ganeti job.
244
    server_created.send(sender=vm, created_vm_params={
245
        'img_id': image['backend_id'],
246
        'img_passwd': password,
247
        'img_format': str(image['format']),
248
        'img_personality': json.dumps(personality),
249
        'img_properties': json.dumps(image['metadata']),
250
    })
251
    # send job to Ganeti
252
    try:
253
        jobID = backend.create_instance(vm, nics, flavor, image)
254
    except:
255
        log.exception("Failed create instance '%s'", vm)
256
        jobID = None
257
        vm.operstate = "ERROR"
258
        vm.backendlogmsg = "Failed to send job to Ganeti."
259
        vm.save()
260
        vm.nics.all().update(state="ERROR")
261

    
262
    # At this point the job is enqueued in the Ganeti backend
263
    vm.backendopcode = "OP_INSTANCE_CREATE"
264
    vm.backendjobid = jobID
265
    vm.save()
266
    log.info("User %s created VM %s, NICs %s, Backend %s, JobID %s",
267
             vm.userid, vm, nics, vm.backend, str(jobID))
268

    
269
    return jobID
270

    
271

    
272
@server_command("DESTROY")
273
def destroy(vm):
274
    # XXX: Workaround for race where OP_INSTANCE_REMOVE starts executing on
275
    # Ganeti before OP_INSTANCE_CREATE. This will be fixed when
276
    # OP_INSTANCE_REMOVE supports the 'depends' request attribute.
277
    if (vm.backendopcode == "OP_INSTANCE_CREATE" and
278
       vm.backendjobstatus not in rapi.JOB_STATUS_FINALIZED and
279
       backend.job_is_still_running(vm) and
280
       not backend.vm_exists_in_backend(vm)):
281
            raise faults.BuildInProgress("Server is being build")
282
    log.info("Deleting VM %s", vm)
283
    return backend.delete_instance(vm)
284

    
285

    
286
@server_command("START")
287
def start(vm):
288
    log.info("Starting VM %s", vm)
289
    return backend.startup_instance(vm)
290

    
291

    
292
@server_command("STOP")
293
def stop(vm):
294
    log.info("Stopping VM %s", vm)
295
    return backend.shutdown_instance(vm)
296

    
297

    
298
@server_command("REBOOT")
299
def reboot(vm, reboot_type):
300
    if reboot_type not in ("SOFT", "HARD"):
301
        raise faults.BadRequest("Malformed request. Invalid reboot"
302
                                " type %s" % reboot_type)
303
    log.info("Rebooting VM %s. Type %s", vm, reboot_type)
304

    
305
    return backend.reboot_instance(vm, reboot_type.lower())
306

    
307

    
308
def resize(vm, flavor):
309
    action_fields = {"beparams": {"vcpus": flavor.cpu,
310
                                  "maxmem": flavor.ram}}
311
    comm = server_command("RESIZE", action_fields=action_fields)
312
    return comm(_resize)(vm, flavor)
313

    
314

    
315
def _resize(vm, flavor):
316
    old_flavor = vm.flavor
317
    # User requested the same flavor
318
    if old_flavor.id == flavor.id:
319
        raise faults.BadRequest("Server '%s' flavor is already '%s'."
320
                                % (vm, flavor))
321
    # Check that resize can be performed
322
    if old_flavor.disk != flavor.disk:
323
        raise faults.BadRequest("Cannot resize instance disk.")
324
    if old_flavor.disk_template != flavor.disk_template:
325
        raise faults.BadRequest("Cannot change instance disk template.")
326

    
327
    log.info("Resizing VM from flavor '%s' to '%s", old_flavor, flavor)
328
    return backend.resize_instance(vm, vcpus=flavor.cpu, memory=flavor.ram)
329

    
330

    
331
@server_command("SET_FIREWALL_PROFILE")
332
def set_firewall_profile(vm, profile, nic):
333
    log.info("Setting VM %s, NIC %s, firewall %s", vm, nic, profile)
334

    
335
    if profile not in [x[0] for x in NetworkInterface.FIREWALL_PROFILES]:
336
        raise faults.BadRequest("Unsupported firewall profile")
337
    backend.set_firewall_profile(vm, profile=profile, nic=nic)
338
    return None
339

    
340

    
341
@server_command("CONNECT")
342
def connect(vm, network, port=None):
343
    if port is None:
344
        port = _create_port(vm.userid, network)
345
    associate_port_with_machine(port, vm)
346

    
347
    log.info("Creating NIC %s with IPv4 Address %s", port, port.ipv4_address)
348

    
349
    return backend.connect_to_network(vm, port)
350

    
351

    
352
@server_command("DISCONNECT")
353
def disconnect(vm, nic):
354
    log.info("Removing NIC %s from VM %s", nic, vm)
355
    return backend.disconnect_from_network(vm, nic)
356

    
357

    
358
def console(vm, console_type):
359
    """Arrange for an OOB console of the specified type
360

361
    This method arranges for an OOB console of the specified type.
362
    Only consoles of type "vnc" are supported for now.
363

364
    It uses a running instance of vncauthproxy to setup proper
365
    VNC forwarding with a random password, then returns the necessary
366
    VNC connection info to the caller.
367

368
    """
369
    log.info("Get console  VM %s, type %s", vm, console_type)
370

    
371
    # Use RAPI to get VNC console information for this instance
372
    if vm.operstate != "STARTED":
373
        raise faults.BadRequest('Server not in ACTIVE state.')
374

    
375
    if settings.TEST:
376
        console_data = {'kind': 'vnc', 'host': 'ganeti_node', 'port': 1000}
377
    else:
378
        console_data = backend.get_instance_console(vm)
379

    
380
    if console_data['kind'] != 'vnc':
381
        message = 'got console of kind %s, not "vnc"' % console_data['kind']
382
        raise faults.ServiceUnavailable(message)
383

    
384
    # Let vncauthproxy decide on the source port.
385
    # The alternative: static allocation, e.g.
386
    # sport = console_data['port'] - 1000
387
    sport = 0
388
    daddr = console_data['host']
389
    dport = console_data['port']
390
    password = util.random_password()
391

    
392
    if settings.TEST:
393
        fwd = {'source_port': 1234, 'status': 'OK'}
394
    else:
395
        vnc_extra_opts = settings.CYCLADES_VNCAUTHPROXY_OPTS
396
        fwd = request_vnc_forwarding(sport, daddr, dport, password,
397
                                     **vnc_extra_opts)
398

    
399
    if fwd['status'] != "OK":
400
        raise faults.ServiceUnavailable('vncauthproxy returned error status')
401

    
402
    # Verify that the VNC server settings haven't changed
403
    if not settings.TEST:
404
        if console_data != backend.get_instance_console(vm):
405
            raise faults.ServiceUnavailable('VNC Server settings changed.')
406

    
407
    console = {
408
        'type': 'vnc',
409
        'host': getfqdn(),
410
        'port': fwd['source_port'],
411
        'password': password}
412

    
413
    return console
414

    
415

    
416
def rename(server, new_name):
417
    """Rename a VirtualMachine."""
418
    old_name = server.name
419
    server.name = new_name
420
    server.save()
421
    log.info("Renamed server '%s' from '%s' to '%s'", server, old_name,
422
             new_name)
423
    return server
424

    
425

    
426
@transaction.commit_on_success
427
def create_port(*args, **kwargs):
428
    return _create_port(*args, **kwargs)
429

    
430

    
431
def _create_port(userid, network, machine=None, use_ipaddress=None,
432
                 address=None, name="", security_groups=None,
433
                 device_owner=None):
434
    """Create a new port on the specified network.
435

436
    Create a new Port(NetworkInterface model) on the specified Network. If
437
    'machine' is specified, the machine will be connected to the network using
438
    this port. If 'use_ipaddress' argument is specified, the port will be
439
    assigned this IPAddress. Otherwise, an IPv4 address from the IPv4 subnet
440
    will be allocated.
441

442
    """
443
    if network.state != "ACTIVE":
444
        raise faults.Conflict("Cannot create port while network '%s' is in"
445
                              " '%s' status" % (network.id, network.state))
446
    elif network.action == "DESTROY":
447
        msg = "Cannot create port. Network %s is being deleted."
448
        raise faults.Conflict(msg % network.id)
449
    elif network.drained:
450
        raise faults.Conflict("Cannot create port while network %s is in"
451
                              " 'SNF:DRAINED' status" % network.id)
452

    
453
    ipaddress = None
454
    if use_ipaddress is not None:
455
        # Use an existing IPAddress object.
456
        ipaddress = use_ipaddress
457
        if ipaddress and (ipaddress.network_id != network.id):
458
            msg = "IP Address %s does not belong to network %s"
459
            raise faults.Conflict(msg % (ipaddress.address, network.id))
460
    else:
461
        # If network has IPv4 subnets, try to allocate the address that the
462
        # the user specified or a random one.
463
        if network.subnets.filter(ipversion=4).exists():
464
            ipaddress = ips.allocate_ip(network, userid=userid,
465
                                        address=address)
466
        elif address is not None:
467
            raise faults.BadRequest("Address %s is not a valid IP for the"
468
                                    " defined network subnets" % address)
469

    
470
    if ipaddress is not None and ipaddress.nic is not None:
471
        raise faults.Conflict("IP address '%s' is already in use" %
472
                              ipaddress.address)
473

    
474
    port = NetworkInterface.objects.create(network=network,
475
                                           state="DOWN",
476
                                           userid=userid,
477
                                           device_owner=None,
478
                                           name=name)
479

    
480
    # add the security groups if any
481
    if security_groups:
482
        port.security_groups.add(*security_groups)
483

    
484
    if ipaddress is not None:
485
        # Associate IPAddress with the Port
486
        ipaddress.nic = port
487
        ipaddress.save()
488

    
489
    if machine is not None:
490
        # Connect port to the instance.
491
        machine = connect(machine, network, port)
492
        jobID = machine.task_job_id
493
        log.info("Created Port %s with IP %s. Ganeti Job: %s",
494
                 port, ipaddress, jobID)
495
    else:
496
        log.info("Created Port %s with IP %s not attached to any instance",
497
                 port, ipaddress)
498

    
499
    return port
500

    
501

    
502
def associate_port_with_machine(port, machine):
503
    """Associate a Port with a VirtualMachine.
504

505
    Associate the port with the VirtualMachine and add an entry to the
506
    IPAddressLog if the port has a public IPv4 address from a public network.
507

508
    """
509
    if port.machine is not None:
510
        raise faults.Conflict("Port %s is already in use." % port.id)
511
    if port.network.public:
512
        ipv4_address = port.ipv4_address
513
        if ipv4_address is not None:
514
            ip_log = IPAddressLog.objects.create(server_id=machine.id,
515
                                                 network_id=port.network_id,
516
                                                 address=ipv4_address,
517
                                                 active=True)
518
            log.debug("Created IP log entry %s", ip_log)
519
    port.machine = machine
520
    port.state = "BUILD"
521
    port.device_owner = "vm"
522
    port.save()
523
    return port
524

    
525

    
526
@transaction.commit_on_success
527
def delete_port(port):
528
    """Delete a port by removing the NIC card from the instance.
529

530
    Send a Job to remove the NIC card from the instance. The port
531
    will be deleted and the associated IPv4 addressess will be released
532
    when the job completes successfully.
533

534
    """
535

    
536
    if port.machine is not None:
537
        vm = disconnect(port.machine, port)
538
        log.info("Removing port %s, Job: %s", port, vm.task_job_id)
539
    else:
540
        backend.remove_nic_ips(port)
541
        port.delete()
542
        log.info("Removed port %s", port)
543

    
544
    return port
545

    
546

    
547
def create_instance_ports(user_id, networks=None):
548
    # First connect the instance to the networks defined by the admin
549
    forced_ports = create_ports_for_setting(user_id, category="admin")
550
    if networks is None:
551
        # If the user did not asked for any networks, connect instance to
552
        # default networks as defined by the admin
553
        ports = create_ports_for_setting(user_id, category="default")
554
    else:
555
        # Else just connect to the networks that the user defined
556
        ports = create_ports_for_request(user_id, networks)
557
    return forced_ports + ports
558

    
559

    
560
def create_ports_for_setting(user_id, category):
561
    if category == "admin":
562
        network_setting = settings.CYCLADES_FORCED_SERVER_NETWORKS
563
        exception = faults.ServiceUnavailable
564
    elif category == "default":
565
        network_setting = settings.CYCLADES_DEFAULT_SERVER_NETWORKS
566
        exception = faults.Conflict
567
    else:
568
        raise ValueError("Unknown category: %s" % category)
569

    
570
    ports = []
571
    for network_ids in network_setting:
572
        # Treat even simple network IDs as group of networks with one network
573
        if type(network_ids) not in (list, tuple):
574
            network_ids = [network_ids]
575

    
576
        error_msgs = []
577
        for network_id in network_ids:
578
            success = False
579
            try:
580
                ports.append(_port_from_setting(user_id, network_id, category))
581
                # Port successfully created in one of the networks. Skip the
582
                # the rest.
583
                success = True
584
                break
585
            except faults.Conflict as e:
586
                if len(network_ids) == 1:
587
                    raise exception(e.message)
588
                else:
589
                    error_msgs.append(e.message)
590

    
591
        if not success:
592
            if category == "admin":
593
                log.error("Cannot connect server to forced networks '%s': %s",
594
                          network_ids, error_msgs)
595
                raise exception("Cannot connect server to forced server"
596
                                " networks.")
597
            else:
598
                log.debug("Cannot connect server to default networks '%s': %s",
599
                          network_ids, error_msgs)
600
                raise exception("Cannot connect server to default server"
601
                                " networks.")
602

    
603
    return ports
604

    
605

    
606
def _port_from_setting(user_id, network_id, category):
607
    # TODO: Fix this..you need only IPv4 and only IPv6 network
608
    if network_id == "SNF:ANY_PUBLIC_IPV4":
609
        return create_public_ipv4_port(user_id, category=category)
610
    elif network_id == "SNF:ANY_PUBLIC_IPV6":
611
        return create_public_ipv6_port(user_id, category=category)
612
    elif network_id == "SNF:ANY_PUBLIC":
613
        try:
614
            return create_public_ipv4_port(user_id, category=category)
615
        except faults.Conflict as e1:
616
            try:
617
                return create_public_ipv6_port(user_id, category=category)
618
            except faults.Conflict as e2:
619
                log.error("Failed to connect server to a public IPv4 or IPv6"
620
                          " network. IPv4: %s, IPv6: %s", e1, e2)
621
                msg = ("Cannot connect server to a public IPv4 or IPv6"
622
                       " network.")
623
                raise faults.Conflict(msg)
624
    else:  # Case of network ID
625
        if category in ["user", "default"]:
626
            return _port_for_request(user_id, {"uuid": network_id})
627
        elif category == "admin":
628
            network = util.get_network(network_id, user_id, non_deleted=True)
629
            return _create_port(user_id, network)
630
        else:
631
            raise ValueError("Unknown category: %s" % category)
632

    
633

    
634
def create_public_ipv4_port(user_id, network=None, address=None,
635
                            category="user"):
636
    """Create a port in a public IPv4 network.
637

638
    Create a port in a public IPv4 network (that may also have an IPv6
639
    subnet). If the category is 'user' or 'default' this will try to use
640
    one of the users floating IPs. If the category is 'admin' will
641
    create a port to the public network (without floating IPs or quotas).
642

643
    """
644
    if category in ["user", "default"]:
645
        if address is None:
646
            ipaddress = ips.get_free_floating_ip(user_id, network)
647
        else:
648
            ipaddress = util.get_floating_ip_by_address(user_id, address,
649
                                                        for_update=True)
650
    elif category == "admin":
651
        if network is None:
652
            ipaddress = ips.allocate_public_ip(user_id)
653
        else:
654
            ipaddress = ips.allocate_ip(network, user_id)
655
    else:
656
        raise ValueError("Unknown category: %s" % category)
657
    if network is None:
658
        network = ipaddress.network
659
    return _create_port(user_id, network, use_ipaddress=ipaddress)
660

    
661

    
662
def create_public_ipv6_port(user_id, category=None):
663
    """Create a port in a public IPv6 only network."""
664
    networks = Network.objects.filter(public=True, deleted=False,
665
                                      drained=False, subnets__ipversion=6)\
666
                              .exclude(subnets__ipversion=4)
667
    if networks:
668
        return _create_port(user_id, networks[0])
669
    else:
670
        msg = "No available IPv6 only network!"
671
        log.error(msg)
672
        raise faults.Conflict(msg)
673

    
674

    
675
def create_ports_for_request(user_id, networks):
676
    """Create the server ports requested by the user.
677

678
    Create the ports for the new servers as requested in the 'networks'
679
    attribute. The networks attribute contains either a list of network IDs
680
    ('uuid') or a list of ports IDs ('port'). In case of network IDs, the user
681
    can also specify an IPv4 address ('fixed_ip'). In order to connect to a
682
    public network, the 'fixed_ip' attribute must contain the IPv4 address of a
683
    floating IP. If the network is public but the 'fixed_ip' attribute is not
684
    specified, the system will automatically reserve one of the users floating
685
    IPs.
686

687
    """
688
    return [_port_for_request(user_id, network) for network in networks]
689

    
690

    
691
def _port_for_request(user_id, network_dict):
692
    port_id = network_dict.get("port")
693
    network_id = network_dict.get("uuid")
694
    if port_id is not None:
695
        return util.get_port(port_id, user_id, for_update=True)
696
    elif network_id is not None:
697
        address = network_dict.get("fixed_ip")
698
        network = util.get_network(network_id, user_id, non_deleted=True)
699
        if network.public:
700
            if network.subnet4 is not None:
701
                if not "fixed_ip" in network_dict:
702
                    return create_public_ipv4_port(user_id, network)
703
                elif address is None:
704
                    msg = "Cannot connect to public network"
705
                    raise faults.BadRequest(msg % network.id)
706
                else:
707
                    return create_public_ipv4_port(user_id, network, address)
708
            else:
709
                raise faults.Forbidden("Cannot connect to IPv6 only public"
710
                                       " network %" % network.id)
711
        else:
712
            return _create_port(user_id, network, address=address)
713
    else:
714
        raise faults.BadRequest("Network 'uuid' or 'port' attribute"
715
                                " is required.")