Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (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 functools import wraps
34
from django.db import transaction
35

    
36
from snf_django.lib.api import faults
37
from synnefo.api import util
38
from synnefo import quotas
39
from synnefo.db.models import Network, Backend
40
from synnefo.db.utils import validate_mac
41
from synnefo.db.pools import EmptyPool
42
from synnefo.logic import backend as backend_mod
43

    
44
from logging import getLogger
45
log = getLogger(__name__)
46

    
47

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

    
52

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

    
63

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

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

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

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

    
93
    mode = mode or fmode
94
    link = link or flink
95
    mac_prefix = mac_prefix or fmac_prefix
96
    tags = tags or ftags
97

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

    
103
    validate_mac(mac_prefix + "0:00:00:00")
104

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

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

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

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

    
143

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

    
150

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

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

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