Commit 99b81c02 authored by Christos Stavrakakis's avatar Christos Stavrakakis
Browse files

cyclades: Fix code for networks logic and API

parent ee483f14
# Copyright 2011-2013 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials
# provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.
from django.conf import settings
from django.conf.urls import patterns
from django.http import HttpResponse
from django.utils import simplejson as json
from django.db import transaction
from django.db.models import Q
from synnefo.db.pools import EmptyPool
from synnefo.db.utils import validate_mac
from django.conf import settings
from snf_django.lib import api
from snf_django.lib.api import utils
from synnefo.logic import backend
from django.template.loader import render_to_string
from snf_django.lib import api
from synnefo.api import util
from synnefo.db.models import Network
from synnefo.logic import networks
from logging import getLogger
from synnefo import quotas
log = getLogger(__name__)
urlpatterns = patterns(
'synnefo.api.networks',
(r'^(?:/|.json|.xml)?$', 'demux'),
(r'^/detail(?:.json|.xml)?$', 'list_networks', {'detail': True}),
(r'^/(\w+)(?:/|.json|.xml)?$', 'network_demux'))
def demux(request):
if request.method == 'GET':
#return HttpResponse("in network get")
return list_networks(request)
elif request.method == 'POST':
return create_network(request)
#return HttpResponse("in network post")
else:
return api.api_method_not_allowed(request)
def network_demux(request, offset):
def network_demux(request, network_id):
if request.method == 'GET':
return get_network(request, offset)
#return HttpResponse("in network det get")
return get_network_details(request, network_id)
elif request.method == 'DELETE':
return delete_network(request, offset)
#return HttpResponse("in network det delete")
return delete_network(request, network_id)
elif request.method == 'PUT':
return update_network(request, offset)
#return HttpResponse("in network det put")
return update_network(request, network_id)
else:
return api.api_method_not_allowed(request)
......@@ -57,174 +81,84 @@ def network_demux(request, offset):
def list_networks(request, detail=False):
log.debug('list_networks detail=%s', detail)
user_networks = Network.objects.filter(
Q(userid=request.user_uniq) | Q(public=True))
user_networks = Network.objects.filter(Q(userid=request.user_uniq) |
Q(public=True))\
.prefetch_related("subnets")
user_networks = utils.filter_modified_since(request, objects=user_networks)
user_networks = api.utils.filter_modified_since(request,
objects=user_networks)
networks = [network_to_dict(network, detail)
for network in user_networks.order_by('id')]
network_dicts = [network_to_dict(network, detail)
for network in user_networks.order_by('id')]
if request.serialization == 'xml':
data = render_to_string('list_networks.xml', {
"networks": networks})
"networks": network_dicts})
else:
data = json.dumps({'networks': networks})
data = json.dumps({'networks': network_dicts})
return HttpResponse(data, status=200)
@api.api_method(http_method='POST', user_required=True, logger=log)
@transaction.commit_manually
def create_network(request):
try:
user_id = request.user_uniq
req = utils.get_request_dict(request)
log.info('create_network %s', req)
try:
d = req['network']
except KeyError:
raise api.faults.BadRequest("Malformed request")
try:
flavor = d['type']
except KeyError:
raise api.faults.BadRequest("Missing request parameter 'type'")
if flavor not in Network.FLAVORS.keys():
raise api.faults.BadRequest("Invalid network type '%s'"
% flavor)
if flavor not in settings.API_ENABLED_NETWORK_FLAVORS:
msg = "Can not create network of type '%s'"
raise api.faults.Forbidden(msg % flavor)
try:
name = d['name']
except KeyError:
name = ""
try:
#mode, link, mac_prefix, tags = util.values_from_flavor(flavor)
#validate_mac(mac_prefix + "0:00:00:00")
network = Network.objects.create(
name=name,
userid=user_id,
flavor=flavor,
#mode=mode,
#link=link,
#mac_prefix=mac_prefix,
#tags=tags,
action='CREATE',
state='ACTIVE')
except EmptyPool:
msg = "Failed to allocate resources for network of type: %s"
log.error(msg, flavor)
raise api.faults.ServiceUnavailable("Failed to allocate network\
resources")
# Issue commission to Quotaholder and accept it since at the end of
# this transaction the Network object will be created in the DB.
# Note: the following call does a commit!
#quotas.issue_and_accept_commission(network)
# COME BACK....
except:
transaction.rollback()
log.info("roll")
raise
else:
transaction.commit()
log.info("commit")
networkdict = network_to_dict(network)
userid = request.user_uniq
req = api.utils.get_request_dict(request)
log.info('create_network %s', req)
network_dict = api.utils.get_attribute(req, "network")
flavor = api.utils.get_attribute(network_dict, "type")
if flavor not in Network.FLAVORS.keys():
raise api.faults.BadRequest("Invalid network type '%s'" % flavor)
if flavor not in settings.API_ENABLED_NETWORK_FLAVORS:
raise api.faults.Forbidden("Can not create network of type '%s'." %
flavor)
name = api.utils.get_attribute(network_dict, "name", required=False)
if name is None:
name = ""
network = networks.create(userid=userid, name=name, flavor=flavor,
public=False)
networkdict = network_to_dict(network, detail=True)
response = render_network(request, networkdict, status=201)
return response
@api.api_method(http_method='GET', user_required=True, logger=log)
def get_network(request, network_id):
def get_network_details(request, network_id):
log.debug('get_network_details %s', network_id)
net = util.get_network(network_id, request.user_uniq)
network = util.get_network(network_id, request.user_uniq)
return render_network(request, network_to_dict(network, detail=True))
#needs discussion
if net.deleted:
raise api.faults.BadRequest("Network has been deleted.")
else:
netdict = network_to_dict(net)
return render_network(request, netdict)
@api.api_method(http_method='PUT', user_required=True, logger=log)
def update_network(request, network_id):
info = api.utils.get_request_dict(request)
network = api.utils.get_attribute(info, "network", required=True)
new_name = api.utils.get_attribute(network, "name")
network = util.get_network(network_id, request.user_uniq, for_update=True)
if network.public:
raise api.faults.Forbidden("Can not rename the public network.")
network = networks.rename(network, new_name)
return render_network(request, network_to_dict(network), 200)
@api.api_method(http_method='DELETE', user_required=True, logger=log)
@transaction.commit_on_success
def delete_network(request, network_id):
log.info('delete_network %s', network_id)
net = util.get_network(network_id, request.user_uniq, for_update=True)
log.info(net.name)
if net.public:
raise api.faults.Forbidden('Can not delete the public network.')
if net.deleted:
raise api.faults.BadRequest("Network has been deleted.")
if net.machines.all(): # Nics attached on network
#raise api.faults.NetworkInUse('Machines are connected to network.')
#edit to return with 409
return HttpResponse("Network in use", status=409)
#check if there are any floating ips reserved
#if net.floating_ips.all():
# #raise api.faults.NetworkInUse('Machines are connected to network.')
# #edit to return with 409
# return HttpResponse("Network in use", status=409)
net.action = 'DESTROY'
'''
skip the backend part...
backend_networks = net.backend_networks.exclude(operstate="DELETED")
for bnet in backend_networks:
backend.delete_network(net, bnet.backend)
if not backend_networks:
backend.update_network_state(net)
'''
#delete all the subnets
for s in net.subnets.all():
s.deleted = True
#the following has to leave when fix the backend thing
net.deleted = True
net.save()
network = util.get_network(network_id, request.user_uniq, for_update=True)
if network.public:
raise api.faults.Forbidden("Can not delete the public network.")
networks.delete(network)
return HttpResponse(status=204)
@api.api_method(http_method='PUT', user_required=True, logger=log)
def update_network(request, network_id):
'''
You can update only name
'''
net = util.get_network(network_id, request.user_uniq, for_update=True)
info = utils.get_request_dict(request)
updatable = set(["name"])
try:
new_vals = info["network"]
except KeyError:
raise api.faults.BadRequest("Malformed request")
for key, val in new_vals.iteritems():
if key in updatable:
setattr(net, key, val)
else:
raise api.faults.BadRequest("Wrong field update")
net.save()
netdict = network_to_dict(net)
return render_network(request, netdict, 200)
def network_to_dict(network, detail=True):
d = {'id': str(network.id), 'name': network.name}
d['links'] = util.network_to_links(network.id)
......@@ -232,15 +166,13 @@ def network_to_dict(network, detail=True):
d['user_id'] = network.userid
d['tenant_id'] = network.userid
d['type'] = network.flavor
d['updated'] = utils.isoformat(network.updated)
d['created'] = utils.isoformat(network.created)
d['updated'] = api.utils.isoformat(network.updated)
d['created'] = api.utils.isoformat(network.created)
d['status'] = network.state
d['public'] = network.public
d['external_router'] = network.external_router
d['external_router'] = network.external_router
d['admin_state_up'] = True
subnet_cidr = [s.id for s in network.subnets.all()]
d['subnets'] = subnet_cidr
d['subnets'] = list(network.subnets.values_list('id', flat=True))
return d
......
......@@ -212,7 +212,7 @@ def get_network(network_id, user_id, for_update=False, non_deleted=False):
try:
network_id = int(network_id)
objects = Network.objects
objects = Network.objects.prefetch_related("subnets")
if for_update:
objects = objects.select_for_update()
network = objects.get(Q(userid=user_id) | Q(public=True),
......
......@@ -466,6 +466,12 @@ def update_network_state(network):
return
elif not network.public:
log.warning("Network %s does not have an owner!", network.id)
# TODO!!!!!
# Set all subnets as deleted
network.subnets.update(deleted=True)
# And delete the IP pools
network.subnets.ip_pools.all().delete()
network.save()
......
......@@ -65,7 +65,7 @@ def network_command(action):
@transaction.commit_on_success
def create(user_id, name, flavor, subnet=None, gateway=None, subnet6=None,
def create(userid, name, flavor, subnet=None, gateway=None, subnet6=None,
gateway6=None, public=False, dhcp=True, link=None, mac_prefix=None,
mode=None, floating_ip_pool=False, tags=None, backends=None,
lazy_create=True):
......@@ -80,7 +80,7 @@ def create(user_id, name, flavor, subnet=None, gateway=None, subnet6=None,
raise faults.BadRequest("Can not override PHYSICAL_VLAN link")
if subnet is None and floating_ip_pool:
raise faults.BadRequest("IPv6 only networks can not be"
raise faults.BadRequest("IPv6 only networks can not be floating"
" pools.")
# Check that network parameters are valid
validate_network_params(subnet, gateway, subnet6, gateway6)
......@@ -107,7 +107,7 @@ def create(user_id, name, flavor, subnet=None, gateway=None, subnet6=None,
network = Network.objects.create(
name=name,
userid=user_id,
userid=userid,
flavor=flavor,
mode=mode,
link=link,
......@@ -160,11 +160,11 @@ def rename(network, name):
@network_command("DESTROY")
def delete(network):
if network.machines.exists():
raise faults.NetworkInUse("Can not delete network. Servers connected"
" to this network exists.")
if network.floating_ips.filter(deleted=False).exists():
raise faults.Conflict("Can not delete network. Servers connected"
" to this network exists.")
if network.ips.filter(deleted=False, floating_ip=True).exists():
msg = "Can not delete netowrk. Network has allocated floating IPs."
raise faults.NetworkInUse(msg)
raise faults.Conflict(msg)
network.action = "DESTROY"
network.save()
......@@ -180,9 +180,6 @@ def delete(network):
def validate_network_params(subnet=None, gateway=None, subnet6=None,
gateway6=None):
if (subnet is None) and (subnet6 is None):
raise faults.BadRequest("subnet or subnet6 is required")
if subnet:
try:
# Use strict option to not all subnets with host bits set
......
......@@ -44,7 +44,7 @@ class NetworkTest(TestCase):
def test_create(self):
kwargs = {
"name": "test",
"user_id": "user",
"userid": "user",
"subnet": "192.168.20.0/24",
"flavor": "CUSTOM",
}
......@@ -130,7 +130,7 @@ class NetworkTest(TestCase):
def test_create_network_ipv6(self):
kwargs = {
"name": "test",
"user_id": "user",
"userid": "user",
"flavor": "CUSTOM",
"subnet6": "2001:648:2ffc:1112::/64",
}
......
......@@ -133,3 +133,11 @@ def filter_modified_since(request, objects):
return modified_objs
else:
return objects.filter(deleted=False)
def get_attribute(request, attribute, required=True):
value = request.get(attribute, None)
if required and value is None:
raise faults.BadRequest("Malformed request. Missing attribute '%s'." %
attribute)
return value
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment