blob: e6308b5c5708d96ad779c5e9d599833bf595b7a7 [file] [log] [blame]
gstepanov94531b82015-02-11 14:20:34 +02001from functools import partial
2import json
3import urllib2
4from keystoneclient.v2_0 import Client as keystoneclient
5from keystoneclient import exceptions
6
koder aka kdanilov0f0546c2015-02-17 20:42:05 -08007
gstepanov94531b82015-02-11 14:20:34 +02008class Urllib2HTTP(object):
9 """
10 class for making HTTP requests
11 """
12
13 allowed_methods = ('get', 'put', 'post', 'delete', 'patch', 'head')
14
15 def __init__(self, root_url, headers=None, echo=False):
16 """
17 """
18 if root_url.endswith('/'):
19 self.root_url = root_url[:-1]
20 else:
21 self.root_url = root_url
22
23 self.headers = headers if headers is not None else {}
24 self.echo = echo
25
26 def do(self, method, path, params=None):
27 if path.startswith('/'):
28 url = self.root_url + path
29 else:
30 url = self.root_url + '/' + path
31
32 if method == 'get':
33 assert params == {} or params is None
34 data_json = None
35 else:
36 data_json = json.dumps(params)
37
38 request = urllib2.Request(url,
39 data=data_json,
40 headers=self.headers)
41 if data_json is not None:
42 request.add_header('Content-Type', 'application/json')
43
44 request.get_method = lambda: method.upper()
45 response = urllib2.urlopen(request)
46
gstepanov94531b82015-02-11 14:20:34 +020047 if response.code < 200 or response.code > 209:
48 raise IndexError(url)
49
50 content = response.read()
51
52 if '' == content:
53 return None
54
55 return json.loads(content)
56
57 def __getattr__(self, name):
58 if name in self.allowed_methods:
59 return partial(self.do, name)
60 raise AttributeError(name)
61
62
63class KeystoneAuth(Urllib2HTTP):
64 def __init__(self, root_url, creds, headers=None, echo=False,
65 admin_node_ip=None):
66 super(KeystoneAuth, self).__init__(root_url, headers, echo)
67 self.keystone_url = "http://{0}:5000/v2.0".format(admin_node_ip)
68 self.keystone = keystoneclient(
69 auth_url=self.keystone_url, **creds)
70 self.refresh_token()
71
72 def refresh_token(self):
73 """Get new token from keystone and update headers"""
74 try:
75 self.keystone.authenticate()
76 self.headers['X-Auth-Token'] = self.keystone.auth_token
77 except exceptions.AuthorizationFailure:
78 print 'asdfsf'
79
80 def do(self, method, path, params=None):
81 """Do request. If gets 401 refresh token"""
82 try:
83 return super(KeystoneAuth, self).do(method, path, params)
84 except urllib2.HTTPError as e:
85 if e.code == 401:
86 self.refresh_token()
87 return super(KeystoneAuth, self).do(method, path, params)
88 else:
89 raise