Exemple #1
0
def main():
    context = utils.collect_context()
    subject = get_subject(context)
    text = get_text(context)

    api_key = context["PARAMETER_API_KEY"]
    recipient_key = context["PARAMETER_RECIPIENT_KEY"]

    return send_push_notification(api_key, recipient_key, subject, text, context)
Exemple #2
0
def main() -> NoReturn:
    """Construct needed context and call the related class."""
    raw_context: RawContext = collect_context()

    context = _get_context_parameter(raw_context)

    if isinstance(context, Errors):
        sys.stdout.write(" ".join(context))
        sys.exit(2)

    sys.exit(process_notifications(context))
Exemple #3
0
def main():
    # gather all options from env
    context = utils.collect_context()

    # check if configured via flexible notifications
    if "PARAMETER_1" in context:
        context["PARAMETER_COMMUNITY"] = context["PARAMETER_1"]
        context["PARAMETER_DESTINATION"] = context["PARAMETER_2"]
        context["PARAMETER_BASEOID"] = context["PARAMETER_3"]

    base_oid = context.get("PARAMETER_BASEOID", "1.3.6.1.4.1.1234")

    # adjust these oids to your needs
    complete_url = "https://" + context["MONITORING_HOST"]
    if "OMD_SITE" in context:
        complete_url += "/" + context["OMD_SITE"]
    complete_url += context.get("SERVICEURL", context.get("HOSTURL", u''))

    oids = {
        base_oid + ".1":
        context['MONITORING_HOST'],
        base_oid + ".2":
        context['HOSTNAME'],
        base_oid + ".3":
        context['HOSTADDRESS'],
        base_oid + ".4":
        context.get('HOSTGROUPNAMES', ""),
        base_oid + ".5":
        context.get('SERVICEDESC', 'Connectivity'),
        base_oid + ".6":
        context.get('SERVICESTATE', context.get('HOSTSTATE')),
        base_oid + ".7":
        context.get('SERVICEOUTPUT', context.get("HOSTOUTPUT")),
        base_oid + ".8":
        "HARD",  # Notifications always are in HARDSTATE
        base_oid + ".9":
        context.get('SERVICEDESC', 'Connectivity'),
        base_oid + ".10":
        3,  # SPECIFIC TRAP (type) NUMBER
        base_oid + ".11":
        "Call number 123456",  # CALLOUT STRING
        base_oid + ".12":
        complete_url,
        base_oid + ".13":
        "%s alarm on host %s" %
        (context.get('SERVICEDESC', 'Connectivity'), context['HOSTNAME']),
        base_oid + ".14":
        context.get('SERVICEGROUPNAMES', ""),
    }

    sys.exit(
        send_trap(oids, context['PARAMETER_DESTINATION'],
                  context['PARAMETER_COMMUNITY']))
def main():
    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()

    # get all env vars to dict
    context = utils.collect_context()

    # ... and payload specified via command line
    for arg in args.payload:
        if arg:
            a = arg.split('=', 1)
            if a and a[0] and a[1]:
                context.update({a[0]: a[1]})

    if args.apikey is not None:
        apikey = args.apikey
    elif 'PARAMETER_WEBHOOK_URL' in context:
        apikey = context.get['PARAMETER_WBHOOK_URL']
    else:
        apikey = None

    if apikey is None:
        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"
        )
        exit(1)
    create_and_send(args.endpoint, args.port, apikey, context)

    exit(0)
Exemple #5
0
def main():
    if bulk_mode:
        content_txt = ""
        parameters, contexts = utils.read_bulk_contexts()
        hosts = set()
        for context in contexts:
            context.update(parameters)
            content_txt += construct_content(context)
            mailto = context["CONTACTEMAIL"]  # Assume the same in each context
            subject = context["SUBJECT"]
            hosts.add(context["HOSTNAME"])

        # Use the single context subject in case there is only one context in the bulk
        if len(contexts) > 1:
            subject = utils.get_bulk_notification_subject(contexts, hosts)

    else:
        # gather all options from env
        context = utils.collect_context()
        content_txt = construct_content(context)
        mailto = context["CONTACTEMAIL"]
        subject = context["SUBJECT"]

    if not mailto:  # e.g. empty field in user database
        sys.stdout.write(
            "Cannot send ASCII email: empty destination email address\n")
        sys.exit(2)

    # Create the mail and send it
    from_address = utils.format_address(
        context.get("PARAMETER_FROM_DISPLAY_NAME", ""),
        context.get("PARAMETER_FROM_ADDRESS", utils.default_from_address()),
    )
    reply_to = utils.format_address(
        context.get("PARAMETER_REPLY_TO_DISPLAY_NAME", ""),
        context.get("PARAMETER_REPLY_TO_ADDRESS", ""),
    )
    m = utils.set_mail_headers(
        mailto, subject, from_address, reply_to,
        MIMEText(content_txt, "plain", _charset="utf-8"))
    try:
        sys.exit(utils.send_mail_sendmail(m, mailto, from_address))
    except Exception as e:
        sys.stderr.write("Unhandled exception: %s\n" % e)
        # unhandled exception, don't retry this...
        sys.exit(2)
Exemple #6
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)
Exemple #7
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
def main():
    """
    Main part to sendout notification
    """
    context = utils.collect_context()

    api_url = context['PARAMETER_1']
    auth_user = context['PARAMETER_2']
    auth_password = context['PARAMETER_3']

    proxies = {}
    if 'PARAMETER_4' in context:
        proxies['https'] = context['PARAMETER_4']

    auth = HTTPBasicAuth(auth_user, auth_password)

    host_name = context['HOSTNAME']
    site_name = context['OMD_SITE']
    contacts = context['CONTACTS']
    service_account = site_name
    event_time = context['MICROTIME']
    long_plugin_output = ""

    if context['NOTIFICATIONTYPE'] == "PROBLEM":
        api_url += "checkmk/incident/create"
        if context['WHAT'] == "HOST":
            mngmt_pack = {
                "hostname": host_name,
                "contacts" : contacts,
                }
            source_id = "{}|{}".format(site_name, host_name)
            serverity = context['HOSTNAME']
            plugin_output = context['HOSTOUTPUT']
        else:
            service_name = context['SERVICEDESC']
            mngmt_pack = {
                "hostname": host_name,
                "servicename" : service_name,
                "contacts" : contacts,
                }
            source_id = "{}|{}|{}".format(site_name, host_name, service_name)
            serverity = context['SERVICESTATE']
            plugin_output = context['SERVICEOUTPUT']

        payload = {
            "QUELLE" : "Checkmk",
            "QUELLEID": source_id,
            "ZIEL" : "ServiceNow",
            "FUNKTION" : "create",
            "FQDN" : host_name,
            "MP" : mngmt_pack,
            "SERVERITY" : serverity,
            "DIENSTKONTO" : service_account,
            "EVENTZEITPUNKT" : event_time,
            "KURZBESCHREIBUNG" : plugin_output,
            "LANGBESCHREIBUNG" : long_plugin_output,
        }
    elif context['NOTIFICATIONTYPE'] == "RECOVERY":
        api_url += "checkmk/incident/close"
        if context['WHAT'] == "HOST":
            source_id = "{}|{}".format(site_name, host_name)
        else:
            service_name = context['SERVICEDESC']
            source_id = "{}|{}|{}".format(site_name, host_name, service_name)

        payload = {
            "QUELLEID": source_id,
            "ZIEL" : "ServiceNow",
            "ZIELID" : "TBD",
            "FUNKTION" : "close"
        }


    response = requests.post(api_url, json=payload, auth=auth, proxies=proxies)
    if response.status_code != 200:
        print(response.json())
        sys.exit(2)
    sys.exit(0)
Exemple #9
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
Exemple #10
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
Exemple #11
0
def main():
    context = utils.collect_context()
    tmpl_host_summary = 'Check_MK: $HOSTNAME$ - $HOSTSHORTSTATE$'
    tmpl_service_summary = 'Check_MK: $HOSTNAME$/$SERVICEDESC$ $SERVICESHORTSTATE$'
    tmpl_label = 'monitoring'

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

    if "PARAMETER_IGNORE_SSL" in context:
        sys.stdout.write(
            "Unverified HTTPS request warnings are ignored. Use with caution.\n"
        )
        jira = JIRA(server=context['PARAMETER_URL'],
                    basic_auth=(context['PARAMETER_USERNAME'],
                                context['PARAMETER_PASSWORD']),
                    options={'verify': False})
    else:
        jira = JIRA(server=context['PARAMETER_URL'],
                    basic_auth=(context['PARAMETER_USERNAME'],
                                context['PARAMETER_PASSWORD']))

    if context['WHAT'] == 'HOST':
        summary = context.get('PARAMETER_HOST_SUMMARY') or tmpl_host_summary
        svc_desc = context['HOSTOUTPUT']
        custom_field = int(context['PARAMETER_HOST_CUSTOMID'])
        custom_field_value = int(context['HOSTPROBLEMID'])
    else:
        summary = context.get(
            'PARAMETER_SERVICE_SUMMARY') or tmpl_service_summary
        svc_desc = context['SERVICEOUTPUT']
        custom_field = int(context['PARAMETER_SERVICE_CUSTOMID'])
        custom_field_value = int(context['SERVICEPROBLEMID'])

    context['SUBJECT'] = utils.substitute_context(summary, context)
    label = context.get('PARAMETER_LABEL') or tmpl_label
    newissue = {
        u'labels': [label],
        u'summary': context['SUBJECT'],
        u'description': svc_desc,
    }

    if 'PARAMETER_PROJECT' in context:
        newissue[u'project'] = {u'id': context['PARAMETER_PROJECT']}
    if 'CONTACT_JIRAPROJECT' in context:
        newissue[u'project'] = {u'id': context['CONTACT_JIRAPROJECT']}
    if 'PARAMETER_ISSUETYPE' in context:
        newissue[u'issuetype'] = {u'id': context['PARAMETER_ISSUETYPE']}
    if 'CONTACT_JIRAISSUETYPE' in context:
        newissue[u'issuetype'] = {u'id': context['CONTACT_JIRAISSUETYPE']}
    if 'PARAMETER_PRIORITY' in context:
        newissue[u'priority'] = {u'id': context['PARAMETER_PRIORITY']}
    if 'CONTACT_JIRAPRIORITY' in context:
        newissue[u'priority'] = {u'id': context['CONTACT_JIRAPRIORITY']}
    if 'project' not in newissue:
        sys.stderr.write("No JIRA project ID set, discarding notification")
        return 2
    if 'issuetype' not in newissue:
        sys.stderr.write("No JIRA issue type ID set")
        return 2

    try:
        custom_field_exists = jira.search_issues(
            "cf[%d]=%d" % (custom_field, custom_field_value))
    except JIRAError, err:
        sys.stderr.write(
            'Unable to query custom field search, JIRA response code %s, %s' %
            (err.status_code, err.text))
        return 2
Exemple #12
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
Exemple #13
0
def main():
    context = utils.collect_context()
    tmpl_host_summary = 'Check_MK: $HOSTNAME$ - $HOSTSHORTSTATE$'
    tmpl_service_summary = 'Check_MK: $HOSTNAME$/$SERVICEDESC$ $SERVICESHORTSTATE$'
    tmpl_label = 'monitoring'

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

    if "PARAMETER_IGNORE_SSL" in context:
        sys.stdout.write(
            "Unverified HTTPS request warnings are ignored. Use with caution.\n"
        )
        jira = JIRA(server=context['PARAMETER_URL'],
                    basic_auth=(context['PARAMETER_USERNAME'],
                                context['PARAMETER_PASSWORD']),
                    options={'verify': False})
    else:
        jira = JIRA(server=context['PARAMETER_URL'],
                    basic_auth=(context['PARAMETER_USERNAME'],
                                context['PARAMETER_PASSWORD']))

    if context['WHAT'] == 'HOST':
        summary = context.get('PARAMETER_HOST_SUMMARY') or tmpl_host_summary
        svc_desc = context['HOSTOUTPUT']
        custom_field = int(context['PARAMETER_HOST_CUSTOMID'])
        custom_field_value = int(context['HOSTPROBLEMID'])
    else:
        summary = context.get(
            'PARAMETER_SERVICE_SUMMARY') or tmpl_service_summary
        svc_desc = context['SERVICEOUTPUT']
        custom_field = int(context['PARAMETER_SERVICE_CUSTOMID'])
        custom_field_value = int(context['SERVICEPROBLEMID'])

    context['SUBJECT'] = utils.substitute_context(summary, context)
    label = context.get('PARAMETER_LABEL') or tmpl_label
    newissue = {
        u'labels': [label],
        u'summary': context['SUBJECT'],
        u'description': svc_desc,
    }

    if 'PARAMETER_PROJECT' in context:
        newissue[u'project'] = {u'id': context['PARAMETER_PROJECT']}
    if 'CONTACT_JIRAPROJECT' in context:
        newissue[u'project'] = {u'id': context['CONTACT_JIRAPROJECT']}
    if 'PARAMETER_ISSUETYPE' in context:
        newissue[u'issuetype'] = {u'id': context['PARAMETER_ISSUETYPE']}
    if 'CONTACT_JIRAISSUETYPE' in context:
        newissue[u'issuetype'] = {u'id': context['CONTACT_JIRAISSUETYPE']}
    if 'PARAMETER_PRIORITY' in context:
        newissue[u'priority'] = {u'id': context['PARAMETER_PRIORITY']}
    if 'CONTACT_JIRAPRIORITY' in context:
        newissue[u'priority'] = {u'id': context['CONTACT_JIRAPRIORITY']}
    if 'project' not in newissue:
        sys.stderr.write("No JIRA project ID set, discarding notification")
        return 2
    if 'issuetype' not in newissue:
        sys.stderr.write("No JIRA issue type ID set")
        return 2

    try:
        custom_field_exists = jira.search_issues(
            "cf[%d]=%d" % (custom_field, custom_field_value))
    except JIRAError as err:
        sys.stderr.write(
            'Unable to query custom field search, JIRA response code %s, %s' %
            (err.status_code, err.text))
        return 2

    if not custom_field_exists:
        newissue[u'customfield_%d' % custom_field] = custom_field_value

    if context['NOTIFICATIONTYPE'] == 'PROBLEM':
        try:
            issue = jira.create_issue(fields=newissue)
        except JIRAError as err:
            sys.stderr.write(
                'Unable to create issue, JIRA response code %s, %s' %
                (err.status_code, err.text))
            return 2
        sys.stdout.write('Created %s\n' % issue.permalink())
        if 'PARAMETER_MONITORING' in context:
            if context['PARAMETER_MONITORING'].endswith('/'):
                # remove trailing slash
                context['PARAMETER_MONITORING'] = context[
                    'PARAMETER_MONITORING'][:-1]
            if context['WHAT'] == 'SERVICE':
                url = context['PARAMETER_MONITORING'] + context['SERVICEURL']
            else:
                url = context['PARAMETER_MONITORING'] + context['HOSTURL']
            try:
                rl = jira.add_simple_link(issue, {
                    'url': url,
                    'title': 'Monitoring'
                })
            except JIRAError as err:
                sys.stderr.write(
                    'Unable to create link in issue, JIRA response code %s, %s\n'
                    % (err.status_code, err.text))
                return 2
            sys.stdout.write('Created JIRA simple link: %s' % rl)

    if context['NOTIFICATIONTYPE'] == 'RECOVERY' and custom_field_exists:
        if "PARAMETER_RESOLUTION" not in context:
            sys.stderr.write(
                "Ticket resolution not enabled in wato rule. Don't send a resolution to jira\n"
            )
            return 0
        else:
            resolution = None
            if 'PARAMETER_RESOLUTION' in context:
                resolution = context['PARAMETER_RESOLUTION']
            if 'CONTACT_JIRARESOLUTION' in context:
                resolution = context['CONTACT_JIRARESOLUTION']
            if resolution is None:
                sys.stderr.write("No JIRA resolution ID set")
                return 2
        for issue in custom_field_exists:
            try:
                jira.transition_issue(issue,
                                      resolution,
                                      comment=newissue['description'])
                sys.stdout.write('Resolved %s' % issue.permalink())
            except JIRAError as err:
                sys.stderr.write(
                    'Unable to resolve %s, JIRA response code %s, %s' %
                    (issue.permalink(), err.status_code, err.text))
                return 2