예제 #1
0
def pagerduty_msg(context: Dict) -> Dict:
    """Build the PagerDuty incident payload"""

    if context.get('WHAT', None) == "SERVICE":
        state = context["SERVICESTATE"]
        incident_key = '{SERVICEDESC}/{HOSTNAME}:{HOSTADDRESS}'.format(**context).replace(" ", "")
        incident = "{SERVICESTATE}: {SERVICEDESC} on {HOSTNAME}".format(**context)
        output = context["SERVICEOUTPUT"]
        incident_url = service_url_from_context(context)
    else:
        state = context["HOSTSTATE"]
        incident_key = '{HOSTNAME}:{HOSTADDRESS}'.format(**context).replace(" ", "")
        incident = '{HOSTNAME} is {HOSTSTATE}'.format(**context)
        output = context["HOSTOUTPUT"]
        incident_url = host_url_from_context(context)

    msg_payload = {
        "routing_key": retrieve_from_passwordstore(context.get('PARAMETER_ROUTING_KEY')),
        "event_action": pagerduty_event_type(context.get('NOTIFICATIONTYPE')),
        "dedup_key": incident_key,
        "payload": {
            "summary": incident,
            "source": _notification_source_from_context(context),
            "severity": pagerduty_severity(state),
            "custom_details": {
                "info": output,
                "host": context.get('HOSTNAME'),
                "host_address": context.get('HOSTADDRESS'),
            }
        }
    }
    if incident_url:
        msg_payload.update({"client": "Check_MK", "client_url": incident_url})

    return msg_payload
예제 #2
0
def _get_request_params_from_context(raw_context: RawContext) -> Union[Errors, RequestParameter]:
    recipient = raw_context["CONTACTPAGER"].replace(" ", "")
    if not recipient:
        return Errors(["Error: Pager Number of %s not set\n" % raw_context["CONTACTNAME"]])

    proxy_url = raw_context.get("PARAMETER_PROXY_URL", "")
    proxies = {"https": proxy_url} if proxy_url else None

    return RequestParameter(
        recipient=recipient,
        url=raw_context["PARAMETER_URL"],
        verify="PARAMETER_IGNORE_SSL" in raw_context,
        proxies=proxies,
        user=raw_context["PARAMETER_USERNAME"],
        pwd=retrieve_from_passwordstore(raw_context["PARAMETER_PASSWORD"]),
        timeout=float(raw_context.get("PARAMETER_TIMEOUT", 10.0)),
    )
예제 #3
0
def main(argv=None):
    parser = argparse.ArgumentParser(
        description='send events from CheckMK to iLert')
    parser.add_argument('-a',
                        '--apikey',
                        help='API key for the alert source in iLert')
    parser.add_argument('-e',
                        '--endpoint',
                        default='https://api.ilert.com',
                        help='iLert API endpoint (default: %(default)s)')
    parser.add_argument('-p',
                        '--port',
                        type=int,
                        default=443,
                        help='endpoint port (default: %(default)s)')
    parser.add_argument('--version', action='version', version=PLUGIN_VERSION)
    parser.add_argument(
        'payload',
        nargs=argparse.REMAINDER,
        help=
        'event payload as key value pairs in the format key1=value1 key2=value2 ...'
    )
    args = parser.parse_args(argv)

    context = utils.collect_context()

    if not args.apikey:
        try:
            apikey = utils.retrieve_from_passwordstore(
                context['PARAMETER_ILERT_API_KEY'])
        except ValueError:
            log(
                "ERROR",
                "parameter apikey is required in save mode and must be provided either via command line or in the pager field of the contact definition in CheckMK"
            )
            sys.exit(1)
    else:
        apikey = args.apikey

    send(args.endpoint, args.port, apikey, context)

    sys.exit(0)
예제 #4
0
def test_api_endpoint_url(monkeypatch, value, result):
    monkeypatch.setattr('cmk.utils.password_store.extract', lambda x: 'http://secret.host')
    assert utils.retrieve_from_passwordstore(value) == result
예제 #5
0
def main():
    context = utils.collect_context()
    priority = u'P3'  # type: Optional[Text]
    teams_list = []
    tags_list = None
    action_list = None

    if 'PARAMETER_PASSWORD' not in context:
        sys.stderr.write("API key not set\n")
        return 2

    key = retrieve_from_passwordstore(context['PARAMETER_PASSWORD'])
    note_created = 'Alert created by Check_MK' or context.get(
        'PARAMETER_NOTE_CREATED')
    note_closed = 'Alert closed by Check_MK' or context.get(
        'PARAMETER_NOTE_CLOSED')
    priority = context.get('PARAMETER_PRIORITY')
    alert_source = context.get('PARAMETER_SOURCE')
    owner = context.get('PARAMETER_OWNER')
    entity_value = context.get('PARAMETER_ENTITY')
    host_url = context.get("PARAMETER_URL")

    if context.get('PARAMETER_TAGSS'):
        tags_list = None or context.get('PARAMETER_TAGSS', u'').split(" ")

    if context.get('PARAMETER_ACTIONSS'):
        action_list = None or context.get('PARAMETER_ACTIONSS', u'').split(" ")

    if context.get('PARAMETER_TEAMSS'):
        for team in context['PARAMETER_TEAMSS'].split(" "):
            teams_list.append(TeamRecipient(name=str(team), type='team'))

    if context['WHAT'] == 'HOST':
        tmpl_host_msg = "Check_MK: $HOSTNAME$ - $HOSTSHORTSTATE$"
        tmpl_host_desc = """Host: $HOSTNAME$
Event:    $EVENT_TXT$
Output:   $HOSTOUTPUT$
Perfdata: $HOSTPERFDATA$
$LONGHOSTOUTPUT$
"""
        desc = context.get('PARAMETER_HOST_DESC') or tmpl_host_desc
        msg = context.get('PARAMETER_HOST_MSG') or tmpl_host_msg
        alias = 'HOST_PROBLEM_ID: %s' % context['HOSTPROBLEMID']
        ack_author = context['HOSTACKAUTHOR']
        ack_comment = context['HOSTACKCOMMENT']
    else:
        tmpl_svc_msg = 'Check_MK: $HOSTNAME$/$SERVICEDESC$ $SERVICESHORTSTATE$'
        tmpl_svc_desc = """Host: $HOSTNAME$
Service:  $SERVICEDESC$
Event:    $EVENT_TXT$
Output:   $SERVICEOUTPUT$
Perfdata: $SERVICEPERFDATA$
$LONGSERVICEOUTPUT$
"""
        desc = context.get('PARAMETER_SVC_DESC') or tmpl_svc_desc
        msg = context.get('PARAMETER_SVC_MSG') or tmpl_svc_msg
        alias = 'SVC_PROBLEM_ID: %s' % context['SERVICEPROBLEMID']
        ack_author = context['SERVICEACKAUTHOR']
        ack_comment = context['SERVICEACKCOMMENT']

    desc = utils.substitute_context(desc, context)
    msg = utils.substitute_context(msg, context)

    if context['NOTIFICATIONTYPE'] == 'PROBLEM':
        handle_alert_creation(
            key,
            note_created,
            action_list,
            desc,
            alert_source,
            msg,
            priority,
            teams_list,
            tags_list,
            alias,
            owner,
            entity_value,
            host_url,
        )
    elif context['NOTIFICATIONTYPE'] == 'RECOVERY':
        handle_alert_deletion(key, owner, alias, alert_source, note_closed,
                              host_url)
    elif context['NOTIFICATIONTYPE'] == 'ACKNOWLEDGEMENT':
        handle_alert_ack(key, ack_author, ack_comment, alias, alert_source,
                         host_url)
    else:
        sys.stdout.write(
            six.ensure_str('Notification type %s not supported\n' %
                           (context['NOTIFICATIONTYPE'])))
        return 0
예제 #6
0
def main() -> int:
    context = utils.collect_context()

    if 'PARAMETER_PASSWORD' not in context:
        sys.stderr.write("API key not set\n")
        return 2

    api_key = retrieve_from_passwordstore(context['PARAMETER_PASSWORD'])
    note_created = context.get('PARAMETER_NOTE_CREATED') or 'Alert created by Check_MK'
    note_closed = context.get('PARAMETER_NOTE_CLOSED') or 'Alert closed by Check_MK'
    priority = context.get('PARAMETER_PRIORITY', 'P3')
    entity_value = context.get('PARAMETER_ENTITY', '')
    alert_source: Optional[str] = context.get('PARAMETER_SOURCE')
    owner: Optional[str] = context.get('PARAMETER_OWNER')
    host_url: Optional[str] = context.get("PARAMETER_URL")
    proxy_url: Optional[str] = context.get("PARAMETER_PROXY_URL")

    tags_list: List[str] = []
    if context.get('PARAMETER_TAGSS'):
        tags_list = context.get('PARAMETER_TAGSS', u'').split(" ")

    actions_list: List[str] = []
    if context.get('PARAMETER_ACTIONSS'):
        actions_list = context.get('PARAMETER_ACTIONSS', u'').split(" ")

    teams_list: List[Optional[Dict[str, str]]] = []
    if context.get('PARAMETER_TEAMSS'):
        for team in context['PARAMETER_TEAMSS'].split(" "):
            teams_list.append({'name': str(team), 'type': 'team'})

    if context['WHAT'] == 'HOST':
        tmpl_host_msg: str = "Check_MK: $HOSTNAME$ - $HOSTSHORTSTATE$"
        tmpl_host_desc: str = """Host: $HOSTNAME$
Event:    $EVENT_TXT$
Output:   $HOSTOUTPUT$
Perfdata: $HOSTPERFDATA$
$LONGHOSTOUTPUT$
"""
        desc = context.get('PARAMETER_HOST_DESC') or tmpl_host_desc
        msg = context.get('PARAMETER_HOST_MSG') or tmpl_host_msg
        alias = 'HOST_PROBLEM_ID: %s' % context['HOSTPROBLEMID']
        ack_author = context['HOSTACKAUTHOR']
        ack_comment = context['HOSTACKCOMMENT']
    else:
        tmpl_svc_msg = 'Check_MK: $HOSTNAME$/$SERVICEDESC$ $SERVICESHORTSTATE$'
        tmpl_svc_desc = """Host: $HOSTNAME$
Service:  $SERVICEDESC$
Event:    $EVENT_TXT$
Output:   $SERVICEOUTPUT$
Perfdata: $SERVICEPERFDATA$
$LONGSERVICEOUTPUT$
"""
        desc = context.get('PARAMETER_SVC_DESC') or tmpl_svc_desc
        msg = context.get('PARAMETER_SVC_MSG') or tmpl_svc_msg
        alias = 'SVC_PROBLEM_ID: %s' % context['SERVICEPROBLEMID']
        ack_author = context['SERVICEACKAUTHOR']
        ack_comment = context['SERVICEACKCOMMENT']

    desc = utils.substitute_context(desc, context)
    msg = utils.substitute_context(msg, context)

    connector = Connector(api_key, host_url, proxy_url)

    if context['NOTIFICATIONTYPE'] == 'PROBLEM':
        return connector.handle_alert_creation(
            note_created,
            actions_list,
            desc,
            msg,
            priority,
            teams_list,
            tags_list,
            entity_value,
            alert_source,
            alias,
            owner,
        )
    if context['NOTIFICATIONTYPE'] == 'RECOVERY':
        return connector.handle_alert_deletion(note_closed, owner, alias, alert_source)
    if context['NOTIFICATIONTYPE'] == 'ACKNOWLEDGEMENT':
        return connector.handle_alert_ack(ack_author, ack_comment, alias, alert_source)

    sys.stdout.write(
        ensure_str('Notification type %s not supported\n' % (context['NOTIFICATIONTYPE'])))
    return 0
예제 #7
0
def main():
    context = utils.collect_context()
    timeout = 10
    urgency = 3
    impact = 3
    ack_state = 0
    dtstart_state = 0
    dtend_state = 0

    for necessary in [
            'PARAMETER_URL', 'PARAMETER_USERNAME', 'PARAMETER_PASSWORD',
            'PARAMETER_CALLER'
    ]:
        if necessary not in context:
            sys.stderr.write("%s not set\n" % necessary)
            return 2

    hostname = context['HOSTNAME']
    url = context['PARAMETER_URL']
    user = context['PARAMETER_USERNAME']
    pwd = retrieve_from_passwordstore(context['PARAMETER_PASSWORD'])
    caller = context['PARAMETER_CALLER']

    if 'PARAMETER_TIMEOUT' in context:
        timeout = float(context['PARAMETER_TIMEOUT'])
    if 'PARAMETER_URGENCY' in context:
        urgency = PRIORITY_STATES[context['PARAMETER_URGENCY']]
    if 'PARAMETER_IMPACT' in context:
        impact = PRIORITY_STATES[context['PARAMETER_IMPACT']]
    if 'PARAMETER_ACK_STATE_START' in context:
        ack_state = COMMAND_STATES[context['PARAMETER_ACK_STATE_START']]
    if 'PARAMETER_DT_STATE_START' in context:
        dtstart_state = COMMAND_STATES[context['PARAMETER_DT_STATE_START']]
    if 'PARAMETER_DT_STATE_END' in context:
        dtend_state = COMMAND_STATES[context['PARAMETER_DT_STATE_END']]
    if context['WHAT'] == 'HOST':
        tmpl_host_short_desc = 'Check_MK: $HOSTNAME$ - $HOSTSHORTSTATE$'
        tmpl_host_desc = """Host: $HOSTNAME$
Event:    $EVENT_TXT$
Output:   $HOSTOUTPUT$
Perfdata: $HOSTPERFDATA$
$LONGHOSTOUTPUT$
"""
        short_desc = context.get(
            'PARAMETER_HOST_SHORT_DESC') or tmpl_host_short_desc
        desc = context.get('PARAMETER_HOST_DESC') or tmpl_host_desc
        problem_id = context['HOSTPROBLEMID']
        ack_author = context['HOSTACKAUTHOR']
        ack_comment = context['HOSTACKCOMMENT']
        servicename = context['HOSTOUTPUT']
    else:
        tmpl_svc_short_desc = 'Check_MK: $HOSTNAME$/$SERVICEDESC$ $SERVICESHORTSTATE$'
        tmpl_svc_desc = """Host: $HOSTNAME$
Service:  $SERVICEDESC$
Event:    $EVENT_TXT$
Output:   $SERVICEOUTPUT$
Perfdata: $SERVICEPERFDATA$
$LONGSERVICEOUTPUT$
"""
        short_desc = context.get(
            'PARAMETER_SVC_SHORT_DESC') or tmpl_svc_short_desc
        servicename = context['SERVICEDESC']
        desc = context.get('PARAMETER_SVC_DESC') or tmpl_svc_desc
        problem_id = context['SERVICEPROBLEMID']
        ack_author = context['SERVICEACKAUTHOR']
        ack_comment = context['SERVICEACKCOMMENT']

    short_desc = utils.substitute_context(short_desc, context)
    desc = utils.substitute_context(desc, context)

    if context['NOTIFICATIONTYPE'] == 'PROBLEM':
        handle_problem(url, user, pwd, short_desc, desc, hostname, servicename,
                       problem_id, caller, urgency, impact, timeout)
    elif context['NOTIFICATIONTYPE'] == 'RECOVERY':
        handle_recovery(problem_id, url, user, pwd, desc, caller, timeout)
    elif context['NOTIFICATIONTYPE'] == 'ACKNOWLEDGEMENT':
        handle_ack(problem_id, url, user, pwd, ack_comment, ack_author,
                   ack_state, caller, timeout)
    elif context['NOTIFICATIONTYPE'] == 'DOWNTIMESTART':
        desc = """Downtime was set.
User: $NOTIFICATIONAUTHOR$
Comment: $NOTIFICATIONCOMMENT$
"""
        desc = utils.substitute_context(desc, context)
        handle_downtime(problem_id, url, user, pwd, desc, "start",
                        dtstart_state, caller, timeout)
    elif context['NOTIFICATIONTYPE'] == 'DOWNTIMECANCELLED':
        desc = """Downtime expired.
"""
        handle_downtime(problem_id, url, user, pwd, desc, "end", dtend_state,
                        caller, timeout)
    else:
        sys.stdout.write("Noticication type %s not supported\n" %
                         (context['NOTIFICATIONTYPE']))
        return 0
예제 #8
0
def main() -> int:
    context = utils.collect_context()

    if "PARAMETER_PASSWORD" not in context:
        sys.stderr.write("API key not set\n")
        return 2

    api_key = retrieve_from_passwordstore(context["PARAMETER_PASSWORD"])
    note_created = context.get(
        "PARAMETER_NOTE_CREATED") or "Alert created by Check_MK"
    note_closed = context.get(
        "PARAMETER_NOTE_CLOSED") or "Alert closed by Check_MK"
    priority = context.get("PARAMETER_PRIORITY", "P3")
    entity_value = context.get("PARAMETER_ENTITY", "")
    alert_source: Optional[str] = context.get("PARAMETER_SOURCE")
    owner: Optional[str] = context.get("PARAMETER_OWNER")
    host_url: Optional[str] = context.get("PARAMETER_URL")
    proxy_url: Optional[str] = context.get("PARAMETER_PROXY_URL")

    tags_list: List[str] = []
    if context.get("PARAMETER_TAGSS"):
        tags_list = context.get("PARAMETER_TAGSS", "").split(" ")

    actions_list: List[str] = []
    if context.get("PARAMETER_ACTIONSS"):
        actions_list = context.get("PARAMETER_ACTIONSS", "").split(" ")

    teams_list: List[Optional[Dict[str, str]]] = []
    if context.get("PARAMETER_TEAMSS"):
        for team in context["PARAMETER_TEAMSS"].split(" "):
            teams_list.append({"name": str(team), "type": "team"})

    if context["WHAT"] == "HOST":
        tmpl_host_msg: str = "Check_MK: $HOSTNAME$ - $HOSTSHORTSTATE$"
        tmpl_host_desc: str = """Host: $HOSTNAME$
Event:    $EVENT_TXT$
Output:   $HOSTOUTPUT$
Perfdata: $HOSTPERFDATA$
$LONGHOSTOUTPUT$
"""
        desc = context.get("PARAMETER_HOST_DESC") or tmpl_host_desc
        msg = context.get("PARAMETER_HOST_MSG") or tmpl_host_msg
        alias = "HOST_PROBLEM_ID: %s" % context["HOSTPROBLEMID"]
        ack_author = context["HOSTACKAUTHOR"]
        ack_comment = context["HOSTACKCOMMENT"]
    else:
        tmpl_svc_msg = "Check_MK: $HOSTNAME$/$SERVICEDESC$ $SERVICESHORTSTATE$"
        tmpl_svc_desc = """Host: $HOSTNAME$
Service:  $SERVICEDESC$
Event:    $EVENT_TXT$
Output:   $SERVICEOUTPUT$
Perfdata: $SERVICEPERFDATA$
$LONGSERVICEOUTPUT$
"""
        desc = context.get("PARAMETER_SVC_DESC") or tmpl_svc_desc
        msg = context.get("PARAMETER_SVC_MSG") or tmpl_svc_msg
        alias = "SVC_PROBLEM_ID: %s" % context["SERVICEPROBLEMID"]
        ack_author = context["SERVICEACKAUTHOR"]
        ack_comment = context["SERVICEACKCOMMENT"]

    desc = utils.substitute_context(desc, context)
    msg = utils.substitute_context(msg, context)

    connector = Connector(api_key, host_url, proxy_url)

    if context["NOTIFICATIONTYPE"] == "PROBLEM":
        return connector.handle_alert_creation(
            note_created,
            actions_list,
            desc,
            msg,
            priority,
            teams_list,
            tags_list,
            entity_value,
            alert_source,
            alias,
            owner,
        )
    if context["NOTIFICATIONTYPE"] == "RECOVERY":
        return connector.handle_alert_deletion(note_closed, owner, alias,
                                               alert_source)
    if context["NOTIFICATIONTYPE"] == "ACKNOWLEDGEMENT":
        return connector.handle_alert_ack(ack_author, ack_comment, alias,
                                          alert_source)

    sys.stdout.write("Notification type %s not supported\n" %
                     (context["NOTIFICATIONTYPE"]))
    return 0