blob: d7f4a48f352bf2dc19ab797878862ceae74d5d63 [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):
Soren Hansenbc1d3a02011-09-08 13:33:17 +020017 timeout = kwargs.pop('timeout', 180)
18 interval = kwargs.pop('interval', 2)
19 # Start timestamp
20 start_ts = int(time.time())
21
22 while True:
23 resp, body = self.request(method, url, **kwargs)
24 if (check_response(resp, body)):
25 break
26 if (int(time.time()) - start_ts >= timeout):
27 raise exceptions.TimeoutException
28 time.sleep(interval)
29
30 def poll_request_status(self, method, url, status=200, **kwargs):
Soren Hansenbc1d3a02011-09-08 13:33:17 +020031 def check_response(resp, body):
32 return resp['status'] == str(status)
33
34 self.poll_request(method, url, check_response, **kwargs)
35
Soren Hansenbc1d3a02011-09-08 13:33:17 +020036 def request(self, method, url, **kwargs):
Dolph Mathewsc3bc0962011-11-13 21:05:19 -060037 # Default to management_url, but can be overridden here
Soren Hansenbc1d3a02011-09-08 13:33:17 +020038 # (for auth requests)
39 base_url = kwargs.get('base_url', self.management_url)
40
41 self.http_obj = httplib2.Http()
42
43 params = {}
44 params['headers'] = {'User-Agent': self.USER_AGENT}
45 params['headers'].update(kwargs.get('headers', {}))
46 if 'Content-Type' not in params.get('headers',{}):
47 params['headers']['Content-Type'] = 'application/json'
48
49 if 'body' in kwargs:
50 params['body'] = kwargs.get('body')
51
52 req_url = os.path.join(base_url, url.strip('/'))
53 resp, body = self.http_obj.request(req_url, method, **params)
54 return resp, body