Statistics
| Branch: | Tag: | Revision:

root / api / images.py @ c36934a7

History | View | Annotate | Download (4.8 kB)

1
#
2
# Copyright (c) 2010 Greek Research and Technology Network
3
#
4

    
5
from synnefo.api.util import *
6
from synnefo.db.models import Image
7

    
8
from django.conf.urls.defaults import *
9
from django.http import HttpResponse
10
from django.template.loader import render_to_string
11

    
12

    
13
urlpatterns = patterns('synnefo.api.images',
14
    (r'^(?:/|.json|.xml)?$', 'demux'),
15
    (r'^/detail(?:.json|.xml)?$', 'list_images', {'detail': True}),
16
    (r'^/(\d+)(?:.json|.xml)?$', 'image_demux'),
17
)
18

    
19
def demux(request):
20
    if request.method == 'GET':
21
        return list_images(request)
22
    elif request.method == 'POST':
23
        return create_image(request)
24
    else:
25
        fault = BadRequest()
26
        return render_fault(request, fault)
27

    
28
def image_demux(request, image_id):
29
    if request.method == 'GET':
30
        return get_image_details(request, image_id)
31
    elif request.method == 'DELETE':
32
        return delete_image(request, image_id)
33
    else:
34
        fault = BadRequest()
35
        return render_fault(request, fault)
36

    
37

    
38
def image_to_dict(image, detail=True):
39
    d = {'id': image.id, 'name': image.name}
40
    if detail:
41
        d['updated'] = image.updated.isoformat()
42
        d['created'] = image.created.isoformat()
43
        d['status'] = image.state
44
        d['progress'] = 100 if image.state == 'ACTIVE' else 0
45
        d['description'] = image.description
46
        if image.sourcevm:
47
            d['serverRef'] = image.sourcevm.id
48
    return d
49

    
50

    
51
@api_method('GET')
52
def list_images(request, detail=False):
53
    # Normal Response Codes: 200, 203
54
    # Error Response Codes: computeFault (400, 500),
55
    #                       serviceUnavailable (503),
56
    #                       unauthorized (401),
57
    #                       badRequest (400),
58
    #                       overLimit (413)
59
    
60
    all_images = Image.objects.all()
61
    images = [image_to_dict(image, detail) for image in all_images]
62
    
63
    if request.type == 'xml':
64
        mimetype = 'application/xml'
65
        data = render_to_string('list_images.xml', {'images': images, 'detail': detail})
66
    else:
67
        mimetype = 'application/json'
68
        data = json.dumps({'images': {'values': images}})
69
    
70
    return HttpResponse(data, mimetype=mimetype, status=200)
71

    
72
@api_method('POST')
73
def create_image(request):
74
    # Normal Response Code: 202
75
    # Error Response Codes: computeFault (400, 500),
76
    #                       serviceUnavailable (503),
77
    #                       unauthorized (401),
78
    #                       badMediaType(415),
79
    #                       itemNotFound (404),
80
    #                       badRequest (400),
81
    #                       serverCapacityUnavailable (503),
82
    #                       buildInProgress (409),
83
    #                       resizeNotAllowed (403),
84
    #                       backupOrResizeInProgress (409),
85
    #                       overLimit (413)
86
    
87
    req = get_request_dict(request)
88
    owner = get_user()
89
    
90
    try:
91
        d = req['image']
92
        server_id = int(d['serverRef'])
93
        vm = VirtualMachine.objects.get(id=server_id)
94
        image = Image.objects.create(name=d['name'], size=0, owner=owner, sourcevm=vm)
95
        image.save()
96
    except KeyError:
97
        raise BadRequest
98
    except ValueError:
99
        raise BadRequest
100
    except VirtualMachine.DoesNotExist:
101
        raise ItemNotFound
102
    
103
    imagedict = image_to_dict(image)
104
    if request.type == 'xml':
105
        data = render_to_string('image.xml', {'image': imagedict})
106
    else:
107
        data = json.dumps({'image': imagedict})
108
    
109
    return HttpResponse(data, status=202)
110

    
111
@api_method('GET')
112
def get_image_details(request, image_id):
113
    # Normal Response Codes: 200, 203
114
    # Error Response Codes: computeFault (400, 500),
115
    #                       serviceUnavailable (503),
116
    #                       unauthorized (401),
117
    #                       badRequest (400),
118
    #                       itemNotFound (404),
119
    #                       overLimit (413)
120
    
121
    try:
122
        image_id = int(image_id)
123
        imagedict = image_to_dict(Image.objects.get(id=image_id))
124
    except Image.DoesNotExist:
125
        raise ItemNotFound
126
    
127
    if request.type == 'xml':
128
        data = render_to_string('image.xml', {'image': imagedict})
129
    else:
130
        data = json.dumps({'image': imagedict})
131
    
132
    return HttpResponse(data, status=200)
133

    
134
@api_method('DELETE')
135
def delete_image(request, image_id):
136
    # Normal Response Code: 204
137
    # Error Response Codes: computeFault (400, 500),
138
    #                       serviceUnavailable (503),
139
    #                       unauthorized (401),
140
    #                       itemNotFound (404),
141
    #                       overLimit (413)
142
    
143
    try:
144
        image_id = int(image_id)
145
        image = Image.objects.get(id=image_id)
146
    except Image.DoesNotExist:
147
        raise ItemNotFound
148
    
149
    if image.owner != get_user():
150
        raise Unauthorized()
151
    image.delete()
152
    return HttpResponse(status=204)