blob: 0d2c5f3affc2226c4522950c45458a2af640a79f [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
7class Urllib2HTTP(object):
8 """
9 class for making HTTP requests
10 """
11
12 allowed_methods = ('get', 'put', 'post', 'delete', 'patch', 'head')
13
14 def __init__(self, root_url, headers=None, echo=False):
15 """
16 """
17 if root_url.endswith('/'):
18 self.root_url = root_url[:-1]
19 else:
20 self.root_url = root_url
21
22 self.headers = headers if headers is not None else {}
23 self.echo = echo
24
25 def do(self, method, path, params=None):
26 if path.startswith('/'):
27 url = self.root_url + path
28 else:
29 url = self.root_url + '/' + path
30
31 if method == 'get':
32 assert params == {} or params is None
33 data_json = None
34 else:
35 data_json = json.dumps(params)
36
37 request = urllib2.Request(url,
38 data=data_json,
39 headers=self.headers)
40 if data_json is not None:
41 request.add_header('Content-Type', 'application/json')
42
43 request.get_method = lambda: method.upper()
44 response = urllib2.urlopen(request)
45
46 print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
47 # if method.lower() == "put":
48 # import ipdb;ipdb.set_trace()
49
50 if response.code < 200 or response.code > 209:
51 raise IndexError(url)
52
53 content = response.read()
54
55 if '' == content:
56 return None
57
58 return json.loads(content)
59
60 def __getattr__(self, name):
61 if name in self.allowed_methods:
62 return partial(self.do, name)
63 raise AttributeError(name)
64
65
66class KeystoneAuth(Urllib2HTTP):
67 def __init__(self, root_url, creds, headers=None, echo=False,
68 admin_node_ip=None):
69 super(KeystoneAuth, self).__init__(root_url, headers, echo)
70 self.keystone_url = "http://{0}:5000/v2.0".format(admin_node_ip)
71 self.keystone = keystoneclient(
72 auth_url=self.keystone_url, **creds)
73 self.refresh_token()
74
75 def refresh_token(self):
76 """Get new token from keystone and update headers"""
77 try:
78 self.keystone.authenticate()
79 self.headers['X-Auth-Token'] = self.keystone.auth_token
80 except exceptions.AuthorizationFailure:
81 print 'asdfsf'
82
83 def do(self, method, path, params=None):
84 """Do request. If gets 401 refresh token"""
85 try:
86 return super(KeystoneAuth, self).do(method, path, params)
87 except urllib2.HTTPError as e:
88 if e.code == 401:
89 self.refresh_token()
90 return super(KeystoneAuth, self).do(method, path, params)
91 else:
92 raise
93
94#
95# cred = {"username": "admin", "password": "admin", "tenant_name": "admin"}
96# keystone = KeystoneAuth(root_url='http://172.16.52.112:8000', creds=cred, admin_node_ip='172.16.52.112')
97# result = keystone.do(method='get', path="api/nodes")
98# print result