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
|
#!/usr/bin/env python
#
# This syslog server receives UDP based syslog entries and
# serves them in the format munin can understand
#
# Read an EDI dump file and transmit over UDP
#
# The MIT License (MIT)
#
# Copyright (c) 2017 Matthias P. Braendli
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
HOST, syslogport, muninport = "127.0.0.1", 51400, 51401
import SocketServer
import Queue
import re
import threading
LOG_FACILITY = {
0: 'kernel messages',
1: 'user-level messages',
2: 'mail system',
3: 'system daemons',
4: 'security/authorization messages',
5: 'messages generated internally by syslogd',
6: 'line printer subsystem',
7: 'network news subsystem',
8: 'UUCP subsystem',
9: 'clock daemon',
10: 'security/authorization messages',
11: 'FTP daemon',
12: 'NTP subsystem',
13: 'log audit',
14: 'log alert',
15: 'clock daemon',
16: 'local use 0 (local0)',
17: 'local use 1 (local1)',
18: 'local use 2 (local2)',
19: 'local use 3 (local3)',
20: 'local use 4 (local4)',
21: 'local use 5 (local5)',
22: 'local use 6 (local6)',
23: 'local use 7 (local7)'
}
LOG_LEVEL = {
0: 'Emergency',
1: 'Alert',
2: 'Critical',
3: 'Error',
4: 'Warning',
5: 'Notice',
6: 'Informational',
7: 'Debug'
}
def split_priority_from_message(msg):
'''
https://www.fir3net.com/UNIX/Linux/how-to-determine-the-syslog-facility-
using-tcpdump.html
Each Syslog message contains a priority value. The priority value is
enclosed within the characters < >. The priority value can be
between 0 and 191 and consists of a Facility value and a Level value.
Facility being the type of message, such as a kernel or mail message.
And level being a severity level of the message.
To calculate the priority value the following formula is used :
Priority = Facility * 8 + Level
So to determine the facility value of a syslog message we divide the
priority value by 8. The remainder is the level value.
'''
match = re.search(r"\b(?=\w)(\d*)\b(?!\w)>(.*)", msg, re.MULTILINE)
if match:
result = match.group(1)
return int(result), str(match.group(2))
else:
raise
def get_facility_from_priority(priority):
return int(priority/8)
def get_level_from_priority(priority):
return priority % 8
class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
pass
class SyslogUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = bytes.decode(self.request[0].strip())
socket = self.request[1]
syslog_message = str(data)
priority, text = split_priority_from_message(syslog_message)
facility = get_facility_from_priority(priority)
lvl = get_level_from_priority(priority)
logentry = dict()
logentry['raw'] = syslog_message
logentry['level'] = LOG_LEVEL[lvl]
logentry['facility'] = LOG_FACILITY[facility]
logentry['text'] = text
print("Push {}".format(logentry['text']))
logentries.put(logentry)
munin_config = """
multigraph mmbtools_log
graph_title mmbTools errors and warnings
graph_order high low
graph_args --base 1000
graph_vlabel number of entries in log during last ${{graph_period}}
graph_category mmbtools
graph_info This graph shows number of error and warning messages generated by the mmbTools
errors.info Errors
errors.label Errors
errors.min 0
errors.type ABSOLUTE
warnings.info Warnings
warnings.label Warnings
warnings.min 0
warnings.type ABSOLUTE
"""
class MuninHandler(SocketServer.BaseRequestHandler):
def handle(self):
global error_count, warning_count
self.data = self.request.recv(128).strip()
print self.data
if self.data == 'config':
self.request.sendall(munin_config)
elif self.data == 'values':
self.update_log_counts()
values = ["multigraph mmbtools_log"]
values += ["errors.value {}".format(error_count)]
values += ["warnings.value {}".format(warning_count)]
error_count = 0
warning_count = 0
self.request.sendall("\n".join(values) + "\n")
def update_log_counts(self):
global error_count, warning_count
try:
while True:
entry = logentries.get_nowait()
print("Pop {}".format(entry['text']))
if entry['level'] in ['Emergency', 'Alert', 'Critical', 'Error']:
error_count += 1
elif entry['level'] == 'Warning':
warning_count += 1
except Queue.Empty:
print("No data in queue")
if __name__ == "__main__":
try:
print("Startup")
logentries = Queue.Queue(10000)
error_count = 0
warning_count = 0
muninserver = None
logudp = None
print("Init Syslog handler")
logudp = ThreadedUDPServer((HOST, syslogport), SyslogUDPHandler)
print("Create Syslog thread")
syslogthread = threading.Thread(target=logudp.serve_forever, kwargs={'poll_interval': 0.1})
print("Init Munin handler")
muninserver = SocketServer.TCPServer((HOST, muninport), MuninHandler)
print("Starting handlers")
syslogthread.start()
muninserver.serve_forever()
except KeyboardInterrupt:
print("Ctrl-C received")
finally:
if muninserver is not None:
muninserver.shutdown()
if logudp is not None:
logudp.shutdown()
print("Waiting for thread to finish")
syslogthread.join()
print("Quitting")
|