Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / images.py @ 2035039b

History | View | Annotate | Download (11.3 kB)

1
# Copyright 2011-2012 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 logging import getLogger
35

    
36
import dateutil.parser
37

    
38
from django.conf.urls.defaults import patterns
39
from django.http import HttpResponse
40
from django.template.loader import render_to_string
41
from django.utils import simplejson as json
42

    
43
from synnefo.api import util
44
from synnefo.api.common import method_not_allowed
45
from synnefo.api.faults import BadRequest, ItemNotFound, ServiceUnavailable
46
from synnefo.api.util import api_method, isoformat, isoparse
47
from synnefo.plankton.backend import ImageBackend
48

    
49

    
50
log = getLogger('synnefo.api')
51

    
52
urlpatterns = patterns('synnefo.api.images',
53
    (r'^(?:/|.json|.xml)?$', 'demux'),
54
    (r'^/detail(?:.json|.xml)?$', 'list_images', {'detail': True}),
55
    (r'^/([\w-]+)(?:.json|.xml)?$', 'image_demux'),
56
    (r'^/([\w-]+)/meta(?:.json|.xml)?$', 'metadata_demux'),
57
    (r'^/([\w-]+)/meta/(.+?)(?:.json|.xml)?$', 'metadata_item_demux')
58
)
59

    
60
def demux(request):
61
    if request.method == 'GET':
62
        return list_images(request)
63
    elif request.method == 'POST':
64
        return create_image(request)
65
    else:
66
        return method_not_allowed(request)
67

    
68
def image_demux(request, image_id):
69
    if request.method == 'GET':
70
        return get_image_details(request, image_id)
71
    elif request.method == 'DELETE':
72
        return delete_image(request, image_id)
73
    else:
74
        return method_not_allowed(request)
75

    
76
def metadata_demux(request, image_id):
77
    if request.method == 'GET':
78
        return list_metadata(request, image_id)
79
    elif request.method == 'POST':
80
        return update_metadata(request, image_id)
81
    else:
82
        return method_not_allowed(request)
83

    
84
def metadata_item_demux(request, image_id, key):
85
    if request.method == 'GET':
86
        return get_metadata_item(request, image_id, key)
87
    elif request.method == 'PUT':
88
        return create_metadata_item(request, image_id, key)
89
    elif request.method == 'DELETE':
90
        return delete_metadata_item(request, image_id, key)
91
    else:
92
        return method_not_allowed(request)
93

    
94

    
95
def image_to_dict(image, detail=True):
96
    d = dict(id=image['id'], name=image['name'])
97
    if detail:
98
        d['updated'] = isoformat(dateutil.parser.parse(image['updated_at']))
99
        d['created'] = isoformat(dateutil.parser.parse(image['created_at']))
100
        d['status'] = 'DELETED' if image['deleted_at'] else 'ACTIVE'
101
        d['progress'] = 100 if image['status'] == 'available' else 0
102
        if image['properties']:
103
            d['metadata'] = {'values': image['properties']}
104
    return d
105

    
106

    
107
@api_method('GET')
108
def list_images(request, detail=False):
109
    # Normal Response Codes: 200, 203
110
    # Error Response Codes: computeFault (400, 500),
111
    #                       serviceUnavailable (503),
112
    #                       unauthorized (401),
113
    #                       badRequest (400),
114
    #                       overLimit (413)
115
    
116
    log.debug('list_images detail=%s', detail)
117
    backend = ImageBackend(request.user)
118
    
119
    since = isoparse(request.GET.get('changes-since'))
120
    if since:
121
        images = []
122
        for image in backend.iter():
123
            updated = dateutil.parser.parse(image['updated_at'])
124
            if updated >= since:
125
                images.append(image)
126
        if not images:
127
            return HttpResponse(status=304)
128
    else:
129
        images = backend.list()
130
    
131
    reply = [image_to_dict(image, detail) for image in images]
132
    
133
    if request.serialization == 'xml':
134
        data = render_to_string('list_images.xml',
135
                                dict(images=reply, detail=detail))
136
    else:
137
        data = json.dumps(dict(images={'values': reply}))
138
    
139
    return HttpResponse(data, status=200)
140

    
141

    
142
@api_method('POST')
143
def create_image(request):
144
    # Normal Response Code: 202
145
    # Error Response Codes: computeFault (400, 500),
146
    #                       serviceUnavailable (503),
147
    #                       unauthorized (401),
148
    #                       badMediaType(415),
149
    #                       itemNotFound (404),
150
    #                       badRequest (400),
151
    #                       serverCapacityUnavailable (503),
152
    #                       buildInProgress (409),
153
    #                       resizeNotAllowed (403),
154
    #                       backupOrResizeInProgress (409),
155
    #                       overLimit (413)
156
    
157
    raise ServiceUnavailable('Not supported.')
158

    
159

    
160
@api_method('GET')
161
def get_image_details(request, image_id):
162
    # Normal Response Codes: 200, 203
163
    # Error Response Codes: computeFault (400, 500),
164
    #                       serviceUnavailable (503),
165
    #                       unauthorized (401),
166
    #                       badRequest (400),
167
    #                       itemNotFound (404),
168
    #                       overLimit (413)
169
    
170
    log.debug('get_image_details %s', image_id)
171
    image = util.get_image(image_id, request.user)
172
    reply = image_to_dict(image)
173
    
174
    if request.serialization == 'xml':
175
        data = render_to_string('image.xml', dict(image=reply))
176
    else:
177
        data = json.dumps(dict(image=reply))
178
    
179
    return HttpResponse(data, status=200)
180

    
181

    
182
@api_method('DELETE')
183
def delete_image(request, image_id):
184
    # Normal Response Code: 204
185
    # Error Response Codes: computeFault (400, 500),
186
    #                       serviceUnavailable (503),
187
    #                       unauthorized (401),
188
    #                       itemNotFound (404),
189
    #                       overLimit (413)
190
    
191
    log.debug('delete_image %s', image_id)
192
    backend = ImageBackend(request.user)
193
    backend.delete(image_id)
194
    backend.close()
195
    log.info('User %s deleted image %s', request.user, image_id)
196
    return HttpResponse(status=204)
197

    
198

    
199
@api_method('GET')
200
def list_metadata(request, image_id):
201
    # Normal Response Codes: 200, 203
202
    # Error Response Codes: computeFault (400, 500),
203
    #                       serviceUnavailable (503),
204
    #                       unauthorized (401),
205
    #                       badRequest (400),
206
    #                       overLimit (413)
207
    
208
    log.debug('list_image_metadata %s', image_id)
209
    image = util.get_image(image_id, request.user)
210
    metadata = image['properties']
211
    return util.render_metadata(request, metadata, use_values=True, status=200)
212

    
213

    
214
@api_method('POST')
215
def update_metadata(request, image_id):
216
    # Normal Response Code: 201
217
    # Error Response Codes: computeFault (400, 500),
218
    #                       serviceUnavailable (503),
219
    #                       unauthorized (401),
220
    #                       badRequest (400),
221
    #                       buildInProgress (409),
222
    #                       badMediaType(415),
223
    #                       overLimit (413)
224
    
225
    req = util.get_request_dict(request)
226
    log.debug('update_image_metadata %s %s', image_id, req)
227
    image = util.get_image(image_id, request.user)
228
    try:
229
        metadata = req['metadata']
230
        assert isinstance(metadata, dict)
231
    except (KeyError, AssertionError):
232
        raise BadRequest('Malformed request.')
233
    
234
    properties = image['properties']
235
    properties.update(metadata)
236
    
237
    backend = ImageBackend(request.user)
238
    backend.update(image_id, dict(properties=properties))
239
    backend.close()
240
    
241
    return util.render_metadata(request, properties, status=201)
242

    
243

    
244
@api_method('GET')
245
def get_metadata_item(request, image_id, key):
246
    # Normal Response Codes: 200, 203
247
    # Error Response Codes: computeFault (400, 500),
248
    #                       serviceUnavailable (503),
249
    #                       unauthorized (401),
250
    #                       itemNotFound (404),
251
    #                       badRequest (400),
252
    #                       overLimit (413)
253
    
254
    log.debug('get_image_metadata_item %s %s', image_id, key)
255
    image = util.get_image(image_id, request.user)
256
    val = image['properties'].get(key)
257
    if val is None:
258
        raise ItemNotFound('Metadata key not found.')
259
    return util.render_meta(request, {key: val}, status=200)
260

    
261

    
262
@api_method('PUT')
263
def create_metadata_item(request, image_id, key):
264
    # Normal Response Code: 201
265
    # Error Response Codes: computeFault (400, 500),
266
    #                       serviceUnavailable (503),
267
    #                       unauthorized (401),
268
    #                       itemNotFound (404),
269
    #                       badRequest (400),
270
    #                       buildInProgress (409),
271
    #                       badMediaType(415),
272
    #                       overLimit (413)
273
    
274
    req = util.get_request_dict(request)
275
    log.debug('create_image_metadata_item %s %s %s', image_id, key, req)
276
    try:
277
        metadict = req['meta']
278
        assert isinstance(metadict, dict)
279
        assert len(metadict) == 1
280
        assert key in metadict
281
    except (KeyError, AssertionError):
282
        raise BadRequest('Malformed request.')
283

    
284
    val = metadict[key]
285
    image = util.get_image(image_id, request.user)
286
    properties = image['properties']
287
    properties[key] = val
288
    
289
    backend = ImageBackend(request.user)
290
    backend.update(image_id, dict(properties=properties))
291
    backend.close()
292
    
293
    return util.render_meta(request, {key: val}, status=201)
294

    
295

    
296
@api_method('DELETE')
297
def delete_metadata_item(request, image_id, key):
298
    # Normal Response Code: 204
299
    # Error Response Codes: computeFault (400, 500),
300
    #                       serviceUnavailable (503),
301
    #                       unauthorized (401),
302
    #                       itemNotFound (404),
303
    #                       badRequest (400),
304
    #                       buildInProgress (409),
305
    #                       badMediaType(415),
306
    #                       overLimit (413),
307
    
308
    log.debug('delete_image_metadata_item %s %s', image_id, key)
309
    image = util.get_image(image_id, request.user)
310
    properties = image['properties']
311
    properties.pop(key, None)
312
    
313
    backend = ImageBackend(request.user)
314
    backend.update(image_id, dict(properties=properties))
315
    backend.close()
316
    
317
    return HttpResponse(status=204)