-
Notifications
You must be signed in to change notification settings - Fork 2
/
remote_api.py
274 lines (230 loc) · 9.01 KB
/
remote_api.py
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"""
Copyright (c) 2017 IBM Corp.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import requests
import json
from os import getenv
HOST= 'patchport-http.mybluemix.net'
VER = 'v0'
TOKEN = getenv("TOKEN")
if not TOKEN:
print ("Set env variable TOKEN with the access token if you want to access the remote API.")
class Remote(object):
def __init__(self):
self.APIurl = "https://%s/api/%s" % (HOST, VER)
self.token = TOKEN
def _requestPOST(self, path, data={}):
headers = {'content-type': 'application/json'}
u = "%s/%s?access_token=%s" % (self.APIurl, path, self.token)
r = requests.post(u,data=data,headers=headers)
if not r.status_code == 200:
raise Exception('Error %d: %s\n%s' % (r.status_code,r.reason,u))
return r.json()
def _requestPATCH(self, path, data={}):
headers = {'content-type': 'application/json'}
u = "%s/%s?access_token=%s" % (self.APIurl, path, self.token)
r = requests.patch(u,data=data,headers=headers)
if not r.status_code == 200:
raise Exception('Error %d: %s\n%s' % (r.status_code,r.reason,u))
return r.json()
def _requestDELETE(self, path):
u = "%s/%s?access_token=%s" % (self.APIurl, path, self.token)
r = requests.delete(u)
if not r.status_code == 200:
raise Exception('Error %d: %s\n%s' % (r.status_code,r.reason,u))
return r.json()
def _requestGET(self, path, where=None, order=None, limit=None):
filter = {}
if where:
filter["where"] = where
if order:
filter["order"] = order
if limit:
filter["limit"] = limit
u = "%s/%s?filter=%s&access_token=%s" % (self.APIurl, path, json.dumps(filter), self.token)
r = requests.get(u)
if not r.status_code == 200:
raise Exception('Error %d: %s\n%s' % (r.status_code,r.reason,u))
return r.json()
def _findById(self,path, id):
# Is it a local file (instead of a remote id). This is just for debugging and should be removed TODO
if len(id) > 1 and id[0] == '<' and id[-1] == '>' and id != "<removed>":
with open(id[1:-1]) as data_file:
return json.load(data_file)
return self._requestGET(path=path % id)
#TODO catch empty
def reprJSON(self):
r = {}
for k, v in self.__dict__.iteritems():
if k in self._postableFields: r[k] = v
return r
class CVE(Remote):
def __init__(self, name=None, id=None):
Remote.__init__(self)
if id: cve = self._findById("cves/%s", id)
elif name: cve = self._findByName(name)
else: raise Exception('You have to give something to construct this CVE')
self.__dict__.update(cve)
def _findByName(self,name):
cves = self._requestGET(where={"name": name}, path='cves')
if len(cves) == 1:
return cves[0]
elif len(cves) == 0:
raise Exception('CVE id not found: %s' % name)
else:
raise Exception('Multiple CVEs match %s' % name)
def __getattr__(self, item):
if item is "patchsets":
patchsets = self._requestGET(path="cves/%s/patchsets" % self.id)
self.patchsets = [Patchsets(json=patchset) for patchset in patchsets]
return self.patchsets
else:
raise AttributeError(item)
class Patchsets(Remote):
def __init__(self,json={}):
Remote.__init__(self)
self.__dict__.update(json)
def __getattr__(self, item):
if item is "patches":
patches = self._requestGET(path="patchsets/%s/patches" % self.id)
self.patches = [Hunk(json=patch) for patch in patches]
return self.patches
else:
raise AttributeError(item)
class Patch(Remote):
def __init__(self,json={}):
Remote.__init__(self)
self.__dict__.update(json)
def __getattr__(self, item):
if item is "hunks":
hunks = self._requestGET(path="patches/%s/hunks" % self.id)
self.hunks= [Hunk(json=patch) for patch in hunks]
return self.hunks
else:
raise AttributeError(item)
class Hunk(Remote):
_postableFields = [
'cveId',
'data',
'fileName',
'id',
'patchId',
'patchsetId'
]
def __init__(self,json={},id=None):
Remote.__init__(self)
if id: json=self._findById("hunks/%s", id)
self.__dict__.update(json)
def __getattr__(self, item):
if item is "hunks":
hunks = self._requestGET(path="patches/%s/hunks" % self.id)
self.hunks= [Hunk(json=patch) for patch in hunks]
elif item is "cve":
self.cve = CVE(id=self.cveId)
else:
return self.__dict__[item]
return getattr(self,item)
class Setup(Remote):
def __init__(self,json={},id=None):
Remote.__init__(self)
if id: json=self._findById("setups/%s", id)
self.name = json['name']
self.content = json['content']
self.id = json['id']
class Build(Remote):
_postableFields = ['pkgName',
'pkgVersion',
'mode',
'status',
'dist',
'urgency',
'hunks',
'results',
'cveId',
'patchsetId',
'cveName',
'id']
def __init__(self,json={},where=None, id=None):
'''if empty, get the next waiting build.
with where, it gives you the next waiting with that filter'''
Remote.__init__(self)
if id: json = self._findById("builds/%s",id)
if not json: json = self._nextWaiting(where=where)
if not json:
from json import dumps
raise Exception('No pending builds (filter: %s)' % dumps(where))
self.__dict__.update(json)
def _nextWaiting(self,json={},where={}):
where["status"] = "waiting"
result = self._requestGET(where=where, limit=1, order='timestamp ASC', path='builds')
if len(result): return result[0]
else: return None
def updateResults(self,data):
if not isinstance(data,list):
data = [data]
o = {'buildId':self.id, 'data': {}}
for d in data:
o['data'] = d
self._requestPOST(path='results', data=json.dumps(o))
# TODO update the object with the new data?
def updateStatus(self, status):
result = self._requestPATCH(path='builds/%s' % self.id,data=json.dumps({'status': status}))
# TODO update the object with the new data?
return result
def updateStarted(self, now):
result = self._requestPATCH(path='builds/%s' % self.id,data=json.dumps({'started': now}))
return result
def postme(self):
data = json.dumps(self.reprJSON(), cls=ComplexEncoder)
result = self._requestPOST(path='builds',data=data)
return Build(result)
class RemoteEncoder(json.JSONEncoder):
def default(self, o):
r = {}
if type(o) is str: return o
for k,v in o.__dict__.iteritems():
if k in o._postableFields: r[k] = json.dumps(v, cls=RemoteEncoder)
return r
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj,'reprJSON'):
return obj.reprJSON()
else:
return json.JSONEncoder.default(self, obj)
class Result(Remote):
_postableFields =[
'children',
'deb',
'debdiff',
'hunkId',
'id',
'log',
'results',
'status',
'type']
def __init__(self, json={}):
Remote.__init__(self)
self.__dict__.update(json)
class Results(list):
def __init__(self, results=[],buildId=None):
list.__init__(self)
if buildId:
r = Remote()
results = r._requestGET(where={"buildId": buildId}, path='results')
for result in results:
self.append(Result(json=result))