forked from alerta/alerta-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
syslogfwder.py
275 lines (227 loc) · 8.44 KB
/
syslogfwder.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import os
import sys
import platform
import socket
import select
import re
import logging
from alertaclient.api import Client
__version__ = '3.5.0'
SYSLOG_TCP_PORT = int(os.environ.get('SYSLOG_TCP_PORT', 514))
SYSLOG_UDP_PORT = int(os.environ.get('SYSLOG_UDP_PORT', 514))
SYSLOG_FACILITY_NAMES = [
"kern",
"user",
"mail",
"daemon",
"auth",
"syslog",
"lpr",
"news",
"uucp",
"cron",
"authpriv",
"ftp",
"ntp",
"audit",
"alert",
"clock",
"local0",
"local1",
"local2",
"local3",
"local4",
"local5",
"local6",
"local7"
]
SYSLOG_SEVERITY_NAMES = [
"emerg",
"alert",
"crit",
"err",
"warning",
"notice",
"info",
"debug"
]
SYSLOG_SEVERITY_MAP = {
"emerg": "critical",
"alert": "critical",
"crit": "major",
"err": "minor",
"warning": "warning",
"notice": "normal",
"info": "informational",
"debug": "debug",
}
if sys.version_info[0] >= 3:
unicode = str
def priority_to_code(name):
return SYSLOG_SEVERITY_MAP.get(name, "unknown")
def decode_priority(priority):
facility = priority >> 3
level = priority & 7
return SYSLOG_FACILITY_NAMES[facility], SYSLOG_SEVERITY_NAMES[level]
LOOP_EVERY = 20 # seconds
LOG = logging.getLogger("alerta.syslog")
logging.basicConfig(format="%(asctime)s - %(name)s: %(levelname)s - %(message)s", level=logging.DEBUG)
class SyslogDaemon(object):
def __init__(self):
self.api = Client()
LOG.info('Starting UDP listener...')
# Set up syslog UDP listener
try:
self.udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udp.bind(('', SYSLOG_UDP_PORT))
except socket.error as e:
LOG.error('Syslog UDP error: %s', e)
sys.exit(2)
LOG.info('Listening on syslog port %s/udp' % SYSLOG_UDP_PORT)
LOG.info('Starting TCP listener...')
# Set up syslog TCP listener
try:
self.tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.tcp.bind(('', SYSLOG_TCP_PORT))
self.tcp.listen(5)
except socket.error as e:
LOG.error('Syslog TCP error: %s', e)
sys.exit(2)
LOG.info('Listening on syslog port %s/tcp' % SYSLOG_TCP_PORT)
self.shuttingdown = False
def run(self):
count = 0
while not self.shuttingdown:
try:
LOG.debug('Waiting for syslog messages...')
ip, op, rdy = select.select([self.udp, self.tcp], [], [], LOOP_EVERY)
if ip:
for i in ip:
if i == self.udp:
data, addr = self.udp.recvfrom(4096)
data = unicode(data, 'utf-8', errors='ignore')
LOG.debug('Syslog UDP data received from %s: %s', addr, data)
if i == self.tcp:
client, addr = self.tcp.accept()
data = client.recv(4096)
data = unicode(data, 'utf-8', errors='ignore')
client.close()
LOG.debug('Syslog TCP data received from %s: %s', addr, data)
alerts = self.parse_syslog(ip=addr[0], data=data)
for alert in alerts:
try:
self.api.send_alert(**alert)
except Exception as e:
LOG.warning('Failed to send alert: %s', e)
count += 1
if not ip or count % 5 == 0:
LOG.debug('Send heartbeat...')
try:
origin = '{}/{}'.format('syslog', platform.uname()[1])
self.api.heartbeat(origin, tags=[__version__])
except Exception as e:
LOG.warning('Failed to send heartbeat: %s', e)
except (KeyboardInterrupt, SystemExit):
self.shuttingdown = True
LOG.info('Shutdown request received...')
def parse_syslog(self, ip, data):
LOG.debug('Parsing syslog message...')
syslogAlerts = list()
event = None
resource = None
for msg in data.split('\n'):
if not msg or 'last message repeated' in msg:
continue
if re.match('<\d+>1', msg):
# Parse RFC 5424 compliant message
m = re.match(r'<(\d+)>1 (\S+) (\S+) (\S+) (\S+) (\S+) (.*)', msg)
if m:
PRI = int(m.group(1))
ISOTIMESTAMP = m.group(2)
HOSTNAME = m.group(3)
APPNAME = m.group(4)
PROCID = m.group(5)
MSGID = m.group(6)
TAG = '%s[%s] %s' % (APPNAME, PROCID, MSGID)
MSG = m.group(7)
LOG.info("Parsed RFC 5424 message OK")
else:
LOG.error("Could not parse RFC 5424 syslog message: %s", msg)
continue
elif re.match(r'<(\d{1,3})>\S{3}\s', msg):
# Parse RFC 3164 compliant message
m = re.match(r'<(\d{1,3})>\S{3}\s{1,2}\d?\d \d{2}:\d{2}:\d{2} (\S+)( (\S+):)? (.*)', msg)
if m:
PRI = int(m.group(1))
HOSTNAME = m.group(2)
TAG = m.group(4)
MSG = m.group(5)
LOG.info("Parsed RFC 3164 message OK")
else:
LOG.error("Could not parse RFC 3164 syslog message: %s", msg)
continue
elif re.match('<\d+>.*%[A-Z0-9_-]+', msg):
# Parse Cisco Syslog message
m = re.match('<(\d+)>.*(%([A-Z0-9_-]+)):? (.*)', msg)
if m:
LOG.debug(m.groups())
PRI = int(m.group(1))
CISCO_SYSLOG = m.group(2)
try:
CISCO_FACILITY, CISCO_SEVERITY, CISCO_MNEMONIC = m.group(3).split('-')
except ValueError as e:
LOG.error('Could not parse Cisco syslog - %s: %s', e, m.group(3))
CISCO_FACILITY = CISCO_SEVERITY = CISCO_MNEMONIC = 'na'
TAG = CISCO_MNEMONIC
MSG = m.group(4)
event = CISCO_SYSLOG
# replace IP address with a hostname, if necessary
try:
socket.inet_aton(ip)
(resource, _, _) = socket.gethostbyaddr(ip)
except (socket.error, socket.herror):
resource = ip
resource = '%s:%s' % (resource, CISCO_FACILITY)
else:
LOG.error("Could not parse Cisco syslog message: %s", msg)
continue
facility, level = decode_priority(PRI)
# Defaults
event = event or '%s%s' % (facility.capitalize(), level.capitalize())
resource = resource or '%s%s' % (HOSTNAME, ':' + TAG if TAG else '')
severity = priority_to_code(level)
group = 'Syslog'
value = level
text = MSG
environment = 'Production'
service = ['Platform']
tags = ['%s.%s' % (facility, level)]
correlate = ['%s%s' % (facility.capitalize(), s.capitalize()) for s in SYSLOG_SEVERITY_NAMES]
raw_data = msg
syslogAlert = {
'resource': resource,
'event': event,
'environment': environment,
'severity': severity,
'correlate':correlate,
'service': service,
'group': group,
'value': value,
'text': text,
'tags': tags,
'event_type': 'syslogAlert',
'raw_data': raw_data
}
syslogAlerts.append(syslogAlert)
return syslogAlerts
def main():
LOG = logging.getLogger("alerta.syslog")
try:
SyslogDaemon().run()
except (SystemExit, KeyboardInterrupt):
LOG.info("Exiting alerta syslog.")
sys.exit(0)
except Exception as e:
LOG.error(e, exc_info=1)
sys.exit(1)