blob: 47ac058b7d2e8cf3e1882e9fbf80feca56f6fe14 [file] [log] [blame]
Soren Hansenbc1d3a02011-09-08 13:33:17 +02001from kong import exceptions
2
3import httplib2
4import os
5import time
6
7
8class Client(object):
9
10 USER_AGENT = 'python-nova_test_client'
11
12 def __init__(self, host='localhost', port=80, base_url=''):
13 #TODO: join these more robustly
14 self.base_url = "http://%s:%s/%s" % (host, port, base_url)
15
16 def poll_request(self, method, url, check_response, **kwargs):
17
18 timeout = kwargs.pop('timeout', 180)
19 interval = kwargs.pop('interval', 2)
20 # Start timestamp
21 start_ts = int(time.time())
22
23 while True:
24 resp, body = self.request(method, url, **kwargs)
25 if (check_response(resp, body)):
26 break
27 if (int(time.time()) - start_ts >= timeout):
28 raise exceptions.TimeoutException
29 time.sleep(interval)
30
31 def poll_request_status(self, method, url, status=200, **kwargs):
32
33 def check_response(resp, body):
34 return resp['status'] == str(status)
35
36 self.poll_request(method, url, check_response, **kwargs)
37
38
39 def request(self, method, url, **kwargs):
40 # Default to management_url, but can be overridden here
41 # (for auth requests)
42 base_url = kwargs.get('base_url', self.management_url)
43
44 self.http_obj = httplib2.Http()
45
46 params = {}
47 params['headers'] = {'User-Agent': self.USER_AGENT}
48 params['headers'].update(kwargs.get('headers', {}))
49 if 'Content-Type' not in params.get('headers',{}):
50 params['headers']['Content-Type'] = 'application/json'
51
52 if 'body' in kwargs:
53 params['body'] = kwargs.get('body')
54
55 req_url = os.path.join(base_url, url.strip('/'))
56 resp, body = self.http_obj.request(req_url, method, **params)
57 return resp, body