Debian Codegraph @

Nagstamon/servers/Thruk.py

raw symbols SCIP
1 # encoding: utf-8
2
3 # Nagstamon - Nagios status monitor for your desktop
4 # Copyright (C) 2008-2026 Henri Wahl <[email protected]> et al.
5 # Thruk additions copyright by dcec@Github
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
20
21 from collections import OrderedDict
22 from Nagstamon.servers.Generic import GenericServer
23 from Nagstamon.config import conf
24 import sys
25 import json
26 import datetime
27 import copy
28 import urllib.parse
29
30 from Nagstamon.helpers import human_readable_duration_from_timestamp
31 from Nagstamon.helpers import webbrowser_open
32 from Nagstamon.objects import (GenericHost, GenericService, Result)
33
34
35 class ThrukServer(GenericServer):
36 """
37 Thruk is derived from generic (Nagios) server
38 """
39 TYPE = 'Thruk'
40
41 # dictionary to translate status bitmaps on webinterface into status flags
42 # this are defaults from Nagios
43 # "disabled.gif" is in Nagios for hosts the same as "passiveonly.gif" for services
44 STATUS_MAPPING = { "ack.gif" : "acknowledged", \
45 "passiveonly.gif" : "passiveonly", \
46 "disabled.gif" : "passiveonly", \
47 "ndisabled.gif" : "notifications_disabled", \
48 "downtime.gif" : "scheduled_downtime", \
49 "flapping.gif" : "flapping"}
50
51 # Entries for monitor default actions in context menu
52 MENU_ACTIONS = ["Monitor", "Recheck", "Acknowledge", "Submit check result", "Downtime"]
53
54 # Arguments available for submitting check results
55 SUBMIT_CHECK_RESULT_ARGS = ["check_output", "performance_data"]
56
57 # URLs for browser shortlinks/buttons on popup window
58 BROWSER_URLS = { "monitor": "$MONITOR$", \
59 "hosts": "$MONITOR-CGI$/status.cgi?hostgroup=all&style=hostdetail&hoststatustypes=12&page=1&entries=all", \
60 "services": "$MONITOR-CGI$/status.cgi?dfl_s0_value_sel=5&dfl_s0_servicestatustypes=29&dfl_s0_op=%3D&style=detail&dfl_s0_type=host&dfl_s0_serviceprops=0&dfl_s0_servicestatustype=4&dfl_s0_servicestatustype=8&dfl_s0_servicestatustype=16&dfl_s0_servicestatustype=1&hidetop=&dfl_s0_hoststatustypes=15&dfl_s0_val_pre=&hidesearch=2&dfl_s0_value=all&dfl_s0_hostprops=0&nav=&page=1&entries=all", \
61 "history": "$MONITOR-CGI$/history.cgi?host=all&page=1&entries=all"}
62
63 STATES_MAPPING = {"hosts" : {0 : "OK", 1 : "DOWN", 2 : "UNREACHABLE"}, \
64 "services" : {0 : "OK", 1 : "WARNING", 2 : "CRITICAL", 3 : "UNKNOWN"}}
65
66
67 def __init__(self, **kwds):
68 GenericServer.__init__(self, **kwds)
69
70
71 def init_http(self):
72 """
73 partly not constantly working Basic Authorization requires extra Autorization headers,
74 different between various server types
75 """
76 if self.session is None:
77 GenericServer.init_http(self)
78
79 # get cookie from login page via url retrieving as with other urls
80 try:
81 # login and get cookie
82 if self.session is None or self.session.cookies.get('thruk_auth') is None:
83 self.login()
84 except:
85 self.error(sys.exc_info())
86
87
88 def init_config(self):
89 """
90 set URLs for CGI - they are static and there is no need to set them with every cycle
91 """
92 # create filters like described in
93 # http://www.nagios-wiki.de/nagios/tips/host-_und_serviceproperties_fuer_status.cgi?s=servicestatustypes
94 # Thruk allows requesting only needed information to reduce traffic
95 self.cgiurl_services = self.monitor_cgi_url + "/status.cgi?host=all&servicestatustypes=28&view_mode=json&"\
96 "entries=all&columns=host_name,description,state,last_check,"\
97 "last_state_change,plugin_output,current_attempt,"\
98 "max_check_attempts,active_checks_enabled,is_flapping,"\
99 "notifications_enabled,acknowledged,state_type,"\
100 "scheduled_downtime_depth,host_display_name,display_name"
101 # hosts (up or down or unreachable)
102 self.cgiurl_hosts = self.monitor_cgi_url + "/status.cgi?hostgroup=all&style=hostdetail&"\
103 "dfl_s0_hoststatustypes=12&dfl_s1_hostprops=1&dfl_s2_hostprops=4&dfl_s3_hostprops=524288&&dfl_s4_hostprops=4096&dfl_s5_hostprop=16&"\
104 "view_mode=json&entries=all&"\
105 "columns=name,state,last_check,last_state_change,"\
106 "plugin_output,current_attempt,max_check_attempts,"\
107 "active_checks_enabled,notifications_enabled,is_flapping,"\
108 "acknowledged,scheduled_downtime_depth,state_type,host_display_name,display_name"
109
110 def login(self):
111 """
112 use pure session instead of fetch_url to get Thruk session
113 """
114 if self.session is None:
115 self.refresh_authentication = False
116 GenericServer.init_http(self)
117
118 if self.use_autologin is True:
119 req = self.session.post(self.monitor_cgi_url + '/user.cgi?', data={}, headers={'X-Thruk-Auth-Key':self.autologin_key.strip()})
120 if conf.debug_mode:
121 self.debug(server=self.get_name(), debug='Auto Login status: ' + req.url + ' http code : ' + str(req.status_code))
122 if req.status_code != 200:
123 self.refresh_authentication = True
124 return Result(result=None, error="Login failed")
125 else:
126 # set thruk test cookie to in order to directly login
127 self.session.cookies.set('thruk_test', '***')
128 req = self.session.post(self.monitor_cgi_url + '/login.cgi?',
129 data={'login': self.get_username(),
130 'password': self.get_password(),
131 'submit': 'Login'})
132 if conf.debug_mode:
133 self.debug(server=self.get_name(), debug='Login status: ' + req.url + ' http code : ' + str(req.status_code))
134 if req.status_code != 200:
135 self.refresh_authentication = True
136 return Result(result=None, error="Login failed")
137
138 if self.disabled_backends is not None:
139 self.session.cookies.set('thruk_backends', '&'.join((f"{v}=2" for v in self.disabled_backends.split(','))))
140
141 def open_monitor(self, host, service=''):
142 '''
143 open monitor from tablewidget context menu
144 '''
145 # only type is important so do not care of service '' in case of host monitor
146 if service == '':
147 url = self.monitor_cgi_url + '/extinfo.cgi?type=1&' + urllib.parse.urlencode( { 'host': host })
148 else:
149 url = self.monitor_cgi_url + '/extinfo.cgi?type=2&' + urllib.parse.urlencode( { 'host': host, 'service': self.hosts[host].services[ service ].real_name })
150
151 if conf.debug_mode:
152 self.debug(server=self.get_name(), host=host, service=service,
153 debug='Open host/service monitor web page {0}'.format(url))
154 webbrowser_open(url)
155
156 def _set_acknowledge(self, host, service, author, comment, sticky, notify, persistent, all_services=None):
157 '''
158 send acknowledge to monitor server - might be different on every monitor type
159 '''
160
161 url = self.monitor_cgi_url + '/cmd.cgi'
162
163 # the following flags apply to hosts and services
164 #
165 # according to sf.net bug #3304098 (https://sourceforge.net/tracker/?func=detail&atid=1101370&aid=3304098&group_id=236865)
166 # the send_notification-flag must not exist if it is set to 'off', otherwise
167 # the Nagios core interpretes it as set, regardless its real value
168 #
169 # for whatever silly reason Icinga depends on the correct order of submitted form items...
170 # see sf.net bug 3428844
171 #
172 # Thanks to Icinga ORDER OF ARGUMENTS IS IMPORTANT HERE!
173 #
174 cgi_data = OrderedDict()
175 if service == '':
176 cgi_data['cmd_typ'] = '33'
177 else:
178 cgi_data['cmd_typ'] = '34'
179 cgi_data['cmd_mod'] = '2'
180 cgi_data['host'] = host
181 if service != '':
182 cgi_data['service'] = self.hosts[host].services[ service ].real_name
183 cgi_data['com_author'] = author
184 cgi_data['com_data'] = comment
185 cgi_data['btnSubmit'] = 'Commit'
186 if notify is True:
187 cgi_data['send_notification'] = 'on'
188 if persistent is True:
189 cgi_data['persistent'] = 'on'
190 if sticky is True:
191 cgi_data['sticky_ack'] = 'on'
192
193 self.fetch_url(url, giveback='raw', cgi_data=cgi_data)
194
195 # acknowledge all services on a host
196 if all_services:
197 for s in all_services:
198 cgi_data['cmd_typ'] = '34'
199 cgi_data['service'] = self.hosts[host].services[ s ].real_name
200 self.fetch_url(url, giveback='raw', cgi_data=cgi_data)
201
202 def _set_recheck(self, host, service):
203 self.session.headers.update({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'})
204
205 if service != '':
206 if self.hosts[host].services[ service ].is_passive_only():
207 # Do not check passive only checks
208 return
209 try:
210 # get start time from Nagios as HTML to use same timezone setting like the locally installed Nagios
211 result = self.fetch_url(
212 self.monitor_cgi_url + '/cmd.cgi?' + urllib.parse.urlencode({'cmd_typ': '96', 'host': host}))
213 self.start_time = dict(result.result.find(attrs={'name': 'start_time'}).attrs)['value']
214 # decision about host or service - they have different URLs
215 if service == '':
216 # host
217 cmd_typ = '96'
218 service_name = ''
219 else:
220 # service @ host
221 cmd_typ = '7'
222 service_name = self.hosts[host].services[ service ].real_name
223 # ignore empty service in case of rechecking a host
224 cgi_data = urllib.parse.urlencode([('cmd_typ', cmd_typ),
225 ('cmd_mod', '2'),
226 ('host', host),
227 ('service', service_name),
228 ('start_time', self.start_time),
229 ('force_check', 'on'),
230 ('btnSubmit', 'Commit')])
231 # execute POST request
232 self.fetch_url(self.monitor_cgi_url + '/cmd.cgi', giveback='raw', cgi_data=cgi_data)
233 except:
234 traceback.print_exc(file=sys.stdout)
235
236 def _set_downtime(self, host, service, author, comment, fixed, start_time, end_time, hours, minutes):
237 '''
238 finally send downtime command to monitor server
239 '''
240 url = self.monitor_cgi_url + '/cmd.cgi'
241
242 # for some reason Icinga is very fastidiuos about the order of CGI arguments, so please
243 # here we go... it took DAYS :-(
244 cgi_data = OrderedDict()
245 if service == '':
246 cgi_data['cmd_typ'] = '55'
247 else:
248 cgi_data['cmd_typ'] = '56'
249 cgi_data['cmd_mod'] = '2'
250 cgi_data['trigger'] = '0'
251 cgi_data['host'] = host
252 if service != '':
253 cgi_data['service'] = self.hosts[host].services[ service ].real_name
254 cgi_data['com_author'] = author
255 cgi_data['com_data'] = comment
256 cgi_data['fixed'] = fixed
257 cgi_data['start_time'] = start_time
258 cgi_data['end_time'] = end_time
259 cgi_data['hours'] = hours
260 cgi_data['minutes'] = minutes
261 cgi_data['btnSubmit'] = 'Commit'
262
263 # running remote cgi command
264 self.fetch_url(url, giveback='raw', cgi_data=cgi_data)
265
266 def _get_status(self):
267 """
268 Get status from Thruk Server
269 """
270 # new_hosts dictionary
271 self.new_hosts = dict()
272
273 # hosts - mostly the down ones
274 # unfortunately the hosts status page has a different structure so
275 # hosts must be analyzed separately
276 try:
277 # JSON experiments
278 result = self.fetch_url(self.cgiurl_hosts, giveback='raw')
279 jsonraw, error, status_code = copy.deepcopy(result.result),\
280 copy.deepcopy(result.error),\
281 result.status_code
282
283 # check if any error occured
284 errors_occured = self.check_for_error(jsonraw, error, status_code)
285 # if there are errors return them
286 if errors_occured is not None:
287 return errors_occured
288
289 # in case basic auth did not work try form login cookie based login
290 if jsonraw.startswith("<"):
291 self.refresh_authentication = True
292 return Result(result=None, error="Login failed")
293
294 # in case JSON is not empty evaluate it
295 elif not jsonraw == "[]":
296 hosts = json.loads(jsonraw)
297
298 for h in hosts:
299 if h["name"] not in self.new_hosts:
300 self.new_hosts[h["name"]] = GenericHost()
301 self.new_hosts[h["name"]].name = h["name"]
302 self.new_hosts[h["name"]].server = self.name
303 self.new_hosts[h["name"]].status = self.STATES_MAPPING["hosts"][h["state"]]
304 self.new_hosts[h["name"]].last_check = datetime.datetime.fromtimestamp(int(h["last_check"])).isoformat(" ")
305 self.new_hosts[h["name"]].duration = human_readable_duration_from_timestamp(h["last_state_change"])
306 self.new_hosts[h["name"]].attempt = "%s/%s" % (h["current_attempt"], h["max_check_attempts"])
307 self.new_hosts[h["name"]].status_information = h["plugin_output"].replace("\n", " ").strip()
308 self.new_hosts[h["name"]].passiveonly = not(bool(int(h["active_checks_enabled"])))
309 self.new_hosts[h["name"]].notifications_disabled = not(bool(int(h["notifications_enabled"])))
310 self.new_hosts[h["name"]].flapping = bool(int(h["is_flapping"]))
311 self.new_hosts[h["name"]].acknowledged = bool(int(h["acknowledged"]))
312 self.new_hosts[h["name"]].scheduled_downtime = bool(int(h["scheduled_downtime_depth"]))
313 self.new_hosts[h["name"]].status_type = {0: "soft", 1: "hard"}[h["state_type"]]
314 del h
315 except:
316 import traceback
317 traceback.print_exc(file=sys.stdout)
318 # set checking flag back to False
319 self.isChecking = False
320 result, error = self.error(sys.exc_info())
321 return Result(result=result, error=error)
322
323 # services
324 try:
325 # JSON experiments
326 result = self.fetch_url(self.cgiurl_services, giveback="raw")
327 jsonraw, error, status_code = copy.deepcopy(result.result),\
328 copy.deepcopy(result.error),\
329 result.status_code
330
331 # check if any error occured
332 errors_occured = self.check_for_error(jsonraw, error, status_code)
333 # if there are errors return them
334 if errors_occured is not None:
335 return errors_occured
336
337 # in case basic auth did not work try form login cookie based login
338 if jsonraw.startswith("<"):
339 self.refresh_authentication = True
340 return Result(result=None, error="Login failed")
341
342 # in case JSON is not empty evaluate it
343 elif not jsonraw == "[]":
344 services = json.loads(jsonraw)
345
346 for s in services:
347 # host objects contain service objects
348 if s["host_name"] not in self.new_hosts:
349 self.new_hosts[s["host_name"]] = GenericHost()
350 self.new_hosts[s["host_name"]].name = s["host_name"]
351 self.new_hosts[s["host_name"]].server = self.name
352 self.new_hosts[s["host_name"]].status = "UP"
353
354 if self.use_display_name_service:
355 entry = s["display_name"]
356 else:
357 entry = s["description"]
358
359 # if a service does not exist create its object
360 if entry not in self.new_hosts[s["host_name"]].services:
361 self.new_hosts[s["host_name"]].services[ entry ] = GenericService()
362 self.new_hosts[s["host_name"]].services[ entry ].host = s["host_name"]
363
364 self.new_hosts[s["host_name"]].services[ entry ].name = entry
365 self.new_hosts[s["host_name"]].services[ entry ].real_name = s["description"]
366
367 self.new_hosts[s["host_name"]].services[ entry ].server = self.name
368 self.new_hosts[s["host_name"]].services[ entry ].status = self.STATES_MAPPING["services"][s["state"]]
369 self.new_hosts[s["host_name"]].services[ entry ].last_check = datetime.datetime.fromtimestamp(int(s["last_check"])).isoformat(" ")
370 self.new_hosts[s["host_name"]].services[ entry ].duration = human_readable_duration_from_timestamp(s["last_state_change"])
371 self.new_hosts[s["host_name"]].services[ entry ].attempt = "%s/%s" % (s["current_attempt"], s["max_check_attempts"])
372 self.new_hosts[s["host_name"]].services[ entry ].status_information = s["plugin_output"].replace("\n", " ").strip()
373 self.new_hosts[s["host_name"]].services[ entry ].passiveonly = not(bool(int(s["active_checks_enabled"])))
374 self.new_hosts[s["host_name"]].services[ entry ].notifications_disabled = not(bool(int(s["notifications_enabled"])))
375 self.new_hosts[s["host_name"]].services[ entry ].flapping = not(bool(int(s["notifications_enabled"])))
376 self.new_hosts[s["host_name"]].services[ entry ] .acknowledged = bool(int(s["acknowledged"]))
377 self.new_hosts[s["host_name"]].services[ entry ].scheduled_downtime = bool(int(s["scheduled_downtime_depth"]))
378 self.new_hosts[s["host_name"]].services[ entry ].status_type = {0: "soft", 1: "hard"}[s["state_type"]]
379 del s
380 except:
381 import traceback
382 traceback.print_exc(file=sys.stdout)
383 # set checking flag back to False
384 self.isChecking = False
385 result, error = self.error(sys.exc_info())
386 return Result(result=result, error=error)
387
388 # dummy return in case all is OK
389 return Result()