Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / images.py @ 8a992938

History | View | Annotate | Download (11.7 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
from itertools import ifilter
36

    
37
from dateutil.parser import parse as date_parse
38

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

    
44
from snf_django.lib import api
45
from snf_django.lib.api import faults, utils
46
from synnefo.api import util
47
from synnefo.plankton.utils import image_backend
48

    
49

    
50
log = getLogger(__name__)
51

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

    
61

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

    
70

    
71
def image_demux(request, image_id):
72
    if request.method == 'GET':
73
        return get_image_details(request, image_id)
74
    elif request.method == 'DELETE':
75
        return delete_image(request, image_id)
76
    else:
77
        return api.method_not_allowed(request)
78

    
79

    
80
def metadata_demux(request, image_id):
81
    if request.method == 'GET':
82
        return list_metadata(request, image_id)
83
    elif request.method == 'POST':
84
        return update_metadata(request, image_id)
85
    else:
86
        return api.method_not_allowed(request)
87

    
88

    
89
def metadata_item_demux(request, image_id, key):
90
    if request.method == 'GET':
91
        return get_metadata_item(request, image_id, key)
92
    elif request.method == 'PUT':
93
        return create_metadata_item(request, image_id, key)
94
    elif request.method == 'DELETE':
95
        return delete_metadata_item(request, image_id, key)
96
    else:
97
        return api.method_not_allowed(request)
98

    
99

    
100
def image_to_dict(image, detail=True):
101
    d = dict(id=image['id'], name=image['name'])
102
    if detail:
103
        d['updated'] = utils.isoformat(date_parse(image['updated_at']))
104
        d['created'] = utils.isoformat(date_parse(image['created_at']))
105
        d['status'] = 'DELETED' if image['deleted_at'] else 'ACTIVE'
106
        d['progress'] = 100 if image['status'] == 'available' else 0
107
        if image['properties']:
108
            d['metadata'] = {'values': image['properties']}
109
    return d
110

    
111

    
112
@api.api_method("GET", user_required=True, logger=log)
113
def list_images(request, detail=False):
114
    # Normal Response Codes: 200, 203
115
    # Error Response Codes: computeFault (400, 500),
116
    #                       serviceUnavailable (503),
117
    #                       unauthorized (401),
118
    #                       badRequest (400),
119
    #                       overLimit (413)
120

    
121
    log.debug('list_images detail=%s', detail)
122
    since = utils.isoparse(request.GET.get('changes-since'))
123
    with image_backend(request.user_uniq) as backend:
124
        images = backend.list_images()
125
        if since:
126
            updated_since = lambda img: date_parse(img["updated_at"]) >= since
127
            images = ifilter(updated_since, images)
128
            if not images:
129
                return HttpResponse(status=304)
130

    
131
    images = sorted(images, key=lambda x: x['id'])
132
    reply = [image_to_dict(image, detail) for image in images]
133

    
134
    if request.serialization == 'xml':
135
        data = render_to_string('list_images.xml',
136
                                dict(images=reply, detail=detail))
137
    else:
138
        data = json.dumps(dict(images={'values': reply}))
139

    
140
    return HttpResponse(data, status=200)
141

    
142

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

    
158
    raise faults.NotImplemented('Not supported.')
159

    
160

    
161
@api.api_method('GET', user_required=True, logger=log)
162
def get_image_details(request, image_id):
163
    # Normal Response Codes: 200, 203
164
    # Error Response Codes: computeFault (400, 500),
165
    #                       serviceUnavailable (503),
166
    #                       unauthorized (401),
167
    #                       badRequest (400),
168
    #                       itemNotFound (404),
169
    #                       overLimit (413)
170

    
171
    log.debug('get_image_details %s', image_id)
172
    with image_backend(request.user_uniq) as backend:
173
        image = backend.get_image(image_id)
174
    reply = image_to_dict(image)
175

    
176
    if request.serialization == 'xml':
177
        data = render_to_string('image.xml', dict(image=reply))
178
    else:
179
        data = json.dumps(dict(image=reply))
180

    
181
    return HttpResponse(data, status=200)
182

    
183

    
184
@api.api_method('DELETE', user_required=True, logger=log)
185
def delete_image(request, image_id):
186
    # Normal Response Code: 204
187
    # Error Response Codes: computeFault (400, 500),
188
    #                       serviceUnavailable (503),
189
    #                       unauthorized (401),
190
    #                       itemNotFound (404),
191
    #                       overLimit (413)
192

    
193
    log.info('delete_image %s', image_id)
194
    with image_backend(request.user_uniq) as backend:
195
        backend.unregister(image_id)
196
    log.info('User %s deleted image %s', request.user_uniq, image_id)
197
    return HttpResponse(status=204)
198

    
199

    
200
@api.api_method('GET', user_required=True, logger=log)
201
def list_metadata(request, image_id):
202
    # Normal Response Codes: 200, 203
203
    # Error Response Codes: computeFault (400, 500),
204
    #                       serviceUnavailable (503),
205
    #                       unauthorized (401),
206
    #                       badRequest (400),
207
    #                       overLimit (413)
208

    
209
    log.debug('list_image_metadata %s', image_id)
210
    with image_backend(request.user_uniq) as backend:
211
        image = backend.get_image(image_id)
212
    metadata = image['properties']
213
    return util.render_metadata(request, metadata, use_values=True, status=200)
214

    
215

    
216
@api.api_method('POST', user_required=True, logger=log)
217
def update_metadata(request, image_id):
218
    # Normal Response Code: 201
219
    # Error Response Codes: computeFault (400, 500),
220
    #                       serviceUnavailable (503),
221
    #                       unauthorized (401),
222
    #                       badRequest (400),
223
    #                       buildInProgress (409),
224
    #                       badMediaType(415),
225
    #                       overLimit (413)
226

    
227
    req = utils.get_request_dict(request)
228
    log.info('update_image_metadata %s %s', image_id, req)
229
    with image_backend(request.user_uniq) as backend:
230
        image = backend.get_image(image_id)
231
        try:
232
            metadata = req['metadata']
233
            assert isinstance(metadata, dict)
234
        except (KeyError, AssertionError):
235
            raise faults.BadRequest('Malformed request.')
236

    
237
        properties = image['properties']
238
        properties.update(metadata)
239

    
240
        backend.update_metadata(image_id, dict(properties=properties))
241

    
242
    return util.render_metadata(request, properties, status=201)
243

    
244

    
245
@api.api_method('GET', user_required=True, logger=log)
246
def get_metadata_item(request, image_id, key):
247
    # Normal Response Codes: 200, 203
248
    # Error Response Codes: computeFault (400, 500),
249
    #                       serviceUnavailable (503),
250
    #                       unauthorized (401),
251
    #                       itemNotFound (404),
252
    #                       badRequest (400),
253
    #                       overLimit (413)
254

    
255
    log.debug('get_image_metadata_item %s %s', image_id, key)
256
    with image_backend(request.user_uniq) as backend:
257
        image = backend.get_image(image_id)
258
    val = image['properties'].get(key)
259
    if val is None:
260
        raise faults.ItemNotFound('Metadata key not found.')
261
    return util.render_meta(request, {key: val}, status=200)
262

    
263

    
264
@api.api_method('PUT', user_required=True, logger=log)
265
def create_metadata_item(request, image_id, key):
266
    # Normal Response Code: 201
267
    # Error Response Codes: computeFault (400, 500),
268
    #                       serviceUnavailable (503),
269
    #                       unauthorized (401),
270
    #                       itemNotFound (404),
271
    #                       badRequest (400),
272
    #                       buildInProgress (409),
273
    #                       badMediaType(415),
274
    #                       overLimit (413)
275

    
276
    req = utils.get_request_dict(request)
277
    log.info('create_image_metadata_item %s %s %s', image_id, key, req)
278
    try:
279
        metadict = req['meta']
280
        assert isinstance(metadict, dict)
281
        assert len(metadict) == 1
282
        assert key in metadict
283
    except (KeyError, AssertionError):
284
        raise faults.BadRequest('Malformed request.')
285

    
286
    val = metadict[key]
287
    with image_backend(request.user_uniq) as backend:
288
        image = backend.get_image(image_id)
289
        properties = image['properties']
290
        properties[key] = val
291

    
292
        backend.update_metadata(image_id, dict(properties=properties))
293

    
294
    return util.render_meta(request, {key: val}, status=201)
295

    
296

    
297
@api.api_method('DELETE', user_required=True, logger=log)
298
def delete_metadata_item(request, image_id, key):
299
    # Normal Response Code: 204
300
    # Error Response Codes: computeFault (400, 500),
301
    #                       serviceUnavailable (503),
302
    #                       unauthorized (401),
303
    #                       itemNotFound (404),
304
    #                       badRequest (400),
305
    #                       buildInProgress (409),
306
    #                       badMediaType(415),
307
    #                       overLimit (413),
308

    
309
    log.info('delete_image_metadata_item %s %s', image_id, key)
310
    with image_backend(request.user_uniq) as backend:
311
        image = backend.get_image(image_id)
312
        properties = image['properties']
313
        properties.pop(key, None)
314

    
315
        backend.update_metadata(image_id, dict(properties=properties))
316

    
317
    return HttpResponse(status=204)