Statistics
| Branch: | Tag: | Revision:

root / api / util.py @ 334c1b75

History | View | Annotate | Download (10.1 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
import datetime
35
import dateutil.parser
36
import logging
37

    
38
from base64 import b64encode
39
from datetime import timedelta, tzinfo
40
from functools import wraps
41
from hashlib import sha256
42
from random import choice
43
from string import ascii_letters, digits
44
from time import time
45
from traceback import format_exc
46
from wsgiref.handlers import format_date_time
47

    
48
from Crypto.Cipher import AES
49

    
50
from django.conf import settings
51
from django.http import HttpResponse
52
from django.template.loader import render_to_string
53
from django.utils import simplejson as json
54

    
55
from synnefo.api.faults import (Fault, BadRequest, BuildInProgress,
56
                                ItemNotFound, ServiceUnavailable, Unauthorized)
57
from synnefo.db.models import (SynnefoUser, Flavor, Image, ImageMetadata,
58
                                VirtualMachine, VirtualMachineMetadata,
59
                                Network, NetworkInterface)
60

    
61

    
62
class UTC(tzinfo):
63
    def utcoffset(self, dt):
64
        return timedelta(0)
65

    
66
    def tzname(self, dt):
67
        return 'UTC'
68

    
69
    def dst(self, dt):
70
        return timedelta(0)
71

    
72

    
73
def isoformat(d):
74
    """Return an ISO8601 date string that includes a timezone."""
75

    
76
    return d.replace(tzinfo=UTC()).isoformat()
77

    
78
def isoparse(s):
79
    """Parse an ISO8601 date string into a datetime object."""
80

    
81
    if not s:
82
        return None
83

    
84
    try:
85
        since = dateutil.parser.parse(s)
86
        utc_since = since.astimezone(UTC()).replace(tzinfo=None)
87
    except ValueError:
88
        raise BadRequest('Invalid changes-since parameter.')
89

    
90
    now = datetime.datetime.now()
91
    if utc_since > now:
92
        raise BadRequest('changes-since value set in the future.')
93

    
94
    if now - utc_since > timedelta(seconds=settings.POLL_LIMIT):
95
        raise BadRequest('Too old changes-since value.')
96

    
97
    return utc_since
98

    
99
def random_password(length=8):
100
    pool = ascii_letters + digits
101
    return ''.join(choice(pool) for i in range(length))
102

    
103
def zeropad(s):
104
    """Add zeros at the end of a string in order to make its length
105
       a multiple of 16."""
106
    
107
    npad = 16 - len(s) % 16
108
    return s + '\x00' * npad
109

    
110
def encrypt(plaintext):
111
    # Make sure key is 32 bytes long
112
    key = sha256(settings.SECRET_KEY).digest()
113
    
114
    aes = AES.new(key)
115
    enc = aes.encrypt(zeropad(plaintext))
116
    return b64encode(enc)
117

    
118

    
119
def get_vm(server_id, owner):
120
    """Return a VirtualMachine instance or raise ItemNotFound."""
121

    
122
    try:
123
        server_id = int(server_id)
124
        return VirtualMachine.objects.get(id=server_id, owner=owner)
125
    except ValueError:
126
        raise BadRequest('Invalid server ID.')
127
    except VirtualMachine.DoesNotExist:
128
        raise ItemNotFound('Server not found.')
129

    
130
def get_vm_meta(vm, key):
131
    """Return a VirtualMachineMetadata instance or raise ItemNotFound."""
132

    
133
    try:
134
        return VirtualMachineMetadata.objects.get(meta_key=key, vm=vm)
135
    except VirtualMachineMetadata.DoesNotExist:
136
        raise ItemNotFound('Metadata key not found.')
137

    
138
def get_image(image_id, owner):
139
    """Return an Image instance or raise ItemNotFound."""
140

    
141
    try:
142
        image_id = int(image_id)
143
        image = Image.objects.get(id=image_id)
144
        if not image.public and image.owner != owner:
145
            raise ItemNotFound('Image not found.')
146
        return image
147
    except ValueError:
148
        raise BadRequest('Invalid image ID.')
149
    except Image.DoesNotExist:
150
        raise ItemNotFound('Image not found.')
151

    
152
def get_image_meta(image, key):
153
    """Return a ImageMetadata instance or raise ItemNotFound."""
154

    
155
    try:
156
        return ImageMetadata.objects.get(meta_key=key, image=image)
157
    except ImageMetadata.DoesNotExist:
158
        raise ItemNotFound('Metadata key not found.')
159

    
160
def get_flavor(flavor_id):
161
    """Return a Flavor instance or raise ItemNotFound."""
162

    
163
    try:
164
        flavor_id = int(flavor_id)
165
        return Flavor.objects.get(id=flavor_id)
166
    except ValueError:
167
        raise BadRequest('Invalid flavor ID.')
168
    except Flavor.DoesNotExist:
169
        raise ItemNotFound('Flavor not found.')
170

    
171
def get_network(network_id, owner):
172
    """Return a Network instance or raise ItemNotFound."""
173

    
174
    try:
175
        if network_id == 'public':
176
            return Network.objects.get(public=True)
177
        else:
178
            network_id = int(network_id)
179
            return Network.objects.get(id=network_id, owner=owner)
180
    except ValueError:
181
        raise BadRequest('Invalid network ID.')
182
    except Network.DoesNotExist:
183
        raise ItemNotFound('Network not found.')
184

    
185
def get_nic(machine, network):
186
    try:
187
        return NetworkInterface.objects.get(machine=machine, network=network)
188
    except NetworkInterface.DoesNotExist:
189
        raise ItemNotFound('Server not connected to this network.')
190

    
191

    
192
def get_request_dict(request):
193
    """Returns data sent by the client as a python dict."""
194

    
195
    data = request.raw_post_data
196
    if request.META.get('CONTENT_TYPE').startswith('application/json'):
197
        try:
198
            return json.loads(data)
199
        except ValueError:
200
            raise BadRequest('Invalid JSON data.')
201
    else:
202
        raise BadRequest('Unsupported Content-Type.')
203

    
204
def update_response_headers(request, response):
205
    if request.serialization == 'xml':
206
        response['Content-Type'] = 'application/xml'
207
    elif request.serialization == 'atom':
208
        response['Content-Type'] = 'application/atom+xml'
209
    else:
210
        response['Content-Type'] = 'application/json'
211

    
212
    if settings.TEST:
213
        response['Date'] = format_date_time(time())
214

    
215
def render_metadata(request, metadata, use_values=False, status=200):
216
    if request.serialization == 'xml':
217
        data = render_to_string('metadata.xml', {'metadata': metadata})
218
    else:
219
        if use_values:
220
            d = {'metadata': {'values': metadata}}
221
        else:
222
            d = {'metadata': metadata}
223
        data = json.dumps(d)
224
    return HttpResponse(data, status=status)
225

    
226
def render_meta(request, meta, status=200):
227
    if request.serialization == 'xml':
228
        data = render_to_string('meta.xml', {'meta': meta})
229
    else:
230
        data = json.dumps({'meta': {meta.meta_key: meta.meta_value}})
231
    return HttpResponse(data, status=status)
232

    
233
def render_fault(request, fault):
234
    if settings.DEBUG or settings.TEST:
235
        fault.details = format_exc(fault)
236

    
237
    if request.serialization == 'xml':
238
        data = render_to_string('fault.xml', {'fault': fault})
239
    else:
240
        d = {fault.name: {
241
                'code': fault.code,
242
                'message': fault.message,
243
                'details': fault.details}}
244
        data = json.dumps(d)
245

    
246
    resp = HttpResponse(data, status=fault.code)
247
    update_response_headers(request, resp)
248
    return resp
249

    
250

    
251
def request_serialization(request, atom_allowed=False):
252
    """Return the serialization format requested.
253

254
    Valid formats are 'json', 'xml' and 'atom' if `atom_allowed` is True.
255
    """
256

    
257
    path = request.path
258

    
259
    if path.endswith('.json'):
260
        return 'json'
261
    elif path.endswith('.xml'):
262
        return 'xml'
263
    elif atom_allowed and path.endswith('.atom'):
264
        return 'atom'
265

    
266
    for item in request.META.get('HTTP_ACCEPT', '').split(','):
267
        accept, sep, rest = item.strip().partition(';')
268
        if accept == 'application/json':
269
            return 'json'
270
        elif accept == 'application/xml':
271
            return 'xml'
272
        elif atom_allowed and accept == 'application/atom+xml':
273
            return 'atom'
274

    
275
    return 'json'
276

    
277
def api_method(http_method=None, atom_allowed=False):
278
    """Decorator function for views that implement an API method."""
279

    
280
    def decorator(func):
281
        @wraps(func)
282
        def wrapper(request, *args, **kwargs):
283
            try:
284
                request.serialization = request_serialization(
285
                    request,
286
                    atom_allowed)
287
                if not request.user:
288
                    raise Unauthorized('No user found.')
289
                if http_method and request.method != http_method:
290
                    raise BadRequest('Method not allowed.')
291

    
292
                resp = func(request, *args, **kwargs)
293
                update_response_headers(request, resp)
294
                return resp
295
            except VirtualMachine.DeletedError:
296
                fault = BadRequest('Server has been deleted.')
297
                return render_fault(request, fault)
298
            except VirtualMachine.BuildingError:
299
                fault = BuildInProgress('Server is being built.')
300
                return render_fault(request, fault)
301
            except Fault, fault:
302
                return render_fault(request, fault)
303
            except BaseException, e:
304
                logging.exception('Unexpected error: %s', e)
305
                fault = ServiceUnavailable('Unexpected error.')
306
                return render_fault(request, fault)
307
        return wrapper
308
    return decorator