Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / ports.py @ 69c8d65d

History | View | Annotate | Download (8.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

    
34
#from django.conf import settings
35
import ipaddr
36
from django.conf.urls import patterns
37
from django.http import HttpResponse
38
from django.utils import simplejson as json
39
from django.db import transaction
40
from django.template.loader import render_to_string
41

    
42
from snf_django.lib import api
43
from snf_django.lib.api import faults
44

    
45
from synnefo.api import util
46
from synnefo.db.models import NetworkInterface
47
from synnefo.logic import ports
48

    
49
from logging import getLogger
50

    
51
log = getLogger(__name__)
52

    
53
urlpatterns = patterns(
54
    'synnefo.api.ports',
55
    (r'^(?:/|.json|.xml)?$', 'demux'),
56
    (r'^/([-\w]+)(?:/|.json|.xml)?$', 'port_demux'))
57

    
58

    
59
def demux(request):
60
    if request.method == 'GET':
61
        return list_ports(request)
62
    elif request.method == 'POST':
63
        return create_port(request)
64
    else:
65
        return api.api_method_not_allowed(request)
66

    
67

    
68
def port_demux(request, port_id):
69

    
70
    if request.method == 'GET':
71
        return get_port_details(request, port_id)
72
    elif request.method == 'DELETE':
73
        return delete_port(request, port_id)
74
    elif request.method == 'PUT':
75
        return update_port(request, port_id)
76
    else:
77
        return api.api_method_not_allowed(request)
78

    
79

    
80
@api.api_method(http_method='GET', user_required=True, logger=log)
81
def list_ports(request, detail=False):
82

    
83
    log.debug('list_ports detail=%s', detail)
84

    
85
    user_ports = NetworkInterface.objects.filter(
86
        machine__userid=request.user_uniq)
87

    
88
    port_dicts = [port_to_dict(port, detail)
89
                  for port in user_ports.order_by('id')]
90

    
91
    if request.serialization == 'xml':
92
        data = render_to_string('list_ports.xml', {
93
            "ports": port_dicts})
94
    else:
95
        data = json.dumps({'ports': port_dicts})
96

    
97
    return HttpResponse(data, status=200)
98

    
99

    
100
@api.api_method(http_method='POST', user_required=True, logger=log)
101
def create_port(request):
102
    user_id = request.user_uniq
103
    req = api.utils.get_request_dict(request)
104
    log.info('create_port %s', req)
105

    
106
    port_dict = api.utils.get_attribute(req, "port")
107
    net_id = api.utils.get_attribute(port_dict, "network_id")
108
    dev_id = api.utils.get_attribute(port_dict, "device_id")
109

    
110
    network = util.get_network(net_id, user_id, non_deleted=True)
111

    
112
    # Check if the request contains a valid IPv4 address
113
    fixed_ips = api.utils.get_attribute(port_dict, "fixed_ips", required=False)
114
    if fixed_ips is not None and len(fixed_ips) > 0:
115
        if len(fixed_ips) > 1:
116
            msg = "'fixed_ips' attribute must contain only one fixed IP."
117
            raise faults.BadRequest(msg)
118
        fixed_ip_address = fixed_ips[0].get("ip_address")
119
        if fixed_ip_address is not None:
120
            try:
121
                ip = ipaddr.IPAddress(fixed_ip_address)
122
                if ip.version == 6:
123
                    msg = "'ip_address' can be only an IPv4 address'"
124
                    raise faults.BadRequest(msg)
125
            except ValueError:
126
                msg = "%s is not a valid IPv4 Address" % fixed_ip_address
127
                raise faults.BadRequest(msg)
128
    else:
129
        fixed_ip_address = None
130

    
131
    ipaddress = None
132
    if network.public:
133
        # Creating a port to a public network is only allowed if the user has
134
        # already a floating IP address in this network which is specified
135
        # as the fixed IP address of the port
136
        if fixed_ip_address is None:
137
            msg = ("'fixed_ips' attribute must contain a floating IP address"
138
                   " in order to connect to a public network.")
139
            raise faults.BadRequest(msg)
140
        ipaddress = util.get_floating_ip_by_address(user_id, fixed_ip_address,
141
                                                    for_update=True)
142
    elif fixed_ip_address:
143
        ipaddress = util.allocate_ip(network, user_id,
144
                                     address=fixed_ip_address)
145

    
146
    vm = util.get_vm(dev_id, user_id, for_update=True, non_deleted=True,
147
                     non_suspended=True)
148

    
149
    name = api.utils.get_attribute(port_dict, "name", required=False)
150
    if name is None:
151
        name = ""
152

    
153
    security_groups = api.utils.get_attribute(port_dict,
154
                                              "security_groups",
155
                                              required=False)
156
    #validate security groups
157
    # like get security group from db
158
    sg_list = []
159
    if security_groups:
160
        for gid in security_groups:
161
            sg = util.get_security_group(int(gid))
162
            sg_list.append(sg)
163

    
164
    new_port = ports.create(network, vm, ipaddress=ipaddress,
165
                            security_groups=sg_list)
166

    
167
    response = render_port(request, port_to_dict(new_port), status=201)
168

    
169
    return response
170

    
171

    
172
@api.api_method(http_method='GET', user_required=True, logger=log)
173
def get_port_details(request, port_id):
174
    log.debug('get_port_details %s', port_id)
175
    port = util.get_port(port_id, request.user_uniq)
176
    return render_port(request, port_to_dict(port))
177

    
178

    
179
@api.api_method(http_method='PUT', user_required=True, logger=log)
180
def update_port(request, port_id):
181
    '''
182
    You can update only name, security_groups
183
    '''
184
    port = util.get_port(port_id, request.user_uniq, for_update=True)
185
    req = api.utils.get_request_dict(request)
186

    
187
    port_info = api.utils.get_attribute(req, "port", required=True)
188
    name = api.utils.get_attribute(port_info, "name", required=False)
189

    
190
    if name:
191
        port.name = name
192

    
193
    security_groups = api.utils.get_attribute(port_info, "security_groups",
194
                                              required=False)
195
    if security_groups:
196
        sg_list = []
197
        #validate security groups
198
        for gid in security_groups:
199
            sg = util.get_security_group(int(gid))
200
            sg_list.append(sg)
201

    
202
        #clear the old security groups
203
        port.security_groups.clear()
204

    
205
        #add the new groups
206
        port.security_groups.add(*sg_list)
207

    
208
    port.save()
209
    return render_port(request, port_to_dict(port), 200)
210

    
211

    
212
@api.api_method(http_method='DELETE', user_required=True, logger=log)
213
@transaction.commit_on_success
214
def delete_port(request, port_id):
215
    log.info('delete_port %s', port_id)
216
    user_id = request.user_uniq
217
    port = util.get_port(port_id, user_id, for_update=True)
218
    ports.delete(port)
219
    return HttpResponse(status=204)
220

    
221
#util functions
222

    
223

    
224
def port_to_dict(port, detail=True):
225
    d = {'id': str(port.id), 'name': port.name}
226
    if detail:
227
        user_id = port.machine.id
228
        d['user_id'] = user_id
229
        d['tenant_id'] = user_id
230
        d['device_id'] = str(port.machine.id)
231
        # TODO: Change this based on the status of VM
232
        d['admin_state_up'] = True
233
        d['mac_address'] = port.mac
234
        d['status'] = port.state
235
        d['device_owner'] = port.device_owner
236
        d['network_id'] = str(port.network.id)
237
        d['updated'] = api.utils.isoformat(port.updated)
238
        d['created'] = api.utils.isoformat(port.created)
239
        d['fixed_ips'] = []
240
        for ip in port.ips.all():
241
            d['fixed_ips'].append({"ip_address": ip.address,
242
                                   "subnet": str(ip.subnet.id)})
243
        sg_list = list(port.security_groups.values_list('id', flat=True))
244
        d['security_groups'] = map(str, sg_list)
245

    
246
    return d
247

    
248

    
249
def render_port(request, portdict, status=200):
250
    if request.serialization == 'xml':
251
        data = render_to_string('port.xml', {'port': portdict})
252
    else:
253
        data = json.dumps({'port': portdict})
254
    return HttpResponse(data, status=status)