Skip to content

Instantly share code, notes, and snippets.

@takumakei
Last active August 29, 2015 14:22
Show Gist options
  • Save takumakei/311c2ef487d1065c52e9 to your computer and use it in GitHub Desktop.
Save takumakei/311c2ef487d1065c52e9 to your computer and use it in GitHub Desktop.
Fluentd → HipChat
#!/usr/bin/env python
# coding: utf-8
#
# Copyright (c) 2015 TAKUMA Kei
#
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
#
#
# HOW TO USE THIS SCRIPT:
#
# (1) prepare your config file '/etc/td-agent/td-agent-hipchat.json'
#
# ```
# { "token": "**YOUR HIPCHAT API TOKEN**", "room id": "**ROOM ID**" }
# ```
#
# (2) td-agent.conf
#
# ```
# <match hipchat.**>
# type exec
# command /etc/td-agent/td-agent-hipchat.py
# format json
# buffer_path /var/log/td-agent/buffer/hipchat
# flush_interval 5s
# </match>
# ```
#
import os
import sys
import json
import urllib2
CONFIG_FILE_PATH = '/etc/td-agent/td-agent-hipchat.json'
KEY_TOKEN = 'token' # REQUIRED
KEY_ROOM_ID = 'room id' # REQUIRED
KEY_API_HOST = 'api host'
KEY_COLOR = 'color'
KEY_MESSAGE = 'message' # REQUIRED
KEY_NOTIFY = 'notify'
KEY_FORMAT = 'message_format'
DEFAULT = {
KEY_API_HOST: 'api.hipchat.com',
KEY_COLOR : 'random',
KEY_NOTIFY : False,
KEY_FORMAT : 'html'
}
def filter(obj):
# return falsy value if `obj` should not be sent to the hipchat.
return obj
def main():
load_config(CONFIG_FILE_PATH)
for i in sys.argv[1:]:
with open(i) as f:
process_file(f)
def load_config(path):
if not os.path.isfile(path):
sys.exit("Error: file not found. " + path)
try:
with open(path) as f:
global DEFAULT
DEFAULT.update(json.loads(f.read()))
except:
sys.exit("Error: can't load " + path)
def process_file(f):
for line in f:
try:
dic = json.loads(line)
except:
continue
dic = {k: v for a in [DEFAULT, dic] for k, v in a.items()}
dic = filter(dic)
hipchat(dic)
def hipchat(dic):
if not dic or not dic.has_key(KEY_MESSAGE):
return
host = dic[KEY_API_HOST]
room = dic[KEY_ROOM_ID]
token = dic[KEY_TOKEN]
dic = {k: dic[k] for k in [KEY_COLOR, KEY_MESSAGE, KEY_NOTIFY, KEY_FORMAT]}
url = 'https://%s/v2/room/%s/notification?auth_token=%s' % (host, room, token)
req = urllib2.Request(url)
req.add_header('Content-Type', 'application/json')
return urllib2.urlopen(req, json.dumps(dic))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment