Filling in the chapter 4 alerts consumer

This commit is contained in:
Dan Buch 2012-11-20 07:39:33 -05:00
parent 0be6b37318
commit 4e980011d6
2 changed files with 100 additions and 0 deletions

View File

@ -0,0 +1,100 @@
from __future__ import print_function
import json
import smtplib
import sys
import pika
AMQP_SERVER = 'localhost'
AMQP_USER = 'alert_user'
AMQP_PASS = 'alertme'
AMQP_VHOST = '/'
AMQP_EXCHANGE = 'alerts'
OPS_EMAILS = ['daniel.buch+sylvilagus-alerts-ops@gmail.com']
ADMIN_EMAILS = ['daniel.buch+sylvilagus-alerts-admin@gmail.com']
def main():
creds_broker = pika.PlainCredentials(AMQP_USER, AMQP_PASS)
conn_params = pika.ConnectionParameters(AMQP_SERVER,
virtual_host=AMQP_VHOST,
credentials=creds_broker)
conn_broker = pika.BlockingConnection(conn_params)
channel = conn_broker.channel()
channel.exchange_declare(exchange=AMQP_EXCHANGE,
exchange_type='topic',
auto_delete=False)
channel.queue_declare(queue='critical', auto_delete=False)
channel.queue_bind(queue='critical',
exchange='alerts',
routing_key='critical.*')
channel.queue_declare(queue='rate_limit', auto_delete=False)
channel.queue_bind(queue='rate_limit',
exchange='alerts',
routing_key='*.rate_limit')
channel.basic_consume(critical_notify,
queue='critical',
no_ack=False,
consumer_tag='critical')
channel.basic_consume(rate_limit_notify,
queue='rate_limit',
no_ack=False,
consumer_tag='rate_limit')
try:
print('Ready for alerts!')
channel.start_consuming()
except KeyboardInterrupt:
conn_broker.close()
return 0
def send_mail(recipients, subject, message):
"""Email generator for received alerts."""
headers = '\r\n'.join([
'From: alerts@sylvilagus.local',
'To: ',
'Date: ',
'Subject: {}'.format(subject)
]) + '\r\n'
smtp_server = smtplib.SMTP()
smtp_server.connect('localhost', 25)
smtp_server.sendmail('alerts@sylvilagus.local',
recipients,
headers + str(message))
smtp_server.close()
def critical_notify(channel, method, header, body):
"""Sends CRITICAL alerts to administrators via email."""
message = json.loads(body)
send_mail(OPS_EMAILS, 'CRITICAL ALERT', message)
print('Sent alert via email! Alert Text: {} \nRecipients: {}'.format(
message, OPS_EMAILS
)
)
channel.basic_ack(delivery_tag=method.delivery_tag)
def rate_limit_notify(channel, method, header, body):
"""Sends the message to the administrators via email."""
message = json.loads(body)
send_mail(ADMIN_EMAILS, 'RATE LIMIT ALERT!', message)
print('Sent alert via email! Alert Text: {} \nRecipients: {}'.format(
message, ADMIN_EMAILS
)
)
channel.basic_ack(delivery_tag=method.delivery_tag)
if __name__ == '__main__':
sys.exit(main())