Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (11.9 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

    
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.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.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.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
        d['user_id'] = image['owner']
108
        d['tenant_id'] = image['owner']
109
        d['links'] = util.image_to_links(image["id"])
110
        if image["properties"]:
111
            d['metadata'] = image['properties']
112
        else:
113
            d['metadata'] = {}
114
    return d
115

    
116

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

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

    
136
    images = sorted(images, key=lambda x: x['id'])
137
    reply = [image_to_dict(image, detail) for image in images]
138

    
139
    if request.serialization == 'xml':
140
        data = render_to_string('list_images.xml',
141
                                dict(images=reply, detail=detail))
142
    else:
143
        data = json.dumps(dict(images=reply))
144

    
145
    return HttpResponse(data, status=200)
146

    
147

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

    
163
    raise faults.NotImplemented('Not supported.')
164

    
165

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

    
176
    log.debug('get_image_details %s', image_id)
177
    with image_backend(request.user_uniq) as backend:
178
        image = backend.get_image(image_id)
179
    reply = image_to_dict(image)
180

    
181
    if request.serialization == 'xml':
182
        data = render_to_string('image.xml', dict(image=reply))
183
    else:
184
        data = json.dumps(dict(image=reply))
185

    
186
    return HttpResponse(data, status=200)
187

    
188

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

    
198
    log.info('delete_image %s', image_id)
199
    with image_backend(request.user_uniq) as backend:
200
        backend.unregister(image_id)
201
    log.info('User %s deleted image %s', request.user_uniq, image_id)
202
    return HttpResponse(status=204)
203

    
204

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

    
214
    log.debug('list_image_metadata %s', image_id)
215
    with image_backend(request.user_uniq) as backend:
216
        image = backend.get_image(image_id)
217
    metadata = image['properties']
218
    return util.render_metadata(request, metadata, use_values=False,
219
                                status=200)
220

    
221

    
222
@api.api_method('POST', user_required=True, logger=log)
223
def update_metadata(request, image_id):
224
    # Normal Response Code: 201
225
    # Error Response Codes: computeFault (400, 500),
226
    #                       serviceUnavailable (503),
227
    #                       unauthorized (401),
228
    #                       badRequest (400),
229
    #                       buildInProgress (409),
230
    #                       badMediaType(415),
231
    #                       overLimit (413)
232

    
233
    req = utils.get_request_dict(request)
234
    log.info('update_image_metadata %s %s', image_id, req)
235
    with image_backend(request.user_uniq) as backend:
236
        image = backend.get_image(image_id)
237
        try:
238
            metadata = req['metadata']
239
            assert isinstance(metadata, dict)
240
        except (KeyError, AssertionError):
241
            raise faults.BadRequest('Malformed request.')
242

    
243
        properties = image['properties']
244
        properties.update(metadata)
245

    
246
        backend.update_metadata(image_id, dict(properties=properties))
247

    
248
    return util.render_metadata(request, properties, status=201)
249

    
250

    
251
@api.api_method('GET', user_required=True, logger=log)
252
def get_metadata_item(request, image_id, key):
253
    # Normal Response Codes: 200, 203
254
    # Error Response Codes: computeFault (400, 500),
255
    #                       serviceUnavailable (503),
256
    #                       unauthorized (401),
257
    #                       itemNotFound (404),
258
    #                       badRequest (400),
259
    #                       overLimit (413)
260

    
261
    log.debug('get_image_metadata_item %s %s', image_id, key)
262
    with image_backend(request.user_uniq) as backend:
263
        image = backend.get_image(image_id)
264
    val = image['properties'].get(key)
265
    if val is None:
266
        raise faults.ItemNotFound('Metadata key not found.')
267
    return util.render_meta(request, {key: val}, status=200)
268

    
269

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

    
282
    req = utils.get_request_dict(request)
283
    log.info('create_image_metadata_item %s %s %s', image_id, key, req)
284
    try:
285
        metadict = req['meta']
286
        assert isinstance(metadict, dict)
287
        assert len(metadict) == 1
288
        assert key in metadict
289
    except (KeyError, AssertionError):
290
        raise faults.BadRequest('Malformed request.')
291

    
292
    val = metadict[key]
293
    with image_backend(request.user_uniq) as backend:
294
        image = backend.get_image(image_id)
295
        properties = image['properties']
296
        properties[key] = val
297

    
298
        backend.update_metadata(image_id, dict(properties=properties))
299

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

    
302

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

    
315
    log.info('delete_image_metadata_item %s %s', image_id, key)
316
    with image_backend(request.user_uniq) as backend:
317
        image = backend.get_image(image_id)
318
        properties = image['properties']
319
        properties.pop(key, None)
320

    
321
        backend.update_metadata(image_id, dict(properties=properties))
322

    
323
    return HttpResponse(status=204)