a0c5052d75fe904a7ecc55409d61ea4f8442828c
[monitor.git] / web / MonitorWeb / monitorweb / monitor_xmlrpc.py
1 import sys
2 import xmlrpclib
3 import cherrypy
4 import turbogears
5 from datetime import datetime, timedelta
6 import time
7
8 from monitor.database.info.model import *
9 from monitor.database.info.interface import *
10
11 class MonitorXmlrpcServerMethods:
12         @cherrypy.expose
13         def listMethods(self):
14                 mod = MonitorXmlrpcServer()
15                 ret_list = []
16                 for f in dir(mod):
17                         if isinstance(mod.__getattribute__(f),type(mod.__getattribute__('addDowntime'))):
18                                 ret_list += [f]
19                 return ret_list
20
21 def convert_datetime(d, keys=None):
22         ret = d.copy()
23         n = datetime.now()
24         if keys == None:
25                 keys = d.keys()
26         for k in keys:
27                 if type(d[k]) == type(n):
28                         ret[k] = time.mktime(d[k].utctimetuple())
29         
30         return ret
31
32 class MonitorXmlrpcServer(object):
33
34         @cherrypy.expose
35         def listMethods(self):
36                 mod = MonitorXmlrpcServer()
37                 ret_list = []
38                 for f in dir(mod):
39                         if isinstance(mod.__getattribute__(f),type(mod.__getattribute__('addDowntime'))):
40                                 ret_list += [f]
41                 return ret_list
42
43         @turbogears.expose()
44         def XMLRPC(self):
45                 params, method = xmlrpclib.loads(cherrypy.request.body.read())
46                 try:
47                         if method == "xmlrpc":
48                                 # prevent recursion
49                                 raise AssertionError("method cannot be 'xmlrpc'")
50                         # Get the function and make sure it's exposed.
51                         method = getattr(self, method, None)
52                         # Use the same error message to hide private method names
53                         if method is None or not getattr(method, "exposed", False):
54                                 raise AssertionError("method does not exist")
55
56                         session.clear()
57                         # Call the method, convert it into a 1-element tuple
58                         # as expected by dumps                                     
59                         response = method(*params)
60
61                         session.flush()
62                         response = xmlrpclib.dumps((response,), methodresponse=1, allow_none=1)
63                 except xmlrpclib.Fault, fault:
64                         # Can't marshal the result
65                         response = xmlrpclib.dumps(fault, allow_none=1)
66                 except:
67                         # Some other error; send back some error info
68                         response = xmlrpclib.dumps(
69                                 xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value))
70                                 )
71
72                 cherrypy.response.headers["Content-Type"] = "text/xml"
73                 return response
74
75         # User-defined functions must use cherrypy.expose; turbogears.expose
76         #       does additional checking of the response type that we don't want.
77         @cherrypy.expose
78         def upAndRunning(self):
79                 return True
80
81         # SITES ------------------------------------------------------------
82
83         @cherrypy.expose
84         def getSiteStatus(self, auth):
85                 ret_list = []
86                 sites = HistorySiteRecord.query.all()
87                 for q in sites:
88                         d = q.to_dict(exclude=['timestamp', 'version', ])
89                         d = convert_datetime(d, ['last_checked', 'last_changed', 'message_created'])
90                         ret_list.append(d)
91                 return ret_list
92
93         @cherrypy.expose
94         def clearSitePenalty(self, auth, loginbase):
95                 sitehist = SiteInterface.get_or_make(loginbase=loginbase)
96                 sitehist.clearPenalty()
97                 #sitehist.applyPenalty()
98                 #sitehist.sendMessage('clear_penalty')
99                 sitehist.closeTicket()
100                 return True
101
102         @cherrypy.expose
103         def increaseSitePenalty(self, auth, loginbase):
104                 sitehist = SiteInterface.get_or_make(loginbase=loginbase)
105                 sitehist.increasePenalty()
106                 #sitehist.applyPenalty()
107                 #sitehist.sendMessage('increase_penalty')
108                 return True
109
110         # NODES ------------------------------------------------------------
111
112         @cherrypy.expose
113         def getNodeStatus(self, auth):
114                 ret_list = []
115                 sites = HistoryNodeRecord.query.all()
116                 for q in sites:
117                         d = q.to_dict(exclude=['timestamp', 'version', ])
118                         d = convert_datetime(d, ['last_checked', 'last_changed',])
119                         ret_list.append(d)
120                 return ret_list
121
122         @cherrypy.expose
123         def getRecentActions(self, auth, loginbase=None, hostname=None):
124                 ret_list = []
125                 return ret_list
126
127         # BLACKLIST ------------------------------------------------------------
128
129         @cherrypy.expose
130         def getBlacklist(self, auth):
131                 bl = BlacklistRecord.query.all()
132                 ret_list = []
133                 for q in bl:
134                         d = q.to_dict(exclude=['timestamp', 'version', 'id', ])
135                         d = convert_datetime(d, ['date_created'])
136                         ret_list.append(d)
137
138                 return ret_list
139                 # datetime.datetime.fromtimestamp(time.mktime(time.strptime(mytime, time_format)))
140         
141         @cherrypy.expose
142         def addHostToBlacklist(self, auth, hostname, expires=0):
143                 bl = BlacklistRecord.findby_or_create(hostname=hostname, expires=expires)
144                 return True
145
146         @cherrypy.expose
147         def addSiteToBlacklist(self, auth, loginbase, expires=0):
148                 bl = BlacklistRecord.findby_or_create(hostname=hostname, expires=expires)
149                 return True
150
151         @cherrypy.expose
152         def deleteFromBlacklist(self, auth, loginbase=None, hostname=None):
153                 if (loginbase==None and hostname == None) or (loginbase != None and hostname != None):
154                         raise Exception("Please specify a single record to delete: either hostname or loginbase")
155                 elif loginbase != None:
156                         bl = BlacklistRecord.get_by(loginbase=loginbase)
157                         bl.delete()
158                 elif hostname != None:
159                         bl = BlacklistRecord.get_by(hostname=hostname)
160                         bl.delete()
161                 return True