Snippets
Created by
Edelberto Mania
last modified
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | #!/usr/bin/env python
# script to check /_zstatus and checks RTAPI nodes been took out and put in route
# and sends slack and email message
# Edelberto Mania <ed@zenoradio.com>
# 20160707
node_env='STAGING'
rtapi="https://stage-rtapi.zenoradio.com/_zstatus"
#rtapi="https://rtapi-lb.zenoradio.com/_zstatus"
slack_webhook_url='https://hooks.slack.com/services/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'
slack_channel='edel_s-playground' # system-status, zeno-sysadmins
email_username='noreply@zenoradio.com'
email_password='XXXX'
email_server='smtp.gmail.com:587'
email_from='RTAPI Node Messenger <noreply@zenoradio.com>'
email_to=['ed@zenoradio.com','ed@zenoradio.com']
email_cc=['edel@iconstrategiesbpo.com']
email_bcc=['sierra2@gmail.com']
import requests,json,sys,datetime,smtplib,email.utils
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from socket import gethostname
from time import sleep
def send_slack_message(webhook_url=None,bot_name='bot',channel=None,message=None,emoji=None):
if bot_name is not None: bot_name=gethostname()
if channel is None:channel=slack_channel
if webhook_url is None:webhook_url=slack_webhook_url
slack_data={"channel": "#{0}".format(channel),"username":bot_name,"text":message,"icon_emoji":emoji}
m=requests.post(webhook_url,data=json.dumps(slack_data),headers={'content-type':'application/json'})
return(m)
def send_email(
from_addr,
to_addrs,
cc_addrs,
bcc_addrs,
subject,
message,
login,password,smtpserver='smtp.gmail.com:587',secured=False):
message_id=email.utils.make_msgid()
msg=MIMEMultipart('alternative')
msg['Subject']=subject
msg['From']=from_addr
msg['To']='%s\n'%','.join(to_addrs)
msg['Cc']='%s\n'%','.join(cc_addrs)
msg['Bcc']='%s\n'%','.join(bcc_addrs)
msg.add_header("reply-to",from_addr) # does not work, even with plain email address
msg.add_header("Message-ID",message_id)
email_list=[]
email_list.extend(to_addrs)
email_list.extend(cc_addrs)
email_list.extend(bcc_addrs)
## remove empty in the list (the u'') - yes, ugly line of code
while u'' in email_list:email_list.remove(u'')
part1=MIMEText(message,'plain')
part2=MIMEText(message,'html')
msg.attach(part1)
msg.attach(part2)
try:
server=smtplib.SMTP(smtpserver)
if secured:
server.starttls()
server.ehlo()
else:server.ehlo()
server.login(login,password)
problems=server.sendmail(from_addr,email_list,msg.as_string())
server.quit()
except(Exception):return False
return True
def query_rtapi_status(url):
return(requests.get(url).text.split('\n'))
in_route=[]
out_of_route=[]
c=0
if __name__=='__main__':
try:
while(True):
print 'routed:',in_route
print 'not routed:',out_of_route
in_route_total=len(in_route)
out_of_route_total=len(out_of_route)
r=query_rtapi_status(rtapi)
for i in r:
if i.endswith('up'):
h=i.strip().split()[0]
if h not in in_route:
if h in out_of_route:
out_of_route.remove(h)
in_route.append(i.split()[0])
if c>0: ## skip sending message when we'er starting up
_date=datetime.datetime.now().strftime("%a, %B %d %Y at %H:%M:%S")
_stats='{0}/{1}'.format(in_route_total+1,out_of_route_total-1)
subject='RTAPI node {0} is now IN route'.format(h)
message='[{1}] *{3}* node {0} is *now in route* ({2})'.format(h,_date,_stats,node_env)
send_slack_message(message=message)
message='{0}<br><br>You can also follow updates via https://zenoradio.slack.com/messages/{1}/<br><br>--<br>System-generated message. Please do not reply (ESM 20160707).'.format(message,slack_channel)
s=send_email(from_addr=email_from, to_addrs=email_to, cc_addrs=email_cc,bcc_addrs=email_bcc,subject=subject,message=message,login=email_username,password=email_password,smtpserver=email_server,secured=True)
print(s)
elif i.endswith('DOWN'):
h=i.strip().split()[0]
if h not in out_of_route:
if h in in_route:
in_route.remove(h)
out_of_route.append(i.split()[0])
if c>0:
_date=datetime.datetime.now().strftime("%a, %B %d %Y at %H:%M:%S")
_stats='{0}/{1}'.format(in_route_total-1,out_of_route_total+1)
subject='RTAPI node {0} is now OUT of route'.format(h)
message='[{1}] *{3}* node {0} was *removed* from route ({2})'.format(h,_date,_stats,node_env)
send_slack_message(message=message)
message='{0}<br><br>You can also follow updates via https://zenoradio.slack.com/messages/{1}/<br><br>--<br>System-generated message. Please do not reply (ESM 20160707).'.format(message,slack_channel)
s=send_email(from_addr=email_from, to_addrs=email_to, cc_addrs=email_cc,bcc_addrs=email_bcc,subject=subject,message=message,login=email_username,password=email_password,smtpserver=email_server,secured=True)
print(s)
c+=1
sleep(1)
except KeyboardInterrupt:
print('Exiting...')
sys.exit(0)
except:
print('Unexpected error: ',sys.exc_info())
sys.exit(1)
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.