Debian Codegraph @

Nagstamon/qui/dialogs/server.py

raw
1 # Nagstamon - Nagios status monitor for your desktop
2 # Copyright (C) 2008-2026 Henri Wahl <[email protected]> et al.
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
17
18 from copy import deepcopy
19 from functools import wraps
20 import os
21 from urllib.parse import quote
22
23 from Nagstamon.config import conf, CONFIG_STRINGS, BOOLPOOL, Server
24 from Nagstamon.cookies import delete_cookie
25 from Nagstamon.qui.globals import (ecp_available,
26 kerberos_available)
27 from Nagstamon.qui.qt import (QFileDialog,
28 QMessageBox,
29 QStyle,
30 QWidget,
31 Signal,
32 Slot)
33 from Nagstamon.qui.dialogs.dialog import Dialog
34 from Nagstamon.servers import (create_server,
35 servers,
36 SERVER_TYPES)
37
38
39 class DialogServer(Dialog):
40 """
41 dialog used to set up one single server
42 """
43
44 # tell server has been edited
45 edited = Signal()
46
47 # signal to emit when ok button is pressed - used to remove previous server
48 edited_remove_previous = Signal(str)
49
50 # signal to emit when ok button is pressed - used to update the list of servers
51 edited_update_list = Signal(str, str, str)
52
53 # signal to emit when a new server vbox has to be created
54 create_server_vbox = Signal(str)
55
56 # signal to emit when web cookies should be deleted for a server
57 delete_web_cookies = Signal(str, QWidget)
58
59 def __init__(self):
60 Dialog.__init__(self, 'settings_server')
61 # file chooser Dialog
62 self.file_chooser = QFileDialog()
63 # configuration for server
64 self.server_conf = None
65 # define checkbox-to-widgets dependencies which apply at initialization
66 # which widgets have to be hidden because of irrelevance
67 # dictionary holds checkbox/radiobutton as key and relevant widgets in a list
68 self.TOGGLE_DEPS = {
69 self.window.input_checkbox_use_autologin: [self.window.label_autologin_key,
70 self.window.input_lineedit_autologin_key],
71 self.window.input_checkbox_use_proxy: [self.window.groupbox_proxy],
72
73 self.window.input_checkbox_use_proxy_from_os: [self.window.label_proxy_address,
74 self.window.input_lineedit_proxy_address,
75 self.window.label_proxy_username,
76 self.window.input_lineedit_proxy_username,
77 self.window.label_proxy_password,
78 self.window.input_lineedit_proxy_password],
79 self.window.input_checkbox_show_options: [self.window.groupbox_options],
80 self.window.input_checkbox_custom_cert_use: [self.window.label_custom_ca_file,
81 self.window.input_lineedit_custom_cert_ca_file,
82 self.window.button_choose_custom_cert_ca_file]}
83
84 self.TOGGLE_DEPS_INVERTED = [self.window.input_checkbox_use_proxy_from_os]
85
86 # these widgets are shown or hidden depending on server type properties
87 # the servers listed at each widget do need them
88 self.VOLATILE_WIDGETS = {
89 self.window.label_monitor_cgi_url: ['Nagios', 'Icinga', 'Thruk', 'Sensu', 'SensuGo'],
90 self.window.input_lineedit_monitor_cgi_url: ['Nagios', 'Icinga', 'Thruk', 'Sensu', 'SensuGo'],
91 self.window.input_checkbox_use_autologin: ['Centreon', 'monitos4x', 'Thruk'],
92 self.window.input_lineedit_autologin_key: ['Centreon', 'monitos4x', 'Thruk'],
93 self.window.label_autologin_key: ['Centreon', 'monitos4x', 'Thruk'],
94 self.window.input_checkbox_no_cookie_auth: ['IcingaWeb2', 'Sensu'],
95 self.window.input_checkbox_use_display_name_host: ['Icinga', 'IcingaWeb2'],
96 self.window.input_checkbox_use_display_name_service: ['Icinga', 'IcingaWeb2', 'Thruk'],
97 self.window.input_checkbox_use_description_name_service: ['Zabbix'],
98 self.window.input_checkbox_force_authuser: ['Checkmk Multisite'],
99 self.window.groupbox_checkmk_views: ['Checkmk Multisite'],
100 self.window.input_lineedit_host_filter: ['op5Monitor'],
101 self.window.input_lineedit_service_filter: ['op5Monitor'],
102 self.window.label_service_filter: ['op5Monitor'],
103 self.window.label_host_filter: ['op5Monitor'],
104 self.window.input_lineedit_hashtag_filter: ['Opsview'],
105 self.window.label_hashtag_filter: ['Opsview'],
106 self.window.input_checkbox_can_change_only: ['Opsview'],
107 self.window.label_monitor_site: ['Sensu'],
108 self.window.input_lineedit_monitor_site: ['Sensu'],
109 self.window.label_map_to_hostname: ['Prometheus', 'Alertmanager'],
110 self.window.input_lineedit_map_to_hostname: ['Prometheus', 'Alertmanager'],
111 self.window.input_checkbox_treat_services_as_alerts: ['LibreNMS'],
112 self.window.label_map_to_servicename: ['Prometheus', 'Alertmanager'],
113 self.window.input_lineedit_map_to_servicename: ['Prometheus', 'Alertmanager'],
114 self.window.label_map_to_status_information: ['Prometheus', 'Alertmanager'],
115 self.window.input_lineedit_map_to_status_information: ['Prometheus', 'Alertmanager'],
116 self.window.label_alertmanager_filter: ['Alertmanager'],
117 self.window.input_lineedit_alertmanager_filter: ['Alertmanager'],
118 self.window.label_map_to_ok: ['Alertmanager'],
119 self.window.input_lineedit_map_to_ok: ['Alertmanager'],
120 self.window.label_map_to_unknown: ['Alertmanager'],
121 self.window.input_lineedit_map_to_unknown: ['Alertmanager'],
122 self.window.label_map_to_warning: ['Alertmanager'],
123 self.window.input_lineedit_map_to_warning: ['Alertmanager'],
124 self.window.label_map_to_critical: ['Alertmanager'],
125 self.window.input_lineedit_map_to_critical: ['Alertmanager'],
126 self.window.label_map_to_down: ['Alertmanager'],
127 self.window.input_lineedit_map_to_down: ['Alertmanager'],
128 self.window.input_lineedit_notification_filter: ['IcingaDBWebNotifications'],
129 self.window.label_notification_filter: ['IcingaDBWebNotifications'],
130 self.window.input_lineedit_notification_lookback: ['IcingaDBWebNotifications'],
131 self.window.label_notification_lookback: ['IcingaDBWebNotifications'],
132 self.window.input_lineedit_custom_filter: ['IcingaDBWeb'],
133 self.window.label_custom_filter: ['IcingaDBWeb'],
134 self.window.label_disabled_backends: ['Thruk'],
135 self.window.input_lineedit_disabled_backends: ['Thruk'],
136 }
137
138 # to be used when selecting authentication method Kerberos or Web
139 self.AUTHENTICATION_WIDGETS = [
140 self.window.label_username,
141 self.window.input_lineedit_username,
142 self.window.label_password,
143 self.window.input_lineedit_password,
144 self.window.input_checkbox_save_password]
145
146 self.AUTHENTICATION_BEARER_WIDGETS = [
147 self.window.label_username,
148 self.window.input_lineedit_username]
149
150 self.AUTHENTICATION_ECP_WIDGETS = [
151 self.window.label_idp_ecp_endpoint,
152 self.window.input_lineedit_idp_ecp_endpoint]
153
154 # custom CA is not possible with authentification method Web due to the underlying Qt WebEngine aka Chromium
155 self.CUSTOM_CERT_CA_WIDGETS = [ self.window.input_checkbox_custom_cert_use ]
156
157 # fill default order fields combobox with monitor server types
158 self.window.input_combobox_type.addItems(sorted(SERVER_TYPES.keys(), key=str.lower))
159 # default to Nagios as it is the mostly used monitor server
160 self.window.input_combobox_type.setCurrentText('Nagios')
161
162 # set folder and play symbols to choose and play buttons
163 self.window.button_choose_custom_cert_ca_file.setText('')
164 self.window.button_choose_custom_cert_ca_file.setIcon(
165 self.window.button_choose_custom_cert_ca_file.style().standardIcon(QStyle.StandardPixmap.SP_DirIcon))
166 # connect choose custom cert CA file button with file dialog
167 self.window.button_choose_custom_cert_ca_file.clicked.connect(self.choose_custom_cert_ca_file)
168
169 # fill authentication combobox
170 combobox_authentication_items = ['Basic', 'Bearer', 'Digest']
171 if ecp_available:
172 combobox_authentication_items.append('ECP')
173 if kerberos_available:
174 combobox_authentication_items.append('Kerberos')
175 # Keyring availability is checked in Config - only show Web authentication if keyring is available,
176 # because otherwise encryption key cannot be stored securely
177 if conf.is_keyring_available():
178 combobox_authentication_items.append('Web')
179 # sort items
180 self.window.input_combobox_authentication.addItems(sorted(combobox_authentication_items))
181
182 # detect change of a server type which leads to certain options shown or hidden
183 self.window.input_combobox_type.activated.connect(self.toggle_type)
184
185 # when authentication is changed to Kerberos then disable username/password as they are now useless
186 self.window.input_combobox_authentication.activated.connect(self.toggle_authentication)
187
188 # reset Checkmk views
189 self.window.button_checkmk_view_hosts_reset.clicked.connect(self.checkmk_view_hosts_reset)
190 self.window.button_checkmk_view_services_reset.clicked.connect(self.checkmk_view_services_reset)
191
192 self.window.button_delete_web_cookies.clicked.connect(self.on_delete_web_cookies)
193
194 # mode needed for evaluate dialog after ok button pressed - defaults to 'new'
195 self.mode = 'new'
196
197 @Slot(int)
198 def toggle_type(self, server_type_index=0):
199 # server_type_index is not needed - we get the server type from .currentText()
200 # check if server type is listed in volatile widgets to decide if it has to be shown or hidden
201 for widget, server_types in self.VOLATILE_WIDGETS.items():
202 if self.window.input_combobox_type.currentText() in server_types:
203 widget.show()
204 else:
205 widget.hide()
206
207 @Slot()
208 def toggle_authentication(self):
209 """
210 when authentication is changed to Kerberos then disable username/password as they are now useless
211 """
212 if self.window.input_combobox_authentication.currentText() == 'Kerberos':
213 for widget in self.AUTHENTICATION_WIDGETS:
214 widget.hide()
215 else:
216 for widget in self.AUTHENTICATION_WIDGETS:
217 widget.show()
218
219 if self.window.input_combobox_authentication.currentText() == 'ECP':
220 for widget in self.AUTHENTICATION_ECP_WIDGETS:
221 widget.show()
222 else:
223 for widget in self.AUTHENTICATION_ECP_WIDGETS:
224 widget.hide()
225
226 # change credential input for bearer auth
227 if self.window.input_combobox_authentication.currentText() == 'Bearer':
228 for widget in self.AUTHENTICATION_BEARER_WIDGETS:
229 widget.hide()
230 self.window.label_password.setText('Token')
231 else:
232 for widget in self.AUTHENTICATION_BEARER_WIDGETS:
233 widget.show()
234 self.window.label_password.setText('Password')
235
236 # no need for username + password when using Web authentication
237 if self.window.input_combobox_authentication.currentText() == 'Web':
238 for widget in self.AUTHENTICATION_WIDGETS + self.CUSTOM_CERT_CA_WIDGETS:
239 widget.hide()
240 self.window.button_delete_web_cookies.show()
241 else:
242 for widget in self.AUTHENTICATION_WIDGETS + self.CUSTOM_CERT_CA_WIDGETS:
243 widget.show()
244 self.window.button_delete_web_cookies.hide()
245
246 # after hiding authentication widgets dialog might shrink
247 self.window.adjustSize()
248
249 def dialog_decoration(method, *args, **kwargs):
250 """
251 try with a decorator instead of repeated calls
252 """
253
254 # the function which decorates method
255 # wraps is used to keep the original method's name and docstring
256 @wraps(method)
257 def decoration_function(self, *args, **kwargs):
258 """
259 self.server_conf has to be set by decorated method
260 """
261 # previous server conf only useful when editing - defaults to None
262 self.previous_server_conf = None
263
264 # call decorated method
265 method(self, *args, **kwargs)
266
267 # run through all input widgets and apply defaults from config
268 for widget in self.window.__dict__:
269
270 if widget.startswith('input_'):
271 if widget.startswith('input_checkbox_'):
272 setting = widget.split('input_checkbox_')[1]
273 self.window.__dict__[widget].setChecked(self.server_conf.__dict__[setting])
274 elif widget.startswith('input_radiobutton_'):
275 setting = widget.split('input_radiobutton_')[1]
276 self.window.__dict__[widget].setChecked(self.server_conf.__dict__[setting])
277 elif widget.startswith('input_combobox_'):
278 setting = widget.split('input_combobox_')[1]
279 self.window.__dict__[widget].setCurrentText(self.server_conf.__dict__[setting])
280 elif widget.startswith('input_lineedit_'):
281 setting = widget.split('input_lineedit_')[1]
282 self.window.__dict__[widget].setText(self.server_conf.__dict__[setting])
283 elif widget.startswith('input_spinbox_'):
284 setting = widget.split('input_spinbox_')[1]
285 self.window.__dict__[widget].setValue(self.server_conf.__dict__[setting])
286
287 # set the current authentication type by using capitalized first letter via .title()
288 self.window.input_combobox_authentication.setCurrentText(self.server_conf.authentication.title())
289
290 # initially hide unnecessary widgets
291 self.toggle_type()
292
293 # disable unneeded authentication widgets if Kerberos is used
294 self.toggle_authentication()
295
296 # apply toggle-dependencies between checkboxes and certain widgets
297 self.toggle_toggles()
298
299 # open extra options if wanted, for example, by button_fix_tls_error
300 if 'show_options' in self.__dict__:
301 if self.show_options:
302 self.window.input_checkbox_show_options.setChecked(True)
303
304 # important final size adjustment
305 self.window.adjustSize()
306
307 # if running on macOS with disabled dock icon, the dock icon might have to be made visible
308 # to make Nagstamon accept keyboard input
309 self.check_macos_dock_icon_fix_show.emit()
310
311 # force modality - using .open() still allows to switch to main settings dialog
312 self.window.exec()
313
314 # en reverse the dock icon might be hidden again after a potential keyboard input
315 self.check_macos_dock_icon_fix_hide.emit()
316
317 # give back decorated function
318 return decoration_function
319
320 @Slot()
321 @dialog_decoration
322 def new(self):
323 """
324 create new server, set default values
325 """
326 self.mode = 'new'
327
328 # create a new server config object
329 self.server_conf = Server()
330 # window title might be pretty simple
331 self.window.setWindowTitle('New server')
332
333 @Slot(str)
334 @dialog_decoration
335 def edit(self, name=None, show_options=False):
336 """
337 edit existing server
338 when called by Edit button in ServerVBox use given server name to get server config
339 """
340
341 self.mode = 'edit'
342 # shorter server conf
343 # if name is None:
344 # self.server_conf = conf.servers[dialogs.settings.window.list_servers.currentItem().text()]
345 # else:
346 # self.server_conf = conf.servers[name]
347 self.server_conf = conf.servers[name]
348 # store monitor name in case it will be changed
349 self.previous_server_conf = deepcopy(self.server_conf)
350 # set window title
351 self.window.setWindowTitle('Edit %s' % (self.server_conf.name))
352 # set self.show_options to give value to decorator
353 self.show_options = show_options
354
355 @Slot(str)
356 @dialog_decoration
357 def copy(self, name=None):
358 """
359 copy existing server
360 """
361 self.mode = 'copy'
362 # shorter server conf
363 self.server_conf = deepcopy(conf.servers[name])
364 # set window title before name change to reflect copy
365 self.window.setWindowTitle(f'Copy {self.server_conf.name}')
366 # indicate copy of another server
367 self.server_conf.name = f'Copy of {self.server_conf.name}'
368
369 def ok(self):
370 """
371 evaluate the state of widgets to get new configuration
372 """
373 # strip name to avoid whitespace
374 server_name = self.window.input_lineedit_name.text().strip()
375
376 # check that no duplicate name exists
377 if server_name in conf.servers and \
378 (self.mode in ['new', 'copy'] or
379 self.mode == 'edit' and self.server_conf != conf.servers[server_name]):
380 # cry if duplicate name exists
381 QMessageBox.critical(self.window,
382 'Nagstamon',
383 f'The monitor server name <b>{server_name}</b> is already used.',
384 QMessageBox.StandardButton.Ok)
385 else:
386 # get configuration from UI
387 for widget in self.window.__dict__:
388 if widget.startswith('input_'):
389 if widget.startswith('input_checkbox_'):
390 setting = widget.split('input_checkbox_')[1]
391 self.server_conf.__dict__[setting] = self.window.__dict__[widget].isChecked()
392 elif widget.startswith('input_radiobutton_'):
393 setting = widget.split('input_radiobutton_')[1]
394 self.server_conf.__dict__[setting] = self.window.__dict__[widget].isChecked()
395 elif widget.startswith('input_combobox_'):
396 setting = widget.split('input_combobox_')[1]
397 self.server_conf.__dict__[setting] = self.window.__dict__[widget].currentText()
398 elif widget.startswith('input_lineedit_'):
399 setting = widget.split('input_lineedit_')[1]
400 self.server_conf.__dict__[setting] = self.window.__dict__[widget].text()
401 elif widget.startswith('input_spinbox_'):
402 setting = widget.split('input_spinbox_')[1]
403 self.server_conf.__dict__[setting] = self.window.__dict__[widget].value()
404
405 # URLs should not end with / - clean it
406 self.server_conf.monitor_url = self.server_conf.monitor_url.rstrip('/')
407 self.server_conf.monitor_cgi_url = self.server_conf.monitor_cgi_url.rstrip('/')
408
409 # convert some strings to integers and bools
410 for item in self.server_conf.__dict__:
411 if type(self.server_conf.__dict__[item]) == str:
412 # when an item is not one of those which always have to be strings, then it might be OK to convert it
413 if not item in CONFIG_STRINGS:
414 if self.server_conf.__dict__[item] in BOOLPOOL:
415 self.server_conf.__dict__[item] = BOOLPOOL[self.server_conf.__dict__[item]]
416 elif self.server_conf.__dict__[item].isdecimal():
417 self.server_conf.__dict__[item] = int(self.server_conf.__dict__[item])
418
419 # store lowered authentication type
420 self.server_conf.authentication = self.server_conf.authentication.lower()
421
422 # edited servers will be deleted and recreated with new configuration
423 if self.mode == 'edit':
424 # remove old server vbox from the status window if still running
425 self.edited_remove_previous.emit(self.previous_server_conf.name)
426
427 # delete previous name
428 conf.servers.pop(self.previous_server_conf.name)
429
430 # delete edited and now not needed server instance - if it exists
431 if self.previous_server_conf.name in servers.keys():
432 servers.pop(self.previous_server_conf.name)
433
434 # some monitor servers do not need cgi-url - reuse self.VOLATILE_WIDGETS to find out which one
435 if self.server_conf.type not in self.VOLATILE_WIDGETS[self.window.input_lineedit_monitor_cgi_url]:
436 self.server_conf.monitor_cgi_url = self.server_conf.monitor_url
437
438 # add new server configuration in every case and use stripped name to avoid spaces
439 self.server_conf.name = server_name
440 conf.servers[server_name] = self.server_conf
441
442 # add new server instance to global servers dict
443 servers[server_name] = create_server(self.server_conf)
444 if self.server_conf.enabled:
445 servers[server_name].enabled = True
446 # create vbox
447 self.create_server_vbox.emit(server_name)
448
449 # reorder servers in dict to reflect changes
450 servers_freshly_sorted = sorted(servers.items())
451 servers.clear()
452 servers.update(servers_freshly_sorted)
453 del servers_freshly_sorted
454
455 # refresh the list of servers, give call the current server name to highlight it
456 self.edited_update_list.emit('list_servers', 'servers', self.server_conf.name)
457
458 # tell the main window about changes (Zabbix, Opsview, for example)
459 self.edited.emit()
460
461 # delete the old server .conf file to reflect name changes
462 # new one will be written soon
463 if self.previous_server_conf is not None:
464 conf.delete_file('servers', f"server_{quote(self.previous_server_conf.name, safe='')}.conf")
465
466 # store server settings
467 conf.save_multiple_config('servers', 'server')
468
469 # call close and macOS dock icon treatment from ancestor
470 super().ok()
471
472 @Slot()
473 def choose_custom_cert_ca_file(self):
474 """
475 show dialog for selection of non-default browser
476 """
477 file_filter = 'All files (*)'
478 file = self.file_chooser.getOpenFileName(self.window,
479 directory=os.path.expanduser('~'),
480 filter=file_filter)[0]
481
482 # only take filename if QFileDialog gave something useful back
483 if file != '':
484 self.window.input_lineedit_custom_cert_ca_file.setText(file)
485
486 @Slot()
487 def checkmk_view_hosts_reset(self):
488 self.window.input_lineedit_checkmk_view_hosts.setText('nagstamon_hosts')
489
490 @Slot()
491 def checkmk_view_services_reset(self):
492 self.window.input_lineedit_checkmk_view_services.setText('nagstamon_svc')
493
494 def on_delete_web_cookies(self):
495 """
496 delete all cookies for given server
497 """
498 # strip name to avoid whitespace
499 server_name = self.window.input_lineedit_name.text().strip()
500 self.delete_web_cookies.emit(server_name, self)
501
502 @Slot(str)
503 def delete_web_cookies_action(self, server_name=None, parent=None):
504 # strip name to avoid whitespace
505 if server_name is None:
506 server_name = self.window.input_lineedit_name.text().strip()
507 if parent is None:
508 parent = self.window
509
510 reply = QMessageBox.question(parent, 'Nagstamon',
511 f'Do you really want to delete <b>all web cookies</b> of monitor server <b>{server_name}</b>?',
512 QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
513 QMessageBox.StandardButton.No)
514 if reply == QMessageBox.StandardButton.Yes:
515 delete_cookie(server_name)