-
Notifications
You must be signed in to change notification settings - Fork 1
/
GUI.py
executable file
·3662 lines (3056 loc) · 170 KB
/
GUI.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding: utf-8
try:
import pygtk
pygtk.require("2.0")
except Exception, err:
print
print err
print
print "Could not load pygtk, maybe you need to install python gtk."
print
import sys
sys.exit()
import gtk
import gobject
import os
import platform
# module egg.trayicon doesnt exists on Windows
if platform.system() != "Windows" and platform.system() != "Darwin":
try:
import egg.trayicon
except Exception, err:
print
print err
print
print "Could not load egg.trayicon, so you cannot put nagstamon statusbar into systray."
print
# needed for actions e.g. triggered by pressed buttons
from Nagstamon import Config
from Nagstamon import Actions
from Nagstamon import Objects
from Nagstamon import Custom # used for initialization of custom components
import subprocess
import sys
import gc
import time
class Sorting(object):
""" Sorting persistence purpose class
Stores tuple pairs in form of:
(<column_id>, <gtk.SORT_ASCENDING|gtk.SORT_DESCENDING)
"""
def __init__(self, sorting_tuple_list=[], max_remember=8):
self.sorting_tuple_list = sorting_tuple_list
self.max_remember = max_remember
def iteritems(self):
for item in reversed(self.sorting_tuple_list):
yield item
def add(self, id, order):
length = len(self.sorting_tuple_list)
if length > 0:
if length >= self.max_remember:
self.sorting_tuple_list.pop()
if id == self.sorting_tuple_list[0][0]:
self.sorting_tuple_list.remove(self.sorting_tuple_list[0])
self.sorting_tuple_list.insert(0, (id, order))
class GUI(object):
"""
class which organizes the GUI
"""
def __init__(self, **kwds):
"""
some fundamental preliminaries
"""
# add all keywords to object
for k in kwds: self.__dict__[k] = kwds[k]
# Meta
self.name = "Nagstamon"
self.version = "0.9.10.5"
self.website = "http://nagstamon.ifw-dresden.de/"
self.copyright = "©2008-2012 Henri Wahl et al.\nh.wahl@ifw-dresden.de"
self.comments = "Nagios status monitor for your desktop"
# initialize overall status flag
self.status_ok = True
# if run first it is impossible to refresh the display with
# non-existent settings so there has to be extra treatment
# at the second run nagstamon will be configured and so no first run
if self.conf.unconfigured:
self.firstrun = True
else:
self.firstrun = False
# font size, later adjusted by StatusBar
self.fontsize = 10000
# store information about monitors
self.monitors = dict()
self.current_monitor = 0
# define colors for detailed status table in dictionaries
self.TAB_BG_COLORS = {
"UNKNOWN": str(self.conf.color_unknown_background),
"CRITICAL": str(self.conf.color_critical_background),
'INFORMATION': str(self.conf.color_information_background),
'HIGH': str(self.conf.color_high_background),
'AVERAGE': str(self.conf.color_average_background),
"WARNING": str(self.conf.color_warning_background),
"DOWN": str(self.conf.color_down_background),
"UNREACHABLE": str(self.conf.color_unreachable_background) }
self.TAB_FG_COLORS = {
"UNKNOWN": str(self.conf.color_unknown_text),
'INFORMATION': str(self.conf.color_information_text),
'AVERAGE': str(self.conf.color_average_text),
'HIGH': str(self.conf.color_high_text),
"CRITICAL": str(self.conf.color_critical_text),
"WARNING": str(self.conf.color_warning_text),
"DOWN": str(self.conf.color_down_text),
"UNREACHABLE": str(self.conf.color_unreachable_text)
}
# define popwin table liststore types
self.LISTSTORE_COLUMNS = [gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING,\
gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING,\
gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING,\
gobject.TYPE_STRING,\
gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, gtk.gdk.Pixbuf,\
gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, gtk.gdk.Pixbuf]
# create all GUI widgets
self._CreateOutputVisuals()
# set size of popup-window
self.popwin.Resize()
# flag which is set True if already notifying
self.Notifying = False
# saving sorting state between refresh
self.rows_reordered_handler = {}
self.last_sorting = {}
for server in self.servers.values():
self.last_sorting[server.get_name()] = Sorting([(server.DEFAULT_SORT_COLUMN_ID, gtk.SORT_ASCENDING),
(server.HOST_COLUMN_ID, gtk.SORT_ASCENDING)],
len(server.COLUMNS)+1) # stores sorting between table refresh
def get_last_sorting(self, server):
return self.last_sorting[server.get_name()]
def get_rows_reordered_handler(self, server):
return self.rows_reordered_handler.get(server.get_name())
def set_rows_reordered_handler(self, server, handler):
self.rows_reordered_handler[server.get_name()] = handler
def set_sorting(self, liststore, server):
""" Restores sorting after refresh """
for id, order in self.get_last_sorting(server).iteritems():
liststore.set_sort_column_id(id, order)
# this makes sorting arrows visible according to
# sort order after refresh
column = self.popwin.ServerVBoxes[server.get_name()].TreeView.get_column(id)
if column is not None:
column.set_property('sort-order', order)
def on_column_header_click(self, model, id, liststore, server):
""" Sets current sorting according to column id """
# makes column headers sortable by first time click (hack)
order = model.get_sort_order()
liststore.set_sort_column_id(id, order)
rows_reordered_handler = self.get_rows_reordered_handler(server)
if rows_reordered_handler is not None:
liststore.disconnect(rows_reordered_handler)
new_rows_reordered_handler = liststore.connect_after('rows-reordered', self.on_sorting_order_change, id, model, server)
self.set_rows_reordered_handler(server, new_rows_reordered_handler)
else:
new_rows_reordered_handler = liststore.connect_after('rows-reordered', self.on_sorting_order_change, id, model, server, False)
self.set_rows_reordered_handler(server, new_rows_reordered_handler)
self.on_sorting_order_change(liststore, None, None, None, id, model, server)
model.set_sort_column_id(id)
def on_sorting_order_change(self, liststore, path, iter, new_order, id, model, server, do_action=True):
""" Saves current sorting change in object property """
if do_action:
order = model.get_sort_order()
last_sorting = self.get_last_sorting(server)
last_sorting.add(id, order)
def _CreateOutputVisuals(self):
"""
create output visuals
"""
# decide if the platform can handle SVG if not use PNG
if platform.system() in ["Darwin", "Windows"]:
self.BitmapSuffix = ".png"
else:
self.BitmapSuffix = ".svg"
# set app icon for all app windows
gtk.window_set_default_icon_from_file(self.Resources + os.sep + "nagstamon" + self.BitmapSuffix)
# icons for acknowledgement/downtime visualization
self.STATE_ICONS = dict()
for icon in ["acknowledged", "downtime", "flapping", "passive"]:
self.STATE_ICONS[icon] = gtk.gdk.pixbuf_new_from_file_at_size(self.Resources\
+ os.sep + "nagstamon_" + icon + self.BitmapSuffix,\
int(self.fontsize/650), int(self.fontsize/650))
# Icon in systray and statusbar both get created but
# only one of them depending on the settings will
# be shown
self.statusbar = StatusBar(conf=self.conf, output=self)
# Popup is a WINDOW_POPUP without border etc.
self.popwin = Popwin(conf=self.conf, output=self)
# Windows workaround for faulty behavior in case the statusbar label shrinks -
# it does not in Windows, maybe a Gtk bug
# do this only if statusbar is enabled
if str(self.conf.statusbar_systray) == "True" or str(self.conf.statusbar_systray) == "True":
x,y = self.statusbar.HBox.size_request()
self.statusbar.StatusBar.resize(x, y)
# connect events to actions
# when talking about "systray" the Windows variant of upper left desktop corner
# statusbar is meant synonymical
# if pointer on systray do popup the long-summary-status-window aka popwin
self.statusbar.SysTray.connect("activate", self.statusbar.SysTrayClicked)
#self.statusbar.SysTray.connect("popup-menu", self.statusbar.MenuPopup, self.statusbar.Menu)
self.statusbar.SysTray.connect("popup-menu", self.statusbar.MenuPopup)
# if pointer clicks on logo move stautsbar
self.statusbar.LogoEventbox.connect("button-press-event", self.statusbar.LogoClicked)
self.statusbar.LogoEventbox.connect("button-release-event", self.statusbar.LogoReleased)
# if pointer hovers or clicks statusbar show details
self.statusbar.EventBoxLabel.connect("enter-notify-event", self.statusbar.Hovered)
self.statusbar.EventBoxLabel.connect("button-press-event", self.statusbar.Clicked)
# server combobox
self.popwin.ComboboxMonitor.connect("changed", self.popwin.ComboboxClicked)
# attempt to place and resize statusbar where it belongs to in Windows - workaround
self.statusbar.StatusBar.move(int(self.conf.position_x), int(self.conf.position_y))
self.statusbar.Resize()
def RefreshDisplayStatus(self):
"""
load current nagios status and refresh trayicon and detailed treeview
add only services which are not on maintained or acknowledged hosts
this way applying the nagios filter more comfortably because in
nagios one had to schedule/acknowledge every single service
"""
# refresh statusbar
# flag for overall status, needed by popwin.popup to decide if popup in case all is OK
self.status_ok = False
# set handler to None for do not disconnecting it after display refresh
self.rows_reordered_handler = {}
# local counters for summarize all miserable hosts
downs = 0
unreachables = 0
unknowns = 0
criticals = 0
warnings = 0
average = 0
high = 0
information = 0
# display "ERROR" in case of startup connection trouble
errors = ""
# walk through all servers,RefreshDisplayStatus their hosts and their services
for server in self.servers.values():
# only refresh monitor server output if enabled and only once every server loop
if str(self.conf.servers[server.get_name()].enabled) == "True" or\
server.refresh_authentication == True:
try:
# otherwise it must be shown, full of problems
self.popwin.ServerVBoxes[server.get_name()].show()
self.popwin.ServerVBoxes[server.get_name()].set_visible(True)
self.popwin.ServerVBoxes[server.get_name()].set_no_show_all(False)
# if needed show auth line:
if server.refresh_authentication == True:
self.popwin.ServerVBoxes[server.get_name()].HBoxAuth.set_no_show_all(False)
self.popwin.ServerVBoxes[server.get_name()].HBoxAuth.show_all()
if self.popwin.ServerVBoxes[server.get_name()].AuthEntryUsername.get_text() == "":
self.popwin.ServerVBoxes[server.get_name()].AuthEntryUsername.set_text(server.username)
if self.popwin.ServerVBoxes[server.get_name()].AuthEntryPassword.get_text() == "":
self.popwin.ServerVBoxes[server.get_name()].AuthEntryPassword.set_text(server.password)
# use a bunch of filtered nagitems, services and hosts sorted by different
# grades of severity
# summarize states
downs += server.downs
unreachables += server.unreachables
unknowns += server.unknowns
criticals += server.criticals
warnings += server.warnings
information += server.information
high += server.high
average += server.average
# if there is no trouble...
if len(server.nagitems_filtered["hosts"]["DOWN"]) == 0 and \
len(server.nagitems_filtered["hosts"]["UNREACHABLE"]) == 0 and \
len(server.nagitems_filtered["services"]["INFORMATION"]) == 0 and \
len(server.nagitems_filtered["services"]["AVERAGE"]) == 0 and \
len(server.nagitems_filtered["services"]["HIGH"]) == 0 and \
len(server.nagitems_filtered["services"]["CRITICAL"]) == 0 and \
len(server.nagitems_filtered["services"]["WARNING"]) == 0 and \
len(server.nagitems_filtered["services"]["UNKNOWN"]) == 0 and \
server.status_description == "":
# ... there is no need to show a label or treeview...
self.popwin.ServerVBoxes[server.get_name()].hide()
self.popwin.ServerVBoxes[server.get_name()].set_visible(False)
self.popwin.ServerVBoxes[server.get_name()].set_no_show_all(True)
self.status_ok = True
else:
# otherwise it must be shown, full of problems
self.popwin.ServerVBoxes[server.get_name()].show()
self.popwin.ServerVBoxes[server.get_name()].set_visible(True)
self.popwin.ServerVBoxes[server.get_name()].set_no_show_all(False)
self.status_ok = False
# use a liststore for treeview where the table headers all are strings - first empty it
# now added with some simple repair after settings dialog has been used
# because sometimes after settings changes ListStore and TreeView become NoneType
# would be more logical to do this in Actions.CreateServer() but this gives a segfault :-(
if not type(server.ListStore) == type(None):
server.ListStore.clear()
else:
server.ListStore = gtk.ListStore(*self.LISTSTORE_COLUMNS)
if type(server.TreeView) == type(None):
server.TreeView = gtk.TreeView()
# apart from status informations there we need two columns which
# hold the color information, which is derived from status which
# is used as key at the above color dictionaries
# Update: new columns added which contain pixbufs of flag indicators if needed
for item_type, status_dict in server.nagitems_filtered.iteritems():
for status, item_list in status_dict.iteritems():
for item in list(item_list):
line = list(server.get_columns(item))
#print line
line.append(self.TAB_FG_COLORS[item.status])
line.append(self.TAB_BG_COLORS[item.status])
# add a slightly changed version of bg_color for better recognition in treeview
color = gtk.gdk.color_parse(self.TAB_BG_COLORS[item.status])
color = gtk.gdk.Color(red = self._GetAlternateColor(color.red),\
green = self._GetAlternateColor(color.green),\
blue = self._GetAlternateColor(color.blue),\
pixel = color.pixel)
line.append(color.to_string())
# icons for hosts
if item.is_host():
if item.is_acknowledged():
line.append(self.STATE_ICONS["acknowledged"])
else:
line.append(None)
if item.is_in_scheduled_downtime():
line.append(self.STATE_ICONS["downtime"])
else:
line.append(None)
if item.is_flapping():
line.append(self.STATE_ICONS["flapping"])
else:
line.append(None)
if item.is_passive_only():
line.append(self.STATE_ICONS["passive"])
else:
line.append(None)
# fill line with dummmy values because there will
# be none for services if this is a host
line.extend([None, None, None, None])
# icons for services
else:
# if the hosting host of a service has any flags display them too
if server.hosts[item.host].is_acknowledged():
line.append(self.STATE_ICONS["acknowledged"])
else:
line.append(None)
if server.hosts[item.host].is_in_scheduled_downtime():
line.append(self.STATE_ICONS["downtime"])
else:
line.append(None)
if server.hosts[item.host].is_flapping():
line.append(self.STATE_ICONS["flapping"])
else:
line.append(None)
if server.hosts[item.host].is_passive_only():
line.append(self.STATE_ICONS["passive"])
else:
line.append(None)
# now the service...
if item.is_acknowledged():
line.append(self.STATE_ICONS["acknowledged"])
else:
line.append(None)
if item.is_in_scheduled_downtime():
line.append(self.STATE_ICONS["downtime"])
else:
line.append(None)
if item.is_flapping():
line.append(self.STATE_ICONS["flapping"])
else:
line.append(None)
if item.is_passive_only():
line.append(self.STATE_ICONS["passive"])
else:
line.append(None)
server.ListStore.append(line)
# give new ListStore to the view, overwrites the old one automatically - theoretically
server.TreeView.set_model(server.ListStore)
# restore sorting order from previous refresh
self.set_sorting(server.ListStore, server)
# status field in server vbox in popwin
self.popwin.UpdateStatus(server)
except:
server.Error(sys.exc_info())
#self.popwin.VBox.hide_all()
#self.popwin.VBox.show_all()
if self.popwin.Window.get_properties("visible")[0] == True:
self.popwin.Resize()
# everything OK
if unknowns == 0 and warnings == 0 and criticals == 0 and unreachables == 0 and downs == 0 and self.status_ok is not False:
self.statusbar.statusbar_labeltext = '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_ok_background) + '" foreground="' + str(self.conf.color_ok_text) + '"> OK </span>'
self.statusbar.statusbar_labeltext_inverted = self.statusbar.statusbar_labeltext
self.statusbar.Label.set_markup(self.statusbar.statusbar_labeltext)
# fix size when loading with network errors
self.statusbar.Resize()
# if all is OK there is no need to pop up popwin so set self.showPopwin to False
self.popwin.showPopwin = False
#self.popwin.Close()
self.popwin.PopDown()
self.status_ok = True
# set systray icon to green aka OK
self.statusbar.SysTray.set_from_pixbuf(self.statusbar.SYSTRAY_ICONS["green"])
# switch notification off
self.NotificationOff()
else:
self.status_ok = False
# put text for label together
self.statusbar.statusbar_labeltext = self.statusbar.statusbar_labeltext_inverted = ""
if downs > 0:
if str(self.conf.long_display) == "True": downs = str(downs) + " DOWN"
self.statusbar.statusbar_labeltext = '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_down_background) + '" foreground="' + str(self.conf.color_down_text) + '"> ' + str(downs) + ' </span>'
self.statusbar.statusbar_labeltext_inverted = '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_down_text) + '" foreground="' + str(self.conf.color_down_background) + '"> ' + str(downs) + ' </span>'
if unreachables > 0:
if str(self.conf.long_display) == "True": unreachables = str(unreachables) + " UNREACHABLE"
self.statusbar.statusbar_labeltext = self.statusbar.statusbar_labeltext + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_unreachable_background) + '" foreground="' + str(self.conf.color_unreachable_text) + '"> ' + str(unreachables) + ' </span>'
self.statusbar.statusbar_labeltext_inverted = self.statusbar.statusbar_labeltext_inverted + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_unreachable_text) + '" foreground="' + str(self.conf.color_unreachable_background) + '"> ' + str(unreachables) + ' </span>'
if criticals > 0:
if str(self.conf.long_display) == "True": criticals = str(criticals) + " CRITICAL"
self.statusbar.statusbar_labeltext = self.statusbar.statusbar_labeltext + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_critical_background) + '" foreground="' + str(self.conf.color_critical_text) + '"> ' + str(criticals) + ' </span>'
self.statusbar.statusbar_labeltext_inverted = self.statusbar.statusbar_labeltext_inverted + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_critical_text) + '" foreground="' + str(self.conf.color_critical_background) + '"> ' + str(criticals) + ' </span>'
if unknowns > 0:
if str(self.conf.long_display) == "True": unknowns = str(unknowns) + " UNKNOWN"
self.statusbar.statusbar_labeltext = self.statusbar.statusbar_labeltext + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_unknown_background) + '" foreground="' + str(self.conf.color_unknown_text) + '"> ' + str(unknowns) + ' </span>'
self.statusbar.statusbar_labeltext_inverted = self.statusbar.statusbar_labeltext_inverted + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_unknown_text) + '" foreground="' + str(self.conf.color_unknown_background) + '"> ' + str(unknowns) + ' </span>'
if high > 0:
if str(self.conf.long_display) == "True": high = str(high) + " HIGH"
self.statusbar.statusbar_labeltext = self.statusbar.statusbar_labeltext + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_high_background) + '" foreground="' + str(self.conf.color_high_text) + '"> ' + str(high) + ' </span>'
self.statusbar.statusbar_labeltext_inverted = self.statusbar.statusbar_labeltext_inverted + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_average_text) + '" foreground="' + str(self.conf.color_high_background) + '"> ' + str(high) + ' </span>'
if average > 0:
if str(self.conf.long_display) == "True": average = str(average) + " AVERAGE"
self.statusbar.statusbar_labeltext = self.statusbar.statusbar_labeltext + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_average_background) + '" foreground="' + str(self.conf.color_average_text) + '"> ' + str(average) + ' </span>'
self.statusbar.statusbar_labeltext_inverted = self.statusbar.statusbar_labeltext_inverted + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_average_text) + '" foreground="' + str(self.conf.color_average_background) + '"> ' + str(average) + ' </span>'
if warnings > 0:
if str(self.conf.long_display) == "True": warnings = str(warnings) + " WARNING"
self.statusbar.statusbar_labeltext = self.statusbar.statusbar_labeltext + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_warning_background) + '" foreground="' + str(self.conf.color_warning_text) + '"> ' + str(warnings) + ' </span>'
self.statusbar.statusbar_labeltext_inverted = self.statusbar.statusbar_labeltext_inverted + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_warning_text) + '" foreground="' + str(self.conf.color_warning_background) + '"> ' + str(warnings) + ' </span>'
if information > 0:
if str(self.conf.long_display) == "True": information = str(information) + " INFORMATION"
self.statusbar.statusbar_labeltext = self.statusbar.statusbar_labeltext + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_information_background) + '" foreground="' + str(self.conf.color_information_text) + '"> ' + str(information) + ' </span>'
self.statusbar.statusbar_labeltext_inverted = self.statusbar.statusbar_labeltext_inverted + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_information_text) + '" foreground="' + str(self.conf.color_information_background) + '"> ' + str(information) + ' </span>'
# if connections fails at starting do not display OK - Debian bug #617490
if unknowns == 0 and warnings == 0 and average ==0 and information == 0 and high ==0 and criticals == 0 and unreachables == 0 and downs == 0 and self.status_ok is False:
if str(self.conf.long_display) == "True":
errors = "ERROR"
else:
errors = "ERR"
self.statusbar.statusbar_labeltext = self.statusbar.statusbar_labeltext + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_error_background) + '" foreground="' + str(self.conf.color_error_text) + '"> ' + str(errors) + ' </span>'
self.statusbar.statusbar_labeltext_inverted = self.statusbar.statusbar_labeltext_inverted + '<span size="' + str(self.fontsize) + '" background="' + str(self.conf.color_error_text) + '" foreground="' + str(self.conf.color_error_background) + '"> ' + str(errors) + ' </span>'
color = "error"
# put text into label in statusbar, only if not already flashing
if self.statusbar.Flashing == False:
self.statusbar.Label.set_markup(self.statusbar.statusbar_labeltext)
# Windows workaround for non-automatically-shrinking desktop statusbar
if str(self.conf.statusbar_floating) == "True":
self.statusbar.Resize()
# choose icon for systray - the worst case decides the shown color
if warnings > 0 or information >0: color = "yellow"
if unknowns > 0 or average >0: color = "orange"
if criticals > 0 or high >0: color = "red"
if unreachables > 0: color = "darkred"
if downs > 0: color = "black"
self.statusbar.SysTray.set_from_pixbuf(self.statusbar.SYSTRAY_ICONS[color])
# if there has been any status change notify user
# first find out which of all servers states is the worst similar to nagstamonObjects.GetStatus()
worst = 0
worst_status = "UP"
"""
the last worse state should be saved here and taken for
comparison to decide if keep warning if the respective
(and not yet existing) option is set
"""
for server in self.servers.values():
if not server.WorstStatus == "UP":
# switch server status back because it has been recognized
if server.States.index(server.WorstStatus) > worst:
worst_status = server.WorstStatus
# reset status of the server for only processing it once
server.WorstStatus = "UP"
if not worst_status == "UP" and str(self.conf.notification) == "True":
self.NotificationOn(status=worst_status)
# set self.showPopwin to True because there is something to show
self.popwin.showPopwin = True
# if only one monitor cannot be reached show popwin to inform about its trouble
for server in self.servers.values():
if server.status_description != "" or server.refresh_authentication == True:
self.status_ok = False
self.popwin.showPopwin = True
# try to fix vanishing statusbar
if str(self.conf.icon_in_systray) == "False":
self.statusbar.Raise()
# return False to get removed as gobject idle source
return False
def AcknowledgeDialogShow(self, server, host, service=None):
"""
create and show acknowledge_dialog from gtkbuilder file
"""
# set the gtkbuilder file
self.builderfile = self.Resources + os.sep + "acknowledge_dialog.ui"
self.acknowledge_xml = gtk.Builder()
self.acknowledge_xml.add_from_file(self.builderfile)
self.acknowledge_dialog = self.acknowledge_xml.get_object("acknowledge_dialog")
# connect with action
# only OK needs to be connected - if this action gets canceled nothing happens
# use connect_signals to assign methods to handlers
handlers_dict = { "button_ok_clicked": self.Acknowledge,
"button_acknowledge_settings_clicked": self.AcknowledgeDefaultSettings }
self.acknowledge_xml.connect_signals(handlers_dict, server)
# did not get it to work with glade so comments will be fired up this way when pressing return
self.acknowledge_xml.get_object("input_entry_author").connect("key-release-event", self._FocusJump, self.acknowledge_xml, "input_entry_comment")
self.acknowledge_xml.get_object("input_entry_comment").connect("key-release-event", self.AcknowledgeCommentReturn, server)
# if service is "" it must be a host
if service == "":
# set label for acknowledging a host
self.acknowledge_xml.get_object("input_label_host").set_text(host)
self.acknowledge_xml.get_object("label_service").hide()
self.acknowledge_xml.get_object("input_label_service").hide()
self.acknowledge_dialog.set_title("Acknowledge host")
else:
# set label for acknowledging a service on host
self.acknowledge_xml.get_object("input_label_host").set_text(host)
self.acknowledge_xml.get_object("input_label_service").set_text(service)
self.acknowledge_dialog.set_title("Acknowledge service")
# default flags of Nagios acknowledgement
self.acknowledge_xml.get_object("input_checkbutton_sticky_acknowledgement").set_active(eval(str(self.conf.defaults_acknowledge_sticky)))
self.acknowledge_xml.get_object("input_checkbutton_send_notification").set_active(eval(str(self.conf.defaults_acknowledge_send_notification)))
self.acknowledge_xml.get_object("input_checkbutton_persistent_comment").set_active(eval(str(self.conf.defaults_acknowledge_persistent_comment)))
self.acknowledge_xml.get_object("input_checkbutton_acknowledge_all_services").set_active(eval(str(self.conf.defaults_acknowledge_all_services)))
# default author + comment
self.acknowledge_xml.get_object("input_entry_author").set_text(server.username)
self.acknowledge_xml.get_object("input_entry_comment").set_text(self.conf.defaults_acknowledge_comment)
self.acknowledge_xml.get_object("input_entry_comment").grab_focus()
# show dialog
self.acknowledge_dialog.run()
self.acknowledge_dialog.destroy()
def AcknowledgeDefaultSettings(self, foo, bar):
"""
show settings with tab "defaults" as shortcut from Acknowledge dialog
"""
self.acknowledge_dialog.destroy()
settings=Settings(servers=self.servers, output=self, conf=self.conf, first_page="Defaults")
def AcknowledgeCommentReturn(self, widget, event, server):
"""
if Return key has been pressed in comment entry field interprete this as OK button being pressed
"""
# KP_Enter seems to be the code for return key of numeric key block
if gtk.gdk.keyval_name(event.keyval) in ["Return", "KP_Enter"]:
self.Acknowledge(server=server)
self.acknowledge_dialog.destroy()
def Acknowledge(self, widget=None, server=None):
"""
acknowledge miserable host/service
"""
# various parameters for the CGI request
host = self.acknowledge_xml.get_object("input_label_host").get_text()
service = self.acknowledge_xml.get_object("input_label_service").get_text()
author = self.acknowledge_xml.get_object("input_entry_author").get_text()
comment = self.acknowledge_xml.get_object("input_entry_comment").get_text()
acknowledge_all_services = self.acknowledge_xml.get_object("input_checkbutton_acknowledge_all_services").get_active()
sticky = self.acknowledge_xml.get_object("input_checkbutton_sticky_acknowledgement").get_active()
notify = self.acknowledge_xml.get_object("input_checkbutton_send_notification").get_active()
persistent = self.acknowledge_xml.get_object("input_checkbutton_persistent_comment").get_active()
# create a list of all service of selected host to acknowledge them all
all_services = list()
if acknowledge_all_services == True:
for i in server.nagitems_filtered["services"].values():
for s in i:
if s.host == host:
all_services.append(s.name)
# let thread execute POST request
acknowledge = Actions.Acknowledge(server=server, host=host,\
service=service, author=author, comment=comment, acknowledge_all_services=acknowledge_all_services,\
all_services=all_services, sticky=sticky, notify=notify, persistent=persistent)
acknowledge.start()
def DowntimeDialogShow(self, server, host, service=None):
"""
create and show downtime_dialog from gtkbuilder file
"""
# set the gtkbuilder file
self.builderfile = self.Resources + os.sep + "downtime_dialog.ui"
self.downtime_xml = gtk.Builder()
self.downtime_xml.add_from_file(self.builderfile)
self.downtime_dialog = self.downtime_xml.get_object("downtime_dialog")
# connect with action
# only OK needs to be connected - if this action gets canceled nothing happens
# use connect_signals to assign methods to handlers
handlers_dict = { "button_ok_clicked" : self.Downtime,
"button_downtime_settings_clicked" : self.DowntimeDefaultSettings }
self.downtime_xml.connect_signals(handlers_dict, server)
# focus jump chain - used to connect input fields in downtime dialog and access them via return key
chain = ["input_entry_start_time",
"input_entry_end_time",
"input_entry_author",
"input_entry_comment"]
for i in range(len(chain)-1):
self.downtime_xml.get_object(chain[i]).connect("key-release-event", self._FocusJump, self.downtime_xml, chain[i+1])
# if return key enterd in comment field see this as OK button pressed
self.downtime_xml.get_object("input_entry_comment").connect("key-release-event", self.DowntimeCommentReturn, server)
# if service is None it must be a host
if service == "":
# set label for acknowledging a host
self.downtime_xml.get_object("input_label_host").set_text(host)
self.downtime_xml.get_object("label_service").hide()
self.downtime_xml.get_object("input_label_service").hide()
self.downtime_dialog.set_title("Downtime for host")
else:
# set label for acknowledging a service on host
self.downtime_xml.get_object("input_label_host").set_text(host)
self.downtime_xml.get_object("input_label_service").set_text(service)
self.downtime_dialog.set_title("Downtime for service")
# get start_time and end_time externally from Actions.Downtime_get_start_end() for not mixing GUI and actions too much
start_time, end_time = Actions.Downtime_get_start_end(server=server, host=host)
self.downtime_xml.get_object("input_radiobutton_type_fixed").set_active(eval(str(self.conf.defaults_downtime_type_fixed)))
self.downtime_xml.get_object("input_radiobutton_type_flexible").set_active(eval(str(self.conf.defaults_downtime_type_flexible)))
# default author + comment
self.downtime_xml.get_object("input_entry_author").set_text(server.username)
self.downtime_xml.get_object("input_entry_comment").set_text(self.conf.defaults_downtime_comment)
self.downtime_xml.get_object("input_entry_comment").grab_focus()
# start and end time
self.downtime_xml.get_object("input_entry_start_time").set_text(start_time)
self.downtime_xml.get_object("input_entry_end_time").set_text(end_time)
# flexible downtime duration
self.downtime_xml.get_object("input_spinbutton_duration_hours").set_value(int(self.conf.defaults_downtime_duration_hours))
self.downtime_xml.get_object("input_spinbutton_duration_minutes").set_value(int(self.conf.defaults_downtime_duration_minutes))
# show dialog
self.downtime_dialog.run()
self.downtime_dialog.destroy()
def DowntimeDefaultSettings(self, foo, bar):
"""
show settings with tab "defaults" as shortcut from Downtime dialog
"""
self.downtime_dialog.destroy()
settings=Settings(servers=self.servers, output=self, conf=self.conf, first_page="Defaults")
def DowntimeCommentReturn(self, widget, event, server):
"""
if Return key has been pressed in comment entry field interprete this as OK button being pressed
"""
# KP_Enter seems to be the code for return key of numeric key block
if gtk.gdk.keyval_name(event.keyval) in ["Return", "KP_Enter"]:
self.Downtime(server=server)
self.downtime_dialog.destroy()
def Downtime(self, widget=None, server=None):
"""
schedule downtime for miserable host/service
"""
# various parameters for the CGI request
host = self.downtime_xml.get_object("input_label_host").get_text()
service = self.downtime_xml.get_object("input_label_service").get_text()
author = self.downtime_xml.get_object("input_entry_author").get_text()
comment = self.downtime_xml.get_object("input_entry_comment").get_text()
# start and end time
start_time = self.downtime_xml.get_object("input_entry_start_time").get_text()
end_time = self.downtime_xml.get_object("input_entry_end_time").get_text()
# type of downtime - fixed or flexible
if self.downtime_xml.get_object("input_radiobutton_type_fixed").get_active() == True: fixed = 1
else: fixed = 0
# duration of downtime if flexible
hours = self.downtime_xml.get_object("input_spinbutton_duration_hours").get_value()
minutes = self.downtime_xml.get_object("input_spinbutton_duration_minutes").get_value()
# execute POST request with cgi_data, in this case threaded
downtime = Actions.Downtime(server=server, host=host, service=service, author=author, comment=comment, fixed=fixed, start_time=start_time, end_time=end_time, hours=int(hours), minutes=int(minutes))
downtime.start()
def SubmitCheckResultDialogShow(self, server, host, service=None):
"""
create and show acknowledge_dialog from gtkbuilder file
"""
# set the gtkbuilder file
self.builderfile = self.Resources + os.sep + "submit_check_result_dialog.ui"
self.submitcheckresult_xml = gtk.Builder()
self.submitcheckresult_xml.add_from_file(self.builderfile)
self.submitcheckresult_dialog = self.submitcheckresult_xml.get_object("submit_check_result_dialog")
# connect with action
# only OK needs to be connected - if this action gets canceled nothing happens
# use connect_signals to assign methods to handlers
handlers_dict = { "button_ok_clicked" : self.SubmitCheckResultOK,\
"button_cancel_clicked": self.SubmitCheckResultCancel,\
"button_submit_check_result_settings_clicked" : self.SubmitCheckResultDefaultSettings}
self.submitcheckresult_xml.connect_signals(handlers_dict, server)
# focus jump chain - used to connect input fields in submit check result dialog and access them via return key
# server.SUBMIT_CHECK_RESULT_ARGS contains the valid arguments for this server type so we might use it here too
chain = server.SUBMIT_CHECK_RESULT_ARGS
for i in range(len(chain)-1):
self.submitcheckresult_xml.get_object("input_entry_" + chain[i]).connect("key-release-event", self._FocusJump, self.submitcheckresult_xml, "input_entry_" + chain[i+1])
# if return key entered in lastfield see this as OK button pressed
self.submitcheckresult_xml.get_object("input_entry_" + chain[-1]).connect("key-release-event", self.SubmitCheckResultCommentReturn, server)
# if service is "" it must be a host
if service == "":
# set label for submitting results to an host
self.submitcheckresult_xml.get_object("input_label_host").set_text(host)
self.submitcheckresult_xml.get_object("label_service").hide()
self.submitcheckresult_xml.get_object("input_label_service").hide()
self.submitcheckresult_dialog.set_title("Submit check result for host")
self.submitcheckresult_xml.get_object("label_service").hide()
self.submitcheckresult_xml.get_object("input_radiobutton_result_ok").hide()
self.submitcheckresult_xml.get_object("input_radiobutton_result_warning").hide()
self.submitcheckresult_xml.get_object("input_radiobutton_result_critical").hide()
self.submitcheckresult_xml.get_object("input_radiobutton_result_unknown").hide()
self.submitcheckresult_xml.get_object("input_radiobutton_result_up").set_active(True)
else:
# set label for submitting results to a service on host
self.submitcheckresult_xml.get_object("input_label_host").set_text(host)
self.submitcheckresult_xml.get_object("input_label_service").set_text(service)
self.submitcheckresult_dialog.set_title("Submit check result for service")
self.submitcheckresult_xml.get_object("input_radiobutton_result_unreachable").hide()
self.submitcheckresult_xml.get_object("input_radiobutton_result_up").hide()
self.submitcheckresult_xml.get_object("input_radiobutton_result_down").hide()
for i in server.SUBMIT_CHECK_RESULT_ARGS:
self.submitcheckresult_xml.get_object("label_" + i).show()
self.submitcheckresult_xml.get_object("input_entry_" + i).show()
self.submitcheckresult_xml.get_object("input_entry_comment").set_text(self.conf.defaults_submit_check_result_comment)
# show dialog
self.submitcheckresult_dialog.run()
def SubmitCheckResultDefaultSettings(self, foo, bar):
"""
show settings with tab "defaults" as shortcut from Submit Check Result dialog
"""
self.submitcheckresult_dialog.destroy()
settings=Settings(servers=self.servers, output=self, conf=self.conf, first_page="Defaults")
def SubmitCheckResultOK(self, widget=None, server=None):
"""
submit check result
"""
# various parameters for the CGI request
host = self.submitcheckresult_xml.get_object("input_label_host").get_text()
service = self.submitcheckresult_xml.get_object("input_label_service").get_text()
comment = self.submitcheckresult_xml.get_object("input_entry_comment").get_text()
check_output = self.submitcheckresult_xml.get_object("input_entry_check_output").get_text()
performance_data = self.submitcheckresult_xml.get_object("input_entry_performance_data").get_text()
# dummy default state
state = "ok"
for s in ["ok", "up", "warning", "critical", "unreachable", "unknown", "down"]:
if self.submitcheckresult_xml.get_object("input_radiobutton_result_" + s).get_active() == True:
state = s
break
if "check_output" in server.SUBMIT_CHECK_RESULT_ARGS and len(check_output) == 0:
self.Dialog(message="Submit check result needs a check output.")
else:
# let thread execute POST request
submit_check_result = Actions.SubmitCheckResult(server=server, host=host,\
service=service, comment=comment, check_output=check_output,\
performance_data=performance_data, state=state)
submit_check_result.start()
# only close dialog if input was correct
self.submitcheckresult_dialog.destroy()
def SubmitCheckResultCancel(self, widget, server):
self.submitcheckresult_dialog.destroy()
def SubmitCheckResultCommentReturn(self, widget, event, server):
"""
if Return key has been pressed in comment entry field interprete this as OK button being pressed
"""
# KP_Enter seems to be the code for return key of numeric key block
if gtk.gdk.keyval_name(event.keyval) in ["Return", "KP_Enter"]:
self.SubmitCheckResultOK(server=server)
self.submitcheckresult_dialog.destroy()
def AboutDialog(self):
"""
about nagstamon
"""
about = gtk.AboutDialog()
about.set_name(self.name)
about.set_version(self.version)
about.set_website(self.website)
about.set_copyright(self.copyright)
about.set_comments(self.comments)
about.set_authors(["Henri Wahl",\
" ",\
"Thank you very much for code",\
"contributions, patches, packaging,",\
"testing, hints and ideas:",\
" ",\
"Antoine Jacoutot",\
"Benoît Soenen",\
"Carl Chenet",\
"Emile Heitor ",\
"John Conroy",\
"Lars Michelsen",\
"M. Cigdem Cebe",\
"Mattias Ryrlén",\
"Michał Rzeszut",\
"Patrick Cernko",\
"Pawel Połewicz",\
"Robin Sonefors",\
"Sandro Tosi",\
"Thomas Gelf",\
"Tobias Scheerbaum",\
"Yannick Charton",\
" ",\
"...and those I forgot to mention but who helped a lot...",
" ",\
"Third party software used by Nagstamon",\
"under their respective license:",\
"BeautifulSoup - http://www.crummy.com/software/BeautifulSoup",\
"Pyinstaller - http://www.pyinstaller.org"])
# read LICENSE file
license = ""
try:
# try to find license file in resource directory
f = open(self.Resources + os.sep + "LICENSE", "r")
s = f.readlines()
f.close()
for line in s:
license += line
except:
license = "Nagstamon is licensed under GPL 2.0.\nYou should have got a LICENSE file distributed with nagstamon.\nGet it at http://www.gnu.org/licenses/gpl-2.0.txt."
about.set_license(license)
# use gobject.idle_add() to be thread safe
gobject.idle_add(self.AddGUILock, self.__class__.__name__)
#self.popwin.Close()
self.popwin.PopDown()
about.run()
# use gobject.idle_add() to be thread safe
gobject.idle_add(self.DeleteGUILock, self.__class__.__name__)
about.destroy()
def Dialog(self, type=gtk.MESSAGE_ERROR, message="", buttons=gtk.BUTTONS_CANCEL):
"""
versatile message dialog
"""
# close popwin to make sure the error dialog will not be covered by popwin
#self.popwin.Close()
self.popwin.PopDown()
dialog = gtk.MessageDialog(parent=None, flags=gtk.DIALOG_MODAL, type=type, buttons=buttons, message_format=str(message))
# gtk.Dialog.run() does a mini loop to wait
dialog.run()
dialog.destroy()
def CheckForNewVersionDialog(self, version_status=None, version=None):
"""
Show results of Settings.CheckForNewVersion()
"""
try:
# close popwin to make sure the error dialog will not be covered by popwin
#self.popwin.Close()
self.popwin.PopDown()
# if used version is latest version only inform about
if version_status == "latest":
dialog = gtk.MessageDialog(parent=None, flags=gtk.DIALOG_MODAL, type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_OK, \
message_format="You are already using the\nlatest version of Nagstamon.\n\nLatest version: %s" % (version))
dialog.run()
dialog.destroy()
# if used version is out of date offer downloading latest one
elif version_status == "out_of_date":
dialog = gtk.MessageDialog(parent=None, flags=gtk.DIALOG_MODAL, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_YES_NO, \
message_format="You are not using the latest version of Nagstamon.\n\nYour version:\t\t%s\nLatest version:\t%s\n\nDo you want to download the latest version?" % (self.version, version))
response = dialog.run()
if response == gtk.RESPONSE_YES:
Actions.OpenNagstamonDownload(output=self)
dialog.destroy()
except: