images.py 9.37 KB
Newer Older
1
2
3
4
#
# Copyright (c) 2010 Greek Research and Technology Network
#

Giorgos Verigakis's avatar
Giorgos Verigakis committed
5
from synnefo.api.common import method_not_allowed
6
from synnefo.api.util import *
Giorgos Verigakis's avatar
Giorgos Verigakis committed
7
from synnefo.db.models import Image, ImageMetadata, VirtualMachine
8

Giorgos Verigakis's avatar
Giorgos Verigakis committed
9
from django.conf.urls.defaults import patterns
10
11
from django.http import HttpResponse
from django.template.loader import render_to_string
12
from django.utils import simplejson as json
13
14
15
16
17
18


urlpatterns = patterns('synnefo.api.images',
    (r'^(?:/|.json|.xml)?$', 'demux'),
    (r'^/detail(?:.json|.xml)?$', 'list_images', {'detail': True}),
    (r'^/(\d+)(?:.json|.xml)?$', 'image_demux'),
19
20
    (r'^/(\d+)/meta(?:.json|.xml)?$', 'metadata_demux'),
    (r'^/(\d+)/meta/(.+?)(?:.json|.xml)?$', 'metadata_item_demux'),
21
22
23
24
25
26
27
28
)

def demux(request):
    if request.method == 'GET':
        return list_images(request)
    elif request.method == 'POST':
        return create_image(request)
    else:
Giorgos Verigakis's avatar
Giorgos Verigakis committed
29
        return method_not_allowed(request)
30
31
32
33
34
35
36

def image_demux(request, image_id):
    if request.method == 'GET':
        return get_image_details(request, image_id)
    elif request.method == 'DELETE':
        return delete_image(request, image_id)
    else:
Giorgos Verigakis's avatar
Giorgos Verigakis committed
37
        return method_not_allowed(request)
38

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def metadata_demux(request, image_id):
    if request.method == 'GET':
        return list_metadata(request, image_id)
    elif request.method == 'POST':
        return update_metadata(request, image_id)
    else:
        return method_not_allowed(request)

def metadata_item_demux(request, image_id, key):
    if request.method == 'GET':
        return get_metadata_item(request, image_id, key)
    elif request.method == 'PUT':
        return create_metadata_item(request, image_id, key)
    elif request.method == 'DELETE':
        return delete_metadata_item(request, image_id, key)
    else:
        return method_not_allowed(request)

57
58
59
60

def image_to_dict(image, detail=True):
    d = {'id': image.id, 'name': image.name}
    if detail:
Giorgos Verigakis's avatar
Giorgos Verigakis committed
61
62
        d['updated'] = isoformat(image.updated)
        d['created'] = isoformat(image.created)
63
64
65
66
        d['status'] = image.state
        d['progress'] = 100 if image.state == 'ACTIVE' else 0
        if image.sourcevm:
            d['serverRef'] = image.sourcevm.id
67
68
69
70
71
72
73
74
        
        metadata = {}
        for meta in ImageMetadata.objects.filter(image=image):
            metadata[meta.meta_key] = meta.meta_value
        
        if metadata:
            d['metadata'] = {'values': metadata}
    
75
76
    return d

77
78
79
80
def metadata_to_dict(image):
    image_meta = image.imagemetadata_set.all()
    return dict((meta.meta_key, meta.meta_value) for meta in image_meta)

81
82
83
84
85
86
87
88
89
90

@api_method('GET')
def list_images(request, detail=False):
    # Normal Response Codes: 200, 203
    # Error Response Codes: computeFault (400, 500),
    #                       serviceUnavailable (503),
    #                       unauthorized (401),
    #                       badRequest (400),
    #                       overLimit (413)
    
Giorgos Verigakis's avatar
Giorgos Verigakis committed
91
    since = isoparse(request.GET.get('changes-since'))
92
    
Giorgos Verigakis's avatar
Giorgos Verigakis committed
93
94
95
96
97
98
99
100
101
102
    if since:
        avail_images = Image.objects.filter(updated__gt=since)
        if not avail_images:
            return HttpResponse(status=304)
    else:
        avail_images = Image.objects.all()
    
    images = [image_to_dict(image, detail) for image in avail_images]
    
    if request.serialization == 'xml':
103
104
105
106
        data = render_to_string('list_images.xml', {'images': images, 'detail': detail})
    else:
        data = json.dumps({'images': {'values': images}})
    
Giorgos Verigakis's avatar
Giorgos Verigakis committed
107
    return HttpResponse(data, status=200)
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

@api_method('POST')
def create_image(request):
    # Normal Response Code: 202
    # Error Response Codes: computeFault (400, 500),
    #                       serviceUnavailable (503),
    #                       unauthorized (401),
    #                       badMediaType(415),
    #                       itemNotFound (404),
    #                       badRequest (400),
    #                       serverCapacityUnavailable (503),
    #                       buildInProgress (409),
    #                       resizeNotAllowed (403),
    #                       backupOrResizeInProgress (409),
    #                       overLimit (413)
    
    req = get_request_dict(request)
    
    try:
        d = req['image']
128
129
130
131
132
133
134
135
136
        server_id = d['serverRef']
        name = d['name']
    except (KeyError, ValueError):
        raise BadRequest('Malformed request.')
    
    owner = get_user()
    vm = get_vm(server_id)
    image = Image.objects.create(name=name, size=0, owner=owner, sourcevm=vm)
    image.save()
137
138
    
    imagedict = image_to_dict(image)
Giorgos Verigakis's avatar
Giorgos Verigakis committed
139
    if request.serialization == 'xml':
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
        data = render_to_string('image.xml', {'image': imagedict})
    else:
        data = json.dumps({'image': imagedict})
    
    return HttpResponse(data, status=202)

@api_method('GET')
def get_image_details(request, image_id):
    # Normal Response Codes: 200, 203
    # Error Response Codes: computeFault (400, 500),
    #                       serviceUnavailable (503),
    #                       unauthorized (401),
    #                       badRequest (400),
    #                       itemNotFound (404),
    #                       overLimit (413)
    
Giorgos Verigakis's avatar
Giorgos Verigakis committed
156
157
    image = get_image(image_id)
    imagedict = image_to_dict(image)
158
    
Giorgos Verigakis's avatar
Giorgos Verigakis committed
159
    if request.serialization == 'xml':
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
        data = render_to_string('image.xml', {'image': imagedict})
    else:
        data = json.dumps({'image': imagedict})
    
    return HttpResponse(data, status=200)

@api_method('DELETE')
def delete_image(request, image_id):
    # Normal Response Code: 204
    # Error Response Codes: computeFault (400, 500),
    #                       serviceUnavailable (503),
    #                       unauthorized (401),
    #                       itemNotFound (404),
    #                       overLimit (413)
    
Giorgos Verigakis's avatar
Giorgos Verigakis committed
175
    image = get_image(image_id)
176
177
178
179
    if image.owner != get_user():
        raise Unauthorized()
    image.delete()
    return HttpResponse(status=204)
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280

@api_method('GET')
def list_metadata(request, image_id):
    # Normal Response Codes: 200, 203
    # Error Response Codes: computeFault (400, 500),
    #                       serviceUnavailable (503),
    #                       unauthorized (401),
    #                       badRequest (400),
    #                       overLimit (413)

    image = get_image(image_id)
    metadata = metadata_to_dict(image)
    return render_metadata(request, metadata, use_values=True, status=200)

@api_method('POST')
def update_metadata(request, image_id):
    # Normal Response Code: 201
    # Error Response Codes: computeFault (400, 500),
    #                       serviceUnavailable (503),
    #                       unauthorized (401),
    #                       badRequest (400),
    #                       buildInProgress (409),
    #                       badMediaType(415),
    #                       overLimit (413)

    image = get_image(image_id)
    req = get_request_dict(request)
    try:
        metadata = req['metadata']
        assert isinstance(metadata, dict)
    except (KeyError, AssertionError):
        raise BadRequest('Malformed request.')

    updated = {}

    for key, val in metadata.items():
        try:
            meta = ImageMetadata.objects.get(meta_key=key, image=image)
            meta.meta_value = val
            meta.save()
            updated[key] = val
        except ImageMetadata.DoesNotExist:
            pass    # Ignore non-existent metadata

    return render_metadata(request, metadata, status=201)

@api_method('GET')
def get_metadata_item(request, image_id, key):
    # Normal Response Codes: 200, 203
    # Error Response Codes: computeFault (400, 500),
    #                       serviceUnavailable (503),
    #                       unauthorized (401),
    #                       itemNotFound (404),
    #                       badRequest (400),
    #                       overLimit (413)

    meta = get_image_meta(image_id, key)
    return render_meta(request, meta, status=200)

@api_method('PUT')
def create_metadata_item(request, image_id, key):
    # Normal Response Code: 201
    # Error Response Codes: computeFault (400, 500),
    #                       serviceUnavailable (503),
    #                       unauthorized (401),
    #                       itemNotFound (404),
    #                       badRequest (400),
    #                       buildInProgress (409),
    #                       badMediaType(415),
    #                       overLimit (413)

    image = get_image(image_id)
    req = get_request_dict(request)
    try:
        metadict = req['meta']
        assert isinstance(metadict, dict)
        assert len(metadict) == 1
        assert key in metadict
    except (KeyError, AssertionError):
        raise BadRequest('Malformed request.')

    meta, created = ImageMetadata.objects.get_or_create(meta_key=key, image=image)
    meta.meta_value = metadict[key]
    meta.save()
    return render_meta(request, meta, status=201)

@api_method('DELETE')
def delete_metadata_item(request, image_id, key):
    # Normal Response Code: 204
    # Error Response Codes: computeFault (400, 500),
    #                       serviceUnavailable (503),
    #                       unauthorized (401),
    #                       itemNotFound (404),
    #                       badRequest (400),
    #                       buildInProgress (409),
    #                       badMediaType(415),
    #                       overLimit (413),

    meta = get_image_meta(image_id, key)
    meta.delete()
    return HttpResponse(status=204)