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