コード例 #1
0
def slack_msg(context):
    # type: (Dict) -> Dict
    """Build the message for slack"""

    extend_context_with_link_urls(context, '<{}|{}>')

    if context.get('WHAT', None) == "SERVICE":
        color = COLORS.get(context["SERVICESTATE"])
        title = "Service {NOTIFICATIONTYPE} notification".format(**context)
        text = "Host: {LINKEDHOSTNAME} (IP: {HOSTADDRESS})\nService: {LINKEDSERVICEDESC}\nState: {SERVICESTATE}".format(
            **context)
        output = context["SERVICEOUTPUT"]
    else:
        color = COLORS.get(context["HOSTSTATE"])
        title = "Host {NOTIFICATIONTYPE} notification".format(**context)
        text = "Host: {LINKEDHOSTNAME} (IP: {HOSTADDRESS})\nState: {HOSTSTATE}".format(**context)
        output = context["HOSTOUTPUT"]

    return {
        "attachments": [
            {
                "color": color,
                "title": title,
                "text": text,
            },
            {
                "color": color,
                "title": "Additional Info",
                "text": output + "\nPlease take a look: " +
                        ", ".join(map("@{}".format, context["CONTACTNAME"].split(','))),
                "footer": "Check_MK notification: {LONGDATETIME}".format(**context),
            },
        ]
    }
コード例 #2
0
def victorops_msg(context):
    # type: (Dict) -> Dict
    """Build the message for slack"""

    extend_context_with_link_urls(context, '{0}')

    if context.get('WHAT', None) == "SERVICE":
        state = translate_states(context["SERVICESTATE"])
        entity_id = '{SERVICEDESC}/{HOSTNAME}:{HOSTADDRESS}'.format(
            **context).replace(" ", "")
        title = "{SERVICEDESC} on {HOSTNAME}".format(**context)
        text = "{SERVICEOUTPUT}\n\n{LINKEDSERVICEDESC}".format(**context)
    else:
        state = translate_states(context["HOSTSTATE"])
        entity_id = '{HOSTNAME}:{HOSTADDRESS}'.format(**context).replace(
            " ", "")
        title = '{HOSTNAME} is {HOSTSTATE}'.format(**context)
        text = "{HOSTOUTPUT}\n\n{LINKEDHOSTNAME}".format(**context)
    hostname = context.get('HOSTNAME')

    return {
        "message_type": state,
        "entity_id": entity_id,
        "entity_display_name": title,
        "state_message": text,
        "host_name": hostname,
        "monitoring_tool": "Check_MK notification",
    }
コード例 #3
0
def get_text(context):
    s = ""

    s += "$@OUTPUT$"

    if "PARAMETER_URL_PREFIX" in context:
        utils.extend_context_with_link_urls(context, '<a href="%s">%s</a>')
        s += " <i>Link: </i>"
        s += context["LINKEDHOSTNAME"]
        if context["WHAT"] != "HOST":
            s += context["LINKEDSERVICEDESC"]

    return utils.substitute_context(s.replace("@", context["WHAT"]), context)
コード例 #4
0
def test_extend_with_link_urls(context, link_template, testkey, result):
    utils.extend_context_with_link_urls(context, link_template)
    assert context[testkey] == result
コード例 #5
0
def construct_content(context):
    # A list of optional information is configurable via the parameter "elements"
    # (new configuration style)
    # Note: The value PARAMETER_ELEMENTSS is NO TYPO.
    #       Have a look at the function events.py:add_to_event_context(..)
    if "PARAMETER_ELEMENTSS" in context:
        elements = context["PARAMETER_ELEMENTSS"].split()
    else:
        elements = ["perfdata", "graph", "abstime", "address", "longoutput"]

    # If argument 2 is given (old style) or the parameter url_prefix is set (new style),
    # we know the base url to the installation and can add
    # links to hosts and services. ubercomfortable!
    if context.get('PARAMETER_2'):
        context["PARAMETER_URL_PREFIX"] = context["PARAMETER_2"]

    utils.extend_context_with_link_urls(context, '<a href="%s">%s</a>')

    # Create a notification summary in a new context variable
    # Note: This code could maybe move to cmk --notify in order to
    # make it available every in all notification scripts
    # We have the following types of notifications:

    # - Alerts                OK -> CRIT
    #   NOTIFICATIONTYPE is "PROBLEM" or "RECOVERY"

    # - Flapping              Started, Ended
    #   NOTIFICATIONTYPE is "FLAPPINGSTART" or "FLAPPINGSTOP"

    # - Downtimes             Started, Ended, Cancelled
    #   NOTIFICATIONTYPE is "DOWNTIMESTART", "DOWNTIMECANCELLED", or "DOWNTIMEEND"

    # - Acknowledgements
    #   NOTIFICATIONTYPE is "ACKNOWLEDGEMENT"

    # - Custom notifications
    #   NOTIFICATIONTYPE is "CUSTOM"

    html_info = ""
    html_state = '<span class="state$@STATE$">$@STATE$</span>'
    notification_type = context["NOTIFICATIONTYPE"]
    if notification_type in ["PROBLEM", "RECOVERY"]:
        txt_info = "$PREVIOUS@HARDSHORTSTATE$ -> $@SHORTSTATE$"
        html_info = '<span class="state$PREVIOUS@HARDSTATE$">$PREVIOUS@HARDSTATE$</span> &rarr; ' + \
                    html_state

    elif notification_type.startswith("FLAP"):
        if "START" in notification_type:
            txt_info = "Started Flapping"
        else:
            txt_info = "Stopped Flapping ($@SHORTSTATE$)"
            html_info = "Stopped Flapping (while " + html_state + ")"

    elif notification_type.startswith("DOWNTIME"):
        what = notification_type[8:].title()
        txt_info = "Downtime " + what + " ($@SHORTSTATE$)"
        html_info = "Downtime " + what + " (while " + html_state + ")"

    elif notification_type == "ACKNOWLEDGEMENT":

        txt_info = "Acknowledged ($@SHORTSTATE$)"
        html_info = "Acknowledged (while " + html_state + ")"

    elif notification_type == "CUSTOM":
        txt_info = "Custom Notification ($@SHORTSTATE$)"
        html_info = "Custom Notification (while " + html_state + ")"

    else:
        txt_info = notification_type  # Should never happen

    if not html_info:
        html_info = txt_info

    txt_info = utils.substitute_context(txt_info.replace("@", context["WHAT"]), context)
    context["EVENT_TXT"] = txt_info

    # Add HTML formated plugin output
    html_info = utils.substitute_context(html_info.replace("@", context["WHAT"]), context)
    context["EVENT_HTML"] = html_info
    if "HOSTOUTPUT" in context:
        context["HOSTOUTPUT_HTML"] = utils.format_plugin_output(context["HOSTOUTPUT"])
    if context["WHAT"] == "SERVICE":
        context["SERVICEOUTPUT_HTML"] = utils.format_plugin_output(context["SERVICEOUTPUT"])

        long_serviceoutput = context["LONGSERVICEOUTPUT"]\
            .replace('\\n', '<br>')\
            .replace('\n', '<br>')
        context["LONGSERVICEOUTPUT_HTML"] = utils.format_plugin_output(long_serviceoutput)

    attachments = []

    # Compute the subject of the mail
    if context['WHAT'] == 'HOST':
        tmpl = context.get('PARAMETER_HOST_SUBJECT') or tmpl_host_subject
        context['SUBJECT'] = utils.substitute_context(tmpl, context)
    else:
        tmpl = context.get('PARAMETER_SERVICE_SUBJECT') or tmpl_service_subject
        context['SUBJECT'] = utils.substitute_context(tmpl, context)

    # Prepare the mail contents
    content_txt, content_html = render_elements(context, elements)

    if "graph" in elements and not "ALERTHANDLEROUTPUT" in context:
        # Add PNP or Check_MK graph
        try:
            attachments, graph_code = render_performance_graphs(context)
            content_html += graph_code
        except Exception as e:
            sys.stderr.write("Failed to add graphs to mail. Continue without them. (%s)\n" % e)

    extra_html_section = ""
    if "PARAMETER_INSERT_HTML_SECTION" in context:
        extra_html_section = context['PARAMETER_INSERT_HTML_SECTION']

    content_html = utils.substitute_context(tmpl_head_html(extra_html_section), context) + \
                   content_html + \
                   utils.substitute_context(tmpl_foot_html, context)

    return content_txt, content_html, attachments