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

34
35
36
37
38
39
from functools import wraps
from django.db import transaction

from snf_django.lib.api import faults
from synnefo.api import util
from synnefo import quotas
40
from synnefo.db.models import Network, Backend
41
42
from synnefo.db.utils import validate_mac
from synnefo.db.pools import EmptyPool
43
from synnefo.logic import backend as backend_mod
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

from logging import getLogger
log = getLogger(__name__)


def validate_network_action(network, action):
    if network.deleted:
        raise faults.BadRequest("Network has been deleted.")


def network_command(action):
    def decorator(func):
        @wraps(func)
        @transaction.commit_on_success()
        def wrapper(network, *args, **kwargs):
            validate_network_action(network, action)
            return func(network, *args, **kwargs)
        return wrapper
    return decorator


@transaction.commit_on_success
66
def create(userid, name, flavor, link=None, mac_prefix=None, mode=None,
67
           floating_ip_pool=False, tags=None, public=False):
68
69
70
71
72
    if flavor is None:
        raise faults.BadRequest("Missing request parameter 'type'")
    elif flavor not in Network.FLAVORS.keys():
        raise faults.BadRequest("Invalid network type '%s'" % flavor)

73
    if mac_prefix is not None and flavor == "MAC_FILTERED":
74
        raise faults.BadRequest("Cannot override MAC_FILTERED mac-prefix")
75
    if link is not None and flavor == "PHYSICAL_VLAN":
76
        raise faults.BadRequest("Cannot override PHYSICAL_VLAN link")
77

78
    try:
79
        fmode, flink, fmac_prefix, ftags = util.values_from_flavor(flavor)
80
81
82
83
84
    except EmptyPool:
        log.error("Failed to allocate resources for network of type: %s",
                  flavor)
        msg = "Failed to allocate resources for network."
        raise faults.ServiceUnavailable(msg)
85
86
87
88
89
90

    mode = mode or fmode
    link = link or flink
    mac_prefix = mac_prefix or fmac_prefix
    tags = tags or ftags

91
92
93
94
95
    if (flavor == "IP_LESS_ROUTED" and
       Network.objects.filter(deleted=False, mode=mode, link=link).exists()):
        msg = "Link '%s' is already used." % link
        raise faults.BadRequest(msg)

96
97
98
99
    validate_mac(mac_prefix + "0:00:00:00")

    network = Network.objects.create(
        name=name,
100
        userid=userid,
101
102
103
104
105
        flavor=flavor,
        mode=mode,
        link=link,
        mac_prefix=mac_prefix,
        tags=tags,
106
        public=public,
107
        external_router=public,
108
        floating_ip_pool=floating_ip_pool,
109
110
111
112
113
114
        action='CREATE',
        state='ACTIVE')

    # Issue commission to Quotaholder and accept it since at the end of
    # this transaction the Network object will be created in the DB.
    # Note: the following call does a commit!
115
116
    if not public:
        quotas.issue_and_accept_commission(network)
117

118
119
120
    return network


121
122
123
124
125
126
127
128
129
130
def create_network_in_backends(network):
    job_ids = []
    for bend in Backend.objects.filter(offline=False):
        network.create_backend_network(bend)
        jobs = backend_mod.create_network(network=network, backend=bend,
                                          connect=True)
        job_ids.extend(jobs)
    return job_ids


131
132
133
134
135
136
137
138
139
@network_command("RENAME")
def rename(network, name):
    network.name = name
    network.save()
    return network


@network_command("DESTROY")
def delete(network):
140
    if network.nics.exists():
141
        raise faults.Conflict("Cannot delete network. There are ports still"
142
                              " configured on network network %s" % network.id)
143
    if network.ips.filter(deleted=False, floating_ip=True).exists():
144
        msg = "Cannot delete netowrk. Network has allocated floating IPs."
145
        raise faults.Conflict(msg)
146
147

    network.action = "DESTROY"
148
149
    # Mark network as drained to prevent automatic allocation of
    # public/floating IPs while the network is being deleted
150
151
    if network.public:
        network.drained = True
152
153
154
    network.save()

    # Delete network to all backends that exists
155
156
157
158
159
    for bnet in network.backend_networks.exclude(operstate="DELETED"):
        backend_mod.delete_network(network, bnet.backend)
    else:
        # If network does not exist in any backend, update the network state
        backend_mod.update_network_state(network)
160
    return network