Revision 59183afc

b/snf-cyclades-app/synnefo/api/floating_ips.py
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 import quotas
43
from synnefo.db.models import Network, FloatingIP
44

  
45

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

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

  
55

  
56
def demux(request):
57
    if request.method == 'GET':
58
        return list_floating_ips(request)
59
    elif request.method == 'POST':
60
        return allocate_floating_ip(request)
61
    else:
62
        return api.method_not_allowed(request)
63

  
64

  
65
def floating_ip_demux(request, floating_ip_id):
66
    if request.method == 'GET':
67
        return get_floating_ip(request, floating_ip_id)
68
    elif request.method == 'DELETE':
69
        return release_floating_ip(request, floating_ip_id)
70
    else:
71
        return api.method_not_allowed(request)
72

  
73

  
74
def ip_to_dict(floating_ip):
75
    machine_id = floating_ip.machine_id
76
    return {"fixed_ip": None,
77
            "id": str(floating_ip.id),
78
            "instance_id": str(machine_id) if machine_id else None,
79
            "ip": floating_ip.ipv4,
80
            "pool": str(floating_ip.network_id)}
81

  
82

  
83
@api.api_method(http_method="GET", user_required=True, logger=log)
84
def list_floating_ips(request):
85
    """Return user reserved floating IPs"""
86
    log.debug("list_floating_ips")
87

  
88
    userid = request.user_uniq
89
    floating_ips = FloatingIP.objects.filter(userid=userid, deleted=False)\
90
                                     .order_by("id")
91

  
92
    floating_ips = map(ip_to_dict, floating_ips)
93

  
94
    request.serialization = "json"
95
    data = json.dumps({"floating_ips": floating_ips})
96

  
97
    return HttpResponse(data, status=200)
98

  
99

  
100
@api.api_method(http_method="GET", user_required=True, logger=log)
101
def get_floating_ip(request, floating_ip_id):
102
    """Return information for a floating IP."""
103
    userid = request.user_uniq
104
    try:
105
        floating_ip = FloatingIP.objects.get(id=floating_ip_id,
106
                                             deleted=False,
107
                                             userid=userid)
108
    except FloatingIP.DoesNotExist:
109
        raise faults.ItemNotFound("Floating IP '%s' does not exist" %
110
                                  floating_ip_id)
111
    request.serialization = "json"
112
    data = json.dumps({"floating_ip": ip_to_dict(floating_ip)})
113
    return HttpResponse(data, status=200)
114

  
115

  
116
@api.api_method(http_method='POST', user_required=True, logger=log)
117
@transaction.commit_manually
118
def allocate_floating_ip(request):
119
    """Allocate a floating IP."""
120
    req = utils.get_request_dict(request)
121
    log.info('allocate_floating_ip %s', req)
122

  
123
    userid = request.user_uniq
124
    try:
125
        pool = req['pool']
126
    except KeyError:
127
        raise faults.BadRequest("Malformed request. Missing"
128
                                " 'pool' attribute")
129

  
130
    try:
131
        network = Network.objects.get(public=True, deleted=False, id=pool)
132
    except Network.DoesNotExist:
133
        raise faults.ItemNotFound("Pool '%s' does not exist." % pool)
134

  
135
    try:
136
        address = util.get_network_free_address(network)
137
        floating_ip = FloatingIP.objects.create(ipv4=address, network=network,
138
                                                userid=userid)
139
        quotas.issue_and_accept_commission(floating_ip)
140
    except:
141
        transaction.rollback()
142
        raise
143
    else:
144
        transaction.commit()
145

  
146
    log.info("User '%s' allocated floating IP '%s", userid, floating_ip)
147

  
148
    request.serialization = "json"
149
    data = json.dumps({"floating_ip": ip_to_dict(floating_ip)})
150
    return HttpResponse(data, status=200)
151

  
152

  
153
@api.api_method(http_method='DELETE', user_required=True, logger=log)
154
@transaction.commit_on_success
155
def release_floating_ip(request, floating_ip_id):
156
    """Release a floating IP."""
157
    userid = request.user_uniq
158
    log.info("release_floating_ip '%s'. User '%s'.", floating_ip_id, userid)
159
    try:
160
        floating_ip = FloatingIP.objects.select_for_update()\
161
                                        .get(id=floating_ip_id,
162
                                             deleted=False,
163
                                             userid=userid)
164
    except FloatingIP.DoesNotExist:
165
        raise faults.ItemNotFound("Floating IP '%s' does not exist" %
166
                                  floating_ip_id)
167

  
168
    if floating_ip.in_use():
169
        msg = "Floating IP '%s' is used" % floating_ip.id
170
        raise faults.Conflict(message=msg)
171

  
172
    try:
173
        floating_ip.network.release_address(floating_ip.ipv4)
174
        floating_ip.deleted = True
175
        quotas.issue_and_accept_commission(floating_ip, delete=True)
176
    except:
177
        transaction.rollback()
178
        raise
179
    else:
180
        floating_ip.delete()
181
        transaction.commit()
182

  
183
    log.info("User '%s' released IP '%s", userid, floating_ip)
184

  
185
    return HttpResponse(status=204)
b/snf-cyclades-app/synnefo/api/urls.py
34 34
from django.conf.urls.defaults import include, patterns
35 35

  
36 36
from snf_django.lib.api import api_endpoint_not_found
37
from synnefo.api import servers, flavors, images, networks, extensions
37
from synnefo import api
38 38
from synnefo.api.versions import versions_list, version_details
39 39

  
40 40

  
......
43 43
#
44 44
api20_patterns = patterns(
45 45
    '',
46
    (r'^servers', include(servers)),
47
    (r'^flavors', include(flavors)),
48
    (r'^images', include(images)),
49
    (r'^networks', include(networks)),
50
    (r'^extensions', include(extensions)),
46
    (r'^servers', include(api.servers)),
47
    (r'^flavors', include(api.flavors)),
48
    (r'^images', include(api.images)),
49
    (r'^networks', include(api.networks)),
50
    (r'^extensions', include(api.extensions)),
51
    (r'^os-floating-ips', include(api.floating_ips)),
51 52
)
52 53

  
53 54

  

Also available in: Unified diff