Exemplo n.º 1
0
    def notify(cls, alert, *args, **kwargs):

        current_span = extract_span_from_kwargs(**kwargs)

        alert_def = alert['alert_def']
        current_span.set_tag('alert_id', alert_def['id'])

        entity = alert.get('entity')
        is_changed = alert.get('alert_changed', False)
        is_alert = alert.get('is_alert', False)

        current_span.set_tag('entity', entity['id'])
        current_span.set_tag('alert_changed', bool(is_changed))
        current_span.set_tag('is_alert', is_alert)

        provider_url = cls._config.get('notifications.sms.provider_url',
                                       SMS_PROVIDER_URL)
        phone_numbers = BaseNotification.resolve_group(args, phone=True)
        repeat = kwargs.get('repeat', 0)

        maxlen = cls._config.get('notifications.sms.maxlength', SMS_MAXLENGTH)
        message = cls._get_subject(
            alert, custom_message=kwargs.get('message'))[:maxlen]

        request_params = {
            'to': '',
            'key': cls._config['notifications.sms.apikey'],
            'from': cls._config.get('notifications.sms.sender', SMS_SENDER),
            'route': cls._config.get('notifications.sms.route', SMS_ROUTE),
            'message': message,
            'cost': 1,
            'message_id': 1,
        }

        try:
            if cls._config.get('notifications.sms.on', True):
                for phone in phone_numbers:
                    request_params['to'] = phone
                    r = requests.get(provider_url,
                                     params=request_params,
                                     verify=False)
                    url_secured = r.url.replace(
                        request_params['key'],
                        '*' * len(request_params['key']))
                    logger.info(
                        'SMS sent: request to %s --> status: %s, response headers: %s, response body: %s',
                        url_secured, r.status_code, r.headers, r.text)
                    r.raise_for_status()
        except Exception as e:
            current_span.set_tag('error', True)
            current_span.log_kv({'exception': str(e)})
            logger.exception(
                'Failed to send sms for alert %s with id %s to: %s',
                alert_def['name'], alert_def['id'], list(phone_numbers))
        finally:
            return repeat
Exemplo n.º 2
0
    def send(cls, alert, *args, **kwargs):
        sender = cls._config.get('notifications.mail.sender')
        subject = cls._get_subject(alert, custom_message=kwargs.get('subject'))
        html = kwargs.get('html', False)
        cc = kwargs.get('cc', [])
        hide_recipients = kwargs.get('hide_recipients', True)
        repeat = kwargs.get('repeat', 0)
        expanded_alert_name = cls._get_expanded_alert_name(alert)

        try:
            tmpl = jinja_env.get_template('alert.txt')
            body_plain = tmpl.render(expanded_alert_name=expanded_alert_name, **alert)
        except Exception:
            logger.exception('Error parsing email template for alert %s with id %s', alert['name'], alert['id'])
        else:
            if html:
                msg = MIMEMultipart('alternative')
                tmpl = jinja_env.get_template('alert.html')
                body_html = tmpl.render(expanded_alert_name=expanded_alert_name, **alert)
                part1 = MIMEText(body_plain.encode('utf-8'), 'plain', 'utf-8')
                part2 = MIMEText(body_html.encode('utf-8'), 'html', 'utf-8')
                msg.attach(part1)
                msg.attach(part2)
            else:
                msg = MIMEText(body_plain.encode('utf-8'), 'plain', 'utf-8')

            msg['Subject'] = subject
            msg['From'] = 'ZMON 2 <{}>'.format(sender)

            args = BaseNotification.resolve_group(args)

            if hide_recipients:
                msg['To'] = 'Undisclosed Recipients <{}>'.format(sender)
                msg['Bcc'] = ', '.join(args)
            else:
                msg['To'] = ', '.join(args)
            msg['Cc'] = ', '.join(cc)

            if cls._config.get('notifications.mail.on', True):
                try:
                    s = smtplib.SMTP(cls._config.get('notifications.mail.host', 'localhost'),
                                     cls._config.get('notifications.mail.port', 25))
                except Exception:
                    logger.exception('Error connecting to SMTP server for alert %s with id %s', alert['name'],
                                     alert['id'])
                else:
                    try:
                        s.sendmail(sender, list(args) + cc, msg.as_string())
                    except Exception:
                        logger.exception('Error sending email for alert %s with id %s', alert['name'], alert['id'])
                    finally:
                        s.quit()
        finally:
            return repeat
Exemplo n.º 3
0
    def notify(cls, alert, *args, **kwargs):

        current_span = extract_span_from_kwargs(**kwargs)

        alert_def = alert['alert_def']
        current_span.set_tag('alert_id', alert_def['id'])

        entity = alert.get('entity')
        is_changed = alert.get('alert_changed', False)
        is_alert = alert.get('is_alert', False)

        current_span.set_tag('entity', entity['id'])
        current_span.set_tag('alert_changed', bool(is_changed))
        current_span.set_tag('is_alert', is_alert)

        provider_url = cls._config.get('notifications.sms.provider_url', SMS_PROVIDER_URL)
        phone_numbers = BaseNotification.resolve_group(args, phone=True)
        repeat = kwargs.get('repeat', 0)

        maxlen = cls._config.get('notifications.sms.maxlength', SMS_MAXLENGTH)
        message = cls._get_subject(alert, custom_message=kwargs.get('message'))[:maxlen]

        request_params = {
            'to': '',
            'key': cls._config['notifications.sms.apikey'],
            'from': cls._config.get('notifications.sms.sender', SMS_SENDER),
            'route': cls._config.get('notifications.sms.route', SMS_ROUTE),
            'message': message,
            'cost': 1,
            'message_id': 1,
        }

        try:
            if cls._config.get('notifications.sms.on', True):
                for phone in phone_numbers:
                    request_params['to'] = phone
                    r = requests.get(provider_url, params=request_params, verify=False)
                    url_secured = r.url.replace(request_params['key'], '*' * len(request_params['key']))
                    logger.info('SMS sent: request to %s --> status: %s, response headers: %s, response body: %s',
                                url_secured, r.status_code, r.headers, r.text)
                    r.raise_for_status()
        except Exception:
            current_span.set_tag('error', True)
            current_span.log_kv({'exception': traceback.format_exc()})
            logger.exception('Failed to send sms for alert %s with id %s to: %s', alert_def['name'], alert_def['id'],
                             list(phone_numbers))
        finally:
            return repeat
Exemplo n.º 4
0
    def notify(cls, alert, *args, **kwargs):
        provider_url = cls._config.get('notifications.sms.provider_url',
                                       SMS_PROVIDER_URL)
        phone_numbers = BaseNotification.resolve_group(args, phone=True)
        repeat = kwargs.get('repeat', 0)

        maxlen = cls._config.get('notifications.sms.maxlength', SMS_MAXLENGTH)
        message = cls._get_subject(
            alert, custom_message=kwargs.get('message'))[:maxlen]

        request_params = {
            'to': '',
            'key': cls._config['notifications.sms.apikey'],
            'from': cls._config.get('notifications.sms.sender', SMS_SENDER),
            'route': cls._config.get('notifications.sms.route', SMS_ROUTE),
            'message': message,
            'cost': 1,
            'message_id': 1,
        }

        # alert_id = alert.get('alert_def', {}).get('id', 0)
        # entity = alert.get('entity', {}).get('id', 0)

        try:
            if cls._config.get('notifications.sms.on', True):
                for phone in phone_numbers:
                    request_params['to'] = phone
                    r = requests.get(provider_url,
                                     params=request_params,
                                     verify=False)
                    url_secured = r.url.replace(
                        request_params['key'],
                        '*' * len(request_params['key']))
                    logger.info(
                        'SMS sent: request to %s --> status: %s, response headers: %s, response body: %s',
                        url_secured, r.status_code, r.headers, r.text)
                    r.raise_for_status()
                    # eventlog.log(cls._EVENTS['SMS_SENT'].id, alertId=alert_id, entity=entity, phoneNumber=phone,
                    #              httpStatus=r.status_code)
        except Exception:
            logger.exception(
                'Failed to send sms for alert %s with id %s to: %s',
                alert['name'], alert['id'], list(phone_numbers))
        finally:
            return repeat
Exemplo n.º 5
0
    def send(cls, alert, *args, **kwargs):
        provider_url = cls._config.get('notifications.sms.provider_url', SMS_PROVIDER_URL)
        phone_numbers = BaseNotification.resolve_group(args, phone=True)
        repeat = kwargs.get('repeat', 0)

        maxlen = cls._config.get('notifications.sms.maxlength', SMS_MAXLENGTH)
        message = cls._get_subject(alert, custom_message=kwargs.get('message'))[:maxlen]

        request_params = {
            'to': '',
            'key': cls._config['notifications.sms.apikey'],
            'from': cls._config.get('notifications.sms.sender', SMS_SENDER),
            'route': cls._config.get('notifications.sms.route', SMS_ROUTE),
            'message': message,
            'cost': 1,
            'message_id': 1,
        }

        alert_id = alert.get('alert_def', {}).get('id', 0)
        entity = alert.get('entity', {}).get('id', 0)

        try:
            if cls._config.get('notifications.sms.on', True):
                for phone in phone_numbers:
                    request_params['to'] = phone
                    r = requests.get(provider_url, params=request_params, verify=False)
                    url_secured = r.url.replace(request_params['key'], '*' * len(request_params['key']))
                    logger.info('SMS sent: request to %s --> status: %s, response headers: %s, response body: %s',
                                url_secured, r.status_code, r.headers, r.text)
                    r.raise_for_status()
                    eventlog.log(cls._EVENTS['SMS_SENT'].id, alertId=alert_id, entity=entity, phoneNumber=phone,
                                 httpStatus=r.status_code)
        except Exception:
            logger.exception('Failed to send sms for alert %s with id %s to: %s', alert['name'], alert['id'],
                             list(phone_numbers))
        finally:
            return repeat
Exemplo n.º 6
0
    def notify(cls, alert, *args, **kwargs):

        current_span = extract_span_from_kwargs(**kwargs)

        repeat = kwargs.get('repeat', 0)
        alert_def = alert['alert_def']
        per_entity = kwargs.get('per_entity', True)

        current_span.set_tag('alert_id', alert_def['id'])

        entity = alert.get('entity', {})
        is_changed = alert.get('alert_changed', False)
        is_alert = alert.get('is_alert', False)

        current_span.set_tag('entity', entity.get('id'))
        current_span.set_tag('alert_changed', bool(is_changed))
        current_span.set_tag('is_alert', is_alert)

        if not cls._config.get('notifications.mail.on', True):
            current_span.set_tag('mail_enabled', False)
            logger.info('Not sending email for alert: {}. Mail notification is not enabled.'.format(alert_def['id']))
            return repeat

        if not is_changed and not per_entity:
            return repeat

        sender = cls._config.get('notifications.mail.sender')
        subject = cls._get_subject(alert, custom_message=kwargs.get('subject'))
        html = kwargs.get('html', False)

        cc = kwargs.get('cc', [])
        if type(cc) is not list:
            cc = [cc]

        hide_recipients = kwargs.get('hide_recipients', True)
        include_value = kwargs.get('include_value', True)
        include_definition = kwargs.get('include_definition', True)
        include_captures = kwargs.get('include_captures', True)
        include_entity = kwargs.get('include_entity', True)
        expanded_alert_name = cls._get_expanded_alert_name(alert)

        zmon_host = kwargs.get('zmon_host', cls._config.get('zmon.host'))
        alert_url = urlparse.urljoin(zmon_host, '/#/alert-details/{}'.format(alert_def['id'])) if zmon_host else ''

        try:
            tmpl = jinja_env.get_template('alert.txt')
            body_plain = tmpl.render(expanded_alert_name=expanded_alert_name,
                                     include_value=include_value,
                                     include_definition=include_definition,
                                     include_captures=include_captures,
                                     include_entity=include_entity,
                                     alert_url=alert_url,
                                     **alert)
        except Exception:
            current_span.set_tag('error', True)
            current_span.log_kv({'exception': traceback.format_exc()})
            logger.exception('Error parsing email template for alert %s with id %s', alert_def['name'], alert_def['id'])
        else:
            if html:
                current_span.set_tag('html', True)
                msg = MIMEMultipart('alternative')
                tmpl = jinja_env.get_template('alert.html')
                body_html = tmpl.render(expanded_alert_name=expanded_alert_name,
                                        include_value=include_value,
                                        include_definition=include_definition,
                                        include_captures=include_captures,
                                        include_entity=include_entity,
                                        alert_url=alert_url,
                                        **alert)
                part1 = MIMEText(body_plain.encode('utf-8'), 'plain', 'utf-8')
                part2 = MIMEText(body_html.encode('utf-8'), 'html', 'utf-8')
                msg.attach(part1)
                msg.attach(part2)
            else:
                msg = MIMEText(body_plain.encode('utf-8'), 'plain', 'utf-8')

            msg['Subject'] = subject
            msg['From'] = 'ZMON 2 <{}>'.format(sender)

            args = BaseNotification.resolve_group(args)

            if hide_recipients:
                msg['To'] = 'Undisclosed Recipients <{}>'.format(sender)
                msg['Bcc'] = ', '.join(args)
            else:
                msg['To'] = ', '.join(args)
            msg['Cc'] = ', '.join(cc)

            mail_host = cls._config.get('notifications.mail.host', 'localhost')
            mail_port = cls._config.get('notifications.mail.port', '25')

            try:
                if mail_host != 'localhost':
                    if cls._config.get('notifications.mail.tls', False):

                        logger.info('Mail notification using TLS!')
                        current_span.set_tag('tls', True)

                        s = smtplib.SMTP(mail_host, mail_port)
                        s.ehlo()
                        if not s.has_extn('STARTTLS'):
                            raise NotificationError('Mail server ({}) does not support TLS!'.format(mail_host))
                        s.starttls()
                        s.ehlo()
                    else:
                        current_span.set_tag('tls', False)
                        s = smtplib.SMTP_SSL(mail_host, mail_port)
                else:
                    s = smtplib.SMTP(mail_host, mail_port)

            except Exception:
                current_span.set_tag('error', True)
                logger.exception('Error connecting to SMTP server %s for alert %s with id %s',
                                 mail_host, alert_def['name'], alert_def['id'])
            else:
                try:
                    mail_user = cls._config.get('notifications.mail.user', None)
                    if mail_user is not None:
                        s.login(mail_user, cls._config.get('notifications.mail.password'))

                    s.sendmail(sender, list(args) + cc, msg.as_string())
                except SMTPAuthenticationError:
                    logger.exception(
                        'Error sending email for alert %s with id %s: authentication failed for %s',
                        alert_def['name'], alert_def['id'], mail_user)
                except Exception:
                    current_span.set_tag('error', True)
                    current_span.log_kv({'exception': traceback.format_exc()})
                    logger.exception(
                        'Error sending email for alert %s with id %s', alert_def['name'], alert_def['id'])
                finally:
                    s.quit()
        finally:
            return repeat
Exemplo n.º 7
0
    def send(cls, alert, *args, **kwargs):

        alert_def = alert['alert_def']
        logger.info("Sending email for alert: {}".format(alert_def['id']))

        sender = cls._config.get('notifications.mail.sender')
        subject = cls._get_subject(alert, custom_message=kwargs.get('subject'))
        html = kwargs.get('html', False)
        cc = kwargs.get('cc', [])
        hide_recipients = kwargs.get('hide_recipients', True)
        repeat = kwargs.get('repeat', 0)
        include_value = kwargs.get('include_value', True)
        include_definition = kwargs.get('include_definition', True)
        include_captures = kwargs.get('include_captures', True)
        include_entity = kwargs.get('include_entity', True)
        expanded_alert_name = cls._get_expanded_alert_name(alert)

        try:
            tmpl = jinja_env.get_template('alert.txt')
            body_plain = tmpl.render(expanded_alert_name=expanded_alert_name,
                                     include_value=include_value,
                                     include_definition=include_definition,
                                     include_captures=include_captures,
                                     include_entity=include_entity,
                                     **alert)
        except Exception:
            logger.exception('Error parsing email template for alert %s with id %s', alert_def['name'], alert_def['id'])
        else:
            if html:
                msg = MIMEMultipart('alternative')
                tmpl = jinja_env.get_template('alert.html')
                body_html = tmpl.render(expanded_alert_name=expanded_alert_name,
                                        include_value=include_value,
                                        include_definition=include_definition,
                                        include_captures=include_captures,
                                        include_entity=include_entity,
                                        **alert)
                part1 = MIMEText(body_plain.encode('utf-8'), 'plain', 'utf-8')
                part2 = MIMEText(body_html.encode('utf-8'), 'html', 'utf-8')
                msg.attach(part1)
                msg.attach(part2)
            else:
                msg = MIMEText(body_plain.encode('utf-8'), 'plain', 'utf-8')

            msg['Subject'] = subject
            msg['From'] = 'ZMON 2 <{}>'.format(sender)

            args = BaseNotification.resolve_group(args)

            if hide_recipients:
                msg['To'] = 'Undisclosed Recipients <{}>'.format(sender)
                msg['Bcc'] = ', '.join(args)
            else:
                msg['To'] = ', '.join(args)
            msg['Cc'] = ', '.join(cc)

            mail_host = cls._config.get('notifications.mail.host', 'localhost')
            mail_port = cls._config.get('notifications.mail.port', '25')

            # logger.info("Relaying via %s %s", mail_host, mail_port)

            if cls._config.get('notifications.mail.on', True):
                try:
                    if mail_host != 'localhost':
                        s = smtplib.SMTP_SSL(mail_host, mail_port)
                    else:
                        s = smtplib.SMTP(mail_host, mail_port)

                except Exception:
                    logger.exception('Error connecting to SMTP server %s for alert %s with id %s',
                                     mail_host, alert_def['name'], alert_def['id'])
                else:
                    try:
                        mail_user = cls._config.get('notifications.mail.user', None)
                        if mail_user is not None:
                            s.login(mail_user, cls._config.get('notifications.mail.password'))

                        s.sendmail(sender, list(args) + cc, msg.as_string())
                    except SMTPAuthenticationError:
                        logger.exception('Error sending email for alert %s with id %s: authentication failed for %s', alert_def['name'], alert_def['id'], mail_user)
                    except Exception:
                        logger.exception('Error sending email for alert %s with id %s', alert_def['name'], alert_def['id'])
                    finally:
                        s.quit()
        finally:
            return repeat