Statistics
| Branch: | Tag: | Revision:

root / api / networks.py @ 13b954b0

History | View | Annotate | Download (5.7 kB)

1
from synnefo.api.actions import network_actions
2
from synnefo.api.common import method_not_allowed
3
from synnefo.api.faults import BadRequest, Unauthorized
4
from synnefo.api.util import (isoformat, isoparse, get_network,
5
                                get_request_dict, api_method)
6
from synnefo.db.models import Network
7

    
8
from django.conf.urls.defaults import patterns
9
from django.http import HttpResponse
10
from django.utils import simplejson as json
11

    
12

    
13
urlpatterns = patterns('synnefo.api.networks',
14
    (r'^(?:/|.json|.xml)?$', 'demux'),
15
    (r'^/detail(?:.json|.xml)?$', 'list_networks', {'detail': True}),
16
    (r'^/(\w+)(?:.json|.xml)?$', 'network_demux'),
17
    (r'^/(\w+)/action(?:.json|.xml)?$', 'network_action'),
18
)
19

    
20

    
21
def demux(request):
22
    if request.method == 'GET':
23
        return list_networks(request)
24
    elif request.method == 'POST':
25
        return create_network(request)
26
    else:
27
        return method_not_allowed(request)
28

    
29
def network_demux(request, network):
30
    if request.method == 'GET':
31
        return get_network_details(request, network)
32
    elif request.method == 'PUT':
33
        return update_network_name(request, network)
34
    elif request.method == 'DELETE':
35
        return delete_network(request, network)
36
    else:
37
        return method_not_allowed(request)
38

    
39

    
40
def network_to_dict(network, detail=True):
41
    d = {'name': network.name}
42
    if detail:
43
        d['servers'] = {'values': [vm.id for vm in network.machines.all()]}
44
    return d
45

    
46
def render_network(request, networkdict, status=200):
47
    if request.serialization == 'xml':
48
        data = render_to_string('network.xml', {'network': networkdict})
49
    else:
50
        data = json.dumps({'network': networkdict})
51
    return HttpResponse(data, status=status)
52

    
53

    
54
@api_method('GET')
55
def list_networks(request, detail=False):
56
    # Normal Response Codes: 200, 203
57
    # Error Response Codes: computeFault (400, 500),
58
    #                       serviceUnavailable (503),
59
    #                       unauthorized (401),
60
    #                       badRequest (400),
61
    #                       overLimit (413)
62
    
63
    since = isoparse(request.GET.get('changes-since'))
64
    
65
    if since:
66
        user_networks = Network.objects.filter(owner=request.user, updated__gte=since)
67
        if not user_networks:
68
            return HttpResponse(status=304)
69
    else:
70
        user_networks = Network.objects.filter(owner=request.user)
71
    
72
    networks = [network_to_dict(network, detail) for network in user_networks]
73
    
74
    if request.serialization == 'xml':
75
        data = render_to_string('list_networks.xml', {'networks': networks, 'detail': detail})
76
    else:
77
        data = json.dumps({'networks': {'values': networks}})
78
    
79
    return HttpResponse(data, status=200)
80

    
81
@api_method('POST')
82
def create_network(request):
83
    # Normal Response Code: 202
84
    # Error Response Codes: computeFault (400, 500),
85
    #                       serviceUnavailable (503),
86
    #                       unauthorized (401),
87
    #                       badMediaType(415),
88
    #                       badRequest (400),
89
    #                       overLimit (413)
90
    
91
    req = get_request_dict(request)
92
    
93
    try:
94
        d = req['network']
95
        name = d['name']
96
    except (KeyError, ValueError):
97
        raise BadRequest('Malformed request.')
98
    
99
    network, created = Network.objects.get_or_create(name=name, owner=request.user)
100
    if not created:
101
        raise BadRequest('Network already exists.')
102
    networkdict = network_to_dict(network)
103
    return render_network(request, networkdict, status=202)
104

    
105
@api_method('GET')
106
def get_network_details(request, network):
107
    # Normal Response Codes: 200, 203
108
    # Error Response Codes: computeFault (400, 500),
109
    #                       serviceUnavailable (503),
110
    #                       unauthorized (401),
111
    #                       badRequest (400),
112
    #                       itemNotFound (404),
113
    #                       overLimit (413)
114
    
115
    net = get_network(network, request.user)
116
    netdict = network_to_dict(net)
117
    return render_network(request, netdict)
118

    
119
@api_method('PUT')
120
def update_network_name(request, network):
121
    # Normal Response Code: 204
122
    # Error Response Codes: computeFault (400, 500),
123
    #                       serviceUnavailable (503),
124
    #                       unauthorized (401),
125
    #                       badRequest (400),
126
    #                       badMediaType(415),
127
    #                       itemNotFound (404),
128
    #                       overLimit (413)
129
    
130
    req = get_request_dict(request)
131

    
132
    try:
133
        name = req['network']['name']
134
    except (TypeError, KeyError):
135
        raise BadRequest('Malformed request.')
136

    
137
    net = get_network(network, request.user)
138
    net.name = name
139
    net.save()
140
    return HttpResponse(status=204)
141

    
142
@api_method('DELETE')
143
def delete_network(request, network):
144
    # Normal Response Code: 204
145
    # Error Response Codes: computeFault (400, 500),
146
    #                       serviceUnavailable (503),
147
    #                       unauthorized (401),
148
    #                       itemNotFound (404),
149
    #                       unauthorized (401),
150
    #                       overLimit (413)
151
    
152
    net = get_network(network, request.user)
153
    net.delete()
154
    return HttpResponse(status=204)
155

    
156
@api_method('POST')
157
def network_action(request, network):
158
    net = get_network(network, request.user)
159
    req = get_request_dict(request)
160
    if len(req) != 1:
161
        raise BadRequest('Malformed request.')
162
    
163
    key = req.keys()[0]
164
    val = req[key]
165
    
166
    try:
167
        assert isinstance(val, dict)
168
        return network_actions[key](request, net, req[key])
169
    except KeyError:
170
        raise BadRequest('Unknown action.')
171
    except AssertionError:
172
        raise BadRequest('Invalid argument.')