Commit 42b7c6ff authored by root's avatar root
Browse files

Added service to existing script to make maintainace easier

Clean up un-needed files
parent 95f0cd99
# sudo may be needed if the formating it stuffed up when run as icinga user
object NotificationCommand "enhanced-mail-host-notification" {
import "plugin-notification-command"
command = [ SysconfDir + "/icinga2/scripts/enhanced-mail-host-notification.py" ]
command = [ SysconfDir + "/icinga2/scripts/enhanced-mail-notification.py" ]
env = {
NOTIFICATIONTYPE = "$notification.type$"
HOSTALIAS = "$host.display_name$"
HOSTDISPLAYNAME = "$host.display_name$"
HOSTADDRESS = "$address$"
HOSTSTATE = "$host.state$"
LONGDATETIME = "$icinga.long_date_time$"
HOSTOUTPUT = "$host.output$"
SERVICEDISPLAYNAME = "$host.check_command$"
LONGDATETIME = "$icinga.long_date_time$"
NOTIFICATIONAUTHORNAME = "$notification.author$"
NOTIFICATIONCOMMENT = "$notification.comment$"
HOSTDISPLAYNAME = "$host.display_name$"
USEREMAIL = "$user.email$"
// Custom ENV variables
HOSTPERFDATA = "$host.perfdata$"
PERFDATA = "$host.perfdata$"
NETBOXHOSTNAME = "$host.vars.host_url$"
NETBOXPANELID = "$host.vars.panel_url$"
}
}
object NotificationCommand "mail-service-notification" {
object NotificationCommand "enhanced-mail-service-notification" {
import "plugin-notification-command"
command = [ SysconfDir + "/icinga2/scripts/mail-service-perfdata-notification.py" ]
command = [ SysconfDir + "/icinga2/scripts/enhanced-mail-notification.py" ]
env = {
NOTIFICATIONTYPE = "$notification.type$"
SERVICEDESC = "$service.name$"
HOSTALIAS = "$host.display_name$"
HOSTDISPLAYNAME = "$host.display_name$"
HOSTADDRESS = "$address$"
SERVICENAME = "$service.name$"
SERVICEDISPLAYNAME = "$service.display_name$"
SERVICECOMMAND = "$service.check_command$"
SERVICESTATE = "$service.state$"
LONGDATETIME = "$icinga.long_date_time$"
SERVICEOUTPUT = "$service.output$"
LONGDATETIME = "$icinga.long_date_time$"
NOTIFICATIONAUTHORNAME = "$notification.author$"
NOTIFICATIONCOMMENT = "$notification.comment$"
HOSTDISPLAYNAME = "$host.display_name$"
SERVICEDISPLAYNAME = "$service.display_name$"
USEREMAIL = "$user.email$"
// Custom ENV variables
SERVICEPERFDATA = "$service.perfdata$"
HOSTURL = "$host.vars.host_url$"
SERVICEURL = "$service.vars.service_url$"
PERFDATA = "$service.perfdata$"
NETBOXHOSTNAME = "$host.vars.host_url$"
PANELURL = "$service.vars.panel_url$"
}
}
......@@ -10,6 +10,8 @@ import smtplib
import socket
import requests
import json
import ConfigParser
import re
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
......@@ -19,31 +21,36 @@ from email.MIMEImage import MIMEImage
###############
# User customization here
# Email
EMAILFROM = 'account@domain.name'
EMAILFROM = 'icinga@domain.local'
EMAILSERVER = 'localhost'
EMAILUSERNAME = ''
EMAILPASSWORD = ''
# Icinga
ICINGA2BASE = 'http://icinga.domain.name/icingaweb2' # INFO: no trailing / on the url, it can generate errors
# INFO: no trailing / on the url, it can generate errors
ICINGA2BASE = 'http://icinga.domain.local/icingaweb2'
ICINGA2LOGOPATH = '/usr/share/icingaweb2/public/img/icinga-logo.png'
# Netbox
# INFO: leave netbox base empty if you don't use netbox and it won't be included
NETBOXBASE = 'http://netbox.domain.name' # INFO: no trailing / on the url, it can generate errors
NETBOXTOKEN = 'abcdefghijklmnopqrstuvwxyz'
# INFO: no trailing / on the url, it can generate errors
NETBOXBASE = 'http://netbox.domain.local'
NETBOXTOKEN = 'abcdefghijklmnopqrstuvwxyz1234567890'
NETBOXPATHDEVICES = '/dcim/devices'
NETBOXPATHVMS = '/virtualization/virtual-machines'
NETBOXPATHIPS = '/ipam/ip-addresses'
# Grafana
GRAFANABASE = 'http://grafana.domain.name' # INFO: no trailing / on the url, it can generate errors
# INFO: no trailing / on the url, it can generate errors
GRAFANABASE = 'http://grafana.domain.local'
GRAFANADASHBOARD = 'icinga2-with-influxdb'
GRAFANAVARHOST = 'var-hostname' # This is the key that grafana sets to search the host name value eg: $hostname translates to var-hostname in a url
# The grafana module in icingaweb2 stores panel id for each service in a ini file
GRAFANAICINGAWEB2INI = '/etc/icingaweb2/modules/grafana/graphs.ini'
# This is the key that grafana users to search the host name value
GRAFANAVARHOST = 'var-hostname'
GRAFANATHEME = 'light'
GRAFANAAPIKEY = '0123456789987654321001234567899876543210'
GRAFANAAPIKEY = 'abcdefghijklmnopqrstuvwxyz1234567890'
GRAFANADEFAULTHOSTPANELID = '2' # Usually ping
# Misc
......@@ -53,37 +60,46 @@ COLUMN = '144'
DIFFERENCE = str(int(WIDTH) - int(COLUMN))
DEBUG = os.getenv('DEBUG')
#DEBUG = True
DEBUG = True
#################
# External Vars #
#################
notification_type = os.getenv('NOTIFICATIONTYPE', 'none')
host_alias = os.getenv('HOSTALIAS', 'none')
notification_type = os.getenv('NOTIFICATIONTYPE', '')
host_alias = os.getenv('HOSTALIAS', '')
host_display_name = os.getenv('HOSTDISPLAYNAME', '')
host_address = os.getenv('HOSTADDRESS', host_alias)
host_state = os.getenv('HOSTSTATE', 'none')
long_date_time = os.getenv('LONGDATETIME', 'none')
host_output = os.getenv('HOSTOUTPUT', 'none')
notification_author = os.getenv('NOTIFICATIONAUTHORNAME', 'none')
notification_comment = os.getenv('NOTIFICATIONCOMMENT', 'none')
host_display_name = os.getenv('HOSTDISPLAYNAME', 'none')
user_email = os.getenv('USEREMAIL', 'none')
host_performance_data = os.getenv('HOSTPERFDATA') # needs to be null to avoid it
host_state = os.getenv('HOSTSTATE', '')
host_output = os.getenv('HOSTOUTPUT', '')
service_name = os.getenv('SERVICENAME', '')
service_display_name = os.getenv('SERVICEDISPLAYNAME', '')
service_command = os.getenv('SERVICECOMMAND', '')
service_state = os.getenv('SERVICESTATE', '')
service_output = os.getenv('SERVICEOUTPUT', '')
long_date_time = os.getenv('LONGDATETIME', '')
notification_author = os.getenv('NOTIFICATIONAUTHORNAME', '')
notification_comment = os.getenv('NOTIFICATIONCOMMENT', '')
user_email = os.getenv('USEREMAIL', '')
performance_data = os.getenv('PERFDATA') # needs to be null to avoid it
netbox_host_name = os.getenv('NETBOXHOSTNAME', host_alias)
if netbox_host_name:
if netbox_host_name == '':
# If the env is set but empty
netbox_host_name = host_alias
grafana_panel_id = os.getenv('NETBOXPANELID', GRAFANADEFAULTHOSTPANELID)
if grafana_panel_id:
grafana_panel_id = GRAFANADEFAULTHOSTPANELID
grafana_host_panel_id = os.getenv('NETBOXPANELID', GRAFANADEFAULTHOSTPANELID)
if grafana_host_panel_id == '':
# If the env is set but empty
grafana_host_panel_id = GRAFANADEFAULTHOSTPANELID
# If the host_address is set to nothing use the alias
if not host_address:
host_address = host_alias
# Email subject
EMAILMESSAGE = notification_type + ' - ' + host_display_name + ' is ' + host_state
if host_state:
EMAILMESSAGE = 'Host ' + notification_type + ' - ' + host_display_name + ' is ' + host_state
elif service_state:
EMAILMESSAGE = 'Service ' + notification_type + ' - ' + host_display_name + ' service ' + service_display_name + ' is ' + service_state
# With debug on each run produces a template that can be rerun for testing
......@@ -91,21 +107,26 @@ if DEBUG:
with open("/tmp/enhanced-mail.sh", "w+") as f:
f.write("#!/bin/bash")
f.write("\n")
f.write('\nexport NOTIFICATIONTYPE="' + notification_type + '"')
f.write('\nexport HOSTALIAS="' + host_alias + '"')
f.write('\nexport HOSTADDRESS="' + host_address + '"')
f.write('\nexport HOSTSTATE="' + host_state + '"')
f.write('\nexport LONGDATETIME="' + long_date_time + '"')
f.write('\nexport HOSTOUTPUT="' + host_output + '"')
f.write('\nexport NOTIFICATIONAUTHORNAME="' + notification_author + '"')
f.write('\nexport NOTIFICATIONCOMMENT="' + notification_comment + '"')
f.write('\nexport HOSTDISPLAYNAME="' + host_display_name + '"')
f.write('\nexport USEREMAIL="' + user_email + '"')
f.write('\nexport HOSTPERFDATA="' + host_performance_data + '"')
f.write('\nexport NETBOXHOSTNAME="' + netbox_host_name + '"')
f.write('\nexport NETBOXPANELID="' + grafana_panel_id + '"')
f.write('\nexport NOTIFICATIONTYPE="{}"'.format(notification_type))
f.write('\nexport HOSTALIAS="{}"'.format(host_alias))
f.write('\nexport HOSTDISPLAYNAME="{}"'.format(host_display_name))
f.write('\nexport HOSTADDRESS="{}"'.format(host_address))
f.write('\nexport HOSTSTATE="{}"'.format(host_state))
f.write('\nexport HOSTOUTPUT="{}"'.format(host_output))
f.write('\nexport SERVICENAME="{}"'.format(service_name))
f.write('\nexport SERVICEDISPLAYNAME="{}"'.format(service_display_name))
f.write('\nexport SERVICECOMMAND="{}"'.format(service_command))
f.write('\nexport SERVICESTATE="{}"'.format(service_state))
f.write('\nexport SERVICEOUTPUT="{}"'.format(service_output))
f.write('\nexport LONGDATETIME="{}"'.format(long_date_time))
f.write('\nexport NOTIFICATIONAUTHORNAME="{}"'.format(notification_author))
f.write('\nexport NOTIFICATIONCOMMENT="{}"'.format(notification_comment))
f.write('\nexport USEREMAIL="{}"'.format(user_email))
f.write('\nexport PERFDATA="{}"'.format(performance_data))
f.write('\nexport NETBOXHOSTNAME="{}"'.format(netbox_host_name))
f.write('\nexport NETBOXPANELID="{}"'.format(grafana_host_panel_id))
f.write("\n")
f.write("\n/etc/icinga2/scripts/mail-host-enhanced-notification.py")
f.write("\n/etc/icinga2/scripts/enhanced-mail-notification.py")
f.close()
# Classes for getting data from each external system
......@@ -188,25 +209,40 @@ class Netbox:
def addNetboxLinkVal(self, title, obj, key1, key2 = None):
val = self.getNetboxVal(obj, key1, key2)
if val:
val = '\n<tr><th width="' + COLUMN + '">' + title + ':</th><td><a href="' + self.getNetboxVal(obj, key1, "url") + '">' + val + '</a></td></tr>'
val = '\n<tr><th width="' + COLUMN + '">' + title + ':</th><td><a href="' + re.sub(r"\/api\/", "/", self.getNetboxVal(obj, key1, "url")) + '">' + val + '</a></td></tr>'
else:
val = ''
return val
# If you don't have a panelID then we can't get any data
class Grafana:
def __init__(self):
self.png_url = ''
self.page_url = ''
self.png = None
self.icingaweb2_ini = None
self.panelID = None
if GRAFANAICINGAWEB2INI:
self.__parseIcingaweb2INI()
if grafana_panel_id:
self.png_url = GRAFANABASE + '/render/dashboard-solo/db/' + GRAFANADASHBOARD + '?panelId=' + grafana_panel_id + '&' + GRAFANAVARHOST + '=' + netbox_host_name + '&theme=' + GRAFANATHEME + '&width=' + WIDTH + '&height=' + HEIGHT
self.page_url = GRAFANABASE + '/dashboard/db/' + GRAFANADASHBOARD + '?fullscreen&panelId=' + grafana_panel_id + '&' + GRAFANAVARHOST + '=' + netbox_host_name
if service_state:
self.panelID = self.__getPanelID(service_display_name, service_name, service_command)
if host_state:
self.panelID = grafana_host_panel_id
if self.panelID:
self.png_url = GRAFANABASE + '/render/dashboard-solo/db/' + GRAFANADASHBOARD + '?panelId=' + self.panelID + '&' + GRAFANAVARHOST + '=' + netbox_host_name + '&theme=' + GRAFANATHEME + '&width=' + WIDTH + '&height=' + HEIGHT
self.page_url = GRAFANABASE + '/dashboard/db/' + GRAFANADASHBOARD + '?fullscreen&panelId=' + self.panelID + '&' + GRAFANAVARHOST + '=' + netbox_host_name
self.png = self.__getPNG()
def __parseIcingaweb2INI(self):
if DEBUG:
print("\nGrafana ini file: {}".format(GRAFANAICINGAWEB2INI))
self.icingaweb2_ini = ConfigParser.ConfigParser()
self.icingaweb2_ini.read(GRAFANAICINGAWEB2INI)
def __getPNG(self):
headers = {'Authorization': 'Bearer ' + GRAFANAAPIKEY}
if DEBUG:
......@@ -217,6 +253,37 @@ class Grafana:
print(response.status_code)
return response
def __searchSections(self, display_name, name, command):
pattern = None
if display_name:
pattern = re.compile(display_name)
if name and pattern == None:
pattern = re.compile(name)
if command and pattern == None:
pattern = re.compile(command)
if DEBUG:
print("\nGrafana ini sections: {}".format(self.icingaweb2_ini.sections()))
print("\nGrafana ini pattern: {}".format(pattern))
section = None
if pattern:
section = filter(pattern.match, self.icingaweb2_ini.sections())
if DEBUG:
print("\nGrafana section: {}".format(section))
if len(section) == 1:
section = section[0]
if DEBUG:
print("\nGrafana section: {}".format(section))
return section
def __getPanelID(self, display_name, name, command):
section = self.__searchSections(display_name, name, command)
panel_id = None
if section:
panel_id = self.icingaweb2_ini.get(section, 'panelId').replace('"', '')
return panel_id
netbox = Netbox()
grafana = Grafana()
......@@ -229,11 +296,12 @@ TEXT += '\nNotification Type: ' + notification_type
TEXT += '\n'
TEXT += '\nHost: ' + host_alias
TEXT += '\nAddress: ' + host_address
TEXT += '\nState: ' + host_state
TEXT += '\nService: ' + service_display_name
TEXT += '\nState: {}{}'.format(host_state, service_state)
TEXT += '\n'
TEXT += '\nDate/Time: ' + long_date_time
TEXT += '\n'
TEXT += '\nAdditional Info: ' + host_output
TEXT += '\nAdditional Info: {}{}'.format(host_output, service_output)
TEXT += '\n'
TEXT += '\nComment: [' + notification_author + '] ' + notification_comment
if grafana.page_url:
......@@ -270,14 +338,17 @@ if os.path.exists(ICINGA2LOGOPATH):
HTML += '\n<tr><th colspan=2 class=icinga width=' + WIDTH +'><img src="cid:icinga2_logo"></th></tr>'
if DEBUG:
HTML += '\n<tr><th width=' + COLUMN + '>Panel:</th><td>' + grafana_panel_id + '</td></tr>'
HTML += '\n<tr><th width=' + COLUMN + '>Notification Type:</th><td class=' + host_state + '>' + notification_type + '</td></tr>'
HTML += '\n<tr><th width={}>Panel:</th><td>{}</td></tr>'.format(COLUMN, grafana.panelID)
HTML += '\n<tr><th width={}>Notification Type:</th><td class={} {}>{}</td></tr>'.format(COLUMN, host_state, service_state, notification_type)
HTML += '\n<tr><th>Hostalias:</th><td><a style="color: #0095bf; text-decoration: none;" href="' + ICINGA2BASE +'/monitoring/host/show?host=' + host_alias + '">' + host_alias + '</a></td></tr>'
HTML += '\n<tr><th>IP Address:</th><td>' + host_address + '</td></tr>'
HTML += '\n<tr><th>Host Status:</th><td>' + host_state + '</td></tr>'
HTML += '\n<tr><th>Service Name:</th><td>ping4</td></tr>'
HTML += '\n<tr><th>Service Data:</th><td><a style="color: #0095bf; text-decoration: none;" href="' + ICINGA2BASE + '/monitoring/host/services?host=' + host_alias + '">' + host_output + '</a></td></tr>'
HTML += '\n<tr><th>Status:</th><td>' + host_state + service_state + '</td></tr>'
HTML += '\n<tr><th>Service Name:</th><td>' + service_display_name + '</td></tr>'
if host_state:
HTML += '\n<tr><th>Service Data:</th><td><a style="color: #0095bf; text-decoration: none;" href="' + ICINGA2BASE + '/monitoring/host/services?host=' + host_alias + '">' + host_output + '</a></td></tr>'
if service_state:
HTML += '\n<tr><th>Service Data:</th><td><a style="color: #0095bf; text-decoration: none;" href="' + ICINGA2BASE + '/monitoring/service/show?host=' + host_alias + '&service=' + service_name + '">' + service_output + '</a></td></tr>'
HTML += '\n<tr><th>Event Time:</th><td>' + long_date_time + '</td></tr>'
if (notification_author and notification_comment):
......@@ -291,7 +362,7 @@ if netbox.host:
HTML += netbox.addNetboxVal('Display Name', netbox.host, 'name')
HTML += netbox.addNetboxLinkVal('Cluster', netbox.host, 'cluster', 'name')
HTML += netbox.addNetboxLinkVal('Tennant', netbox.host, 'tennant', 'name')
HTML += netbox.addNetboxLinkVal('Site', netbox.host, 'site', 'name')
HTML += netbox.addNetboxLinkVal('Site', netbox.host, 'site', 'name') # Sites use the slug
HTML += netbox.addNetboxLinkVal('Rack', netbox.host, 'rack', 'name')
HTML += netbox.addNetboxVal('Position', netbox.host, 'position')
HTML += netbox.addNetboxVal('Primary IP', netbox.host, 'primary_ip')
......@@ -310,13 +381,13 @@ if netbox.ip:
HTML += netbox.addNetboxVal('Host', netbox.ip, 'device', 'name')
if (host_performance_data or grafana_panel_id):
if (performance_data or grafana.panelID):
HTML += '\n</table><br>'
HTML += '\n<table width=' + WIDTH + '>'
HTML += '\n<tr><th colspan=6 class=perfdata>Performance Data</th></tr>'
if (host_performance_data):
if (performance_data):
HTML += '\n<tr><th>Label</th><th>Last Value</th><th>Warning</th><th>Critical</th><th>Min</th><th>Max</th></tr>'
PERFDATALIST = host_performance_data.split(" ")
PERFDATALIST = performance_data.split(" ")
for PERFDATA in PERFDATALIST:
if '=' not in PERFDATA:
continue
......@@ -337,7 +408,7 @@ if grafana.page_url:
HTML += '\n</table><br>'
HTML += '\n<table width=' + WIDTH + '>'
HTML += '\n<tr><td class=center>Generated by Icinga 2 with data from Icinga 2'
if grafana_panel_id:
if grafana.panelID:
HTML += ', Grafana'
if netbox.host or netbox.ip:
......
#!/bin/python
#------------
# Service notification script for Icinga2
# v.20170310 by mmarodin
#
# https://github.com/mmarodin/icinga2-plugins
#
import os
import smtplib
import socket
import urllib2
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
# User customization here
FROM = 'icinga@icinga2.fqdn.here'
SERVER = 'localhost'
USERNAME = ''
PASSWORD = ''
ICINGA2BASE = 'http://icinga2.fqdn.here/icingaweb2'
GRAFANABASE = 'http://grafana.fqdn.here:3000'
GRAFANADASHBOARD = 'yourdashboard'
GRAFANAVARHOST = 'var-HOST'
GRAFANAVARSERVICE = 'var-SERVICE'
GRAFANATHEME = 'light'
GRAFANAAPIKEY = 'yourAPIkey'
WIDTH = '640'
HEIGHT = '321'
COLUMN = '144'
DIFFERENCE = str(int(WIDTH) - int(COLUMN))
NOTIFICATIONTYPE = os.getenv('NOTIFICATIONTYPE', 'none')
SERVICEDESC = os.getenv('SERVICEDESC', 'none')
HOSTALIAS = os.getenv('HOSTALIAS', 'none')
HOSTADDRESS = os.getenv('HOSTADDRESS', HOSTALIAS)
SERVICESTATE = os.getenv('SERVICESTATE', 'none')
LONGDATETIME = os.getenv('LONGDATETIME', 'none')
SERVICEOUTPUT = os.getenv('SERVICEOUTPUT', 'none')
NOTIFICATIONAUTHORNAME = os.getenv('NOTIFICATIONAUTHORNAME', 'none')
NOTIFICATIONCOMMENT = os.getenv('NOTIFICATIONCOMMENT', 'none')
HOSTDISPLAYNAME = os.getenv('HOSTDISPLAYNAME', 'none')
SERVICEDISPLAYNAME = os.getenv('SERVICEDISPLAYNAME', 'none')
USEREMAIL = os.getenv('USEREMAIL', 'none')
SERVICEPERFDATA = os.getenv('SERVICEPERFDATA') # needs to be null to avoid it
HOSTURL = os.getenv('HOSTURL', 'none')
SERVICEURL = os.getenv('SERVICEURL', SERVICEDESC)
PANELURL = os.getenv('PANELURL') # no default initializer, this is optional
DEBUG = os.getenv('DEBUG')
TO = USEREMAIL
#TO = 'root@icinga2.fqdn.here'
# Logo for Icinga2 <= 2.5.x
# logoImagePath = '/usr/share/icingaweb2/public/img/logo_icinga-inv.png'
# Logo for Icinga2 >= 2.6.x
logoImagePath = '/usr/share/icingaweb2/public/img/icinga-logo.png'
if not HOSTADDRESS:
HOSTADDRESS = HOSTALIAS
if not SERVICEURL:
SERVICEURL = SERVICEDESC
SUBJECTMESSAGE = NOTIFICATIONTYPE + ' - ' + HOSTDISPLAYNAME + ' - ' + SERVICEDISPLAYNAME + ' is ' + SERVICESTATE
if PANELURL:
GRAFANAPNG = GRAFANABASE + '/render/dashboard-solo/db/' + GRAFANADASHBOARD + '?fullscreen&panelId=' + PANELURL + '&' + GRAFANAVARHOST + '=' + HOSTURL + '&' + GRAFANAVARSERVICE + '=' + SERVICEURL + '&theme=' + GRAFANATHEME + '&width=' + WIDTH + '&height=' + HEIGHT
GRAFANALINK = GRAFANABASE + '/dashboard/db/' + GRAFANADASHBOARD + '?fullscreen&panelId=' + PANELURL + '&' + GRAFANAVARHOST + '=' + HOSTURL + '&' + GRAFANAVARSERVICE + '=' + SERVICEURL
TEXT = '***** Icinga *****'
TEXT += '\n'
TEXT += '\nNotification Type: ' + NOTIFICATIONTYPE
TEXT += '\n'
TEXT += '\nService: ' + SERVICEDESC
TEXT += '\nHost: ' + HOSTALIAS
TEXT += '\nAddress: ' + HOSTADDRESS
TEXT += '\nState: ' + SERVICESTATE
TEXT += '\n'
TEXT += '\nDate/Time: ' + LONGDATETIME
TEXT += '\n'
TEXT += '\nAdditional Info: ' + SERVICEOUTPUT
TEXT += '\n'
TEXT += '\nComment: [' + NOTIFICATIONAUTHORNAME + '] ' + NOTIFICATIONCOMMENT
HTML = '<html><head><style type="text/css">'
HTML += '\nbody {text-align: left; font-family: calibri, sans-serif, verdana; font-size: 10pt; color: #7f7f7f;}'
HTML += '\ntable {margin-left: auto; margin-right: auto;}'
HTML += '\na:link {color: #0095bf; text-decoration: none;}'
HTML += '\na:visited {color: #0095bf; text-decoration: none;}'
HTML += '\na:hover {color: #0095bf; text-decoration: underline;}'
HTML += '\na:active {color: #0095bf; text-decoration: underline;}'
HTML += '\nth {font-family: calibri, sans-serif, verdana; font-size: 10pt; text-align:left; white-space: nowrap; color: #535353;}'
HTML += '\nth.icinga {background-color: #0095bf; color: #ffffff; margin-left: 7px; margin-top: 5px; margin-bottom: 5px;}'
HTML += '\nth.perfdata {background-color: #0095bf; color: #ffffff; margin-left: 7px; margin-top: 5px; margin-bottom: 5px; text-align:center;}'
HTML += '\ntd {font-family: calibri, sans-serif, verdana; font-size: 10pt; text-align:left; color: #7f7f7f;}'
HTML += '\ntd.center {text-align:center; white-space: nowrap;}'
HTML += '\ntd.OK {background-color: #44bb77; color: #ffffff; margin-left: 2px;}'
HTML += '\ntd.WARNING {background-color: #ffaa44; color: #ffffff; margin-left: 2px;}'
HTML += '\ntd.CRITICAL {background-color: #ff5566; color: #ffffff; margin-left: 2px;}'
HTML += '\ntd.UNKNOWN {background-color: #aa44ff; color: #ffffff; margin-left: 2px;}'
HTML += '\n</style></head><body>'
HTML += '\n<table width=' + WIDTH + '>'
if os.path.exists(logoImagePath):
HTML += '\n<tr><th colspan=2 class=icinga width=' + WIDTH +'><img src="cid:icinga2_logo"></th></tr>'
HTML += '\n<tr><th width=' + COLUMN + '>Notification Type:</th><td class=' + SERVICESTATE + '>' + NOTIFICATIONTYPE + '</td></tr>'
HTML += '\n<tr><th>Service Name:</th><td>' + SERVICEDISPLAYNAME+ '</td></tr>'
HTML += '\n<tr><th>Service Status:</th><td>' + SERVICESTATE + '</td></tr>'
HTML += '\n<tr><th>Service Data:</th><td><a style="color: #0095bf; text-decoration: none;" href="' + ICINGA2BASE + '/monitoring/service/show?host=' + HOSTALIAS + '&service=' + SERVICEDESC + '">' + SERVICEOUTPUT.replace("\n", "<br>") + '</a></td></tr>'
HTML += '\n<tr><th>Hostalias:</th><td><a style="color: #0095bf; text-decoration: none;" href="' + ICINGA2BASE +'/monitoring/host/show?host=' + HOSTALIAS + '">' + HOSTALIAS + '</a></td></tr>'
HTML += '\n<tr><th>IP Address:</th><td>' + HOSTADDRESS + '</td></tr>'
HTML += '\n<tr><th>Event Time:</th><td>' + LONGDATETIME + '</td></tr>'
if (NOTIFICATIONAUTHORNAME and NOTIFICATIONCOMMENT):
HTML += '\n<tr><th>Comment:</th><td>' + NOTIFICATIONCOMMENT + ' (' + NOTIFICATIONAUTHORNAME + ')</td></tr>'
if (SERVICEPERFDATA or PANELURL):
HTML += '\n</table><br>'
HTML += '\n<table width=' + WIDTH + '>'
HTML += '\n<tr><th colspan=6 class=perfdata>Performance Data</th></tr>'
if (SERVICEPERFDATA):
HTML += '\n<tr><th>Label</th><th>Last Value</th><th>Warning</th><th>Critical</th><th>Min</th><th>Max</th></tr>'
PERFDATALIST = SERVICEPERFDATA.split(" ")
for PERFDATA in PERFDATALIST:
if '=' not in PERFDATA:
continue
(LABEL,DATA) = PERFDATA.split("=")
if (len(DATA.split(";")) is 5):
(VALUE,WARNING,CRITICAL,MIN,MAX) = DATA.split(";")
# else:
# (VALUE,WARNING,CRITICAL,MIN) = DATA.split(";")
# MAX = ''
if (len(DATA.split(";")) is 4):
(VALUE,WARNING,CRITICAL,MIN) = DATA.split(";")
MAX = ''
if (len(DATA.split(";")) is 3):
(VALUE,WARNING,CRITICAL) = DATA.split(";")
MAX = ''
MIN = ''
if (len(DATA.split(";")) is 2):
(VALUE,WARNING) = DATA.split(";")
MAX = ''
MIN = ''
CRITICAL = ''
if (len(DATA.split(";")) is 1):
VALUE = DATA
MAX = ''
MIN = ''
CRITICAL = ''
WARNING = ''
HTML += '\n<tr><td>' + LABEL + '</td><td>' + VALUE + '</td><td>' + WARNING + '</td><td>' + CRITICAL + '</td><td>' + MIN + '</td><td>' + MAX + '</td></tr>'
else:
HTML += '\n<tr><th width=' + COLUMN + ' colspan=1>Last Value:</th><td width=' + DIFFERENCE + ' colspan=5>none</td></tr>'
if PANELURL:
HTML += '\n<tr><td colspan=6><a href="' + GRAFANALINK + '"><img src="cid:grafana2_perfdata" width=' + WIDTH + ' height=' + HEIGHT + '></a></td></tr>'
HTML += '\n</table><br>'
HTML += '\n<table width=' + WIDTH + '>'
HTML += '\n<tr><td class=center>Generated by Icinga 2 and Grafana</td></tr>'
HTML += '\n</table><br>'
HTML += '\n</body></html>'
if DEBUG:
print HTML
# Prepare email
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = SUBJECTMESSAGE
msgRoot['From'] = FROM
msgRoot['To'] = TO
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText(TEXT)
msgAlternative.attach(msgText)
msgText = MIMEText(HTML, 'html')
msgAlternative.attach(msgText)
# Attach images
if os.path.exists(logoImagePath):
fp = open(logoImagePath, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<icinga2_logo>')
msgRoot.attach(msgImage)
if PANELURL:
GET = urllib2.Request(GRAFANAPNG)
GET.add_header('Authorization','Bearer ' + GRAFANAAPIKEY)
GRAPH = urllib2.urlopen(GET)
PNG = GRAPH.read()
msgImage = MIMEImage(PNG)
msgImage.add_header('Content-ID', '<grafana2_perfdata>')
msgRoot.attach(msgImage)
# Send mail using SMTP
smtp = smtplib.SMTP()
try:
smtp.connect(SERVER)
except socket.error as e:
print "Unable to connect to SMTP server '" + SERVER + "': " + e.strerror
os.sys.exit(e.errno)
if (USERNAME and PASSWORD):
smtp.login(USERNAME, PASSWORD)
try:
smtp.sendmail(FROM, TO, msgRoot.as_string())
smtp.quit()
except Exception as e:
print "Cannot send mail using SMTP: " + e.message