update basic documentation files.
[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 try:
9         from monitor.database.info.model import *
10         from monitor.database.info.interface import *
11 except:
12         pass
13
14 try:
15     from PLC.Parameter import Parameter, Mixed
16 except:
17     def Parameter(a = None, b = None): pass
18     def Mixed(a = None, b = None, c = None): pass
19
20 def export_to_docbook(**kwargs):
21
22     keywords = {
23         "group" : "Monitor",
24         "status" : "current",
25         "name": None,
26         "args": None,
27         "roles": [],
28         "accepts": [],
29         "returns": [],
30     }
31     def export(method):
32         def args():
33             # Inspect method. Remove self from the argument list.
34             max_args = method.func_code.co_varnames[0:method.func_code.co_argcount]
35             defaults = method.func_defaults
36             if defaults is None:
37                 defaults = ()
38             min_args = max_args[0:len(max_args) - len(defaults)]
39
40             defaults = tuple([None for arg in min_args]) + defaults
41             return (min_args, max_args, defaults)
42
43         keywords['name'] = method.__name__
44         keywords['args'] = args
45         for arg in keywords:
46             method.__setattr__(arg, keywords[arg])
47
48         for arg in kwargs:
49             method.__setattr__(arg, kwargs[arg])
50         return method
51
52     return export
53
54
55 class MonitorXmlrpcServerMethods:
56         @cherrypy.expose
57         def listMethods(self):
58                 mod = MonitorXmlrpcServer()
59                 ret_list = []
60                 for f in dir(mod):
61                         if isinstance(mod.__getattribute__(f),type(mod.__getattribute__('addDowntime'))):
62                                 ret_list += [f]
63                 return ret_list
64
65 def convert_datetime(d, keys=None):
66         ret = d.copy()
67         n = datetime.now()
68         if keys == None:
69                 keys = d.keys()
70         for k in keys:
71                 if type(d[k]) == type(n):
72                         ret[k] = time.mktime(d[k].utctimetuple())
73         
74         return ret
75
76 class MonitorXmlrpcServer(object):
77
78         @cherrypy.expose
79         def listMethods(self):
80                 mod = MonitorXmlrpcServer()
81                 ret_list = []
82                 for f in dir(mod):
83                         if isinstance(mod.__getattribute__(f),type(mod.__getattribute__('addDowntime'))):
84                                 ret_list += [f]
85                 return ret_list
86
87         @turbogears.expose()
88         def XMLRPC(self):
89                 params, method = xmlrpclib.loads(cherrypy.request.body.read())
90                 try:
91                         if method == "xmlrpc":
92                                 # prevent recursion
93                                 raise AssertionError("method cannot be 'xmlrpc'")
94                         # Get the function and make sure it's exposed.
95                         method = getattr(self, method, None)
96                         # Use the same error message to hide private method names
97                         if method is None or not getattr(method, "exposed", False):
98                                 raise AssertionError("method does not exist")
99
100                         session.clear()
101                         # Call the method, convert it into a 1-element tuple
102                         # as expected by dumps                                     
103                         response = method(*params)
104
105                         session.flush()
106                         response = xmlrpclib.dumps((response,), methodresponse=1, allow_none=1)
107                 except xmlrpclib.Fault, fault:
108                         # Can't marshal the result
109                         response = xmlrpclib.dumps(fault, allow_none=1)
110                 except:
111                         # Some other error; send back some error info
112                         response = xmlrpclib.dumps(
113                                 xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value))
114                                 )
115
116                 cherrypy.response.headers["Content-Type"] = "text/xml"
117                 return response
118
119         # User-defined functions must use cherrypy.expose; turbogears.expose
120         #       does additional checking of the response type that we don't want.
121         @cherrypy.expose
122         @export_to_docbook(roles=['tech', 'user', 'pi', 'admin'],
123                            accepts=[],
124                                            returns=Parameter(bool, 'True is successful'))
125         def upAndRunning(self):
126                 """ This is a test """
127                 return True
128
129         # SITES ------------------------------------------------------------
130
131         @cherrypy.expose
132         def getSiteStatus(self, auth):
133                 ret_list = []
134                 sites = HistorySiteRecord.query.all()
135                 for q in sites:
136                         d = q.to_dict(exclude=['timestamp', 'version', ])
137                         d = convert_datetime(d, ['last_checked', 'last_changed', 'message_created'])
138                         ret_list.append(d)
139                 return ret_list
140
141         @cherrypy.expose
142         def clearSitePenalty(self, auth, loginbase):
143                 sitehist = SiteInterface.get_or_make(loginbase=loginbase)
144                 sitehist.clearPenalty()
145                 #sitehist.applyPenalty()
146                 #sitehist.sendMessage('clear_penalty')
147                 sitehist.closeTicket()
148                 return True
149
150         @cherrypy.expose
151         def increaseSitePenalty(self, auth, loginbase):
152                 sitehist = SiteInterface.get_or_make(loginbase=loginbase)
153                 sitehist.increasePenalty()
154                 #sitehist.applyPenalty()
155                 #sitehist.sendMessage('increase_penalty')
156                 return True
157
158         # NODES ------------------------------------------------------------
159
160         @cherrypy.expose
161         def getNodeStatus(self, auth):
162                 ret_list = []
163                 sites = HistoryNodeRecord.query.all()
164                 for q in sites:
165                         d = q.to_dict(exclude=['timestamp', 'version', ])
166                         d = convert_datetime(d, ['last_checked', 'last_changed',])
167                         ret_list.append(d)
168                 return ret_list
169
170         @cherrypy.expose
171         def getRecentActions(self, auth, loginbase=None, hostname=None):
172                 ret_list = []
173                 return ret_list
174
175         # BLACKLIST ------------------------------------------------------------
176
177         @cherrypy.expose
178         def getBlacklist(self, auth):
179                 bl = BlacklistRecord.query.all()
180                 ret_list = []
181                 for q in bl:
182                         d = q.to_dict(exclude=['timestamp', 'version', 'id', ])
183                         d = convert_datetime(d, ['date_created'])
184                         ret_list.append(d)
185
186                 return ret_list
187                 # datetime.datetime.fromtimestamp(time.mktime(time.strptime(mytime, time_format)))
188         
189         @cherrypy.expose
190         def addHostToBlacklist(self, auth, hostname, expires=0):
191                 bl = BlacklistRecord.findby_or_create(hostname=hostname, expires=expires)
192                 return True
193
194         @cherrypy.expose
195         def addSiteToBlacklist(self, auth, loginbase, expires=0):
196                 bl = BlacklistRecord.findby_or_create(hostname=hostname, expires=expires)
197                 return True
198
199         @cherrypy.expose
200         def deleteFromBlacklist(self, auth, loginbase=None, hostname=None):
201                 if (loginbase==None and hostname == None) or (loginbase != None and hostname != None):
202                         raise Exception("Please specify a single record to delete: either hostname or loginbase")
203                 elif loginbase != None:
204                         bl = BlacklistRecord.get_by(loginbase=loginbase)
205                         bl.delete()
206                 elif hostname != None:
207                         bl = BlacklistRecord.get_by(hostname=hostname)
208                         bl.delete()
209                 return True