This repository has been archived by the owner on Mar 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildbot.py
executable file
·163 lines (132 loc) · 3.96 KB
/
buildbot.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
#!/usr/bin/env python3
import argparse
import logging
import configparser, datetime, os, sys, urllib.request, json, platform, subprocess
###
L = logging.getLogger(__name__)
###
BIN_DIR = os.path.dirname(os.path.realpath(__file__))
CONFIG = configparser.ConfigParser()
CONFIG.read_dict({
'general': {
'config_file': os.path.join(BIN_DIR,'buildbot.conf'),
'log_dir': '/home/ateska/Workspace/seacat/buildbot/logs/',
},
'buildbot' : {
'exec': '/home/ateska/Workspace/seacat/buildbot/build.sh',
'working_directory': '/home/ateska/Workspace/seacat/server',
},
'buildbot:slack' : {
"url" : '',
"channel" : '',
}
})
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="Buildbot\n2018 TeskaLabs Ltd\nhttps://www.teskalabs.com/\n\n",
)
parser.add_argument('-c', '--config', help='Specify file path to configuration file')
args = parser.parse_args()
if args.config is not None:
CONFIG['general']['config_file'] = args.config
CONFIG.read(CONFIG['general']['config_file'])
###
def send_slack_message(status, text, attachments):
url = CONFIG.get("buildbot:slack", "url")
if url is None or url == '':
L.info("No Slack URL is given")
return;
dt = datetime.datetime.utcnow()
status_color_map = {
"OK": "good",
"WARN": "warning",
"FAILED": "danger"
}
status_color = status_color_map.get(status, "danger")
data = {
"channel": CONFIG.get("buildbot:slack", "channel", fallback="#apitest"),
"username": "BuildBot",
"icon_emoji": ":robot_face:",
"attachments":[
{
"color": status_color,
"fallback": "{} @ {}".format(status, platform.node().partition('.')[0]),
"title": "{} @ {}".format(status, platform.node().partition('.')[0]),
"text": text,
"mrkdwn_in": ["fields"],
"fields": [
],
"footer": "BuildBot",
"ts": int(dt.replace(tzinfo=datetime.timezone.utc).timestamp())
}
],
}
f = data["attachments"][0]["fields"]
# a = alerts.pop('*')
# if a is not None:
# f.append({"value": '\n'.join(a), "short": False})
#
for k, v in attachments.items():
f.append({"title": k, "value": '\n'.join(v), "short": False})
req = urllib.request.Request(url=url, data=json.dumps(data).encode('utf-8'), method='POST')
with urllib.request.urlopen(req) as f:
pass
if f.status != 200:
L.error("Failed to submit message to Slack: {} {}".format(f.status, f.reason))
###
def contains_warns(line):
line = line.lower()
if 'error' in line: return True
if 'warn' in line: return True
if 'fatal' in line: return True
return False
###
def main():
p = None
try:
p = subprocess.Popen([CONFIG.get("buildbot", "exec")], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=CONFIG['buildbot']['working_directory'])
out, err = p.communicate()
except Exception as e:
out = None
err = str(e).encode('utf-8')
slack_text = []
slack_attachments = {}
if p is not None:
if p.returncode == 0:
status = "OK"
#slack_text.append("Build OK")
else:
status = "FAILED"
slack_text.append("Return code: {}".format(p.returncode))
else:
status = "FAILED"
if out is not None:
out = out.decode('utf-8')
out_arr = []
for line in out.split('\n'):
if contains_warns(line):
out_arr.append(line)
if line.startswith("GIT_VERSION: "):
slack_text.append("SeaCat Server {}".format(line[13:].strip()))
elif line.startswith("SLACK: "):
slack_text.append(line[7:].strip())
if len(out_arr) > 0:
slack_attachments["STDOUT"] = out_arr
if status != "FAILED":
status = "WARN"
if err is not None:
err = err.decode('utf-8')
err_arr = err.split('\n')
slack_attachments["STDERR"] = err_arr
if status != "FAILED":
status = "WARN"
send_slack_message(status, '\n'.join(slack_text), slack_attachments)
try:
if not os.path.exists(CONFIG['general']['log_dir']):
os.makedirs(CONFIG['general']['log_dir'])
open(os.path.join(CONFIG['general']['log_dir'], "out.txt"), "w").write(out)
except Exception as e:
L.error(e)
if __name__ == '__main__':
os.chdir(BIN_DIR)
sys.exit(main())