blob: 44658fab93d19e688e4b40ceb641c95cec42274e [file] [log] [blame]
Daryl Walleck1465d612011-11-02 02:22:15 -05001import httplib2
2import json
3import storm.config
4
5
6class RestClient(object):
7
8 def __init__(self, user, key, auth_url, tenant_name=None):
9 self.config = storm.config.StormConfig()
10
11 if self.config.env.authentication == 'keystone_v2':
12 self.token, self.base_url = self.keystone_v2_auth(user,
13 key,
14 auth_url,
15 tenant_name)
16 else:
17 self.token, self.base_url = self.basic_auth(user,
18 key,
19 auth_url)
20
21 def basic_auth(self, user, api_key, auth_url):
22 """
23 Provides authentication for the target API
24 """
25
26 params = {}
27 params['headers'] = {'User-Agent': 'Test-Client', 'X-Auth-User': user,
28 'X-Auth-Key': api_key}
29
30 self.http_obj = httplib2.Http()
31 resp, body = self.http_obj.request(auth_url, 'GET', **params)
32 try:
33 return resp['x-auth-token'], resp['x-server-management-url']
34 except:
35 raise
36
37 def keystone_v2_auth(self, user, api_key, auth_url, tenant_name):
38 """
39 Provides authentication via Keystone 2.0
40 """
41
42 creds = {'auth': {
43 'passwordCredentials': {
44 'username': user,
45 'password': api_key,
46 },
47 'tenantName': tenant_name
48 }
49 }
50
51 self.http_obj = httplib2.Http()
52 headers = {'Content-Type': 'application/json'}
53 body = json.dumps(creds)
54 resp, body = self.http_obj.request(auth_url, 'POST',
55 headers=headers, body=body)
56
57 try:
58 auth_data = json.loads(body)['access']
59 token = auth_data['token']['id']
60 endpoints = auth_data['serviceCatalog'][0]['endpoints']
61 mgmt_url = endpoints[0]['publicURL']
62
63 #TODO (dwalleck): This is a horrible stopgap.
64 #Need to join strings more cleanly
65 temp = mgmt_url.rsplit('/')
66 service_url = temp[0] + '//' + temp[2] + '/' + temp[3] + '/'
67 management_url = service_url + tenant_name
68 return token, management_url
69 except KeyError:
70 print "Failed to authenticate user"
71 raise
72
73 def post(self, url, body, headers):
74 return self.request('POST', url, headers, body)
75
76 def get(self, url):
77 return self.request('GET', url)
78
79 def delete(self, url):
80 return self.request('DELETE', url)
81
82 def put(self, url, body, headers):
83 return self.request('PUT', url, headers, body)
84
85 def request(self, method, url, headers=None, body=None):
86 """ A simple HTTP request interface."""
87
88 self.http_obj = httplib2.Http()
89 if headers == None:
90 headers = {}
91 headers['X-Auth-Token'] = self.token
92
93 req_url = "%s/%s" % (self.base_url, url)
94 resp, body = self.http_obj.request(req_url, method,
95 headers=headers, body=body)
96 return resp, body