Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / images.py @ 2aba7764

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

    
37
from dateutil.parser import parse as date_parse
38

    
39
from django.conf.urls 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.api_method_not_allowed(request,
69
                                          allowed_methods=['GET', 'POST'])
70

    
71

    
72
def image_demux(request, image_id):
73
    if request.method == 'GET':
74
        return get_image_details(request, image_id)
75
    elif request.method == 'DELETE':
76
        return delete_image(request, image_id)
77
    else:
78
        return api.api_method_not_allowed(request,
79
                                          allowed_methods=['GET', 'DELETE'])
80

    
81

    
82
def metadata_demux(request, image_id):
83
    if request.method == 'GET':
84
        return list_metadata(request, image_id)
85
    elif request.method == 'POST':
86
        return update_metadata(request, image_id)
87
    else:
88
        return api.api_method_not_allowed(request,
89
                                          allowed_methods=['GET', 'POST'])
90

    
91

    
92
def metadata_item_demux(request, image_id, key):
93
    if request.method == 'GET':
94
        return get_metadata_item(request, image_id, key)
95
    elif request.method == 'PUT':
96
        return create_metadata_item(request, image_id, key)
97
    elif request.method == 'DELETE':
98
        return delete_metadata_item(request, image_id, key)
99
    else:
100
        return api.api_method_not_allowed(request,
101
                                          allowed_methods=['GET',
102
                                                           'PUT',
103
                                                           'DELETE'])
104

    
105

    
106
def image_to_dict(image, detail=True):
107
    d = dict(id=image['id'], name=image['name'])
108
    if detail:
109
        d['updated'] = utils.isoformat(date_parse(image['updated_at']))
110
        d['created'] = utils.isoformat(date_parse(image['created_at']))
111
        d['status'] = 'DELETED' if image['deleted_at'] else 'ACTIVE'
112
        d['progress'] = 100 if image['status'] == 'available' else 0
113
        d['user_id'] = image['owner']
114
        d['tenant_id'] = image['owner']
115
        d['links'] = util.image_to_links(image["id"])
116
        if image["properties"]:
117
            d['metadata'] = image['properties']
118
        else:
119
            d['metadata'] = {}
120
    return d
121

    
122

    
123
@api.api_method("GET", user_required=True, logger=log)
124
def list_images(request, detail=False):
125
    # Normal Response Codes: 200, 203
126
    # Error Response Codes: computeFault (400, 500),
127
    #                       serviceUnavailable (503),
128
    #                       unauthorized (401),
129
    #                       badRequest (400),
130
    #                       overLimit (413)
131

    
132
    log.debug('list_images detail=%s', detail)
133
    since = utils.isoparse(request.GET.get('changes-since'))
134
    with image_backend(request.user_uniq) as backend:
135
        images = backend.list_images()
136
        if since:
137
            updated_since = lambda img: date_parse(img["updated_at"]) >= since
138
            images = ifilter(updated_since, images)
139
            if not images:
140
                return HttpResponse(status=304)
141

    
142
    images = sorted(images, key=lambda x: x['id'])
143
    reply = [image_to_dict(image, detail) for image in images]
144

    
145
    if request.serialization == 'xml':
146
        data = render_to_string('list_images.xml',
147
                                dict(images=reply, detail=detail))
148
    else:
149
        data = json.dumps(dict(images=reply))
150

    
151
    return HttpResponse(data, status=200)
152

    
153

    
154
@api.api_method('POST', user_required=True, logger=log)
155
def create_image(request):
156
    # Normal Response Code: 202
157
    # Error Response Codes: computeFault (400, 500),
158
    #                       serviceUnavailable (503),
159
    #                       unauthorized (401),
160
    #                       badMediaType(415),
161
    #                       itemNotFound (404),
162
    #                       badRequest (400),
163
    #                       serverCapacityUnavailable (503),
164
    #                       buildInProgress (409),
165
    #                       resizeNotAllowed (403),
166
    #                       backupOrResizeInProgress (409),
167
    #                       overLimit (413)
168

    
169
    raise faults.NotImplemented('Not supported.')
170

    
171

    
172
@api.api_method('GET', user_required=True, logger=log)
173
def get_image_details(request, image_id):
174
    # Normal Response Codes: 200, 203
175
    # Error Response Codes: computeFault (400, 500),
176
    #                       serviceUnavailable (503),
177
    #                       unauthorized (401),
178
    #                       badRequest (400),
179
    #                       itemNotFound (404),
180
    #                       overLimit (413)
181

    
182
    log.debug('get_image_details %s', image_id)
183
    with image_backend(request.user_uniq) as backend:
184
        image = backend.get_image(image_id)
185
    reply = image_to_dict(image)
186

    
187
    if request.serialization == 'xml':
188
        data = render_to_string('image.xml', dict(image=reply))
189
    else:
190
        data = json.dumps(dict(image=reply))
191

    
192
    return HttpResponse(data, status=200)
193

    
194

    
195
@api.api_method('DELETE', user_required=True, logger=log)
196
def delete_image(request, image_id):
197
    # Normal Response Code: 204
198
    # Error Response Codes: computeFault (400, 500),
199
    #                       serviceUnavailable (503),
200
    #                       unauthorized (401),
201
    #                       itemNotFound (404),
202
    #                       overLimit (413)
203

    
204
    log.info('delete_image %s', image_id)
205
    with image_backend(request.user_uniq) as backend:
206
        backend.unregister(image_id)
207
    log.info('User %s deleted image %s', request.user_uniq, image_id)
208
    return HttpResponse(status=204)
209

    
210

    
211
@api.api_method('GET', user_required=True, logger=log)
212
def list_metadata(request, image_id):
213
    # Normal Response Codes: 200, 203
214
    # Error Response Codes: computeFault (400, 500),
215
    #                       serviceUnavailable (503),
216
    #                       unauthorized (401),
217
    #                       badRequest (400),
218
    #                       overLimit (413)
219

    
220
    log.debug('list_image_metadata %s', image_id)
221
    with image_backend(request.user_uniq) as backend:
222
        image = backend.get_image(image_id)
223
    metadata = image['properties']
224
    return util.render_metadata(request, metadata, use_values=False,
225
                                status=200)
226

    
227

    
228
@api.api_method('POST', user_required=True, logger=log)
229
def update_metadata(request, image_id):
230
    # Normal Response Code: 201
231
    # Error Response Codes: computeFault (400, 500),
232
    #                       serviceUnavailable (503),
233
    #                       unauthorized (401),
234
    #                       badRequest (400),
235
    #                       buildInProgress (409),
236
    #                       badMediaType(415),
237
    #                       overLimit (413)
238

    
239
    req = utils.get_request_dict(request)
240
    log.info('update_image_metadata %s %s', image_id, req)
241
    with image_backend(request.user_uniq) as backend:
242
        image = backend.get_image(image_id)
243
        try:
244
            metadata = req['metadata']
245
            assert isinstance(metadata, dict)
246
        except (KeyError, AssertionError):
247
            raise faults.BadRequest('Malformed request.')
248

    
249
        properties = image['properties']
250
        properties.update(metadata)
251

    
252
        backend.update_metadata(image_id, dict(properties=properties))
253

    
254
    return util.render_metadata(request, properties, status=201)
255

    
256

    
257
@api.api_method('GET', user_required=True, logger=log)
258
def get_metadata_item(request, image_id, key):
259
    # Normal Response Codes: 200, 203
260
    # Error Response Codes: computeFault (400, 500),
261
    #                       serviceUnavailable (503),
262
    #                       unauthorized (401),
263
    #                       itemNotFound (404),
264
    #                       badRequest (400),
265
    #                       overLimit (413)
266

    
267
    log.debug('get_image_metadata_item %s %s', image_id, key)
268
    with image_backend(request.user_uniq) as backend:
269
        image = backend.get_image(image_id)
270
    val = image['properties'].get(key)
271
    if val is None:
272
        raise faults.ItemNotFound('Metadata key not found.')
273
    return util.render_meta(request, {key: val}, status=200)
274

    
275

    
276
@api.api_method('PUT', user_required=True, logger=log)
277
def create_metadata_item(request, image_id, key):
278
    # Normal Response Code: 201
279
    # Error Response Codes: computeFault (400, 500),
280
    #                       serviceUnavailable (503),
281
    #                       unauthorized (401),
282
    #                       itemNotFound (404),
283
    #                       badRequest (400),
284
    #                       buildInProgress (409),
285
    #                       badMediaType(415),
286
    #                       overLimit (413)
287

    
288
    req = utils.get_request_dict(request)
289
    log.info('create_image_metadata_item %s %s %s', image_id, key, req)
290
    try:
291
        metadict = req['meta']
292
        assert isinstance(metadict, dict)
293
        assert len(metadict) == 1
294
        assert key in metadict
295
    except (KeyError, AssertionError):
296
        raise faults.BadRequest('Malformed request.')
297

    
298
    val = metadict[key]
299
    with image_backend(request.user_uniq) as backend:
300
        image = backend.get_image(image_id)
301
        properties = image['properties']
302
        properties[key] = val
303

    
304
        backend.update_metadata(image_id, dict(properties=properties))
305

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

    
308

    
309
@api.api_method('DELETE', user_required=True, logger=log)
310
def delete_metadata_item(request, image_id, key):
311
    # Normal Response Code: 204
312
    # Error Response Codes: computeFault (400, 500),
313
    #                       serviceUnavailable (503),
314
    #                       unauthorized (401),
315
    #                       itemNotFound (404),
316
    #                       badRequest (400),
317
    #                       buildInProgress (409),
318
    #                       badMediaType(415),
319
    #                       overLimit (413),
320

    
321
    log.info('delete_image_metadata_item %s %s', image_id, key)
322
    with image_backend(request.user_uniq) as backend:
323
        image = backend.get_image(image_id)
324
        properties = image['properties']
325
        properties.pop(key, None)
326

    
327
        backend.update_metadata(image_id, dict(properties=properties))
328

    
329
    return HttpResponse(status=204)