~ubuntu-branches/ubuntu/precise/python-novaclient/precise

« back to all changes in this revision

Viewing changes to novaclient/client.py

  • Committer: Bazaar Package Importer
  • Author(s): Chuck Short
  • Date: 2011-08-02 14:28:50 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20110802142850-b98ntnbobuwiapu3
Tags: 2.5.9~bzr65-0ubuntu1
* New upstream release.
* debian/watch: Add url for python-novaclient.
* dh_python2 transition.

Show diffs side-by-side

added added

removed removed

Lines of Context:
7
7
import urlparse
8
8
import urllib
9
9
import httplib2
 
10
import logging
 
11
 
10
12
try:
11
13
    import json
12
14
except ImportError:
20
22
import novaclient
21
23
from novaclient import exceptions
22
24
 
 
25
_logger = logging.getLogger(__name__)
 
26
 
23
27
 
24
28
class OpenStackClient(httplib2.Http):
25
29
 
26
30
    USER_AGENT = 'python-novaclient/%s' % novaclient.__version__
27
31
 
28
 
    def __init__(self, user, apikey, auth_url):
29
 
        super(OpenStackClient, self).__init__()
 
32
    def __init__(self, user, apikey, projectid, auth_url, timeout=None):
 
33
        super(OpenStackClient, self).__init__(timeout=timeout)
30
34
        self.user = user
31
35
        self.apikey = apikey
 
36
        self.projectid = projectid
32
37
        self.auth_url = auth_url
 
38
        self.version = 'v1.0'
33
39
 
34
40
        self.management_url = None
35
41
        self.auth_token = None
37
43
        # httplib2 overrides
38
44
        self.force_exception_to_status_code = True
39
45
 
 
46
    def http_log(self, args, kwargs, resp, body):
 
47
        if not _logger.isEnabledFor(logging.DEBUG):
 
48
            return
 
49
 
 
50
        string_parts = ['curl -i']
 
51
        for element in args:
 
52
            if element in ('GET', 'POST'):
 
53
                string_parts.append(' -X %s' % element)
 
54
            else:
 
55
                string_parts.append(' %s' % element)
 
56
 
 
57
        for element in kwargs['headers']:
 
58
            header = ' -H "%s: %s"' % (element, kwargs['headers'][element])
 
59
            string_parts.append(header)
 
60
 
 
61
        _logger.debug("REQ: %s\n" % "".join(string_parts))
 
62
        _logger.debug("RESP:%s %s\n", resp, body)
 
63
 
40
64
    def request(self, *args, **kwargs):
41
65
        kwargs.setdefault('headers', {})
42
66
        kwargs['headers']['User-Agent'] = self.USER_AGENT
44
68
            kwargs['headers']['Content-Type'] = 'application/json'
45
69
            kwargs['body'] = json.dumps(kwargs['body'])
46
70
 
47
 
        if httplib2.debuglevel == 1:
48
 
            print "ARGS:", args
49
71
        resp, body = super(OpenStackClient, self).request(*args, **kwargs)
50
 
        if httplib2.debuglevel == 1:
51
 
            print "RESPONSE", resp
52
 
            print "BODY", body
 
72
 
 
73
        self.http_log(args, kwargs, resp, body)
 
74
 
53
75
        if body:
54
76
            try:
55
77
                body = json.loads(body)
58
80
        else:
59
81
            body = None
60
82
 
61
 
        if resp.status in (400, 401, 403, 404, 413, 500, 501):
 
83
        if resp.status in (400, 401, 403, 404, 408, 413, 500, 501):
62
84
            raise exceptions.from_response(resp, body)
63
85
 
64
86
        return resp, body
72
94
        # re-authenticate and try again. If it still fails, bail.
73
95
        try:
74
96
            kwargs.setdefault('headers', {})['X-Auth-Token'] = self.auth_token
 
97
            if self.projectid:
 
98
                kwargs['headers']['X-Auth-Project-Id'] = self.projectid
 
99
 
75
100
            resp, body = self.request(self.management_url + url, method,
76
101
                                      **kwargs)
77
102
            return resp, body
98
123
        return self._cs_request(url, 'DELETE', **kwargs)
99
124
 
100
125
    def authenticate(self):
101
 
        headers = {'X-Auth-User': self.user, 'X-Auth-Key': self.apikey}
 
126
        scheme, netloc, path, query, frag = urlparse.urlsplit(
 
127
                                                    self.auth_url)
 
128
        path_parts = path.split('/')
 
129
        for part in path_parts:
 
130
            if len(part) > 0 and part[0] == 'v':
 
131
                self.version = part
 
132
                break
 
133
 
 
134
        headers = {'X-Auth-User': self.user,
 
135
                   'X-Auth-Key': self.apikey}
 
136
        if self.projectid:
 
137
            headers['X-Auth-Project-Id'] = self.projectid
102
138
        resp, body = self.request(self.auth_url, 'GET', headers=headers)
103
139
        self.management_url = resp['x-server-management-url']
 
140
 
104
141
        self.auth_token = resp['x-auth-token']
105
142
 
106
143
    def _munge_get_url(self, url):