<commit_before>#! /usr/bin/env python


import json
import sys
import smtplib
from email.mime.text import MIMEText
import re
import sensuutils


def email(e_from='sensu', e_to=['root@localhost'], e_body='',
          e_smtp_host='localhost', e_smtp_port='25', e_subject='Sensu notification'):
    '''e_from = email from,
       e_to = email to,
       e_body = email body
       e_smtp_host = smtp server to use
       e_smtp_port = smtp port to use
       '''
    msg = MIMEText(e_body)
    msg['Subject'] = e_subject
    msg['From'] = e_from
    e_to = ', '.join(e_to)
    msg['To'] = e_to

    s = smtplib.SMTP(host=e_smtp_host, port=e_smtp_port, timeout=10)
    s.sendmail(e_from, [e_to], msg.as_string())
    s.quit()


def email_template(event):
    '''create the email body based on this template
    and return it as a string'''

    client_name = str(event['client']['name'])
    client_ip = str(event['client']['address'])
    check_name = str(event['check']['name'])

    check = event['check']
    if 'command' in check.keys():
        check_command = str(event['check']['command'])
    else:
        check_command = ''

    check_status = str(event['check']['status'])
    check_output = str(event['check']['output'])
    event_occurrences = str(event['occurrences'])
    event_last_check = str(event['check']['executed'])
    event_id = str(event['id'])

    status_replace = {
        '0': 'OK',
        '1': 'WARNING',
        '2': 'CRITICAL',
        '3': 'UNKNOWN'
    }

    for k, v in status_replace.items():
        check_status = re.sub(k, v, check_status)

    email_body = """
    SENSU NOTIFICATION
    ==================
    Host: {0}
    IP: {1}

    Status: {8}
    Check: {2}
    Command: {3}
    Output: {4}
    Occurrences: {5}
    Last check: {6}
    Event Id: {7}
    """
    e_subject_text = '(sensu) ' + check_status + ': ' + client_name + ': ' + check_name
    return email_body.format(client_name, client_ip, check_name, check_command, check_output, event_occurrences, event_last_check, event_id, check_status), e_subject_text


def main(data):
    '''gets data from stdin, then
    sanitizes, then loads the json and
    until I have a function to create the
    mail body simply converts the data from json/
    dictionary to a string'''

    data = sensuutils.sanitize(data)
    event = json.loads(data)

    settings = sensuutils.yamlconfig(filename='/etc/sensu/conf.d/sensu-mailer.yaml')
    settings = settings['settings']

    e_to = settings['e_to']
    if type(e_to) is not list:
        sys.exit('Exception: e_to must be an array')
    e_from = settings['e_from']
    e_smtp_host = settings['e_smtp_host']
    e_smtp_port = settings['e_smtp_port']

    if sensuutils.checkeventstate(event):
        if sensuutils.checkstashes(event):
            str_event, e_subject_text = email_template(event)
            email(e_from=e_from, e_to=e_to, e_body=str_event,
                  e_smtp_host=e_smtp_host, e_smtp_port=e_smtp_port,
                  e_subject=e_subject_text)


if __name__ == "__main__":
    data = ''
    for line in sys.stdin:
        data += line
    main(data)
<commit_msg>try and load handler config from json passed to script<commit_after>#! /usr/bin/env python


import json
import sys
import smtplib
from email.mime.text import MIMEText
import re
import sensuutils
import os


def email(e_from='sensu', e_to=['root@localhost'], e_body='',
          e_smtp_host='localhost', e_smtp_port='25', e_subject='Sensu notification'):
    '''e_from = email from,
       e_to = email to,
       e_body = email body
       e_smtp_host = smtp server to use
       e_smtp_port = smtp port to use
       '''
    msg = MIMEText(e_body)
    msg['Subject'] = e_subject
    msg['From'] = e_from
    e_to = ', '.join(e_to)
    msg['To'] = e_to

    s = smtplib.SMTP(host=e_smtp_host, port=e_smtp_port, timeout=10)
    s.sendmail(e_from, [e_to], msg.as_string())
    s.quit()


def email_template(event):
    '''create the email body based on this template
    and return it as a string'''

    client_name = str(event['client']['name'])
    client_ip = str(event['client']['address'])
    check_name = str(event['check']['name'])

    check = event['check']
    if 'command' in check.keys():
        check_command = str(event['check']['command'])
    else:
        check_command = ''

    check_status = str(event['check']['status'])
    check_output = str(event['check']['output'])
    event_occurrences = str(event['occurrences'])
    event_last_check = str(event['check']['executed'])
    event_id = str(event['id'])

    status_replace = {
        '0': 'OK',
        '1': 'WARNING',
        '2': 'CRITICAL',
        '3': 'UNKNOWN'
    }

    for k, v in status_replace.items():
        check_status = re.sub(k, v, check_status)

    email_body = """
    SENSU NOTIFICATION
    ==================
    Host: {0}
    IP: {1}

    Status: {8}
    Check: {2}
    Command: {3}
    Output: {4}
    Occurrences: {5}
    Last check: {6}
    Event Id: {7}
    """
    e_subject_text = '(sensu) ' + check_status + ': ' + client_name + ': ' + check_name
    return email_body.format(client_name, client_ip, check_name, check_command, check_output, event_occurrences, event_last_check, event_id, check_status), e_subject_text


def main(data):
    '''gets data from stdin, then
    sanitizes, then loads the json and
    until I have a function to create the
    mail body simply converts the data from json/
    dictionary to a string'''

    data = sensuutils.sanitize(data)
    event = json.loads(data)
    try:
        settings_file = str(event['handler']['name'])
    except:
        settings_file = 'sensu-mailer'

    if os.path.exists('/etc/sensu/conf.d/' + settings_file + '.yaml'):
        settings = sensuutils.yamlconfig(filename='/etc/sensu/conf.d/' + settings_file + '.yaml')
    elif os.path.exists('/etc/sensu/conf.d/settings.yaml'):
        settings = sensuutils.yamlconfig()
    else:
        sys.exit("Unable to find config file: " + settings_file + ".yaml nor settings.yaml")

    settings = settings['settings']
    e_to = settings['e_to']
    if type(e_to) is not list:
        sys.exit('Exception: e_to must be an array')
    e_from = settings['e_from']
    e_smtp_host = settings['e_smtp_host']
    e_smtp_port = settings['e_smtp_port']

    if sensuutils.checkeventstate(event):
        if sensuutils.checkstashes(event):
            str_event, e_subject_text = email_template(event)
            email(e_from=e_from, e_to=e_to, e_body=str_event,
                  e_smtp_host=e_smtp_host, e_smtp_port=e_smtp_port,
                  e_subject=e_subject_text)


if __name__ == "__main__":
    data = ''
    for line in sys.stdin:
        data += line
    main(data)

{'fraction_non_alphanumeric': 0.14018135870373125, 'fraction_numerical': 0.00505425895644418, 'mean_word_length': 3.043269230769231, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5736663', 'n_tokens_mistral': 2388, 'n_tokens_neox': 2295, 'n_words': 527}