Soren Hansen | bc1d3a0 | 2011-09-08 13:33:17 +0200 | [diff] [blame] | 1 | from kong import exceptions |
| 2 | |
| 3 | import httplib2 |
| 4 | import os |
| 5 | import time |
| 6 | |
| 7 | |
| 8 | class 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 Hansen | bc1d3a0 | 2011-09-08 13:33:17 +0200 | [diff] [blame] | 17 | 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 Hansen | bc1d3a0 | 2011-09-08 13:33:17 +0200 | [diff] [blame] | 31 | def check_response(resp, body): |
| 32 | return resp['status'] == str(status) |
| 33 | |
| 34 | self.poll_request(method, url, check_response, **kwargs) |
| 35 | |
Soren Hansen | bc1d3a0 | 2011-09-08 13:33:17 +0200 | [diff] [blame] | 36 | def request(self, method, url, **kwargs): |
Dolph Mathews | c3bc096 | 2011-11-13 21:05:19 -0600 | [diff] [blame] | 37 | # Default to management_url, but can be overridden here |
Soren Hansen | bc1d3a0 | 2011-09-08 13:33:17 +0200 | [diff] [blame] | 38 | # (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 |