root / snf-cyclades-app / synnefo / api / images.py @ 8e057ed0
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 |
d["is_snapshot"] = image["is_snapshot"] |
121 |
return d
|
122 |
|
123 |
|
124 |
@api.api_method("GET", user_required=True, logger=log) |
125 |
def list_images(request, detail=False): |
126 |
# Normal Response Codes: 200, 203
|
127 |
# Error Response Codes: computeFault (400, 500),
|
128 |
# serviceUnavailable (503),
|
129 |
# unauthorized (401),
|
130 |
# badRequest (400),
|
131 |
# overLimit (413)
|
132 |
|
133 |
log.debug('list_images detail=%s', detail)
|
134 |
since = utils.isoparse(request.GET.get('changes-since'))
|
135 |
with image_backend(request.user_uniq) as backend: |
136 |
images = backend.list_images() |
137 |
if since:
|
138 |
updated_since = lambda img: date_parse(img["updated_at"]) >= since |
139 |
images = ifilter(updated_since, images) |
140 |
if not images: |
141 |
return HttpResponse(status=304) |
142 |
|
143 |
images = sorted(images, key=lambda x: x['id']) |
144 |
reply = [image_to_dict(image, detail) for image in images] |
145 |
|
146 |
if request.serialization == 'xml': |
147 |
data = render_to_string('list_images.xml',
|
148 |
dict(images=reply, detail=detail))
|
149 |
else:
|
150 |
data = json.dumps(dict(images=reply))
|
151 |
|
152 |
return HttpResponse(data, status=200) |
153 |
|
154 |
|
155 |
@api.api_method('POST', user_required=True, logger=log) |
156 |
def create_image(request): |
157 |
# Normal Response Code: 202
|
158 |
# Error Response Codes: computeFault (400, 500),
|
159 |
# serviceUnavailable (503),
|
160 |
# unauthorized (401),
|
161 |
# badMediaType(415),
|
162 |
# itemNotFound (404),
|
163 |
# badRequest (400),
|
164 |
# serverCapacityUnavailable (503),
|
165 |
# buildInProgress (409),
|
166 |
# resizeNotAllowed (403),
|
167 |
# backupOrResizeInProgress (409),
|
168 |
# overLimit (413)
|
169 |
|
170 |
raise faults.NotImplemented('Not supported.') |
171 |
|
172 |
|
173 |
@api.api_method('GET', user_required=True, logger=log) |
174 |
def get_image_details(request, image_id): |
175 |
# Normal Response Codes: 200, 203
|
176 |
# Error Response Codes: computeFault (400, 500),
|
177 |
# serviceUnavailable (503),
|
178 |
# unauthorized (401),
|
179 |
# badRequest (400),
|
180 |
# itemNotFound (404),
|
181 |
# overLimit (413)
|
182 |
|
183 |
log.debug('get_image_details %s', image_id)
|
184 |
with image_backend(request.user_uniq) as backend: |
185 |
image = backend.get_image(image_id) |
186 |
reply = image_to_dict(image) |
187 |
|
188 |
if request.serialization == 'xml': |
189 |
data = render_to_string('image.xml', dict(image=reply)) |
190 |
else:
|
191 |
data = json.dumps(dict(image=reply))
|
192 |
|
193 |
return HttpResponse(data, status=200) |
194 |
|
195 |
|
196 |
@api.api_method('DELETE', user_required=True, logger=log) |
197 |
def delete_image(request, image_id): |
198 |
# Normal Response Code: 204
|
199 |
# Error Response Codes: computeFault (400, 500),
|
200 |
# serviceUnavailable (503),
|
201 |
# unauthorized (401),
|
202 |
# itemNotFound (404),
|
203 |
# overLimit (413)
|
204 |
|
205 |
log.info('delete_image %s', image_id)
|
206 |
with image_backend(request.user_uniq) as backend: |
207 |
backend.unregister(image_id) |
208 |
log.info('User %s deleted image %s', request.user_uniq, image_id)
|
209 |
return HttpResponse(status=204) |
210 |
|
211 |
|
212 |
@api.api_method('GET', user_required=True, logger=log) |
213 |
def list_metadata(request, image_id): |
214 |
# Normal Response Codes: 200, 203
|
215 |
# Error Response Codes: computeFault (400, 500),
|
216 |
# serviceUnavailable (503),
|
217 |
# unauthorized (401),
|
218 |
# badRequest (400),
|
219 |
# overLimit (413)
|
220 |
|
221 |
log.debug('list_image_metadata %s', image_id)
|
222 |
with image_backend(request.user_uniq) as backend: |
223 |
image = backend.get_image(image_id) |
224 |
metadata = image['properties']
|
225 |
return util.render_metadata(request, metadata, use_values=False, |
226 |
status=200)
|
227 |
|
228 |
|
229 |
@api.api_method('POST', user_required=True, logger=log) |
230 |
def update_metadata(request, image_id): |
231 |
# Normal Response Code: 201
|
232 |
# Error Response Codes: computeFault (400, 500),
|
233 |
# serviceUnavailable (503),
|
234 |
# unauthorized (401),
|
235 |
# badRequest (400),
|
236 |
# buildInProgress (409),
|
237 |
# badMediaType(415),
|
238 |
# overLimit (413)
|
239 |
|
240 |
req = utils.get_request_dict(request) |
241 |
log.info('update_image_metadata %s %s', image_id, req)
|
242 |
with image_backend(request.user_uniq) as backend: |
243 |
image = backend.get_image(image_id) |
244 |
try:
|
245 |
metadata = req['metadata']
|
246 |
assert isinstance(metadata, dict) |
247 |
except (KeyError, AssertionError): |
248 |
raise faults.BadRequest('Malformed request.') |
249 |
|
250 |
properties = image['properties']
|
251 |
properties.update(metadata) |
252 |
|
253 |
backend.update_metadata(image_id, dict(properties=properties))
|
254 |
|
255 |
return util.render_metadata(request, properties, status=201) |
256 |
|
257 |
|
258 |
@api.api_method('GET', user_required=True, logger=log) |
259 |
def get_metadata_item(request, image_id, key): |
260 |
# Normal Response Codes: 200, 203
|
261 |
# Error Response Codes: computeFault (400, 500),
|
262 |
# serviceUnavailable (503),
|
263 |
# unauthorized (401),
|
264 |
# itemNotFound (404),
|
265 |
# badRequest (400),
|
266 |
# overLimit (413)
|
267 |
|
268 |
log.debug('get_image_metadata_item %s %s', image_id, key)
|
269 |
with image_backend(request.user_uniq) as backend: |
270 |
image = backend.get_image(image_id) |
271 |
val = image['properties'].get(key)
|
272 |
if val is None: |
273 |
raise faults.ItemNotFound('Metadata key not found.') |
274 |
return util.render_meta(request, {key: val}, status=200) |
275 |
|
276 |
|
277 |
@api.api_method('PUT', user_required=True, logger=log) |
278 |
def create_metadata_item(request, image_id, key): |
279 |
# Normal Response Code: 201
|
280 |
# Error Response Codes: computeFault (400, 500),
|
281 |
# serviceUnavailable (503),
|
282 |
# unauthorized (401),
|
283 |
# itemNotFound (404),
|
284 |
# badRequest (400),
|
285 |
# buildInProgress (409),
|
286 |
# badMediaType(415),
|
287 |
# overLimit (413)
|
288 |
|
289 |
req = utils.get_request_dict(request) |
290 |
log.info('create_image_metadata_item %s %s %s', image_id, key, req)
|
291 |
try:
|
292 |
metadict = req['meta']
|
293 |
assert isinstance(metadict, dict) |
294 |
assert len(metadict) == 1 |
295 |
assert key in metadict |
296 |
except (KeyError, AssertionError): |
297 |
raise faults.BadRequest('Malformed request.') |
298 |
|
299 |
val = metadict[key] |
300 |
with image_backend(request.user_uniq) as backend: |
301 |
image = backend.get_image(image_id) |
302 |
properties = image['properties']
|
303 |
properties[key] = val |
304 |
|
305 |
backend.update_metadata(image_id, dict(properties=properties))
|
306 |
|
307 |
return util.render_meta(request, {key: val}, status=201) |
308 |
|
309 |
|
310 |
@api.api_method('DELETE', user_required=True, logger=log) |
311 |
def delete_metadata_item(request, image_id, key): |
312 |
# Normal Response Code: 204
|
313 |
# Error Response Codes: computeFault (400, 500),
|
314 |
# serviceUnavailable (503),
|
315 |
# unauthorized (401),
|
316 |
# itemNotFound (404),
|
317 |
# badRequest (400),
|
318 |
# buildInProgress (409),
|
319 |
# badMediaType(415),
|
320 |
# overLimit (413),
|
321 |
|
322 |
log.info('delete_image_metadata_item %s %s', image_id, key)
|
323 |
with image_backend(request.user_uniq) as backend: |
324 |
image = backend.get_image(image_id) |
325 |
properties = image['properties']
|
326 |
properties.pop(key, None)
|
327 |
|
328 |
backend.update_metadata(image_id, dict(properties=properties))
|
329 |
|
330 |
return HttpResponse(status=204) |