Statistics
| Branch: | Tag: | Revision:

root / api / servers.py @ 76ba77c1

History | View | Annotate | Download (14.4 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
        metadata = server.get('metadata', {})
155
        assert isinstance(metadata, dict)
156
        sourceimage = Image.objects.get(id=server['imageRef'])
157
        flavor = Flavor.objects.get(id=server['flavorRef'])
158
    except (KeyError, AssertionError):
159
        raise BadRequest('Malformed request.')
160
    except Image.DoesNotExist:
161
        raise ItemNotFound
162
    except Flavor.DoesNotExist:
163
        raise ItemNotFound
164
    
165
    vm = VirtualMachine(
166
        name=name,
167
        owner=get_user(),
168
        sourceimage=sourceimage,
169
        ipfour='0.0.0.0',
170
        ipsix='::1',
171
        flavor=flavor)
172

    
173
    # Pick a random password for the VM.
174
    # FIXME: This must be passed to the Ganeti OS provider via CreateInstance()
175
    passwd = random_password()
176

    
177
    # We *must* save the VM instance now,
178
    # so that it gets a vm.id and vm.backend_id is valid.
179
    vm.save() 
180
                
181
    if request.META.get('SERVER_NAME', None) == 'testserver':
182
        backend_name = 'test-server'
183
        dry_run = True
184
    else:
185
        backend_name = vm.backend_id
186
        dry_run = False
187

    
188
    jobId = rapi.CreateInstance(
189
        mode='create',
190
        name=backend_name,
191
        disk_template='plain',
192
        disks=[{"size": 2000}],         #FIXME: Always ask for a 2GB disk for now
193
        nics=[{}],
194
        os='debootstrap+default',       #TODO: select OS from imageRef
195
        ip_check=False,
196
        name_check=False,
197
        pnode=rapi.GetNodes()[0],       #TODO: verify if this is necessary
198
        dry_run=dry_run,
199
        beparams=dict(auto_balance=True, vcpus=flavor.cpu, memory=flavor.ram))
200
    
201
    vm.save()
202
    
203
    for key, val in metadata.items():
204
        VirtualMachineMetadata.objects.create(meta_key=key, meta_value=val, vm=vm)
205
    
206
    logging.info('created vm with %s cpus, %s ram and %s storage' % (flavor.cpu, flavor.ram, flavor.disk))
207
    
208
    server = vm_to_dict(vm, detail=True)
209
    server['status'] = 'BUILD'
210
    server['adminPass'] = passwd
211
    return render_server(request, server, status=202)
212

    
213
@api_method('GET')
214
def get_server_details(request, server_id):
215
    # Normal Response Codes: 200, 203
216
    # Error Response Codes: computeFault (400, 500),
217
    #                       serviceUnavailable (503),
218
    #                       unauthorized (401),
219
    #                       badRequest (400),
220
    #                       itemNotFound (404),
221
    #                       overLimit (413)
222
    
223
    vm = get_vm(server_id)
224
    server = vm_to_dict(vm, detail=True)
225
    return render_server(request, server)
226

    
227
@api_method('PUT')
228
def update_server_name(request, server_id):
229
    # Normal Response Code: 204
230
    # Error Response Codes: computeFault (400, 500),
231
    #                       serviceUnavailable (503),
232
    #                       unauthorized (401),
233
    #                       badRequest (400),
234
    #                       badMediaType(415),
235
    #                       itemNotFound (404),
236
    #                       buildInProgress (409),
237
    #                       overLimit (413)
238
    
239
    req = get_request_dict(request)
240
    
241
    try:
242
        name = req['server']['name']
243
    except KeyError:
244
        raise BadRequest('Malformed request.')
245
    
246
    vm = get_vm(server_id)
247
    vm.name = name
248
    vm.save()
249
    
250
    return HttpResponse(status=204)
251

    
252
@api_method('DELETE')
253
def delete_server(request, server_id):
254
    # Normal Response Codes: 204
255
    # Error Response Codes: computeFault (400, 500),
256
    #                       serviceUnavailable (503),
257
    #                       unauthorized (401),
258
    #                       itemNotFound (404),
259
    #                       unauthorized (401),
260
    #                       buildInProgress (409),
261
    #                       overLimit (413)
262
    
263
    vm = get_vm(server_id)
264
    backend.start_action(vm, 'DESTROY')
265
    rapi.DeleteInstance(vm.backend_id)
266
    return HttpResponse(status=204)
267

    
268
@api_method('POST')
269
def server_action(request, server_id):
270
    vm = get_vm(server_id)
271
    req = get_request_dict(request)
272
    if len(req) != 1:
273
        raise BadRequest('Malformed request.')
274
    
275
    key = req.keys()[0]
276
    val = req[key]
277
    
278
    try:
279
        assert isinstance(val, dict)
280
        return server_actions[key](request, vm, req[key])
281
    except KeyError:
282
        raise BadRequest('Unknown action.')
283
    except AssertionError:
284
        raise BadRequest('Invalid argument.')
285

    
286
@api_method('GET')
287
def list_addresses(request, server_id):
288
    # Normal Response Codes: 200, 203
289
    # Error Response Codes: computeFault (400, 500),
290
    #                       serviceUnavailable (503),
291
    #                       unauthorized (401),
292
    #                       badRequest (400),
293
    #                       overLimit (413)
294
    
295
    vm = get_vm(server_id)
296
    addresses = [address_to_dict(vm.ipfour, vm.ipsix)]
297
    
298
    if request.serialization == 'xml':
299
        data = render_to_string('list_addresses.xml', {'addresses': addresses})
300
    else:
301
        data = json.dumps({'addresses': {'values': addresses}})
302
    
303
    return HttpResponse(data, status=200)
304

    
305
@api_method('GET')
306
def list_addresses_by_network(request, server_id, network_id):
307
    # Normal Response Codes: 200, 203
308
    # Error Response Codes: computeFault (400, 500),
309
    #                       serviceUnavailable (503),
310
    #                       unauthorized (401),
311
    #                       badRequest (400),
312
    #                       itemNotFound (404),
313
    #                       overLimit (413)
314
    
315
    vm = get_vm(server_id)
316
    if network_id != 'public':
317
        raise ItemNotFound('Unknown network.')
318
    
319
    address = address_to_dict(vm.ipfour, vm.ipsix)
320
    
321
    if request.serialization == 'xml':
322
        data = render_to_string('address.xml', {'address': address})
323
    else:
324
        data = json.dumps({'network': address})
325
    
326
    return HttpResponse(data, status=200)
327

    
328
@api_method('GET')
329
def list_metadata(request, server_id):
330
    # Normal Response Codes: 200, 203
331
    # Error Response Codes: computeFault (400, 500),
332
    #                       serviceUnavailable (503),
333
    #                       unauthorized (401),
334
    #                       badRequest (400),
335
    #                       overLimit (413)
336

    
337
    vm = get_vm(server_id)
338
    metadata = metadata_to_dict(vm)
339
    return render_metadata(request, metadata, use_values=True, status=200)
340

    
341
@api_method('POST')
342
def update_metadata(request, server_id):
343
    # Normal Response Code: 201
344
    # Error Response Codes: computeFault (400, 500),
345
    #                       serviceUnavailable (503),
346
    #                       unauthorized (401),
347
    #                       badRequest (400),
348
    #                       buildInProgress (409),
349
    #                       badMediaType(415),
350
    #                       overLimit (413)
351

    
352
    vm = get_vm(server_id)
353
    req = get_request_dict(request)
354
    try:
355
        metadata = req['metadata']
356
        assert isinstance(metadata, dict)
357
    except (KeyError, AssertionError):
358
        raise BadRequest('Malformed request.')
359
    
360
    updated = {}
361
    
362
    for key, val in metadata.items():
363
        try:
364
            meta = VirtualMachineMetadata.objects.get(meta_key=key, vm=vm)
365
            meta.meta_value = val
366
            meta.save()
367
            updated[key] = val
368
        except VirtualMachineMetadata.DoesNotExist:
369
            pass    # Ignore non-existent metadata
370
    
371
    return render_metadata(request, metadata, status=201)
372

    
373
@api_method('GET')
374
def get_metadata_item(request, server_id, key):
375
    # Normal Response Codes: 200, 203
376
    # Error Response Codes: computeFault (400, 500),
377
    #                       serviceUnavailable (503),
378
    #                       unauthorized (401),
379
    #                       itemNotFound (404),
380
    #                       badRequest (400),
381
    #                       overLimit (413)
382

    
383
    meta = get_vm_meta(server_id, key)
384
    return render_meta(request, meta, status=200)
385

    
386
@api_method('PUT')
387
def create_metadata_item(request, server_id, key):
388
    # Normal Response Code: 201
389
    # Error Response Codes: computeFault (400, 500),
390
    #                       serviceUnavailable (503),
391
    #                       unauthorized (401),
392
    #                       itemNotFound (404),
393
    #                       badRequest (400),
394
    #                       buildInProgress (409),
395
    #                       badMediaType(415),
396
    #                       overLimit (413)
397

    
398
    vm = get_vm(server_id)
399
    req = get_request_dict(request)
400
    try:
401
        metadict = req['meta']
402
        assert isinstance(metadict, dict)
403
        assert len(metadict) == 1
404
        assert key in metadict
405
    except (KeyError, AssertionError):
406
        raise BadRequest('Malformed request.')
407
    
408
    meta, created = VirtualMachineMetadata.objects.get_or_create(meta_key=key, vm=vm)
409
    meta.meta_value = metadict[key]
410
    meta.save()
411
    return render_meta(request, meta, status=201)
412

    
413
@api_method('DELETE')
414
def delete_metadata_item(request, server_id, key):
415
    # Normal Response Code: 204
416
    # Error Response Codes: computeFault (400, 500),
417
    #                       serviceUnavailable (503),
418
    #                       unauthorized (401),
419
    #                       itemNotFound (404),
420
    #                       badRequest (400),
421
    #                       buildInProgress (409),
422
    #                       badMediaType(415),
423
    #                       overLimit (413),
424

    
425
    meta = get_vm_meta(server_id, key)
426
    meta.delete()
427
    return HttpResponse(status=204)