__init__.py 4.82 KB
Newer Older
1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
Giorgos Verigakis's avatar
Giorgos Verigakis committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

Giorgos Verigakis's avatar
Giorgos Verigakis committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import json
import logging

import requests

from requests.auth import AuthBase


sendlog = logging.getLogger('clients.send')
recvlog = logging.getLogger('clients.recv')


# Add a convenience json property to the responses
def _json(self):
    try:
Giorgos Verigakis's avatar
Giorgos Verigakis committed
49
        return json.loads(self.content) if self.content else {}
Giorgos Verigakis's avatar
Giorgos Verigakis committed
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
    except ValueError:
        raise ClientError("Invalid JSON reply", self.status_code)
requests.Response.json = property(_json)

# Add a convenience status property to the responses
def _status(self):
    return requests.status_codes._codes[self.status_code][0].upper()
requests.Response.status = property(_status)


class XAuthTokenAuth(AuthBase):
    def __init__(self, token):
        self.token = token
    
    def __call__(self, r):
        r.headers['X-Auth-Token'] = self.token
        return r


Giorgos Verigakis's avatar
Giorgos Verigakis committed
69
70
71
72
73
74
75
class ClientError(Exception):
    def __init__(self, message, status=0, details=''):
        self.message = message
        self.status = status
        self.details = details


Giorgos Verigakis's avatar
Giorgos Verigakis committed
76
class Client(object):
77
    def __init__(self, base_url, token):
Giorgos Verigakis's avatar
Giorgos Verigakis committed
78
79
80
        self.base_url = base_url
        self.auth = XAuthTokenAuth(token)
    
81
82
83
    def raise_for_status(self, r):        
        message = "%d %s" % (r.status_code, r.status)
        details = r.text
Giorgos Verigakis's avatar
Giorgos Verigakis committed
84
85
86
87
88
89
90
91
92
93
94
95
96
        raise ClientError(message, r.status_code, details)

    def request(self, method, path, **kwargs):
        raw = kwargs.pop('raw', False)
        success = kwargs.pop('success', 200)
        if 'json' in kwargs:
            data = json.dumps(kwargs.pop('json'))
            kwargs['data'] = data
            headers = kwargs.setdefault('headers', {})
            headers['content-type'] = 'application/json'

        url = self.base_url + path
        kwargs.setdefault('auth', self.auth)
97
        kwargs.setdefault('verify', False)  # Disable certificate verification
Giorgos Verigakis's avatar
Giorgos Verigakis committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
        r = requests.request(method, url, **kwargs)
        
        req = r.request
        sendlog.info('%s %s', req.method, req.url)
        for key, val in req.headers.items():
            sendlog.info('%s: %s', key, val)
        sendlog.info('')
        if req.data:
            sendlog.info('%s', req.data)
        
        recvlog.info('%d %s', r.status_code, r.status)
        for key, val in r.headers.items():
            recvlog.info('%s: %s', key, val)
        recvlog.info('')
        if not raw and r.text:
            recvlog.debug(r.text)
        
        if success is not None:
            # Success can either be an in or a collection
            success = (success,) if isinstance(success, int) else success
            if r.status_code not in success:
                self.raise_for_status(r)

Giorgos Verigakis's avatar
Giorgos Verigakis committed
121
122
        return r

Giorgos Verigakis's avatar
Giorgos Verigakis committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    def delete(self, path, **kwargs):
        return self.request('delete', path, **kwargs)

    def get(self, path, **kwargs):
        return self.request('get', path, **kwargs)

    def head(self, path, **kwargs):
        return self.request('head', path, **kwargs)

    def post(self, path, **kwargs):
        return self.request('post', path, **kwargs)

    def put(self, path, **kwargs):
        return self.request('put', path, **kwargs)

Giorgos Verigakis's avatar
Giorgos Verigakis committed
138

Giorgos Verigakis's avatar
Giorgos Verigakis committed
139
140
141
142
143
from .compute import ComputeClient as compute
from .image import ImageClient as image
from .storage import StorageClient as storage
from .cyclades import CycladesClient as cyclades
from .pithos import PithosClient as pithos
144
from .astakos import AstakosClient as astakos