/
notify.py
1973 lines (1659 loc) · 80 KB
/
notify.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
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# ails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import pprint, urllib, select, subprocess, socket
# Please have a look at doc/Notifications.png:
#
# There are two types of contexts:
# 1. Raw contexts (purple)
# -> These come out from the monitoring core. They are not yet
# assinged to a certain plugin. In case of rule based notifictions
# they are not even assigned to a certain contact.
#
# 2. Plugin contexts (cyan)
# -> These already bear all information about the contact, the plugin
# to call and its parameters.
# .--Configuration-------------------------------------------------------.
# | ____ __ _ _ _ |
# | / ___|___ _ __ / _(_) __ _ _ _ _ __ __ _| |_(_) ___ _ __ |
# | | | / _ \| '_ \| |_| |/ _` | | | | '__/ _` | __| |/ _ \| '_ \ |
# | | |__| (_) | | | | _| | (_| | |_| | | | (_| | |_| | (_) | | | | |
# | \____\___/|_| |_|_| |_|\__, |\__,_|_| \__,_|\__|_|\___/|_| |_| |
# | |___/ |
# +----------------------------------------------------------------------+
# | Default values of global configuration variables. |
# '----------------------------------------------------------------------'
# Default settings
notification_logdir = var_dir + "/notify"
notification_spooldir = var_dir + "/notify/spool"
notification_bulkdir = var_dir + "/notify/bulk"
notification_core_log = var_dir + "/notify/nagios.log" # Fallback for history if no CMC running
notification_log = log_dir + "/notify.log"
notification_logging = 1
notification_backlog = 10 # keep the last 10 notification contexts for reference
# Settings for new rule based notifications
enable_rulebased_notifications = False
notification_fallback_email = ""
notification_rules = []
notification_bulk_interval = 10 # Check every 10 seconds for ripe bulks
# Notification Spooling
notification_spooling = False
notification_spool_to = None
notification_log_template = \
u"$CONTACTNAME$ - $NOTIFICATIONTYPE$ - " \
u"$HOSTNAME$ $HOSTSTATE$ - " \
u"$SERVICEDESC$ $SERVICESTATE$ "
notification_mail_command = u"mail -s '$SUBJECT$' '$CONTACTEMAIL$'"
notification_host_subject = u"Check_MK: $HOSTNAME$ - $NOTIFICATIONTYPE$"
notification_service_subject = u"Check_MK: $HOSTNAME$/$SERVICEDESC$ $NOTIFICATIONTYPE$"
notification_common_body = u"""Host: $HOSTNAME$
Alias: $HOSTALIAS$
Address: $HOSTADDRESS$
"""
notification_host_body = u"""State: $LASTHOSTSTATE$ -> $HOSTSTATE$ ($NOTIFICATIONTYPE$)
Command: $HOSTCHECKCOMMAND$
Output: $HOSTOUTPUT$
Perfdata: $HOSTPERFDATA$
$LONGHOSTOUTPUT$
"""
notification_service_body = u"""Service: $SERVICEDESC$
State: $LASTSERVICESTATE$ -> $SERVICESTATE$ ($NOTIFICATIONTYPE$)
Command: $SERVICECHECKCOMMAND$
Output: $SERVICEOUTPUT$
Perfdata: $SERVICEPERFDATA$
$LONGSERVICEOUTPUT$
"""
#.
# .--Main----------------------------------------------------------------.
# | __ __ _ |
# | | \/ | __ _(_)_ __ |
# | | |\/| |/ _` | | '_ \ |
# | | | | | (_| | | | | | |
# | |_| |_|\__,_|_|_| |_| |
# | |
# +----------------------------------------------------------------------+
# | Main code entry point. |
# '----------------------------------------------------------------------'
def notify_usage():
sys.stderr.write("""Usage: check_mk --notify [--keepalive]
check_mk --notify spoolfile <filename>
Normally the notify module is called without arguments to send real
notification. But there are situations where this module is called with
COMMANDS to e.g. support development of notification plugins.
Available commands:
spoolfile <filename> Reads the given spoolfile and creates a
notification out of its data
stdin Read one notification context from stdin instead
of taking variables from environment
replay N Uses the N'th recent notification from the backlog
and sends it again, counting from 0.
send-bulks Send out ripe bulk notifications
""")
# Main function called by cmk --notify. It either starts the
# keepalive mode (used by CMC), sends out one notifications from
# several possible sources or sends out all ripe bulk notifications.
def do_notify(args):
global notify_mode, notification_logging
if notification_logging == 0:
notification_logging = 1 # transform deprecated value 0 to 1
try:
if not os.path.exists(notification_logdir):
os.makedirs(notification_logdir)
if not os.path.exists(notification_spooldir):
os.makedirs(notification_spooldir)
notify_mode = 'notify'
if args:
notify_mode = args[0]
if notify_mode not in [ 'stdin', 'spoolfile', 'replay', 'send-bulks' ]:
sys.stderr.write("ERROR: Invalid call to check_mk --notify.\n\n")
notify_usage()
sys.exit(1)
if len(args) != 2 and notify_mode not in [ "stdin", "replay", "send-bulks" ]:
sys.stderr.write("ERROR: need an argument to --notify %s.\n\n" % notify_mode)
sys.exit(1)
elif notify_mode == 'spoolfile':
filename = args[1]
elif notify_mode == 'replay':
try:
replay_nr = int(args[1])
except:
replay_nr = 0
# If the notify_mode is set to 'spoolfile' we try to parse the given spoolfile
# This spoolfile contains a python dictionary
# { context: { Dictionary of environment variables }, plugin: "Plugin name" }
# Any problems while reading the spoolfile results in returning 2
# -> mknotifyd deletes this file
if notify_mode == "spoolfile":
return handle_spoolfile(filename)
elif opt_keepalive:
notify_keepalive()
elif notify_mode == 'replay':
raw_context = raw_context_from_backlog(replay_nr)
notify_notify(raw_context)
elif notify_mode == 'stdin':
notify_notify(raw_context_from_stdin())
elif notify_mode == "send-bulks":
send_ripe_bulks()
else:
notify_notify(raw_context_from_env())
except Exception, e:
crash_dir = var_dir + "/notify"
if not os.path.exists(crash_dir):
os.makedirs(crash_dir)
file(crash_dir + "/crash.log", "a").write("CRASH (%s):\n%s\n" %
(time.strftime("%Y-%m-%d %H:%M:%S"), format_exception()))
# This function processes one raw notification and decides wether it
# should be spooled or not. In the latter cased a local delivery
# is being done.
def notify_notify(raw_context, analyse=False):
if not analyse:
store_notification_backlog(raw_context)
notify_log("----------------------------------------------------------------------")
if analyse:
notify_log("Analysing notification context with %s variables" % len(raw_context))
else:
notify_log("Got raw notification context with %s variables" % len(raw_context))
# Add some further variable for the conveniance of the plugins
if notification_logging >= 2:
encoded_context = dict(raw_context.items())
convert_context_to_unicode(encoded_context)
notify_log("Raw notification context:\n"
+ "\n".join([" %s=%s" % v for v in sorted(encoded_context.items())]))
raw_keys = list(raw_context.keys())
try:
complete_raw_context(raw_context)
except Exception, e:
notify_log("Error on completing raw context: %s" % e)
if notification_logging >= 2:
notify_log("Computed variables:\n"
+ "\n".join(sorted([" %s=%s" % (k, raw_context[k]) for k in raw_context if k not in raw_keys])))
# Spool notification to remote host, if this is enabled
if notification_spool_to:
remote_host, tcp_port, also_local = notification_spool_to
target_site = "%s:%s" % (remote_host, tcp_port)
create_spoolfile({"context": raw_context, "forward": target_site})
if not also_local:
return
return locally_deliver_raw_context(raw_context, analyse=analyse)
# Here we decide which notification implementation we are using.
# Hopefully we can drop a couple of them some day
# 1. Rule Based Notifiations (since 1.2.5i1)
# 2. Flexible Notifications (since 1.2.2)
# 3. Plain email notification (refer to git log if you are really interested)
def locally_deliver_raw_context(raw_context, analyse=False):
contactname = raw_context.get("CONTACTNAME")
try:
# If rule based notifications are enabled then the Micro Core does not set the
# variable CONTACTNAME. In the other cores the CONTACTNAME is being set to
# check-mk-notify.
# We do we not simply check the config variable enable_rulebased_notifications?
# -> Because the core needs are restart in order to reflect this while the
# notification mode of Check_MK not. There are thus situations where the
# setting of the core is different from our global variable. The core must
# have precedence in this situation!
if not contactname or contactname == "check-mk-notify":
# 1. RULE BASE NOTIFICATIONS
notify_log("Preparing rule based notifications")
return notify_rulebased(raw_context, analyse=analyse)
if analyse:
return # Analysis only possible when rule based notifications are enabled
# Now fetch all configuration about that contact (it needs to be configure via
# Check_MK for that purpose). If we do not know that contact then we cannot use
# flexible notifications even if they are enabled.
contact = contacts.get(contactname)
if contact.get("disable_notifications", False):
notify_log("Notifications for %s are disabled in personal settings. Skipping." % contactname)
return
# Get notification settings for the contact in question - if available.
if contact:
method = contact.get("notification_method", "email")
else:
method = "email"
if type(method) == tuple and method[0] == 'flexible':
# 2. FLEXIBLE NOTIFICATIONS
notify_log("Preparing flexible notifications for %s" % contactname)
notify_flexible(raw_context, method[1])
else:
# 3. PLAIN EMAIL NOTIFICATION
notify_log("Preparing plain email notifications for %s" % contactname)
notify_plain_email(raw_context)
except Exception, e:
if opt_debug:
raise
notify_log("ERROR: %s\n%s" % (e, format_exception()))
def notification_replay_backlog(nr):
global notify_mode
notify_mode = "replay"
raw_context = raw_context_from_backlog(nr)
notify_notify(raw_context)
def notification_analyse_backlog(nr):
global notify_mode
notify_mode = "replay"
raw_context = raw_context_from_backlog(nr)
return notify_notify(raw_context, analyse=True)
#.
# .--Keepalive-Mode (Used by CMC)----------------------------------------.
# | _ __ _ _ |
# | | |/ /___ ___ _ __ __ _| (_)_ _____ |
# | | ' // _ \/ _ \ '_ \ / _` | | \ \ / / _ \ |
# | | . \ __/ __/ |_) | (_| | | |\ V / __/ |
# | |_|\_\___|\___| .__/ \__,_|_|_| \_/ \___| |
# | |_| |
# +----------------------------------------------------------------------+
# | Implementation of cmk --notify --keepalive, which is being used |
# | by the Micro Core. |
# '----------------------------------------------------------------------'
def notify_keepalive():
last_config_timestamp = config_timestamp()
# Send signal that we are ready to receive the next notification, but
# not after a config-reload-restart (see below)
if os.getenv("CMK_NOTIFY_RESTART") != "1":
notify_log("Starting in keepalive mode with PID %d" % os.getpid())
sys.stdout.write("*")
sys.stdout.flush()
else:
notify_log("We are back after a restart.")
while True:
try:
# Invalidate timeperiod cache
global g_inactive_timerperiods
g_inactive_timerperiods = None
# If the configuration has changed, we do a restart. But we do
# this check just before the next notification arrives. We must
# *not* read data from stdin, just peek! There is still one
# problem: when restarting we must *not* send the initial '*'
# byte, because that must be not no sooner then the notification
# has been sent. We do this by setting the environment variable
# CMK_NOTIFY_RESTART=1
if notify_data_available():
if last_config_timestamp != config_timestamp():
notify_log("Configuration has changed. Restarting myself.")
os.putenv("CMK_NOTIFY_RESTART", "1")
os.execvp("cmk", sys.argv)
data = ""
while not data.endswith("\n\n"):
try:
new_data = ""
new_data = os.read(0, 32768)
except IOError, e:
new_data = ""
except Exception, e:
if opt_debug:
raise
notify_log("Cannot read data from CMC: %s" % e)
if not new_data:
notify_log("CMC has closed the connection. Shutting down.")
sys.exit(0) # closed stdin, this is
data += new_data
try:
context = raw_context_from_string(data.rstrip('\n'))
notify_notify(context)
except Exception, e:
if opt_debug:
raise
notify_log("ERROR %s\n%s" % (e, format_exception()))
# Signal that we are ready for the next notification
sys.stdout.write("*")
sys.stdout.flush()
# Fix vor Python 2.4:
except SystemExit, e:
sys.exit(e)
except Exception, e:
if opt_debug:
raise
notify_log("ERROR %s\n%s" % (e, format_exception()))
send_ripe_bulks()
def notify_data_available():
readable, writeable, exceptionable = select.select([0], [], [], notification_bulk_interval)
return not not readable
#.
# .--Rule-Based-Notifications--------------------------------------------.
# | ____ _ _ _ |
# | | _ \ _ _| | ___| |__ __ _ ___ ___ __| | |
# | | |_) | | | | |/ _ \ '_ \ / _` / __|/ _ \/ _` | |
# | | _ <| |_| | | __/ |_) | (_| \__ \ __/ (_| | |
# | |_| \_\\__,_|_|\___|_.__/ \__,_|___/\___|\__,_| |
# | |
# +----------------------------------------------------------------------+
# | Logic for rule based notifications |
# '----------------------------------------------------------------------'
def notify_rulebased(raw_context, analyse=False):
# First step: go through all rules and construct our table of
# notification plugins to call. This is a dict from (user, plugin) to
# a pair if (locked, parameters). If locked is True, then a user
# cannot cancel this notification via his personal notification rules.
# Example:
# notifications = {
# ( "hh", "email" ) : ( False, [] ),
# ( "hh", "sms" ) : ( True, [ "0171737337", "bar" ] ),
# }
notifications = {}
num_rule_matches = 0
rule_info = []
for rule in notification_rules + user_notification_rules():
if "contact" in rule:
notify_log("User %s's rule '%s'..." % (rule["contact"], rule["description"]))
else:
notify_log("Global rule '%s'..." % rule["description"])
why_not = rbn_match_rule(rule, raw_context) # also checks disabling
if why_not:
notify_log(" -> does not match: %s" % why_not)
rule_info.append(("miss", rule, why_not))
else:
notify_log(" -> matches!")
num_rule_matches += 1
contacts = rbn_rule_contacts(rule, raw_context)
# Handle old-style and new-style rules
if "notify_method" in rule: # old-style
plugin = rule["notify_plugin"]
plugin_parameters = rule["notify_method"] # None: do cancel, [ str ]: plugin parameters
else:
plugin, plugin_parameters = rule["notify_plugin"]
bulk = rule.get("bulk")
if plugin_parameters == None: # cancelling
for contact in contacts:
key = contact, plugin
if key in notifications:
locked, plugin_parameters, bulk = notifications[key]
if locked and "contact" in rule:
notify_log(" - cannot cancel notification of %s via %s: it is locked" % key)
else:
notify_log(" - cancelling notification of %s via %s" % key)
del notifications[key]
else:
final_parameters = rbn_finalize_plugin_parameters(raw_context["HOSTNAME"], plugin, plugin_parameters)
for contact in contacts:
key = contact, plugin
plugintxt = plugin or "plain email"
if key in notifications:
locked, previous_parameters, old_bulk = notifications[key]
if locked and "contact" in rule:
notify_log(" - cannot modify notification of %s via %s: it is locked" % (contact, plugintxt))
continue
notify_log(" - modifying notification of %s via %s" % (contact, plugintxt))
else:
notify_log(" - adding notification of %s via %s" % (contact, plugintxt))
notifications[key] = ( not rule.get("allow_disable"), final_parameters, bulk )
rule_info.append(("match", rule, ""))
plugin_info = []
if not notifications:
if num_rule_matches:
notify_log("%d rules matched, but no notification has been created." % num_rule_matches)
else:
if notification_fallback_email and not analyse:
notify_log("No rule matched, falling back to email to %s" % notification_fallback_email)
plugin_context = create_plugin_context(raw_context, [])
contact = rbn_fake_email_contact(notification_fallback_email)
rbn_add_contact_information(plugin_context, contact)
notify_via_email(plugin_context)
else:
# Now do the actual notifications
notify_log("Executing %d notifications:" % len(notifications))
entries = notifications.items()
entries.sort()
for (contact, plugin), (locked, params, bulk) in entries:
if analyse:
verb = "would notify"
else:
verb = "notifying"
notify_log(" * %s %s via %s, parameters: %s, bulk: %s" % (
verb, contact, (plugin or "plain email"), params and ", ".join(params) or "(no parameters)",
bulk and "yes" or "no"))
plugin_info.append((contact, plugin, params, bulk)) # for analysis
try:
plugin_context = create_plugin_context(raw_context, params)
rbn_add_contact_information(plugin_context, contact)
if not analyse:
if bulk:
do_bulk_notify(contact, plugin, params, plugin_context, bulk)
elif notification_spooling:
create_spoolfile({"context": plugin_context, "plugin": plugin})
else:
call_notification_script(plugin, plugin_context)
except Exception, e:
if opt_debug:
raise
fe = format_exception()
notify_log(" ERROR: %s" % e)
notify_log(fe)
analysis_info = rule_info, plugin_info
return analysis_info
def rbn_finalize_plugin_parameters(hostname, plugin, rule_parameters):
# Right now we are only able to finalize notification plugins with dict parameters..
if type(rule_parameters) == dict:
parameters = host_extra_conf_merged(hostname, notification_parameters.get(plugin, []))
parameters.update(rule_parameters)
return parameters
else:
return rule_parameters
def add_rulebased_macros(raw_context):
# For the rule based notifications we need the list of contacts
# an object has. The CMC does send this in the macro "CONTACTS"
if "CONTACTS" not in raw_context:
raw_context["CONTACTS"] = livestatus_fetch_contacts(raw_context["HOSTNAME"], raw_context.get("SERVICEDESC"))
# Add a pseudo contact name. This is needed for the correct creation
# of spool files. Spool files are created on a per-contact-base, as in classical
# notifications the core sends out one individual notification per contact.
# In the case of rule based notifications we do not make distinctions between
# the various contacts.
raw_context["CONTACTNAME"] = "check-mk-notify"
# Create a table of all user specific notification rules. Important:
# create deterministic order, so that rule analyses can depend on
# rule indices
def user_notification_rules():
user_rules = []
contactnames = contacts.keys()
contactnames.sort()
for contactname in contactnames:
contact = contacts[contactname]
for rule in contact.get("notification_rules", []):
# Save the owner of the rule for later debugging
rule["contact"] = contactname
# We assume that the "contact_..." entries in the
# rule are allowed and only contain one entry of the
# type "contact_users" : [ contactname ]. This
# is handled by WATO. Contact specific rules are a
# WATO-only feature anyway...
user_rules.append(rule)
notify_log("Found %d user specific rules" % len(user_rules))
return user_rules
def rbn_fake_email_contact(email):
return {
"name" : email,
"alias" : "Explicit email adress " + email,
"email" : email,
"pager" : "",
}
def rbn_add_contact_information(plugin_context, contact):
if type(contact) == dict:
for what in [ "name", "alias", "email", "pager" ]:
plugin_context["CONTACT" + what.upper()] = contact.get(what, "")
for key in contact.keys():
if key[0] == '_':
plugin_context["CONTACT" + key.upper()] = unicode(contact[key])
else:
if contact.startswith("mailto:"): # Fake contact
contact_dict = {
"name" : contact[7:],
"alias" : "Email address " + contact,
"email" : contact[7:],
"pager" : "" }
else:
contact_dict = contacts.get(contact, { "alias" : contact })
contact_dict["name"] = contact
rbn_add_contact_information(plugin_context, contact_dict)
def livestatus_fetch_contacts(host, service):
try:
if service:
query = "GET services\nFilter: host_name = %s\nFilter: service_description = %s\nColumns: contacts\n" % (
host, service)
else:
query = "GET hosts\nFilter: host_name = %s\nColumns: contacts\n" % host
commasepped = livestatus_fetch_query(query).strip()
aslist = commasepped.split(",")
if "check-mk-notify" in aslist: # Remove artifical contact used for rule based notifications
aslist.remove("check-mk-notify")
return ",".join(aslist)
except:
if opt_debug:
raise
return "" # We must allow notifications without Livestatus access
def rbn_match_rule(rule, context):
if rule.get("disabled"):
return "This rule is disabled"
return \
rbn_match_folder(rule, context) or \
rbn_match_hosttags(rule, context) or \
rbn_match_hostgroups(rule, context) or \
rbn_match_servicegroups(rule, context) or \
rbn_match_contactgroups(rule, context) or \
rbn_match_hosts(rule, context) or \
rbn_match_exclude_hosts(rule, context) or \
rbn_match_services(rule, context) or \
rbn_match_exclude_services(rule, context) or \
rbn_match_plugin_output(rule, context) or \
rbn_match_checktype(rule, context) or \
rbn_match_timeperiod(rule) or \
rbn_match_escalation(rule, context) or \
rbn_match_escalation_throtte(rule, context) or \
rbn_match_servicelevel(rule, context) or \
rbn_match_host_event(rule, context) or \
rbn_match_service_event(rule, context) or \
rbn_match_event_console(rule, context)
def rbn_match_folder(rule, context):
if "match_folder" in rule:
mustfolder = rule["match_folder"]
mustpath = mustfolder.split("/")
hasfolder = None
for tag in context.get("HOSTTAGS", "").split():
if tag.startswith("/wato/"):
hasfolder = tag[6:].rstrip("/")
haspath = hasfolder.split("/")
if mustpath == ["",]:
return # Match is on main folder, always OK
while mustpath:
if not haspath or mustpath[0] != haspath[0]:
return "The rule requires WATO folder '%s', but the host is in '%s'" % (
mustfolder, hasfolder)
mustpath = mustpath[1:]
haspath = haspath[1:]
if hasfolder == None:
return "The host is not managed via WATO, but the rule requires a WATO folder"
def rbn_match_hosttags(rule, context):
required = rule.get("match_hosttags")
if required:
tags = context.get("HOSTTAGS", "").split()
if not hosttags_match_taglist(tags, required):
return "The host's tags %s do not match the required tags %s" % (
"|".join(tags), "|".join(required))
def rbn_match_servicegroups(rule, context):
if context["WHAT"] != "SERVICE":
return
required_groups = rule.get("match_servicegroups")
if required_groups != None:
sgn = context.get("SERVICEGROUPNAMES")
if sgn == None:
return "No information about service groups is in the context, but service " \
"must be in group %s" % ( " or ".join(required_groups))
if sgn:
servicegroups = sgn.split(",")
else:
return "The service is in no group, but %s is required" % (
" or ".join(required_groups))
for group in required_groups:
if group in servicegroups:
return
return "The service is only in the groups %s, but %s is required" % (
sgn, " or ".join(required_groups))
def rbn_match_contactgroups(rule, context):
required_groups = rule.get("match_contactgroups")
if context["WHAT"] == "SERVICE":
cgn = context.get("SERVICECONTACTGROUPNAMES")
else:
cgn = context.get("HOSTCONTACTGROUPNAMES")
if required_groups != None:
if cgn == None:
notify_log("Warning: No information about contact groups in the context. " \
"Seams that you don't use the Check_MK Microcore. ")
return
if cgn:
contactgroups = cgn.split(",")
else:
return "The object is in no group, but %s is required" % (
" or ".join(required_groups))
for group in required_groups:
if group in contactgroups:
return
return "The object is only in the groups %s, but %s is required" % (
cgn, " or ".join(required_groups))
def rbn_match_hostgroups(rule, context):
required_groups = rule.get("match_hostgroups")
if required_groups != None:
hgn = context.get("HOSTGROUPNAMES")
if hgn == None:
return "No information about host groups is in the context, but host " \
"must be in group %s" % ( " or ".join(required_groups))
if hgn:
hostgroups = hgn.split(",")
else:
return "The host is in no group, but %s is required" % (
" or ".join(required_groups))
for group in required_groups:
if group in hostgroups:
return
return "The host is only in the groups %s, but %s is required" % (
hgn, " or ".join(required_groups))
def rbn_match_hosts(rule, context):
if "match_hosts" in rule:
hostlist = rule["match_hosts"]
if context["HOSTNAME"] not in hostlist:
return "The host's name '%s' is not on the list of allowed hosts (%s)" % (
context["HOSTNAME"], ", ".join(hostlist))
def rbn_match_exclude_hosts(rule, context):
if context["HOSTNAME"] in rule.get("match_exclude_hosts", []):
return "The host's name '%s' is on the list of excluded hosts" % context["HOSTNAME"]
def rbn_match_services(rule, context):
if "match_services" in rule:
if context["WHAT"] != "SERVICE":
return "The rule specifies a list of services, but this is a host notification."
servicelist = rule["match_services"]
service = context["SERVICEDESC"]
if not in_extraconf_servicelist(servicelist, service):
return "The service's description '%s' dows not match by the list of " \
"allowed services (%s)" % (service, ", ".join(servicelist))
def rbn_match_exclude_services(rule, context):
if context["WHAT"] != "SERVICE":
return
excludelist = rule.get("match_exclude_services", [])
service = context["SERVICEDESC"]
if in_extraconf_servicelist(excludelist, service):
return "The service's description '%s' matches the list of excluded services" \
% context["SERVICEDESC"]
def rbn_match_plugin_output(rule, context):
if "match_plugin_output" in rule:
r = regex(rule["match_plugin_output"])
if context["WHAT"] == "SERVICE":
output = context["SERVICEOUTPUT"]
else:
output = context["HOSTOUTPUT"]
if not r.search(output):
return "The expression '%s' cannot be found in the plugin output '%s'" % \
(rule["match_plugin_output"], output)
def rbn_match_checktype(rule, context):
if "match_checktype" in rule:
if context["WHAT"] != "SERVICE":
return "The rule specifies a list of Check_MK plugins, but this is a host notification."
command = context["SERVICECHECKCOMMAND"]
if not command.startswith("check_mk-"):
return "The rule specified a list of Check_MK plugins, but his is no Check_MK service."
plugin = command[9:]
allowed = rule["match_checktype"]
if plugin not in allowed:
return "The Check_MK plugin '%s' is not on the list of allowed plugins (%s)" % \
(plugin, ", ".join(allowed))
def rbn_match_timeperiod(rule):
if "match_timeperiod" in rule:
timeperiod = rule["match_timeperiod"]
if timeperiod != "24X7" and not check_timeperiod(timeperiod):
return "The timeperiod '%s' is currently not active." % timeperiod
def rbn_match_escalation(rule, context):
if "match_escalation" in rule:
from_number, to_number = rule["match_escalation"]
if context["WHAT"] == "HOST":
notification_number = int(context.get("HOSTNOTIFICATIONNUMBER", 1))
else:
notification_number = int(context.get("SERVICENOTIFICATIONNUMBER", 1))
if notification_number < from_number or notification_number > to_number:
return "The notification number %d does not lie in range %d ... %d" % (
notification_number, from_number, to_number)
def rbn_match_escalation_throtte(rule, context):
if "match_escalation_throttle" in rule:
from_number, rate = rule["match_escalation_throttle"]
if context["WHAT"] == "HOST":
notification_number = int(context.get("HOSTNOTIFICATIONNUMBER", 1))
else:
notification_number = int(context.get("SERVICENOTIFICATIONNUMBER", 1))
if notification_number <= from_number:
return
if (notification_number - from_number) % rate != 0:
return "This notification is being skipped due to throttling. The next number will be %d" % \
(notification_number + rate - ((notification_number - from_number) % rate))
def rbn_match_servicelevel(rule, context):
if "match_sl" in rule:
from_sl, to_sl = rule["match_sl"]
if context['WHAT'] == "SERVICE" and context.get('SVC_SL','').isdigit():
sl = saveint(context.get('SVC_SL'))
else:
sl = saveint(context.get('HOST_SL'))
if sl < from_sl or sl > to_sl:
return "The service level %d is not between %d and %d." % (sl, from_sl, to_sl)
def rbn_match_host_event(rule, context):
if "match_host_event" in rule:
if context["WHAT"] != "HOST":
if "match_service_event" not in rule:
return "This is a service notification, but the rule just matches host events"
else:
return # Let this be handled by match_service_event
allowed_events = rule["match_host_event"]
state = context["HOSTSTATE"]
last_state = context["PREVIOUSHOSTHARDSTATE"]
events = { "UP" : 'r', "DOWN" : 'd', "UNREACHABLE" : 'u' }
return rbn_match_event(context, state, last_state, events, allowed_events)
def rbn_match_service_event(rule, context):
if "match_service_event" in rule:
if context["WHAT"] != "SERVICE":
if "match_host_event" not in rule:
return "This is a host notification, but the rule just matches service events"
else:
return # Let this be handled by match_host_event
allowed_events = rule["match_service_event"]
state = context["SERVICESTATE"]
last_state = context["PREVIOUSSERVICEHARDSTATE"]
events = { "OK" : 'r', "WARNING" : 'w', "CRITICAL" : 'c', "UNKNOWN" : 'u' }
return rbn_match_event(context, state, last_state, events, allowed_events)
def rbn_match_event(context, state, last_state, events, allowed_events):
notification_type = context["NOTIFICATIONTYPE"]
if notification_type == "RECOVERY":
event = events.get(last_state, '?') + 'r'
elif notification_type in [ "FLAPPINGSTART", "FLAPPINGSTOP", "FLAPPINGDISABLED" ]:
event = 'f'
elif notification_type in [ "DOWNTIMESTART", "DOWNTIMEEND", "DOWNTIMECANCELLED"]:
event = 's'
elif notification_type == "ACKNOWLEDGEMENT":
event = 'x'
else:
event = events.get(last_state, '?') + events.get(state, '?')
notify_log("Event type is %s" % event)
# Now go through the allowed events. Handle '?' has matching all types!
for allowed in allowed_events:
if event == allowed or \
event[0] == '?' and event[1] == allowed[1]:
return
return "Event type '%s' not handled by this rule. Allowed are: %s" % (
event, ", ".join(allowed_events))
def rbn_rule_contacts(rule, context):
the_contacts = set([])
if rule.get("contact_object"):
the_contacts.update(rbn_object_contacts(context))
if rule.get("contact_all"):
the_contacts.update(rbn_all_contacts())
if rule.get("contact_all_with_email"):
the_contacts.update(rbn_all_contacts(with_email=True))
if "contact_users" in rule:
the_contacts.update(rule["contact_users"])
if "contact_groups" in rule:
the_contacts.update(rbn_groups_contacts(rule["contact_groups"]))
if "contact_emails" in rule:
the_contacts.update(rbn_emails_contacts(rule["contact_emails"]))
all_enabled = []
for contactname in the_contacts:
contact = contacts.get(contactname)
if contact and contact.get("disable_notifications", False):
notify_log(" - skipping contact %s: he/she has disabled notifications" % contactname)
else:
all_enabled.append(contactname)
return all_enabled
def rbn_match_event_console(rule, context):
if "match_ec" in rule:
match_ec = rule["match_ec"]
is_ec_notification = "EC_ID" in context
if match_ec == False and is_ec_notification:
return "Notification has been created by the Event Console."
elif match_ec != False and not is_ec_notification:
return "Notification has not been created by the Event Console."
if match_ec != False:
# Match Event Console rule ID
if "match_rule_id" in match_ec and context["EC_RULE_ID"] != match_ec["match_rule_id"]:
return "EC Event has rule ID '%s', but '%s' is required" % (
context["EC_RULE_ID"], match_ec["match_rule_id"])
# Match syslog priority of event
if "match_priority" in match_ec:
prio_from, prio_to = match_ec["match_priority"]
if prio_from > prio_to:
prio_to, prio_from = prio_from, prio_to
p = int(context["EC_PRIORITY"])
if p < prio_from or p > prio_to:
return "Event has priority %s, but matched range is %s .. %s" % (
p, prio_from, prio_to)
# Match syslog facility of event
if "match_facility" in match_ec:
if match_ec["match_facility"] != int(context["EC_FACILITY"]):
return "Wrong syslog facility %s, required is %s" % (context["EC_FACILITY"], match_ec["match_facility"])
# Match event comment
if "match_comment" in match_ec:
r = regex(match_ec["match_comment"])
if not r.search(context["EC_COMMENT"]):
return "The event comment '%s' does not match the regular expression '%s'" % (
context["EC_COMMENT"], match_ec["match_comment"])
def rbn_object_contacts(context):
commasepped = context.get("CONTACTS")
if commasepped:
return commasepped.split(",")
else:
return []
def rbn_all_contacts(with_email=None):
if not with_email:
return contacts.keys() # We have that via our main.mk contact definitions!
else:
return [
contact_id
for (contact_id, contact)
in contacts.items()
if contact.get("email")]
def rbn_groups_contacts(groups):
if not groups:
return {}
contacts = set([])
query = "GET contactgroups\nColumns: members\n"
for group in groups:
query += "Filter: name = %s\n" % group
query += "Or: %d\n" % len(groups)
response = livestatus_fetch_query(query)
for line in response.splitlines():
line = line.strip()