-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbert-e_api_client
More file actions
executable file
·206 lines (175 loc) · 6.9 KB
/
Copy pathbert-e_api_client
File metadata and controls
executable file
·206 lines (175 loc) · 6.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#! /usr/bin/env python
"""Create Bert-E jobs from the API.
An OAuth token is required. It can be obtained from
the Git host provider:
Bitbucket:
Go to https://bitbucket.org/account/user/<your_username>/api
and create a new consumer with the following settings:
- permissions:
- account: READ access
- team membership: READ access
-> use the newly create consumer ids with command line options
--consumer-id and --consumer-secret.
Github:
Go to https://github.com/settings/tokens
and create a new token with the following settings:
- scopes: user (read:user, user:email and user:follow)
-> use the newly created token with command line option --token.
Invocation example for a GitHub repository:
bert-e_api_client
--token <token>
--base-url <url of bert-e>
/pull-requests/1377
The script returns json data including the job id that was created.
Report any bug/error at release.engineering@scality.com
"""
import argparse
import base64
try:
# python 3
from http.cookiejar import CookieJar
from urllib.request import Request, HTTPRedirectHandler, build_opener, HTTPError, HTTPCookieProcessor
from urllib.parse import urlparse, parse_qs, urlencode
except ImportError:
# python 2
from cookielib import CookieJar
from urllib import urlencode
from urllib2 import Request, HTTPRedirectHandler, build_opener, HTTPError, HTTPCookieProcessor
from urlparse import urlparse, parse_qs
import json
import sys
def get_access_token(githost, consumer_id, consumer_secret):
"""Get an access token from Bitbucket OAuth API.
Args:
consumer_id (str): username of the consumer.
consumer_secret (str): password of the consumer.
Returns:
string containing the access token
"""
authstr = '{}:{}'.format(consumer_id, consumer_secret)
base64auth = base64.b64encode(authstr.encode('ascii'))
auth_url = 'https://bitbucket.org/site/oauth2/access_token'
data = 'grant_type=client_credentials'.encode('ascii')
req = Request(auth_url, data=data)
req.get_method = lambda: 'POST'
req.add_header("Authorization", "Basic %s" % base64auth.decode())
try:
res = build_opener().open(req)
except HTTPError as excp:
sys.exit('HTTP error: %s, %s (%s)' % (
excp.url, excp.reason, excp.code))
return json.load(res)['access_token']
def request(token, base_url, endpoint, httpmethod, payload):
"""Access API thanks to pre-obtained access token.
Args:
token (str): OAuth2 access token
base_url (str): url of Bert-E
endpoint (str): endpoint to query
httpmethod (str): get/post/put/delete
payload (dict): the json data to send
Returns:
API response (json)
"""
cj = CookieJar()
opener = build_opener(HTTPCookieProcessor(cj))
auth_url = base_url + '/api/auth?access_token=%s' % token
auth_req = Request(auth_url)
auth_req.add_header('Content-Type', 'application/json')
auth_req.add_header('Accept', 'application/json')
try:
auth_res = opener.open(auth_req)
except HTTPError as excp:
sys.exit('HTTP error: %s, %s (%s)' % (
excp.url, excp.reason, excp.code))
data = json.dumps(payload)
if endpoint.startswith('/'):
endpoint = endpoint[1:]
url = '%s/api/%s' % (base_url, endpoint)
req = Request(url, data=data.encode('ascii'))
req.add_header('Content-Type', 'application/json')
req.add_header('Accept', 'application/json')
req.get_method = lambda: httpmethod.upper()
try:
res = opener.open(req)
except HTTPError as excp:
sys.exit('HTTP error: %s (%s)' % (excp.reason, excp.code))
return json.load(res)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument('--client-id', '-u',
help='consumer client id (Bitbucket only)',
default='')
parser.add_argument('--client-secret', '-p',
help='consumer client secret (Bitbucket only)',
default='')
parser.add_argument('--token', '-k',
help='Git host authentication token',
metavar='TOKEN',
default='')
parser.add_argument('--base-url', '-b',
help='Bert-E\'s base url',
metavar='BASE_URL',
required=True)
parser.add_argument('--httpmethod', '-m',
help='HTTP method (default: POST)',
choices=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
default='POST')
parser.add_argument('--payload', '-l',
help='json data to send to the server',
metavar='JSON',
default='{}')
parser.add_argument('--githost', '-g',
help='remote githost (defaults to "auto"; '
'can be either "bitbucket" or "github")',
metavar='GITHOST',
choices=['auto', 'bitbucket', 'github'],
default='auto')
parser.add_argument('endpoint',
help='api endpoint',
metavar='ENDPOINT')
parser.add_argument('--dry-run', '-d',
help='Do not really do anything',
default=False,
action='store_true')
args = parser.parse_args(sys.argv[1:])
if args.githost == 'auto':
if 'github' in args.base_url:
githost = 'github'
elif 'bitbucket' in args.base_url:
githost = 'bitbucket'
else:
sys.exit('cannot extrapolate githost from service URL, '
'please specify it with -g/--githost option')
else:
githost = args.githost
if githost == 'github':
if not args.token:
sys.exit(
'The remote Git host is GitHub. Please provide a valid '
'token obtained from https://github.com/settings/tokens, '
'via the --token option.'
)
token = args.token
else:
if not args.client_id or not args.client_secret:
sys.exit(
'The remote Git host is Bitbucket. Please provide a consumer '
'id and consumer secret obtained from the OAuth page in '
'https://bitbucket.org/account/user, via the --client-id '
'and --client-secret options.'
)
token = get_access_token(githost, args.client_id, args.client_secret)
if args.dry_run:
print('Dry run activated, the request was not executed')
sys.exit(0)
req = request(
token,
args.base_url,
args.endpoint,
args.httpmethod,
json.loads(args.payload),
)
print(json.dumps(req))