|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +import multitail2 |
| 4 | +import hpfeeds |
| 5 | + |
| 6 | +import sys |
| 7 | +import datetime |
| 8 | +import json |
| 9 | +import hpfeeds |
| 10 | +import logging |
| 11 | + |
| 12 | +root = logging.getLogger() |
| 13 | +root.setLevel(logging.ERROR) |
| 14 | + |
| 15 | +ch = logging.StreamHandler(sys.stdout) |
| 16 | +ch.setLevel(logging.INFO) |
| 17 | +formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') |
| 18 | +ch.setFormatter(formatter) |
| 19 | +root.addHandler(ch) |
| 20 | +logger = logging.getLogger("hpfeeds-collector") |
| 21 | + |
| 22 | +def parse(line): |
| 23 | + # TODO: extend this |
| 24 | + return {} |
| 25 | + |
| 26 | +def hpfeeds_connect(host, port, ident, secret): |
| 27 | + try: |
| 28 | + connection = hpfeeds.new(host, port, ident, secret) |
| 29 | + except hpfeeds.FeedException, e: |
| 30 | + logger.error('feed exception: %s'%e) |
| 31 | + sys.exit(1) |
| 32 | + logger.info('connected to %s (%s:%s)'%(connection.brokername, host, port)) |
| 33 | + return connection |
| 34 | + |
| 35 | +def main(): |
| 36 | + cfg = { |
| 37 | + 'host' : '', |
| 38 | + 'port' : 10000, |
| 39 | + 'channel' : '', |
| 40 | + 'ident ' : '', |
| 41 | + 'secret' : '', |
| 42 | + 'tail_file' : '' |
| 43 | + } |
| 44 | + |
| 45 | + if len(sys.argv) > 1: |
| 46 | + logger.info("Parsing config file: %s"%sys.argv[1]) |
| 47 | + cfg.update(json.load(file(sys.argv[1]))) |
| 48 | + |
| 49 | + for name,value in cfg.items(): |
| 50 | + if isinstance(value, basestring): |
| 51 | + # hpfeeds protocol has trouble with unicode, hence the utf-8 encoding here |
| 52 | + cfg[name] = value.encode("utf-8") |
| 53 | + else: |
| 54 | + logger.warning("Warning: no config found, using default values for hpfeeds server") |
| 55 | + publisher = hpfeeds_connect(cfg['host'], cfg['port'], cfg['ident'], cfg['secret']) |
| 56 | + |
| 57 | + tail = multitail2.MultiTail(cfg['tail_file']) |
| 58 | + for filemeta, line in tail: |
| 59 | + logger.debug(filemeta, line) |
| 60 | + record = parse(line) |
| 61 | + if record: |
| 62 | + publisher.publish(cfg['channel'], json.dumps(record)) |
| 63 | + publisher.stop() |
| 64 | + return 0 |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + try: |
| 68 | + sys.exit(main()) |
| 69 | + except KeyboardInterrupt: |
| 70 | + sys.exit(0) |
| 71 | + |
0 commit comments