growlee: add syslog backend
[vuplus_dvbapp-plugin] / growlee / src / Syslog.py
1 from twisted.internet.protocol import DatagramProtocol
2 from twisted.internet import reactor
3 from twisted.internet import reactor
4 from time import strftime, strptime, localtime
5 from os import uname
6
7 from Screens.MessageBox import MessageBox
8 from Tools import Notifications
9
10 from GrowleeConnection import emergencyDisable
11 from . import NOTIFICATIONID
12
13 SYSLOG_UDP_PORT = 514
14
15 FACILITY = {
16         'kern': 0, 'user': 1, 'mail': 2, 'daemon': 3,
17         'auth': 4, 'syslog': 5, 'lpr': 6, 'news': 7,
18         'uucp': 8, 'cron': 9, 'authpriv': 10, 'ftp': 11,
19         'local0': 16, 'local1': 17, 'local2': 18, 'local3': 19,
20         'local4': 20, 'local5': 21, 'local6': 22, 'local7': 23,
21 }
22
23 SEVERITY = {
24         'emerg': 0, 'alert':1, 'crit': 2, 'err': 3,
25         'warning': 4, 'notice': 5, 'info': 6, 'debug': 7
26 }
27
28 reverse = lambda map: dict(zip(map.values(), map.keys()))
29
30 SEVERITYMAP = {
31         MessageBox.TYPE_YESNO: SEVERITY['debug'],
32         MessageBox.TYPE_INFO: SEVERITY['info'],
33         MessageBox.TYPE_WARNING: SEVERITY['warning'],
34         MessageBox.TYPE_ERROR: SEVERITY['err'],
35 }
36
37 class SyslogNetworkProtocol(DatagramProtocol):
38         addr = None
39         def __init__(self, host):
40                 self.host = host
41
42         def gotIP(self, ip):
43                 self.addr = (ip, SYSLOG_UDP_PORT)
44
45         def noIP(self, error):
46                 print "--------------------------------", error
47                 emergencyDisable()
48
49         def startProtocol(self):
50                 reactor.resolve(self.host.address.value).addCallback(self.gotIP).addErrback(self.noIP)
51
52         def sendNotification(self, title='No title.', description='No message.', priority=0):
53                 if not self.transport or not self.addr or not self.host.enable_outgoing.value:
54                         return
55
56                 ltime = localtime()
57                 day = strftime("%d", ltime)
58                 if day[0] == "0":
59                         day = " " + day[1:]
60                 value = strftime("%b %%s %H:%M:%S", ltime)
61                 timestamp = value % (day,)
62                 payload = "<%d>%s %s growlee: (%s) %s" % (FACILITY['local0'] * 8 + SEVERITYMAP[priority], timestamp, uname()[1], title, description.replace('\n', ' '),)
63                 self.transport.write(payload, self.addr)
64
65         def datagramReceived(self, data, addr):
66                 if not self.host.enable_incoming.value:
67                         return
68
69                 Len = len(data)
70                 if Len > 1024: # invalid according to rfc
71                         return
72
73                 # read prio field
74                 prio, data = data.split('>', 1)
75                 prio = int(prio[1:])
76                 facility, severity = divmod(prio, 8) # just the ids
77                 #facility = reverse(FACILITY)[facility]
78                 type = reverse(SEVERITYMAP).get(severity, MessageBox.TYPE_ERROR)
79
80                 # parse remaining header
81                 try:
82                         # try to parse timestamp to determine validity
83                         timestamp = strptime(payload[:15], '%b %d %H:%M:%S')
84                 except ValueError:
85                         message = payload
86                 else:
87                         hostname, payload = payload[16:].split(' ', 1)
88                         # NOTE: we could re-process timestamp to get a customized display format,
89                         # but lets just keep this for now
90                         message = hostname + '@' + payload[:15] + ':' + payload
91
92                 Notifications.AddNotificationWithID(
93                         NOTIFICATIONID,
94                         MessageBox,
95                         text = message,
96                         type = type,
97                         timeout = 10, # XXX: un-hardcode timeout?
98                         close_on_any_key = True,
99                 )
100
101 class SyslogAbstraction:
102         def __init__(self, host):
103                 self.syslog = SyslogNetworkProtocol(host)
104                 self.serverPort = reactor.listenUDP(SYSLOG_UDP_PORT, self.syslog)
105
106         def sendNotification(self, title='No title.', description='No description.', priority=-1, timeout=-1):
107                 self.syslog.sendNotification(title=title, description=description, priority=priority)
108
109         def stop(self):
110                 return self.serverPort.stopListening()