-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpython-ci.py
executable file
·328 lines (255 loc) · 8.62 KB
/
python-ci.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#!/usr/bin/env python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
import os, time, subprocess, errno
from urlparse import urlparse
import hmac, hashlib, re, json
import latex
OUTPUT_SUFFIX = os.environ.get('OUTPUT_SUFFIX', "_build")
SECRET = os.environ.get('SECRET', "")
TOKEN = os.environ.get('TOKEN', "")
DOMAIN = os.environ.get('URL', "")
if TOKEN:
import gh
compileThread = 0
def log(s):
print s
# with open('python-ci.log', 'a') as logFile:
# logFile.write(s+"\n")
def symlink_force(target, link_name):
try:
os.symlink(target, link_name)
except OSError, e:
if e.errno == errno.EEXIST:
os.remove(link_name)
os.symlink(target, link_name)
else:
raise e
def parseRef(ref):
if ref == "":
return "last"
else:
return ref
def loadJSON(fileName):
data = None
try:
f = open(fileName, "r")
try:
data = json.load(f)
finally:
f.close()
except IOError:
pass
except ValueError:
pass
return data
def getConfig(proj):
return loadJSON(proj+"/.ci.json")
def getBuildPath(proj, ref):
if parseRef(ref) is None:
return proj+OUTPUT_SUFFIX +"/"+ "last"
else:
return proj+OUTPUT_SUFFIX +"/"+ parseRef(ref)
def updateStatus(ref, proj, msg, (start, duration), errorMsg = None):
if msg == "success":
color = "#4c1"
elif msg == "pending":
color = "darkgrey"
else:
color = "red"
svg = """
<svg xmlns="http://www.w3.org/2000/svg" width="90" height="20">
<linearGradient id="a" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1" />
<stop offset="1" stop-opacity=".1" />
</linearGradient>
<rect rx="3" width="90" height="20" fill="#555" />
<rect rx="3" x="37" width="53" height="20" fill="{}" />
<path fill="{}" d="M37 0h4v20h-4z" />
<rect rx="3" width="90" height="20" fill="url(#a)" />
<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
<text x="19.5" y="15" fill="#010101" fill-opacity=".3">built</text>
<text x="19.5" y="14">built</text>
<text x="62.5" y="15" fill="#010101" fill-opacity=".3">{}</text>
<text x="62.5" y="14">{}</text>
</g>
</svg>""".format(color, color, ref[:7], ref[:7])
with open(getBuildPath(proj, ref)+"/.status.svg", "w") as f:
f.write(svg)
data = {
"ref": ref,
"status": msg,
"errorMsg": errorMsg,
"start": round(start*1000),
"duration": duration,
"stats": {}
}
cfg = getConfig(proj)
if "stats" in cfg:
if cfg["language"] == "latex" and "counts" in cfg["stats"]:
(success, counts) = latex.count(proj, getBuildPath(proj, ref), cfg["main"]+".tex")
if success:
data["stats"]["counts"] = counts
else:
data["stats"]["counts"] = False
with open(getBuildPath(proj, ref)+"/.status.json", "w") as f:
f.write(json.dumps(data))
if TOKEN:
gh.setStatus(proj, ref, msg, DOMAIN+"/"+proj+"/"+ref, errorMsg)
def getStatus(ref, proj):
return loadJSON(getBuildPath(proj, ref)+"/.status.json")
def updateGit(proj, ref):
lastLog = ""
successful = True
try:
lastLog += subprocess.check_output(["git", "pull", "origin", "master"], cwd=proj, stderr=subprocess.STDOUT) + "\n"
lastLog += subprocess.check_output(["git", "reset", "--hard", ref], cwd=proj, stderr=subprocess.STDOUT) + "\n"
except subprocess.CalledProcessError as exc:
lastLog += exc.output + "\n"
lastLog += "git operations failed: "+str(exc.returncode) + "\n"
successful = False
return (successful, lastLog)
compileLang = dict(
latex = latex.doCompile,
git = lambda a,b,c,d: (True, "")
)
def doCompile(proj, ref):
timeStart = time.time()
log(">>> Started: "+time.strftime("%c"))
lastLog = ">>> Started: "+time.strftime("%c") + "\n"
if not os.path.exists(getBuildPath(proj, ref)):
os.makedirs(getBuildPath(proj, ref))
updateStatus(ref, proj, "pending", (timeStart, None))
successful = True
successfulGit, lastLogGit = updateGit(proj, ref)
lastLog += lastLogGit
successful = successfulGit
if successful:
successfulCfg = True
cfg = getConfig(proj)
lang = cfg.get("language", None)
main = cfg.get("main", None)
if not lang or not main:
successfulCfg = False
successful = successfulCfg
if successful:
successfulCompile, lastLogCompile = compileLang[lang](proj, getBuildPath(proj, ref), main)
lastLog += lastLogCompile
successful = successfulCompile
else:
lastLog += "not compiling" + "\n"
log(">>> Finished "+ref)
lastLog += ">>> Finished: "+time.strftime("%X")+" "+ref + "\n"
with open(getBuildPath(proj, ref)+"/.log", 'w') as lastLogFile:
lastLogFile.write(lastLog)
updateStatus(ref, proj, "success" if successful else "error", (timeStart, time.time() - timeStart),
"Git stage failed" if not successfulGit else
"Config error" if not successfulCfg else
"Compile stage failed" if not successfulCompile else None)
symlink_force(ref, getBuildPath(proj, None))
def startCompile(proj, ref):
global compileThread
# pylint: disable=no-member
if compileThread and compileThread.isAlive():
return (503, "Currently compiling")
else:
compileThread = Thread(target=doCompile, args=(proj, ref))
compileThread.start()
return (200, "Compiling Started")
class Handler(BaseHTTPRequestHandler):
def _send(self, status, data = "", headers = None):
if not data and status == 404:
data = "Not Found"
headers = headers or []
self.send_response(status)
for x in headers:
name, value = x
self.send_header(name, value)
self.end_headers()
self.wfile.write(data)
def _sendFile(self, path, headers, binary = False):
try:
f = open(path, "rb" if binary else "r")
try:
self._send(200, f.read(), headers)
finally:
f.close()
except IOError:
self._send(404)
def do_GET(self):
path = urlparse(self.path).path
message = ""
status = 404
match = re.search(r"^\/([a-zA-z+-]+)(?:\/?$|\/(?:([0-9a-f]*)\/)?(.*)?)", path)
# matches: 1=Project | 2=hash or empty | 3=file or empty
if match is not None:
project, ref, fileName = match.group(1,2,3)
if os.path.isdir(project):
cfg = getConfig(project)
main = cfg.get('main') if cfg else None
# list of all commits
if not ref and not fileName:
dirs = [entry for entry in os.listdir(project+OUTPUT_SUFFIX) if entry != "last" and os.path.isdir(project+OUTPUT_SUFFIX+"/"+entry) ]
data = []
for ref in dirs:
data.append({
"commit": gh.getCommitDetails(project, ref),
"build": getStatus(ref, project)
})
self._send(200, json.dumps({
"list" : data,
"language" : cfg.get("language", None)
}), [("Content-type", "application/json")])
return
# status of ref
elif ref and fileName == "status":
self._send(200, json.dumps(getStatus(ref, project)), [("Content-type", "application/json")])
return
# elif ref and not fileName and main:
# self._send(200, json.dumps(["log", "svg", "pdf"]), [("Content-type", "application/json")])
# return
elif ref and fileName == "build":
status, message = startCompile(project, ref)
else:
if main:
if fileName == "pdf":
self._sendFile(getBuildPath(project, ref)+"/"+main+".pdf", [("Content-type", "application/pdf")], True)
return
elif fileName == "log":
self._sendFile(getBuildPath(project, ref)+"/.log", [("Content-type", "text/plain")])
return
elif fileName == "svg":
self._sendFile(getBuildPath(project, ref)+"/.status.svg",
[("Content-type", "image/svg+xml"),
("etag", ref),
("cache-control", "no-cache")])
return
self._send(status, message)
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
project = self.path[1:]
(signature_func, signature) = self.headers['X-Hub-Signature'].split("=")
output = "Error"
status = 200
if SECRET and SECRET != "<<Github Webhook secret>>":
if signature_func == "sha1":
mac = hmac.new(str(SECRET), msg=post_data, digestmod=hashlib.sha1)
if not hmac.compare_digest(str(mac.hexdigest()), str(signature)):
self._send(403, output)
return
if self.headers["X-GitHub-Event"] == "push" and self.headers["content-type"] == "application/json":
data = json.loads(post_data)
print data['head_commit']['id']+": "+data['head_commit']['message']
status, output = startCompile(project, data['head_commit']['id'])
self._send(status, output)
def log_message(self, format, *args):
log("%s - - [%s] %s" % (self.client_address[0], self.log_date_time_string(), format%args))
if __name__ == '__main__':
try:
server = HTTPServer(('localhost', 8000), Handler)
print "Started server"
server.serve_forever()
except KeyboardInterrupt:
print '\n^C received, shutting down the server'
server.socket.close()