Statistics
| Branch: | Tag: | Revision:

root / snf-app / synnefo / api / servers.py @ 3a9b3cde

History | View | Annotate | Download (19.3 kB)

1
# Copyright 2011 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 base64 import b64decode
35

    
36
from django.conf import settings
37
from django.conf.urls.defaults import patterns
38
from django.http import HttpResponse
39
from django.template.loader import render_to_string
40
from django.utils import simplejson as json
41

    
42
from synnefo.api import faults, util
43
from synnefo.api.actions import server_actions
44
from synnefo.api.common import method_not_allowed
45
from synnefo.db.models import VirtualMachine, VirtualMachineMetadata
46
from synnefo.logic.backend import create_instance, delete_instance
47
from synnefo.logic.utils import get_rsapi_state
48
from synnefo.util.rapi import GanetiApiError
49
from synnefo.util.log import getLogger
50

    
51

    
52
log = getLogger('synnefo.api')
53

    
54
urlpatterns = patterns('synnefo.api.servers',
55
    (r'^(?:/|.json|.xml)?$', 'demux'),
56
    (r'^/detail(?:.json|.xml)?$', 'list_servers', {'detail': True}),
57
    (r'^/(\d+)(?:.json|.xml)?$', 'server_demux'),
58
    (r'^/(\d+)/action(?:.json|.xml)?$', 'server_action'),
59
    (r'^/(\d+)/ips(?:.json|.xml)?$', 'list_addresses'),
60
    (r'^/(\d+)/ips/(.+?)(?:.json|.xml)?$', 'list_addresses_by_network'),
61
    (r'^/(\d+)/meta(?:.json|.xml)?$', 'metadata_demux'),
62
    (r'^/(\d+)/meta/(.+?)(?:.json|.xml)?$', 'metadata_item_demux'),
63
    (r'^/(\d+)/stats(?:.json|.xml)?$', 'server_stats'),
64
)
65

    
66

    
67
def demux(request):
68
    if request.method == 'GET':
69
        return list_servers(request)
70
    elif request.method == 'POST':
71
        return create_server(request)
72
    else:
73
        return method_not_allowed(request)
74

    
75

    
76
def server_demux(request, server_id):
77
    if request.method == 'GET':
78
        return get_server_details(request, server_id)
79
    elif request.method == 'PUT':
80
        return update_server_name(request, server_id)
81
    elif request.method == 'DELETE':
82
        return delete_server(request, server_id)
83
    else:
84
        return method_not_allowed(request)
85

    
86

    
87
def metadata_demux(request, server_id):
88
    if request.method == 'GET':
89
        return list_metadata(request, server_id)
90
    elif request.method == 'POST':
91
        return update_metadata(request, server_id)
92
    else:
93
        return method_not_allowed(request)
94

    
95

    
96
def metadata_item_demux(request, server_id, key):
97
    if request.method == 'GET':
98
        return get_metadata_item(request, server_id, key)
99
    elif request.method == 'PUT':
100
        return create_metadata_item(request, server_id, key)
101
    elif request.method == 'DELETE':
102
        return delete_metadata_item(request, server_id, key)
103
    else:
104
        return method_not_allowed(request)
105

    
106

    
107
def nic_to_dict(nic):
108
    network = nic.network
109
    network_id = str(network.id) if not network.public else 'public'
110
    d = {'id': network_id, 'name': network.name, 'mac': nic.mac}
111
    if nic.firewall_profile:
112
        d['firewallProfile'] = nic.firewall_profile
113
    if nic.ipv4 or nic.ipv6:
114
        d['values'] = []
115
        if nic.ipv4:
116
            d['values'].append({'version': 4, 'addr': nic.ipv4})
117
        if nic.ipv6:
118
            d['values'].append({'version': 6, 'addr': nic.ipv6})
119
    return d
120

    
121

    
122
def vm_to_dict(vm, detail=False):
123
    d = dict(id=vm.id, name=vm.name)
124
    if detail:
125
        d['status'] = get_rsapi_state(vm)
126
        d['progress'] = 100 if get_rsapi_state(vm) == 'ACTIVE' \
127
                        else vm.buildpercentage
128
        d['hostId'] = vm.hostid
129
        d['updated'] = util.isoformat(vm.updated)
130
        d['created'] = util.isoformat(vm.created)
131
        d['flavorRef'] = vm.flavor.id
132
        d['imageRef'] = vm.imageid
133
        
134
        metadata = dict((m.meta_key, m.meta_value) for m in vm.metadata.all())
135
        if metadata:
136
            d['metadata'] = {'values': metadata}
137

    
138
        addresses = [nic_to_dict(nic) for nic in vm.nics.all()]
139
        if addresses:
140
            d['addresses'] = {'values': addresses}
141
    return d
142

    
143

    
144
def render_server(request, server, status=200):
145
    if request.serialization == 'xml':
146
        data = render_to_string('server.xml', {
147
            'server': server,
148
            'is_root': True})
149
    else:
150
        data = json.dumps({'server': server})
151
    return HttpResponse(data, status=status)
152

    
153

    
154
@util.api_method('GET')
155
def list_servers(request, detail=False):
156
    # Normal Response Codes: 200, 203
157
    # Error Response Codes: computeFault (400, 500),
158
    #                       serviceUnavailable (503),
159
    #                       unauthorized (401),
160
    #                       badRequest (400),
161
    #                       overLimit (413)
162
    
163
    log.debug('list_servers detail=%s', detail)
164
    user_vms = VirtualMachine.objects.filter(owner=request.user)
165
    since = util.isoparse(request.GET.get('changes-since'))
166
    
167
    if since:
168
        user_vms = user_vms.filter(updated__gte=since)
169
        if not user_vms:
170
            return HttpResponse(status=304)
171
    else:
172
        user_vms = user_vms.filter(deleted=False)
173
    
174
    servers = [vm_to_dict(server, detail) for server in user_vms]
175

    
176
    if request.serialization == 'xml':
177
        data = render_to_string('list_servers.xml', {
178
            'servers': servers,
179
            'detail': detail})
180
    else:
181
        data = json.dumps({'servers': {'values': servers}})
182

    
183
    return HttpResponse(data, status=200)
184

    
185

    
186
@util.api_method('POST')
187
def create_server(request):
188
    # Normal Response Code: 202
189
    # Error Response Codes: computeFault (400, 500),
190
    #                       serviceUnavailable (503),
191
    #                       unauthorized (401),
192
    #                       badMediaType(415),
193
    #                       itemNotFound (404),
194
    #                       badRequest (400),
195
    #                       serverCapacityUnavailable (503),
196
    #                       overLimit (413)
197

    
198
    req = util.get_request_dict(request)
199
    log.debug('create_server %s', req)
200
    owner = request.user
201
    
202
    try:
203
        server = req['server']
204
        name = server['name']
205
        metadata = server.get('metadata', {})
206
        assert isinstance(metadata, dict)
207
        image_id = server['imageRef']
208
        flavor_id = server['flavorRef']
209
        personality = server.get('personality', [])
210
        assert isinstance(personality, list)
211
    except (KeyError, AssertionError):
212
        raise faults.BadRequest("Malformed request")
213
    
214
    if len(personality) > settings.MAX_PERSONALITY:
215
        raise faults.OverLimit("Maximum number of personalities exceeded")
216
    
217
    for p in personality:
218
        # Verify that personalities are well-formed
219
        try:
220
            assert isinstance(p, dict)
221
            keys = set(p.keys())
222
            allowed = set(['contents', 'group', 'mode', 'owner', 'path'])
223
            assert keys.issubset(allowed)
224
            contents = p['contents']
225
            if len(contents) > settings.MAX_PERSONALITY_SIZE:
226
                # No need to decode if contents already exceed limit
227
                raise faults.OverLimit("Maximum size of personality exceeded")
228
            if len(b64decode(contents)) > settings.MAX_PERSONALITY_SIZE:
229
                raise faults.OverLimit("Maximum size of personality exceeded")
230
        except AssertionError:
231
            raise faults.BadRequest("Malformed personality in request")
232
    
233
    image = {}
234
    try:
235
        img = util.get_image(image_id, owner)
236
        image['backend_id'] = img.backend_id
237
        image['format'] = img.format
238
        image['metadata'] = dict((m.meta_key, m.meta_value)
239
                for m in img.metadata.all())
240
    except faults.ItemNotFound:
241
        img = util.get_backend_image(image_id, owner)
242
        image['backend_id'] = img['location']
243
        image['format'] = img['disk_format']
244
        image['metadata'] = img.get('properties', {})
245
    
246
    flavor = util.get_flavor(flavor_id)
247
    password = util.random_password()
248
    
249
    count = VirtualMachine.objects.filter(owner=owner, deleted=False).count()
250
    if count >= settings.MAX_VMS_PER_USER:
251
        raise faults.OverLimit("Server count limit exceeded for your account.")
252
    
253
    # We must save the VM instance now, so that it gets a valid vm.backend_id.
254
    vm = VirtualMachine.objects.create(
255
        name=name,
256
        owner=owner,
257
        imageid=image_id,
258
        flavor=flavor)
259
    
260
    try:
261
        create_instance(vm, flavor, image, password, personality)
262
    except GanetiApiError:
263
        vm.delete()
264
        raise
265

    
266
    for key, val in metadata.items():
267
        VirtualMachineMetadata.objects.create(
268
            meta_key=key,
269
            meta_value=val,
270
            vm=vm)
271
    
272
    log.info('User %d created vm with %s cpus, %s ram and %s storage',
273
                    owner.id, flavor.cpu, flavor.ram, flavor.disk)
274
    
275
    server = vm_to_dict(vm, detail=True)
276
    server['status'] = 'BUILD'
277
    server['adminPass'] = password
278
    return render_server(request, server, status=202)
279

    
280

    
281
@util.api_method('GET')
282
def get_server_details(request, server_id):
283
    # Normal Response Codes: 200, 203
284
    # Error Response Codes: computeFault (400, 500),
285
    #                       serviceUnavailable (503),
286
    #                       unauthorized (401),
287
    #                       badRequest (400),
288
    #                       itemNotFound (404),
289
    #                       overLimit (413)
290
    
291
    log.debug('get_server_details %s', server_id)
292
    vm = util.get_vm(server_id, request.user)
293
    server = vm_to_dict(vm, detail=True)
294
    return render_server(request, server)
295

    
296

    
297
@util.api_method('PUT')
298
def update_server_name(request, server_id):
299
    # Normal Response Code: 204
300
    # Error Response Codes: computeFault (400, 500),
301
    #                       serviceUnavailable (503),
302
    #                       unauthorized (401),
303
    #                       badRequest (400),
304
    #                       badMediaType(415),
305
    #                       itemNotFound (404),
306
    #                       buildInProgress (409),
307
    #                       overLimit (413)
308

    
309
    req = util.get_request_dict(request)
310
    log.debug('update_server_name %s %s', server_id, req)
311
    
312
    try:
313
        name = req['server']['name']
314
    except (TypeError, KeyError):
315
        raise faults.BadRequest("Malformed request")
316

    
317
    vm = util.get_vm(server_id, request.user)
318
    vm.name = name
319
    vm.save()
320

    
321
    return HttpResponse(status=204)
322

    
323

    
324
@util.api_method('DELETE')
325
def delete_server(request, server_id):
326
    # Normal Response Codes: 204
327
    # Error Response Codes: computeFault (400, 500),
328
    #                       serviceUnavailable (503),
329
    #                       unauthorized (401),
330
    #                       itemNotFound (404),
331
    #                       unauthorized (401),
332
    #                       buildInProgress (409),
333
    #                       overLimit (413)
334
    
335
    log.debug('delete_server %s', server_id)
336
    vm = util.get_vm(server_id, request.user)
337
    delete_instance(vm)
338
    return HttpResponse(status=204)
339

    
340

    
341
@util.api_method('POST')
342
def server_action(request, server_id):
343
    req = util.get_request_dict(request)
344
    log.debug('server_action %s %s', server_id, req)
345
    vm = util.get_vm(server_id, request.user)
346
    if len(req) != 1:
347
        raise faults.BadRequest("Malformed request")
348

    
349
    key = req.keys()[0]
350
    val = req[key]
351

    
352
    try:
353
        assert isinstance(val, dict)
354
        return server_actions[key](request, vm, req[key])
355
    except KeyError:
356
        raise faults.BadRequest("Unknown action")
357
    except AssertionError:
358
        raise faults.BadRequest("Invalid argument")
359

    
360

    
361
@util.api_method('GET')
362
def list_addresses(request, server_id):
363
    # Normal Response Codes: 200, 203
364
    # Error Response Codes: computeFault (400, 500),
365
    #                       serviceUnavailable (503),
366
    #                       unauthorized (401),
367
    #                       badRequest (400),
368
    #                       overLimit (413)
369
    
370
    log.debug('list_addresses %s', server_id)
371
    vm = util.get_vm(server_id, request.user)
372
    addresses = [nic_to_dict(nic) for nic in vm.nics.all()]
373
    
374
    if request.serialization == 'xml':
375
        data = render_to_string('list_addresses.xml', {'addresses': addresses})
376
    else:
377
        data = json.dumps({'addresses': {'values': addresses}})
378

    
379
    return HttpResponse(data, status=200)
380

    
381

    
382
@util.api_method('GET')
383
def list_addresses_by_network(request, server_id, network_id):
384
    # Normal Response Codes: 200, 203
385
    # Error Response Codes: computeFault (400, 500),
386
    #                       serviceUnavailable (503),
387
    #                       unauthorized (401),
388
    #                       badRequest (400),
389
    #                       itemNotFound (404),
390
    #                       overLimit (413)
391
    
392
    log.debug('list_addresses_by_network %s %s', server_id, network_id)
393
    owner = request.user
394
    machine = util.get_vm(server_id, owner)
395
    network = util.get_network(network_id, owner)
396
    nic = util.get_nic(machine, network)
397
    address = nic_to_dict(nic)
398
    
399
    if request.serialization == 'xml':
400
        data = render_to_string('address.xml', {'address': address})
401
    else:
402
        data = json.dumps({'network': address})
403

    
404
    return HttpResponse(data, status=200)
405

    
406

    
407
@util.api_method('GET')
408
def list_metadata(request, server_id):
409
    # Normal Response Codes: 200, 203
410
    # Error Response Codes: computeFault (400, 500),
411
    #                       serviceUnavailable (503),
412
    #                       unauthorized (401),
413
    #                       badRequest (400),
414
    #                       overLimit (413)
415
    
416
    log.debug('list_server_metadata %s', server_id)
417
    vm = util.get_vm(server_id, request.user)
418
    metadata = dict((m.meta_key, m.meta_value) for m in vm.metadata.all())
419
    return util.render_metadata(request, metadata, use_values=True, status=200)
420

    
421

    
422
@util.api_method('POST')
423
def update_metadata(request, server_id):
424
    # Normal Response Code: 201
425
    # Error Response Codes: computeFault (400, 500),
426
    #                       serviceUnavailable (503),
427
    #                       unauthorized (401),
428
    #                       badRequest (400),
429
    #                       buildInProgress (409),
430
    #                       badMediaType(415),
431
    #                       overLimit (413)
432
    
433
    req = util.get_request_dict(request)
434
    log.debug('update_server_metadata %s %s', server_id, req)
435
    vm = util.get_vm(server_id, request.user)
436
    try:
437
        metadata = req['metadata']
438
        assert isinstance(metadata, dict)
439
    except (KeyError, AssertionError):
440
        raise faults.BadRequest("Malformed request")
441
    
442
    for key, val in metadata.items():
443
        meta, created = vm.metadata.get_or_create(meta_key=key)
444
        meta.meta_value = val
445
        meta.save()
446
    
447
    vm.save()
448
    vm_meta = dict((m.meta_key, m.meta_value) for m in vm.metadata.all())
449
    return util.render_metadata(request, vm_meta, status=201)
450

    
451

    
452
@util.api_method('GET')
453
def get_metadata_item(request, server_id, key):
454
    # Normal Response Codes: 200, 203
455
    # Error Response Codes: computeFault (400, 500),
456
    #                       serviceUnavailable (503),
457
    #                       unauthorized (401),
458
    #                       itemNotFound (404),
459
    #                       badRequest (400),
460
    #                       overLimit (413)
461
    
462
    log.debug('get_server_metadata_item %s %s', server_id, key)
463
    vm = util.get_vm(server_id, request.user)
464
    meta = util.get_vm_meta(vm, key)
465
    return util.render_meta(request, meta, status=200)
466

    
467

    
468
@util.api_method('PUT')
469
def create_metadata_item(request, server_id, key):
470
    # Normal Response Code: 201
471
    # Error Response Codes: computeFault (400, 500),
472
    #                       serviceUnavailable (503),
473
    #                       unauthorized (401),
474
    #                       itemNotFound (404),
475
    #                       badRequest (400),
476
    #                       buildInProgress (409),
477
    #                       badMediaType(415),
478
    #                       overLimit (413)
479
    
480
    req = util.get_request_dict(request)
481
    log.debug('create_server_metadata_item %s %s %s', server_id, key, req)
482
    vm = util.get_vm(server_id, request.user)
483
    try:
484
        metadict = req['meta']
485
        assert isinstance(metadict, dict)
486
        assert len(metadict) == 1
487
        assert key in metadict
488
    except (KeyError, AssertionError):
489
        raise faults.BadRequest("Malformed request")
490
    
491
    meta, created = VirtualMachineMetadata.objects.get_or_create(
492
        meta_key=key,
493
        vm=vm)
494
    
495
    meta.meta_value = metadict[key]
496
    meta.save()
497
    vm.save()
498
    return util.render_meta(request, meta, status=201)
499

    
500

    
501
@util.api_method('DELETE')
502
def delete_metadata_item(request, server_id, key):
503
    # Normal Response Code: 204
504
    # Error Response Codes: computeFault (400, 500),
505
    #                       serviceUnavailable (503),
506
    #                       unauthorized (401),
507
    #                       itemNotFound (404),
508
    #                       badRequest (400),
509
    #                       buildInProgress (409),
510
    #                       badMediaType(415),
511
    #                       overLimit (413),
512
    
513
    log.debug('delete_server_metadata_item %s %s', server_id, key)
514
    vm = util.get_vm(server_id, request.user)
515
    meta = util.get_vm_meta(vm, key)
516
    meta.delete()
517
    vm.save()
518
    return HttpResponse(status=204)
519

    
520

    
521
@util.api_method('GET')
522
def server_stats(request, server_id):
523
    # Normal Response Codes: 200
524
    # Error Response Codes: computeFault (400, 500),
525
    #                       serviceUnavailable (503),
526
    #                       unauthorized (401),
527
    #                       badRequest (400),
528
    #                       itemNotFound (404),
529
    #                       overLimit (413)
530
    
531
    log.debug('server_stats %s', server_id)
532
    vm = util.get_vm(server_id, request.user)
533
    #secret = util.encrypt(vm.backend_id)
534
    secret = vm.backend_id      # XXX disable backend id encryption
535
    
536
    stats = {
537
        'serverRef': vm.id,
538
        'refresh': settings.STATS_REFRESH_PERIOD,
539
        'cpuBar': settings.CPU_BAR_GRAPH_URL % secret,
540
        'cpuTimeSeries': settings.CPU_TIMESERIES_GRAPH_URL % secret,
541
        'netBar': settings.NET_BAR_GRAPH_URL % secret,
542
        'netTimeSeries': settings.NET_TIMESERIES_GRAPH_URL % secret}
543
    
544
    if request.serialization == 'xml':
545
        data = render_to_string('server_stats.xml', stats)
546
    else:
547
        data = json.dumps({'stats': stats})
548

    
549
    return HttpResponse(data, status=200)