Statistics
| Branch: | Tag: | Revision:

root / api / servers.py @ 432fc8c3

History | View | Annotate | Download (13.9 kB)

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

    
5
from django.conf import settings
6
from django.conf.urls.defaults import patterns
7
from django.http import HttpResponse
8
from django.template.loader import render_to_string
9
from django.utils import simplejson as json
10

    
11
from synnefo.api.actions import server_actions
12
from synnefo.api.common import method_not_allowed
13
from synnefo.api.faults import BadRequest, ItemNotFound
14
from synnefo.api.util import *
15
from synnefo.db.models import Image, Flavor, VirtualMachine, VirtualMachineMetadata
16
from synnefo.logic.utils import get_rsapi_state
17
from synnefo.util.rapi import GanetiRapiClient
18
from synnefo.logic import backend
19

    
20
import logging
21

    
22

    
23
rapi = GanetiRapiClient(*settings.GANETI_CLUSTER_INFO)
24

    
25
urlpatterns = patterns('synnefo.api.servers',
26
    (r'^(?:/|.json|.xml)?$', 'demux'),
27
    (r'^/detail(?:.json|.xml)?$', 'list_servers', {'detail': True}),
28
    (r'^/(\d+)(?:.json|.xml)?$', 'server_demux'),
29
    (r'^/(\d+)/action(?:.json|.xml)?$', 'server_action'),
30
    (r'^/(\d+)/ips(?:.json|.xml)?$', 'list_addresses'),
31
    (r'^/(\d+)/ips/(.+?)(?:.json|.xml)?$', 'list_addresses_by_network'),
32
    (r'^/(\d+)/meta(?:.json|.xml)?$', 'metadata_demux'),
33
    (r'^/(\d+)/meta/(.+?)(?:.json|.xml)?$', 'metadata_item_demux'),
34
)
35

    
36

    
37
def demux(request):
38
    if request.method == 'GET':
39
        return list_servers(request)
40
    elif request.method == 'POST':
41
        return create_server(request)
42
    else:
43
        return method_not_allowed(request)
44

    
45
def server_demux(request, server_id):
46
    if request.method == 'GET':
47
        return get_server_details(request, server_id)
48
    elif request.method == 'PUT':
49
        return update_server_name(request, server_id)
50
    elif request.method == 'DELETE':
51
        return delete_server(request, server_id)
52
    else:
53
        return method_not_allowed(request)
54

    
55
def metadata_demux(request, server_id):
56
    if request.method == 'GET':
57
        return list_metadata(request, server_id)
58
    elif request.method == 'POST':
59
        return update_metadata(request, server_id)
60
    else:
61
        return method_not_allowed(request)
62

    
63
def metadata_item_demux(request, server_id, key):
64
    if request.method == 'GET':
65
        return get_metadata_item(request, server_id, key)
66
    elif request.method == 'PUT':
67
        return create_metadata_item(request, server_id, key)
68
    elif request.method == 'DELETE':
69
        return delete_metadata_item(request, server_id, key)
70
    else:
71
        return method_not_allowed(request)
72

    
73

    
74
def address_to_dict(ipfour, ipsix):
75
    return {'id': 'public',
76
            'values': [{'version': 4, 'addr': ipfour}, {'version': 6, 'addr': ipsix}]}
77

    
78
def metadata_to_dict(vm):
79
    vm_meta = vm.virtualmachinemetadata_set.all()
80
    return dict((meta.meta_key, meta.meta_value) for meta in vm_meta)
81

    
82
def vm_to_dict(vm, detail=False):
83
    d = dict(id=vm.id, name=vm.name)
84
    if detail:
85
        d['status'] = get_rsapi_state(vm)
86
        d['progress'] = 100 if get_rsapi_state(vm) == 'ACTIVE' else 0
87
        d['hostId'] = vm.hostid
88
        d['updated'] = isoformat(vm.updated)
89
        d['created'] = isoformat(vm.created)
90
        d['flavorRef'] = vm.flavor.id
91
        d['imageRef'] = vm.sourceimage.id
92
        
93
        metadata = metadata_to_dict(vm)
94
        if metadata:
95
            d['metadata'] = {'values': metadata}
96
        
97
        addresses = [address_to_dict(vm.ipfour, vm.ipsix)]
98
        d['addresses'] = {'values': addresses}
99
    return d
100

    
101

    
102
def render_server(request, server, status=200):
103
    if request.serialization == 'xml':
104
        data = render_to_string('server.xml', {'server': server, 'is_root': True})
105
    else:
106
        data = json.dumps({'server': server})
107
    return HttpResponse(data, status=status)
108
    
109

    
110
@api_method('GET')
111
def list_servers(request, detail=False):
112
    # Normal Response Codes: 200, 203
113
    # Error Response Codes: computeFault (400, 500),
114
    #                       serviceUnavailable (503),
115
    #                       unauthorized (401),
116
    #                       badRequest (400),
117
    #                       overLimit (413)
118
    
119
    owner = get_user()
120
    since = isoparse(request.GET.get('changes-since'))
121
    
122
    if since:
123
        user_vms = VirtualMachine.objects.filter(updated__gt=since)
124
        if not user_vms:
125
            return HttpResponse(status=304)
126
    else:
127
        user_vms = VirtualMachine.objects.filter(owner=owner, deleted=False)
128
    servers = [vm_to_dict(server, detail) for server in user_vms]
129
    
130
    if request.serialization == 'xml':
131
        data = render_to_string('list_servers.xml', {'servers': servers, 'detail': detail})
132
    else:
133
        data = json.dumps({'servers': {'values': servers}})
134
    
135
    return HttpResponse(data, status=200)
136

    
137
@api_method('POST')
138
def create_server(request):
139
    # Normal Response Code: 202
140
    # Error Response Codes: computeFault (400, 500),
141
    #                       serviceUnavailable (503),
142
    #                       unauthorized (401),
143
    #                       badMediaType(415),
144
    #                       itemNotFound (404),
145
    #                       badRequest (400),
146
    #                       serverCapacityUnavailable (503),
147
    #                       overLimit (413)
148
    
149
    req = get_request_dict(request)
150
    
151
    try:
152
        server = req['server']
153
        name = server['name']
154
        sourceimage = Image.objects.get(id=server['imageRef'])
155
        flavor = Flavor.objects.get(id=server['flavorRef'])
156
    except KeyError:
157
        raise BadRequest('Malformed request.')
158
    except Image.DoesNotExist:
159
        raise ItemNotFound
160
    except Flavor.DoesNotExist:
161
        raise ItemNotFound
162
    
163
    vm = VirtualMachine.objects.create(
164
        name=name,
165
        owner=get_user(),
166
        sourceimage=sourceimage,
167
        ipfour='0.0.0.0',
168
        ipsix='::1',
169
        flavor=flavor)
170
                
171
    if request.META.get('SERVER_NAME', None) == 'testserver':
172
        name = 'test-server'
173
        dry_run = True
174
    else:
175
        name = vm.backend_id
176
        dry_run = False
177
    
178
    jobId = rapi.CreateInstance(
179
        mode='create',
180
        name=name,
181
        disk_template='plain',
182
        disks=[{"size": 2000}],         #FIXME: Always ask for a 2GB disk for now
183
        nics=[{}],
184
        os='debootstrap+default',       #TODO: select OS from imageRef
185
        ip_check=False,
186
        name_check=False,
187
        pnode=rapi.GetNodes()[0],       #TODO: verify if this is necessary
188
        dry_run=dry_run,
189
        beparams=dict(auto_balance=True, vcpus=flavor.cpu, memory=flavor.ram))
190
    
191
    vm.save()
192
        
193
    logging.info('created vm with %s cpus, %s ram and %s storage' % (flavor.cpu, flavor.ram, flavor.disk))
194
    
195
    server = vm_to_dict(vm, detail=True)
196
    server['status'] = 'BUILD'
197
    server['adminPass'] = random_password()
198
    return render_server(request, server, status=202)
199

    
200
@api_method('GET')
201
def get_server_details(request, server_id):
202
    # Normal Response Codes: 200, 203
203
    # Error Response Codes: computeFault (400, 500),
204
    #                       serviceUnavailable (503),
205
    #                       unauthorized (401),
206
    #                       badRequest (400),
207
    #                       itemNotFound (404),
208
    #                       overLimit (413)
209
    
210
    vm = get_vm(server_id)
211
    server = vm_to_dict(vm, detail=True)
212
    return render_server(request, server)
213

    
214
@api_method('PUT')
215
def update_server_name(request, server_id):
216
    # Normal Response Code: 204
217
    # Error Response Codes: computeFault (400, 500),
218
    #                       serviceUnavailable (503),
219
    #                       unauthorized (401),
220
    #                       badRequest (400),
221
    #                       badMediaType(415),
222
    #                       itemNotFound (404),
223
    #                       buildInProgress (409),
224
    #                       overLimit (413)
225
    
226
    req = get_request_dict(request)
227
    
228
    try:
229
        name = req['server']['name']
230
    except KeyError:
231
        raise BadRequest('Malformed request.')
232
    
233
    vm = get_vm(server_id)
234
    vm.name = name
235
    vm.save()
236
    
237
    return HttpResponse(status=204)
238

    
239
@api_method('DELETE')
240
def delete_server(request, server_id):
241
    # Normal Response Codes: 204
242
    # Error Response Codes: computeFault (400, 500),
243
    #                       serviceUnavailable (503),
244
    #                       unauthorized (401),
245
    #                       itemNotFound (404),
246
    #                       unauthorized (401),
247
    #                       buildInProgress (409),
248
    #                       overLimit (413)
249
    
250
    vm = get_vm(server_id)
251
    backend.start_action(vm, 'DESTROY')
252
    rapi.DeleteInstance(vm.backend_id)
253
    return HttpResponse(status=204)
254

    
255
@api_method('POST')
256
def server_action(request, server_id):
257
    vm = get_vm(server_id)
258
    req = get_request_dict(request)
259
    if len(req) != 1:
260
        raise BadRequest('Malformed request.')
261
    
262
    key = req.keys()[0]
263
    val = req[key]
264
    
265
    try:
266
        assert isinstance(val, dict)
267
        return server_actions[key](request, vm, req[key])
268
    except KeyError:
269
        raise BadRequest('Unknown action.')
270
    except AssertionError:
271
        raise BadRequest('Invalid argument.')
272

    
273
@api_method('GET')
274
def list_addresses(request, server_id):
275
    # Normal Response Codes: 200, 203
276
    # Error Response Codes: computeFault (400, 500),
277
    #                       serviceUnavailable (503),
278
    #                       unauthorized (401),
279
    #                       badRequest (400),
280
    #                       overLimit (413)
281
    
282
    vm = get_vm(server_id)
283
    addresses = [address_to_dict(vm.ipfour, vm.ipsix)]
284
    
285
    if request.serialization == 'xml':
286
        data = render_to_string('list_addresses.xml', {'addresses': addresses})
287
    else:
288
        data = json.dumps({'addresses': {'values': addresses}})
289
    
290
    return HttpResponse(data, status=200)
291

    
292
@api_method('GET')
293
def list_addresses_by_network(request, server_id, network_id):
294
    # Normal Response Codes: 200, 203
295
    # Error Response Codes: computeFault (400, 500),
296
    #                       serviceUnavailable (503),
297
    #                       unauthorized (401),
298
    #                       badRequest (400),
299
    #                       itemNotFound (404),
300
    #                       overLimit (413)
301
    
302
    vm = get_vm(server_id)
303
    if network_id != 'public':
304
        raise ItemNotFound('Unknown network.')
305
    
306
    address = address_to_dict(vm.ipfour, vm.ipsix)
307
    
308
    if request.serialization == 'xml':
309
        data = render_to_string('address.xml', {'address': address})
310
    else:
311
        data = json.dumps({'network': address})
312
    
313
    return HttpResponse(data, status=200)
314

    
315
@api_method('GET')
316
def list_metadata(request, server_id):
317
    # Normal Response Codes: 200, 203
318
    # Error Response Codes: computeFault (400, 500),
319
    #                       serviceUnavailable (503),
320
    #                       unauthorized (401),
321
    #                       badRequest (400),
322
    #                       overLimit (413)
323

    
324
    vm = get_vm(server_id)
325
    metadata = metadata_to_dict(vm)
326
    return render_metadata(request, metadata, use_values=True, status=200)
327

    
328
@api_method('POST')
329
def update_metadata(request, server_id):
330
    # Normal Response Code: 201
331
    # Error Response Codes: computeFault (400, 500),
332
    #                       serviceUnavailable (503),
333
    #                       unauthorized (401),
334
    #                       badRequest (400),
335
    #                       buildInProgress (409),
336
    #                       badMediaType(415),
337
    #                       overLimit (413)
338

    
339
    vm = get_vm(server_id)
340
    req = get_request_dict(request)
341
    try:
342
        metadata = req['metadata']
343
        assert isinstance(metadata, dict)
344
    except (KeyError, AssertionError):
345
        raise BadRequest('Malformed request.')
346
    
347
    updated = {}
348
    
349
    for key, val in metadata.items():
350
        try:
351
            meta = VirtualMachineMetadata.objects.get(meta_key=key, vm=vm)
352
            meta.meta_value = val
353
            meta.save()
354
            updated[key] = val
355
        except VirtualMachineMetadata.DoesNotExist:
356
            pass    # Ignore non-existent metadata
357
    
358
    return render_metadata(request, metadata, status=201)
359

    
360
@api_method('GET')
361
def get_metadata_item(request, server_id, key):
362
    # Normal Response Codes: 200, 203
363
    # Error Response Codes: computeFault (400, 500),
364
    #                       serviceUnavailable (503),
365
    #                       unauthorized (401),
366
    #                       itemNotFound (404),
367
    #                       badRequest (400),
368
    #                       overLimit (413)
369

    
370
    meta = get_vm_meta(server_id, key)
371
    return render_meta(request, meta, status=200)
372

    
373
@api_method('PUT')
374
def create_metadata_item(request, server_id, key):
375
    # Normal Response Code: 201
376
    # Error Response Codes: computeFault (400, 500),
377
    #                       serviceUnavailable (503),
378
    #                       unauthorized (401),
379
    #                       itemNotFound (404),
380
    #                       badRequest (400),
381
    #                       buildInProgress (409),
382
    #                       badMediaType(415),
383
    #                       overLimit (413)
384

    
385
    vm = get_vm(server_id)
386
    req = get_request_dict(request)
387
    try:
388
        metadict = req['meta']
389
        assert isinstance(metadict, dict)
390
        assert len(metadict) == 1
391
        assert key in metadict
392
    except (KeyError, AssertionError):
393
        raise BadRequest('Malformed request.')
394
    
395
    meta, created = VirtualMachineMetadata.objects.get_or_create(meta_key=key, vm=vm)
396
    meta.meta_value = metadict[key]
397
    meta.save()
398
    return render_meta(request, meta, status=201)
399

    
400
@api_method('DELETE')
401
def delete_metadata_item(request, server_id, key):
402
    # Normal Response Code: 204
403
    # Error Response Codes: computeFault (400, 500),
404
    #                       serviceUnavailable (503),
405
    #                       unauthorized (401),
406
    #                       itemNotFound (404),
407
    #                       badRequest (400),
408
    #                       buildInProgress (409),
409
    #                       badMediaType(415),
410
    #                       overLimit (413),
411

    
412
    meta = get_vm_meta(server_id, key)
413
    meta.delete()
414
    return HttpResponse(status=204)