Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / floating_ips.py @ 828a28df

History | View | Annotate | Download (9.3 kB)

1
# Copyright 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

    
34
from django.conf.urls.defaults import patterns
35
from django.db import transaction
36
from django.http import HttpResponse
37
from django.utils import simplejson as json
38

    
39
from snf_django.lib import api
40
from snf_django.lib.api import faults, utils
41
from synnefo.api import util
42
from synnefo.logic import ips
43
from synnefo.db.models import Network, IPAddress
44

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

    
48
'''
49
ips_urlpatterns = patterns(
50
    'synnefo.api.floating_ips',
51
    (r'^(?:/|.json|.xml)?$', 'demux'),
52
    (r'^/(\w+)(?:.json|.xml)?$', 'floating_ip_demux'),
53
)
54

55
pools_urlpatterns = patterns(
56
    "synnefo.api.floating_ips",
57
    (r'^(?:/|.json|.xml)?$', 'list_floating_ip_pools'),
58
)
59
'''
60

    
61
ips_urlpatterns = patterns(
62
    'synnefo.api.floating_ips',
63
    (r'^(?:/|.json|.xml)?$', 'demux'),
64
    (r'^/detail(?:.json|.xml)?$', 'list_floating_ips', {'detail': True}),
65
    (r'^/(\w+)(?:/|.json|.xml)?$', 'floating_ip_demux'))
66

    
67

    
68
def demux(request):
69
    if request.method == 'GET':
70
        return list_floating_ips(request)
71
    elif request.method == 'POST':
72
        return allocate_floating_ip(request)
73
    else:
74
        return api.api_method_not_allowed(request,
75
                                          allowed_methods=['GET', 'POST'])
76

    
77

    
78
def floating_ip_demux(request, floating_ip_id):
79
    if request.method == 'GET':
80
        return get_floating_ip(request, floating_ip_id)
81
    elif request.method == 'DELETE':
82
        return release_floating_ip(request, floating_ip_id)
83
    elif request.method == 'PUT':
84
        return update_floating_ip(request, floating_ip_id)
85
    else:
86
        return api.api_method_not_allowed(request,
87
                                          allowed_methods=['GET', 'DELETE'])
88

    
89

    
90
def ip_to_dict(floating_ip):
91
    machine_id = None
92
    port_id = None
93
    if floating_ip.nic is not None:
94
        machine_id = floating_ip.nic.machine_id
95
        port_id = floating_ip.nic.id
96
    return {"fixed_ip_address": None,
97
            "id": str(floating_ip.id),
98
            "instance_id": str(machine_id) if machine_id else None,
99
            "floating_ip_address": floating_ip.address,
100
            "port_id": str(port_id) if port_id else None,
101
            "floating_network_id": str(floating_ip.network_id),
102
            "deleted": floating_ip.deleted,
103
            "tenant_id": floating_ip.userid,
104
            "user_id": floating_ip.userid}
105

    
106

    
107
@api.api_method(http_method="GET", user_required=True, logger=log,
108
                serializations=["json"])
109
def list_floating_ips(request):
110
    """Return user reserved floating IPs"""
111
    log.debug("list_floating_ips")
112

    
113
    userid = request.user_uniq
114
    floating_ips = IPAddress.objects.filter(userid=userid, deleted=False,
115
                                            floating_ip=True).order_by("id")\
116
                                    .select_related("nic")
117
    floating_ips = utils.filter_modified_since(request, objects=floating_ips)
118

    
119
    floating_ips = map(ip_to_dict, floating_ips)
120

    
121
    request.serialization = "json"
122
    data = json.dumps({"floatingips": floating_ips})
123

    
124
    return HttpResponse(data, status=200)
125

    
126

    
127
@api.api_method(http_method="GET", user_required=True, logger=log,
128
                serializations=["json"])
129
def get_floating_ip(request, floating_ip_id):
130
    """Return information for a floating IP."""
131
    userid = request.user_uniq
132
    floating_ip = util.get_floating_ip_by_id(userid, floating_ip_id)
133
    request.serialization = "json"
134
    data = json.dumps({"floatingip": ip_to_dict(floating_ip)})
135
    return HttpResponse(data, status=200)
136

    
137

    
138
@api.api_method(http_method='POST', user_required=True, logger=log,
139
                serializations=["json"])
140
@transaction.commit_on_success
141
def allocate_floating_ip(request):
142
    """Allocate a floating IP."""
143
    req = utils.get_request_dict(request)
144
    floating_ip_dict = api.utils.get_attribute(req, "floatingip",
145
                                               required=True, attr_type=dict)
146
    userid = request.user_uniq
147
    log.info('allocate_floating_ip user: %s request: %s', userid, req)
148

    
149
    # the network_pool is a mandatory field
150
    network_id = api.utils.get_attribute(floating_ip_dict,
151
                                         "floating_network_id",
152
                                         required=False,
153
                                         attr_type=(basestring, int))
154
    if network_id is None:
155
        floating_ip = ips.create_floating_ip(userid)
156
    else:
157
        try:
158
            network_id = int(network_id)
159
        except ValueError:
160
            raise faults.BadRequest("Invalid networkd ID.")
161

    
162
        network = util.get_network(network_id, userid, for_update=True,
163
                                   non_deleted=True)
164
        address = api.utils.get_attribute(floating_ip_dict,
165
                                          "floating_ip_address",
166
                                          required=False,
167
                                          attr_type=basestring)
168
        floating_ip = ips.create_floating_ip(userid, network, address)
169

    
170
    log.info("User '%s' allocated floating IP '%s'", userid, floating_ip)
171
    request.serialization = "json"
172
    data = json.dumps({"floatingip": ip_to_dict(floating_ip)})
173
    return HttpResponse(data, status=200)
174

    
175

    
176
@api.api_method(http_method='DELETE', user_required=True, logger=log,
177
                serializations=["json"])
178
@transaction.commit_on_success
179
def release_floating_ip(request, floating_ip_id):
180
    """Release a floating IP."""
181
    userid = request.user_uniq
182
    log.info("release_floating_ip '%s'. User '%s'.", floating_ip_id, userid)
183

    
184
    floating_ip = util.get_floating_ip_by_id(userid, floating_ip_id,
185
                                             for_update=True)
186
    ips.delete_floating_ip(floating_ip)
187
    log.info("User '%s' released IP '%s", userid, floating_ip)
188

    
189
    return HttpResponse(status=204)
190

    
191

    
192
@api.api_method(http_method='PUT', user_required=True, logger=log,
193
                serializations=["json"])
194
@transaction.commit_on_success
195
def update_floating_ip(request, floating_ip_id):
196
    """Update a floating IP."""
197
    raise faults.NotImplemented("Updating a floating IP is not supported.")
198
    #userid = request.user_uniq
199
    #log.info("update_floating_ip '%s'. User '%s'.", floating_ip_id, userid)
200

    
201
    #req = utils.get_request_dict(request)
202
    #info = api.utils.get_attribute(req, "floatingip", required=True)
203

    
204
    #device_id = api.utils.get_attribute(info, "device_id", required=False)
205

    
206
    #floating_ip = util.get_floating_ip_by_id(userid, floating_ip_id,
207
    #                                         for_update=True)
208
    #if device_id:
209
    #    # attach
210
    #    vm = util.get_vm(device_id, userid)
211
    #    nic, floating_ip = servers.create_nic(vm, ipaddress=floating_ip)
212
    #    backend.connect_to_network(vm, nic)
213
    #else:
214
    #    # dettach
215
    #    nic = floating_ip.nic
216
    #    if not nic:
217
    #        raise faults.BadRequest("The floating IP is not associated\
218
    #                                with any device")
219
    #    vm = nic.machine
220
    #    servers.disconnect(vm, nic)
221
    #return HttpResponse(status=202)
222

    
223

    
224
# Floating IP pools
225
@api.api_method(http_method='GET', user_required=True, logger=log,
226
                serializations=["json"])
227
def list_floating_ip_pools(request):
228
    networks = Network.objects.filter(public=True, floating_ip_pool=True,
229
                                      deleted=False)
230
    networks = utils.filter_modified_since(request, objects=networks)
231
    floating_ip_pools = map(network_to_floating_ip_pool, networks)
232
    request.serialization = "json"
233
    data = json.dumps({"floating_ip_pools": floating_ip_pools})
234
    request.serialization = "json"
235
    return HttpResponse(data, status=200)
236

    
237

    
238
def network_to_floating_ip_pool(network):
239
    """Convert a 'Network' object to a floating IP pool dict."""
240
    total, free = network.ip_count()
241
    return {"name": str(network.id),
242
            "size": total,
243
            "free": free,
244
            "deleted": network.deleted}