summaryrefslogtreecommitdiffstats
path: root/format-notify
blob: 59a974024d472291e5c9dc509486937619f657f2 (plain)
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
#!/usr/bin/env python

import os, sys, re, syslog, socket

def add_color(status):
    if status == 'WARNING':
        return ("\x034%s\x0f" % status)
    elif status == 'CRITICAL' or status == 'UNKNOWN' or status == 'DOWN':
        return ("\x034\x02%s\x0f" % status)
    elif status == 'OK' or status == 'UP':
        return ("\x033\x02%s\x0f" % status)
    else:
        return status

def clean_output(status, output):
    output = output.strip()
    if output.startswith(status):
        output = output[len(status):]
    return re.sub(r'^[- :]*', '', output)

def main():
    if len(sys.argv) < 5:
        print('Usage: %s (SOCKET|--test) SERVICE STATUS OUTPUT' % sys.argv[0])
        sys.exit(1)

    file = sys.argv.pop(1)
    service = sys.argv.pop(1)
    status = sys.argv.pop(1)
    output = sys.argv.pop(1)
    msg = "%s %s: %s\n" % (service,
                           add_color(status),
                           clean_output(status, output))

    if file == '--test':
        sys.stdout.write(msg)
        sys.exit(0)

    if not os.path.exists(file):
        sys.exit(1)

    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        s.connect(file)
        s.sendall(msg)
        s.close()
    except socket.error:
        syslog.syslog("Dropping message: '%s'" % msg)
        sys.exit(1)

if __name__ == '__main__':
    main()