Created
June 30, 2011 18:16
-
-
Save pbdeuchler/1056826 to your computer and use it in GitHub Desktop.
A sample SkyBot Module for polling support alerts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python -tt | |
''' | |
Didn't you hear? The bird is the word! | |
@author: Philip Deuchler | |
@version: 0.2 Beta | |
''' | |
import urllib2 | |
import json | |
import web | |
from mimerender import mimerender | |
import time | |
from multiprocessing import Process | |
import logging | |
import shelve | |
#Render statements | |
render_xml = lambda message: '<message>%s</message>' % message | |
render_json = lambda **args: json.dumps(args) | |
render_html = lambda message: '<html><body>%s</body></html>' % message | |
render_txt = lambda message: message | |
#Routes | |
urls = ( | |
'/(.*)', 'servClient' | |
) | |
#ReST server | |
app = web.application(urls, globals()) | |
logger = logging.getLogger('supportAlerts') | |
#INITIALIZATION | |
def main(): | |
version = 0.2 | |
shelf = shelve.open("vars") | |
shelf['threshold'] = 30 | |
shelf['poll_interval'] = 15 | |
shelf['cushion'] = 10 | |
shelf['flag'] = 0 | |
shelf['chats'] = ["Queue Alert"] | |
shelf['admin'] = ["voxeophilipdeuchler", "dpolfer"] | |
shelf.close() | |
logger.setLevel(logging.DEBUG) | |
fh = logging.FileHandler('supportAlerts.log') | |
fh.setLevel(logging.DEBUG) | |
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
fh.setFormatter(formatter) | |
logger.addHandler(fh) | |
logger.info('STARTING SUPPORTALERTS MAIN MODULE') | |
logger.info('Checking to see if client is already registered with skybot') | |
check = urllib2.urlopen('http://skybroker.eng.voxeo.com:3333/supportAlerts') | |
currentClient = check.read() | |
currentClient = json.loads(currentClient) | |
currentClient = float(currentClient['message']) | |
print currentClient | |
if currentClient == 0: | |
register(version) | |
elif currentClient == version: | |
logger.info('Registry found. Executing main loop.') | |
elif currentClient != version: | |
dataz = { | |
"name": "supportAlerts" | |
} | |
dataz = json.dumps(dataz) | |
opener = urllib2.build_opener(urllib2.HTTPHandler) | |
request = urllib2.Request('http://skybroker.eng.voxeo.com:3333/supportAlerts', data= dataz) | |
request.add_header('Content-Type', 'application/json') | |
request.get_method = lambda: 'DELETE' | |
url = opener.open(request) | |
register(version) | |
bulldozer() | |
def register(version): | |
logger.info('Registry not found, registering') | |
url = 'http://skybroker.eng.voxeo.com:3333/supportAlerts' | |
data = { | |
"name": "supportAlerts", | |
"ip": "skybroker.eng.voxeo.com", | |
"port": "7070", | |
"protocol": "rest", | |
"version": version, | |
"rules": { | |
"1": [ | |
"[skybot] cotalert alert", | |
"all" | |
], | |
"2": [ | |
"[skybot] cotalert sleep", | |
"all" | |
], | |
"3": [ | |
"[skybot] cotalert buffer", | |
"all" | |
], | |
"4": [ | |
"[skybot] cotalert addchat", | |
"all" | |
], | |
"5": [ | |
"[skybot] cotalert delchat", | |
"all" | |
], | |
"6": [ | |
"[skybot] cotalert help", | |
"all" | |
], | |
"7": [ | |
"[skybot] cotalert addadmin", | |
"all" | |
], | |
"8": [ | |
"[skybot] cotalert deladmin", | |
"all" | |
] | |
} | |
} | |
try: | |
data = json.dumps(data) | |
req = urllib2.Request(url, data) | |
response = urllib2.urlopen(req) | |
returned = response.read() | |
print returned | |
except Exception, detail: | |
print "Err", detail | |
#REST SERVER | |
class servClient: | |
global logger | |
@mimerender( | |
default = 'xml', | |
html = render_html, | |
xml = render_xml, | |
json = render_json, | |
txt = render_txt | |
) | |
def GET(self, name): | |
return {'message': 'hello'} | |
def PUT(self, name): | |
logger.info('Rule match recieved') | |
message = web.data() | |
message = json.loads(message) | |
parse(message) | |
#BEGIN GLOBAL VARIABLE FUNCTIONS | |
def showThreshold(): | |
shelf = shelve.open("vars") | |
num = shelf['threshold'] | |
shelf.close() | |
return num | |
def setThreshold(num): | |
shelf = shelve.open("vars") | |
shelf['threshold'] = num | |
shelf.close() | |
return num | |
def showPollInterval(): | |
shelf = shelve.open("vars") | |
num = shelf['poll_interval'] | |
shelf.close() | |
return num | |
def setPollInterval(num): | |
if num > 20: | |
return | |
shelf = shelve.open("vars") | |
shelf['poll_interval'] = num | |
shelf.close() | |
return num | |
def showCushion(): | |
shelf = shelve.open("vars") | |
num = shelf['cushion'] | |
shelf.close() | |
return num | |
def setCushion(num): | |
shelf = shelve.open("vars") | |
shelf['cushion'] = num | |
shelf.close() | |
return num | |
def showFlag(): | |
shelf = shelve.open("vars") | |
num = shelf['flag'] | |
shelf.close() | |
return num | |
def setFlag(num): | |
shelf = shelve.open("vars") | |
shelf['flag'] = num | |
shelf.close() | |
return num | |
def showChats(): | |
shelf = shelve.open("vars") | |
chats = shelf['chats'] | |
shelf.close() | |
return chats | |
def addChats(string): | |
chats = showChats() | |
chats.append(string) | |
shelf = shelve.open("vars") | |
shelf['chats'] = chats | |
shelf.close() | |
return string | |
def delChats(string): | |
chats = showChats() | |
chats.remove(string) | |
shelf = shelve.open("vars") | |
shelf['chats'] = chats | |
shelf.close() | |
return string | |
def showAdmins(): | |
shelf = shelve.open("vars") | |
admins = shelf['admin'] | |
shelf.close() | |
return admins | |
def addAdmin(string): | |
admins = showAdmins() | |
admins.append(string) | |
shelf = shelve.open("vars") | |
shelf['admin'] = admins | |
shelf.close() | |
return string | |
def delAdmin(string): | |
admins = showAdmins() | |
admins.remove(string) | |
shelf = shelve.open("vars") | |
shelf['admins'] = admins | |
shelf.close() | |
#MESSAGE PARSER (ACTION DELEGATOR) | |
def parse(message): | |
if message['number'] == 1: | |
if isAdmin(message['author']): | |
num = message['body'] | |
num = int(num[24:]) | |
setThreshold(num) | |
logger.info('Threshold set to ' + str(showThreshold())) | |
elif message['number'] == 2: | |
if isAdmin(message['author']): | |
num = message['body'] | |
num = int(num[24:]) | |
setPollInterval(num) | |
logger.info("Poll Interval set to " + str(showPollInterval())) | |
elif message['number'] == 3: | |
if isAdmin(message['author']): | |
num = message['body'] | |
num = int(num[25:]) | |
setCushion(num) | |
logger.info("Cushion set to " + str(showCushion())) | |
elif message['number'] == 4: | |
if isAdmin(message['author']): | |
chat = message['body'] | |
chat = str(chat[26:]) | |
addChats(chat) | |
elif message['number'] == 5: | |
if isAdmin(message['author']): | |
chat = message['body'] | |
chat = str(chat[26:]) | |
delChats(chat) | |
elif message['number'] == 6: | |
author = str(message['author']) | |
body = "(*) (*) (*) SupportAlerts Module Help (*) (*) (*)\n\n[skybot] cotalert alert \"yourvalue\" - Changes the threshold at which alerts are triggered (Current value: " + str(showThreshold()) + ")\n\n[skybot] cotalert sleep \"yourvalue\" - Changes the polling interval (in minutes) of the count query (Current value: " + str(showPollInterval()) + ")\n\n[skybot] cotalert buffer \"yourvalue\" - Changes the cushion where alerts still occur if above normal levels (Current value: " + str(showCushion()) + ")\n\n[skybot] cotalert addchat \"yourvalue\" - Adds a chat to the recipients list\n\n[skybot] cotalert delchat \"yourvalue\" - Removes a chat from the recipients list\n\nCurrent recipients of the alert- " + str(showChats()) + "\n[skybot] cotalert addadmin \"yourvalue\" - Makes a user an admin (able to change values) \n[skybot] cotalert deladmin \"yourvalue\" - Removes a users' admin priveleges \nCurrent admins- " + str(showAdmins()) | |
message_out = { | |
"flag": 1, | |
"body": body, | |
"address": author, | |
"frame": 0, | |
"char": "(flag:MA)" | |
} | |
message_out = json.dumps(message_out) | |
messenger(message_out) | |
elif message['number'] == 7: | |
if isAdmin(message['author']): | |
admin = message['body'] | |
admin = str(admin[27:]) | |
addAdmin(admin) | |
elif message['number'] == 8: | |
if isAdmin(message['author']): | |
admin = message['body'] | |
admin = str(admin[27:]) | |
delAdmin(admin) | |
#ADMIN FUNCTION | |
def isAdmin(author): | |
admins = showAdmins() | |
if author in admins: | |
return True | |
else: | |
admins_str = "" | |
for admin in admins: | |
admins_str += str(admin) + ", " | |
admins_str = admins_str[:-2] | |
body = "(*) (*) (*) You are not a SupportAlerts admin, and thus do not have permission to perform this action. The current admins are " + admins_str + " (*) (*) (*)" | |
message_out = { | |
"flag": 1, | |
"body": body, | |
"address": author, | |
"frame": 0, | |
"char": "(flag:MA)" | |
} | |
message_out = json.dumps(message_out) | |
messenger(message_out) | |
return False | |
#MAIN LOOP | |
def bulldozer(): | |
logger.info('Main Loop') | |
while 1: | |
connection = urllib2.urlopen("http://evolution.voxeo.com/bizblog/admin/getStatusZeroCount.jsp") | |
count = connection.read() | |
count = int(count) | |
logger.info('Current ticket count is: ' + str(count)) | |
logger.info("Current threshold is: " + str(showThreshold())) | |
logger.info("Current poll interval is: " + str(showPollInterval())) | |
logger.info("Current cushion is: " + str(showCushion())) | |
real = showThreshold() - showCushion() | |
if showFlag() == 0 and count > showThreshold(): | |
send("bad", count) | |
elif showFlag() == 1 and count >= real: | |
send("bad", count) | |
elif showFlag() == 1 and count < real: | |
send("good", count) | |
secs = showPollInterval() * 60 | |
time.sleep(secs) | |
#OUTWARD BOUND ALERT MESSENGER | |
def send(status, count = 0): | |
global dyns | |
chats = showChats() | |
if status is "bad": | |
for chat in chats: | |
logger.info('SUPPORT QUEUE HAS REACHED UNACCEPTABLE LEVELS- CURRENT COUNT: ' + str(count)) | |
logger.info('Sending alert') | |
body = " (*) (*) (*) ALL HANDS ON DECK (*) (*) (*) \nThe Support Queue S0 count is at " + str(count) + " RIGHT NOW \nPlease work the Support Queue until the all clear" | |
message = { | |
"flag": 1, | |
"body": body, | |
"address": chat, | |
"frame": 1, | |
"char": "(flag:MA)" | |
} | |
message = json.dumps(message) | |
messenger(message) | |
setFlag(1) | |
else: | |
for chat in chats: | |
logger.info('SUPPORT QUEUE HAS RETURNED TO NORMAL LEVELS- CURRENT COUNT: ' + str(count)) | |
logger.info('Sending all clear alert') | |
body = " (*) (*) (*) (*) ALL CLEAR (*) (*) (*) (*) \nThe Support Queue is at a reasonable level\nResume your regularly scheduled programming" | |
message = { | |
"flag": 1, | |
"body": body, | |
"address": chat, | |
"frame": 1, | |
"char": "(flag:LY)" | |
} | |
message = json.dumps(message) | |
messenger(message) | |
setFlag(0) | |
#GENERIC OUTWARD MESSENGER | |
def messenger(message): | |
opener = urllib2.build_opener(urllib2.HTTPHandler) | |
request = urllib2.Request('http://skybroker.eng.voxeo.com:3333', data = message) | |
request.add_header('Content-Type', 'application/json') | |
request.get_method = lambda: 'PUT' | |
url = opener.open(request) | |
if __name__ == '__main__': | |
p = Process(target=app.run) | |
p.start() | |
main() | |
p.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment