Advertisement
Guest User

Untitled

a guest
May 25th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.85 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # Slack
  3.  
  4. # -*- coding: utf-8 -*-
  5. # +------------------------------------------------------------------+
  6. # |             ____ _               _        __  __ _  __           |
  7. # |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
  8. # |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
  9. # |           | |___| | | |  __/ (__|   <    | |  | | . \            |
  10. # |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
  11. # |                                                                  |
  12. # | Copyright Mathias Kettner 2018             mk@mathias-kettner.de |
  13. # +------------------------------------------------------------------+
  14. #
  15. # This file is part of Check_MK.
  16. # The official homepage is at http://mathias-kettner.de/check_mk.
  17. #
  18. # check_mk is free software;  you can redistribute it and/or modify it
  19. # under the  terms of the  GNU General Public License  as published by
  20. # the Free Software Foundation in version 2.  check_mk is  distributed
  21. # in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
  22. # out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
  23. # PARTICULAR PURPOSE. See the  GNU General Public License for more de-
  24. # tails. You should have  received  a copy of the  GNU  General Public
  25. # License along with GNU Make; see the file  COPYING.  If  not,  write
  26. # to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
  27. # Boston, MA 02110-1301 USA.
  28. r"""
  29. Send notification messages to Slack
  30. ===================================
  31.  
  32. Use a slack webhook to send notification messages
  33. """
  34. from __future__ import unicode_literals
  35. import sys
  36. import requests
  37. import re
  38. import os
  39.  
  40. from typing import AnyStr, Dict, Optional, Tuple  # pylint: disable=unused-import
  41.  
  42. import cmk.password_store
  43.  
  44. COLORS = {
  45.     "CRITICAL": "#EE0000",
  46.     "DOWN": "#EE0000",
  47.     "WARNING": "#FFDD00",
  48.     "OK": "#00CC00",
  49.     "UP": "#00CC00",
  50.     "UNKNOWN": "#CCCCCC",
  51.     "UNREACHABLE": "#CCCCCC",
  52. }
  53.  
  54.  
  55. def cmk_links(context):
  56.     # type: (Dict) -> Tuple[Optional[str], Optional[str]]
  57.     if context.get("PARAMETER_URL_PREFIX"):
  58.         url_prefix = context["PARAMETER_URL_PREFIX"]
  59.     elif context.get("PARAMETER_URL_PREFIX_MANUAL"):
  60.         url_prefix = context["PARAMETER_URL_PREFIX_MANUAL"]
  61.     elif context.get("PARAMETER_URL_PREFIX_AUTOMATIC") == "http":
  62.         url_prefix = "http://%s/%s" % (context["MONITORING_HOST"], context["OMD_SITE"])
  63.     elif context.get("PARAMETER_URL_PREFIX_AUTOMATIC") == "https":
  64.         url_prefix = "https://%s/%s" % (context["MONITORING_HOST"], context["OMD_SITE"])
  65.     else:
  66.         url_prefix = None
  67.  
  68.     if url_prefix:
  69.         base_url = re.sub('/check_mk/?', '', url_prefix)
  70.         host_url = base_url + context['HOSTURL']
  71.  
  72.         if context['WHAT'] == 'SERVICE':
  73.             service_url = base_url + context['SERVICEURL']
  74.             return host_url, service_url
  75.  
  76.         return host_url, None
  77.  
  78.     return None, None
  79.  
  80.  
  81. def extend_context_with_link_urls(context, link_template):
  82.     # type: (Dict, AnyStr) -> None
  83.  
  84.     host_url, service_url = cmk_links(context)
  85.  
  86.     if host_url:
  87.         context['LINKEDHOSTNAME'] = link_template.format(host_url, context['HOSTNAME'])
  88.     else:
  89.         context['LINKEDHOSTNAME'] = context['HOSTNAME']
  90.  
  91.     if service_url:
  92.         context['LINKEDSERVICEDESC'] = link_template.format(service_url, context['SERVICEDESC'])
  93.     else:
  94.         context['LINKEDSERVICEDESC'] = context.get('SERVICEDESC', '')
  95.  
  96.  
  97. def slack_msg(context):
  98.     # type: (Dict) -> Dict
  99.     """Build the message for slack"""
  100.  
  101.     extend_context_with_link_urls(context, '<{}|{}>')
  102.  
  103.     if context.get('WHAT', None) == "SERVICE":
  104.         color = COLORS.get(context["SERVICESTATE"])
  105.         title = "Service {NOTIFICATIONTYPE} notification".format(**context)
  106.         text = "Host: {LINKEDHOSTNAME} (IP: {HOSTADDRESS})\nService: {LINKEDSERVICEDESC}\nState: {SERVICESTATE}".format(
  107.             **context)
  108.         output = context["SERVICEOUTPUT"]
  109.     else:
  110.         color = COLORS.get(context["HOSTSTATE"])
  111.         title = "Host {NOTIFICATIONTYPE} notification".format(**context)
  112.         text = "Host: {LINKEDHOSTNAME} (IP: {HOSTADDRESS})\nState: {HOSTSTATE}".format(**context)
  113.         output = context["HOSTOUTPUT"]
  114.  
  115.     return {
  116.         "attachments": [
  117.             {
  118.                 "color": color,
  119.                 "title": title,
  120.                 "text": text,
  121.             },
  122.             {
  123.                 "color":
  124.                     color,
  125.                 "title":
  126.                     "Additional Info",
  127.                 "text":
  128.                     output + "\nPlease take a look: " + ", ".join(
  129.                         map("@{}".format, context["CONTACTNAME"].split(','))),
  130.                 "footer":
  131.                     "Check_MK notification: {LONGDATETIME}".format(**context),
  132.             },
  133.         ]
  134.     }
  135.  
  136.  
  137. def collect_context():
  138.     # type: () -> Dict
  139.     return {
  140.         var[7:]: value.decode("utf-8")
  141.         for (var, value) in os.environ.items()
  142.         if var.startswith("NOTIFY_")
  143.     }
  144.  
  145.  
  146. def retrieve_from_passwordstore(parameter):
  147.     value = parameter.split()
  148.  
  149.     if len(value) == 2:
  150.         if value[0] == 'store':
  151.             value = cmk.password_store.load().get(value[1])
  152.         else:
  153.             value = value[1]
  154.     else:
  155.         value = value[0]
  156.  
  157.     return value
  158.  
  159.  
  160. def post_request(message_constructor, success_code=200):
  161.     context = collect_context()
  162.  
  163.     url = retrieve_from_passwordstore(context.get("PARAMETER_WEBHOOK_URL"))
  164.  
  165.     r = requests.post(url=url, json=message_constructor(context))
  166.  
  167.     if r.status_code == success_code:
  168.         sys.exit(0)
  169.     else:
  170.         sys.stderr.write(
  171.             "Failed to send notification. Status: %i, Response: %s\n" % (r.status_code, r.text))
  172.         sys.exit(2)
  173.  
  174.  
  175. if __name__ == "__main__":
  176.     post_request(slack_msg)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement