-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathnsqadmin2hipchat.py
executable file
·86 lines (75 loc) · 2.85 KB
/
nsqadmin2hipchat.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
#!/usr/bin/env python
import urllib
import json
import logging
import nsq
import argparse
import functools
def post_to_hipchat(txt, args, user):
params = {
'auth_token' : args.hipchat_auth_token,
'from' : user or 'NSQ Admin',
'color' : 'gray',
'room_id' : args.hipchat_room_id,
'message_format' : 'text',
'message' : txt
}
url = "https://api.hipchat.com/v1/rooms/message"
return urllib.urlopen(url + '?' + urllib.urlencode(params))
action_text_map = {
'create_topic' : 'Created topic',
'create_channel' : 'Created channel',
'delete_topic' : 'Deleted topic',
'delete_channel' : 'Deleted channel',
'empty_channel' : 'Emptied channel',
'empty_topic' : 'Emptied topic',
'pause_channel' : 'Paused channel',
'unpause_channel' : 'Unpaused channel',
'pause_topic' : 'Paused topic',
'unpause_topic' : 'Unpaused topic',
'tombstone_topic_producer': 'Tombstoned Topic Producer',
}
def text_from_nsq_body(body):
try:
event = json.loads(body)
topic_txt = event.get('topic', '')
channel_txt = event.get('channel', '')
if channel_txt:
return action_text_map.get(event['action'], event['action']) + " " + channel_txt +\
" in topic " + topic_txt, event.get('user', 'unknown user')
else:
return action_text_map.get(event['action'], event['action']) + " " + topic_txt,\
event.get('user', 'unknown user')
except ValueError:
logging.exception("Invalid json from nsq")
def process_message(message, args):
msg_txt, user = text_from_nsq_body(message.body)
if args.verbose:
logging.warn(msg_txt)
response = post_to_hipchat(msg_txt, args, user)
if args.verbose:
logging.warn(response.read())
return True
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--hipchat-auth-token', required=True)
parser.add_argument('--hipchat-room-id', required=True)
parser.add_argument('--nsq-topic', required=True)
parser.add_argument('--nsq-channel', default='nsqadmin2hipchat')
parser.add_argument('-v', '--verbose', action='store_true')
sources = parser.add_mutually_exclusive_group(required=True)
sources.add_argument('--nsqd-tcp-address', action='append')
sources.add_argument('--lookupd-http-address', action='append')
args = parser.parse_args()
kwargs = {
'topic': args.nsq_topic,
'channel': args.nsq_channel,
'message_handler' : functools.partial(process_message, args=args)
}
if args.lookupd_http_address:
addresses = [a if a.startswith("http") else "http://%s" % a for a in args.lookupd_http_address]
kwargs['lookupd_http_addresses'] = addresses
else:
kwargs['nsqd_tcp_addresses'] = args.nsqd_tcp_address
r = nsq.Reader(**kwargs)
nsq.run()