This repository has been archived by the owner on May 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrocketgobot.py
118 lines (97 loc) · 3.78 KB
/
rocketgobot.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
import sys
import json
import time
import logging
import argparse
import websocket
import requests
import signal
class GoBotRocket(object):
def __init__(self, webhookurl, godomain, stages):
self.failedpipes = []
self.webhookurl = webhookurl
self.godomain = godomain
self.stages = stages
self.stop = False
signal.signal(signal.SIGINT, self.terminate)
signal.signal(signal.SIGTERM, self.terminate)
websocket.enableTrace(True)
self.ws = websocket.WebSocketApp(
"ws://{domain}:8887/".format(domain=self.godomain),
on_message=self.gocd_message, on_error=self.gocd_error,
on_close=self.gocd_close)
# if we later wanna do more stuff, start a thread in somefunc?
# self.ws.on_open = somefunc
def __del__(self):
self.ws.close()
def terminate(self, signum, frame):
self.stop = True
if self.ws:
try:
self.ws.close()
except:
pass
def run(self):
sleepsecs = 60
while not self.stop:
try:
logging.info('start websocket listener')
self.ws.run_forever()
except:
logging.error("Unexpected error: {}".format(sys.exc_info()[0]))
logging.error(
"Trying websocket reconnect in {} seconds".format(sleepsecs))
time.sleep(sleepsecs)
def gocd_message(self, ws, message):
msg = json.loads(message)
pipename = msg['pipeline']['name']
stage = msg['pipeline']['stage']
if stage['name'] in self.stages:
golink = 'https://{domain}/go/tab/pipeline/history/{pipe}'.format(
domain=self.godomain, pipe=pipename)
baserocketmsg = "[{pipe}]({link}) ({stage})".format(
pipe=pipename, link=golink, stage=stage['name'])
if stage['state'] == 'Passed' and pipename in self.failedpipes:
self.failedpipes.remove(pipename)
self.rocket_message(
"{} *fixed* :grinning:".format(baserocketmsg))
elif stage['state'] == 'Failed' and pipename not in self.failedpipes:
self.failedpipes.append(pipename)
self.rocket_message(
"{} *broken* :scream:".format(baserocketmsg))
def gocd_error(self, ws, error):
logging.error("GOCD ERROR!!!")
logging.error(error)
# we want to rest a little on errors
time.sleep(60)
def gocd_close(self, ws):
logging.info("### gocd ws closed ###")
def rocket_message(self, message):
msgdata = {
"username": "gobot",
"text": message
}
requests.post(self.webhookurl, data=json.dumps(msgdata))
if __name__ == '__main__':
# Setup the command line arguments.
argp = argparse.ArgumentParser(description="GoCD bot for RocketChat")
argp.add_argument('-q', '--quiet', help='set logging to ERROR',
action='store_const', dest='loglevel',
const=logging.ERROR, default=logging.INFO)
argp.add_argument("-w", "--webhook", dest="webhookurl",
help="The RocketChat webhook URL, including token")
argp.add_argument("-g", "--godomain", dest="godomain",
help="GoCD domain to connect to")
argp.add_argument("-s", "--stages", dest="stages",
help="Comma-separated list of stage names to report on")
args = argp.parse_args()
# Setup logging.
logging.basicConfig(
level=args.loglevel,
format='%(levelname)-8s %(message)s')
rocketbot = GoBotRocket(
args.webhookurl,
args.godomain,
args.stages.split(',')
)
rocketbot.run()