1
|
|
|
import httplib |
2
|
|
|
|
3
|
|
|
import requests |
4
|
|
|
|
5
|
|
|
from st2actions.runners.pythonrunner import Action |
6
|
|
|
|
7
|
|
|
BASE_API_URL = 'https://circleci.com/api' |
8
|
|
|
API_VERSION = 'v1' |
9
|
|
|
API_URL = '%s/%s/' % (BASE_API_URL, API_VERSION) |
10
|
|
|
HEADER_ACCEPT = 'application/json' |
11
|
|
|
HEADER_CONTENT_TYPE = 'application/json' |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
class CircleCI(Action): |
15
|
|
|
def _get_base_headers(self): |
16
|
|
|
headers = {} |
17
|
|
|
headers['Content-Type'] = HEADER_CONTENT_TYPE |
18
|
|
|
headers['Accept'] = HEADER_ACCEPT |
19
|
|
|
return headers |
20
|
|
|
|
21
|
|
|
def _get_auth_headers(self): |
22
|
|
|
headers = self._get_base_headers() |
23
|
|
|
token = self.config.get('token', None) |
24
|
|
|
|
25
|
|
|
if not token: |
26
|
|
|
raise Exception('Token not found in config file.') |
27
|
|
|
|
28
|
|
|
headers['circle-token'] = token |
29
|
|
|
return headers |
30
|
|
|
|
31
|
|
|
def _perform_request(self, path, method, data=None, requires_auth=True, |
32
|
|
|
extra_headers=None): |
33
|
|
|
url = API_URL + path |
34
|
|
|
self.logger.debug('URL: %s', url) |
35
|
|
|
|
36
|
|
|
headers = self._get_base_headers() |
37
|
|
|
if requires_auth: |
38
|
|
|
headers = self._get_auth_headers() |
39
|
|
|
|
40
|
|
|
if extra_headers: |
41
|
|
|
headers.update(extra_headers) |
42
|
|
|
|
43
|
|
|
if method == "GET": |
44
|
|
|
response = requests.get(url, headers=headers) |
45
|
|
|
elif method == 'POST': |
46
|
|
|
response = requests.post(url, headers=headers) |
47
|
|
|
elif method == 'PUT': |
48
|
|
|
response = requests.put(url, data=data, headers=headers) |
49
|
|
|
|
50
|
|
|
if response.status_code in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: |
51
|
|
|
msg = ('Invalid or missing Travis CI auth token. ' + |
52
|
|
|
'Make sure you have' |
53
|
|
|
'specified valid token in the config file') |
54
|
|
|
raise Exception(msg) |
55
|
|
|
|
56
|
|
|
return response |
57
|
|
|
|