Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / logic / networks.py @ a4658bbe

History | View | Annotate | Download (7.8 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
import ipaddr
34

    
35
from functools import wraps
36
from django.db import transaction
37

    
38
from django.conf import settings
39
from snf_django.lib.api import faults
40
from synnefo.api import util
41
from synnefo import quotas
42
from synnefo.db.models import Network, Backend
43
from synnefo.db.utils import validate_mac
44
from synnefo.db.pools import EmptyPool
45
from synnefo.logic import backend as backend_mod
46

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

    
50

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

    
55

    
56
def network_command(action):
57
    def decorator(func):
58
        @wraps(func)
59
        @transaction.commit_on_success()
60
        def wrapper(network, *args, **kwargs):
61
            validate_network_action(network, action)
62
            return func(network, *args, **kwargs)
63
        return wrapper
64
    return decorator
65

    
66

    
67
@transaction.commit_on_success
68
def create(user_id, name, flavor, subnet=None, gateway=None, subnet6=None,
69
           gateway6=None, public=False, dhcp=True, link=None, mac_prefix=None,
70
           mode=None, floating_ip_pool=False, tags=None, backends=None,
71
           lazy_create=True):
72
    if flavor is None:
73
        raise faults.BadRequest("Missing request parameter 'type'")
74
    elif flavor not in Network.FLAVORS.keys():
75
        raise faults.BadRequest("Invalid network type '%s'" % flavor)
76

    
77
    if mac_prefix is not None and flavor == "MAC_FILTERED":
78
        raise faults.BadRequest("Can not override MAC_FILTERED mac-prefix")
79
    if link is not None and flavor == "PHYSICAL_VLAN":
80
        raise faults.BadRequest("Can not override PHYSICAL_VLAN link")
81

    
82
    if subnet is None and floating_ip_pool:
83
        raise faults.BadRequest("IPv6 only networks can not be"
84
                                " pools.")
85
    # Check that network parameters are valid
86
    validate_network_params(subnet, gateway, subnet6, gateway6)
87

    
88
    try:
89
        fmode, flink, fmac_prefix, ftags = util.values_from_flavor(flavor)
90
    except EmptyPool:
91
        log.error("Failed to allocate resources for network of type: %s",
92
                  flavor)
93
        msg = "Failed to allocate resources for network."
94
        raise faults.ServiceUnavailable(msg)
95

    
96
    mode = mode or fmode
97
    link = link or flink
98
    mac_prefix = mac_prefix or fmac_prefix
99
    tags = tags or ftags
100

    
101
    if (flavor == "IP_LESS_ROUTED" and
102
       Network.objects.filter(deleted=False, mode=mode, link=link).exists()):
103
        msg = "Link '%s' is already used." % link
104
        raise faults.BadRequest(msg)
105

    
106
    validate_mac(mac_prefix + "0:00:00:00")
107

    
108
    network = Network.objects.create(
109
        name=name,
110
        userid=user_id,
111
        subnet=subnet,
112
        subnet6=subnet6,
113
        gateway=gateway,
114
        gateway6=gateway6,
115
        dhcp=dhcp,
116
        flavor=flavor,
117
        mode=mode,
118
        link=link,
119
        mac_prefix=mac_prefix,
120
        tags=tags,
121
        public=public,
122
        floating_ip_pool=floating_ip_pool,
123
        action='CREATE',
124
        state='ACTIVE')
125

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

    
132
    if not lazy_create:
133
        if floating_ip_pool:
134
            backends = Backend.objects.filter(offline=False)
135
        elif backends is None:
136
            backends = []
137

    
138
        for bend in backends:
139
            network.create_backend_network(bend)
140
            backend_mod.create_network(network=network, backend=bend,
141
                                       connect=True)
142
    return network
143

    
144

    
145
@network_command("RENAME")
146
def rename(network, name):
147
    network.name = name
148
    network.save()
149
    return network
150

    
151

    
152
@network_command("DESTROY")
153
def delete(network):
154
    if network.machines.exists():
155
        raise faults.NetworkInUse("Can not delete network. Servers connected"
156
                                  " to this network exists.")
157
    if network.floating_ips.filter(deleted=False).exists():
158
        msg = "Can not delete netowrk. Network has allocated floating IPs."
159
        raise faults.NetworkInUse(msg)
160

    
161
    network.action = "DESTROY"
162
    network.save()
163

    
164
    # Delete network to all backends that exists
165
    for bnet in network.backend_networks.exclude(operstate="DELETED"):
166
        backend_mod.delete_network(network, bnet.backend)
167
    else:
168
        # If network does not exist in any backend, update the network state
169
        backend_mod.update_network_state(network)
170
    return network
171

    
172

    
173
def validate_network_params(subnet=None, gateway=None, subnet6=None,
174
                            gateway6=None):
175
    if (subnet is None) and (subnet6 is None):
176
        raise faults.BadRequest("subnet or subnet6 is required")
177

    
178
    if subnet:
179
        try:
180
            # Use strict option to not all subnets with host bits set
181
            network = ipaddr.IPv4Network(subnet, strict=True)
182
        except ValueError:
183
            raise faults.BadRequest("Invalid network IPv4 subnet")
184

    
185
        # Check that network size is allowed!
186
        prefixlen = network.prefixlen
187
        if not prefixlen <= 29 and prefixlen > settings.MAX_CIDR_BLOCK:
188
            raise faults.OverLimit(message="Unsupported network size",
189
                                   details="Network mask must be in range"
190
                                           " (%s, 29]"
191
                                           % settings.MAX_CIDR_BLOCK)
192
        if gateway:  # Check that gateway belongs to network
193
            try:
194
                gateway = ipaddr.IPv4Address(gateway)
195
            except ValueError:
196
                raise faults.BadRequest("Invalid network IPv4 gateway")
197
            if not gateway in network:
198
                raise faults.BadRequest("Invalid network IPv4 gateway")
199

    
200
    if subnet6:
201
        try:
202
            # Use strict option to not all subnets with host bits set
203
            network6 = ipaddr.IPv6Network(subnet6, strict=True)
204
        except ValueError:
205
            raise faults.BadRequest("Invalid network IPv6 subnet")
206
        if gateway6:
207
            try:
208
                gateway6 = ipaddr.IPv6Address(gateway6)
209
            except ValueError:
210
                raise faults.BadRequest("Invalid network IPv6 gateway")
211
            if not gateway6 in network6:
212
                raise faults.BadRequest("Invalid network IPv6 gateway")