AM nagios/plc2nagios.py
[monitor.git] / plc.py
1 #
2 # plc.py
3 #
4 # Helper functions that minipulate the PLC api.
5
6 # Faiyaz Ahmed <faiyaza@cs.princeton.edu
7 #
8 # $Id: plc.py,v 1.18 2007/08/29 17:26:50 soltesz Exp $
9 #
10
11 import xml, xmlrpclib
12 import logging
13 try:
14     import auth
15 except:
16         class Anon:
17                 def __init__(self):
18                         self.auth = {'AuthMethod': "anonymous"}
19         auth = Anon()
20
21 import time
22 try:
23         from config import config
24         config = config()
25         debug = config.debug
26 except:
27         debug = False
28         
29 XMLRPC_SERVER="https://boot.planet-lab.org/PLCAPI/"
30
31 logger = logging.getLogger("monitor")
32
33 api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none=True)
34
35 def getAPI(url):
36         api = xmlrpclib.Server(url, verbose=False, allow_none=True)
37         return api
38
39 class PLC:
40         def __init__(self, auth, url):
41                 self.auth = auth
42                 self.url = url
43                 self.api = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
44
45         def __getattr__(self, name):
46                 method = getattr(self.api, name)
47                 if method is None:
48                         raise AssertionError("method does not exist")
49
50                 return lambda *params : method(self.auth, *params)
51
52         def __repr__(self):
53                 return self.api.__repr__()
54
55 def getAuthAPI():
56         import auth
57         return PLC(auth.auth, auth.plc)
58
59 '''
60 Returns list of nodes in dbg as reported by PLC
61 '''
62 def nodesDbg():
63         dbgNodes = []
64         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
65         anon = {'AuthMethod': "anonymous"}
66         for node in api.GetNodes(anon, {"boot_state":"dbg"},["hostname"]):
67                 dbgNodes.append(node['hostname'])
68         logger.info("%s nodes in debug according to PLC." %len(dbgNodes))
69         return dbgNodes
70
71
72 '''
73 Returns loginbase for given nodename
74 '''
75 def siteId(nodename):
76         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
77         anon = {'AuthMethod': "anonymous"}
78         site_id = api.GetNodes (anon, {"hostname": nodename}, ['site_id'])
79         if len(site_id) == 1:
80                 loginbase = api.GetSites (anon, site_id[0], ["login_base"])
81                 return loginbase[0]['login_base']
82
83 '''
84 Returns list of slices for a site.
85 '''
86 def slices(loginbase):
87         siteslices = []
88         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
89         sliceids = api.GetSites (auth.auth, {"login_base" : loginbase}, ["slice_ids"])[0]['slice_ids']
90         for slice in api.GetSlices(auth.auth, {"slice_id" : sliceids}, ["name"]):
91                 siteslices.append(slice['name'])
92         return siteslices
93
94 '''
95 Returns dict of PCU info of a given node.
96 '''
97 def getpcu(nodename):
98         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
99         anon = {'AuthMethod': "anonymous"}
100         nodeinfo = api.GetNodes(auth.auth, {"hostname": nodename}, ["pcu_ids", "ports"])[0]
101         if nodeinfo['pcu_ids']:
102                 sitepcu = api.GetPCUs(auth.auth, nodeinfo['pcu_ids'])[0]
103                 sitepcu[nodename] = nodeinfo["ports"][0]
104                 return sitepcu
105         else:
106                 logger.info("%s doesn't have PCU" % nodename)
107                 return False
108
109 def GetPCUs(filter=None, fields=None):
110         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none=True)
111         pcu_list = api.GetPCUs(auth.auth, filter, fields)
112         return pcu_list 
113
114 '''
115 Returns all site nodes for site id (loginbase).
116 '''
117 def getSiteNodes(loginbase, fields=None):
118         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
119         nodelist = []
120         anon = {'AuthMethod': "anonymous"}
121         try:
122                 nodeids = api.GetSites(anon, {"login_base": loginbase}, fields)[0]['node_ids']
123                 for node in api.GetNodes(anon, {"node_id": nodeids}, ['hostname']):
124                         nodelist.append(node['hostname'])
125         except Exception, exc:
126                 logger.info("getSiteNodes:  %s" % exc)
127                 print "getSiteNodes:  %s" % exc
128         return nodelist
129
130 def getPersons(filter=None, fields=None):
131         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none=True)
132         persons = []
133         try:
134                 persons = api.GetPersons(auth.auth, filter, fields)
135         except Exception, exc:
136                 print "getPersons:  %s" % exc
137                 logger.info("getPersons:  %s" % exc)
138         return persons
139
140 def getSites(filter=None, fields=None):
141         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none=True)
142         sites = []
143         anon = {'AuthMethod': "anonymous"}
144         try:
145                 #sites = api.GetSites(anon, filter, fields)
146                 sites = api.GetSites(auth.auth, filter, fields)
147         except Exception, exc:
148                 import traceback
149                 traceback.print_exc()
150                 print "getSites:  %s" % exc
151                 logger.info("getSites:  %s" % exc)
152         return sites
153
154 def getSiteNodes2(loginbase):
155         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
156         nodelist = []
157         anon = {'AuthMethod': "anonymous"}
158         try:
159                 nodeids = api.GetSites(anon, {"login_base": loginbase})[0]['node_ids']
160                 nodelist += getNodes({'node_id':nodeids})
161         except Exception, exc:
162                 logger.info("getSiteNodes2:  %s" % exc)
163         return nodelist
164
165 def getNodeNetworks(filter=None):
166         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none=True)
167         nodenetworks = api.GetNodeNetworks(auth.auth, filter, None)
168         return nodenetworks
169
170 def getNodes(filter=None, fields=None):
171         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none=True)
172         nodes = api.GetNodes(auth.auth, filter, fields) 
173                         #['boot_state', 'hostname', 
174                         #'site_id', 'date_created', 'node_id', 'version', 'nodenetwork_ids',
175                         #'last_updated', 'peer_node_id', 'ssh_rsa_key' ])
176         return nodes
177
178 '''
179 Sets boot state of a node.
180 '''
181 def nodeBootState(nodename, state):
182         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
183         try:
184                 return api.UpdateNode(auth.auth, nodename, {'boot_state': state})
185         except Exception, exc:
186                 logger.info("nodeBootState:  %s" % exc)
187
188 def updateNodeKey(nodename, key):
189         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
190         try:
191                 return api.UpdateNode(auth.auth, nodename, {'key': key})
192         except Exception, exc:
193                 logger.info("updateNodeKey:  %s" % exc)
194
195 '''
196 Sends Ping Of Death to node.
197 '''
198 def nodePOD(nodename):
199         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
200         logger.info("Sending POD to %s" % nodename)
201         try:
202                 if not debug:
203                         return api.RebootNode(auth.auth, nodename)
204         except Exception, exc:
205                         logger.info("nodePOD:  %s" % exc)
206
207 '''
208 Freeze all site slices.
209 '''
210 def suspendSlices(nodename):
211         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
212         for slice in slices(siteId(nodename)):
213                 logger.info("Suspending slice %s" % slice)
214                 try:
215                         if not debug:
216                                 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
217                 except Exception, exc:
218                         logger.info("suspendSlices:  %s" % exc)
219
220 def enableSlices(nodename):
221         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none=True)
222         for slice in slices(siteId(nodename)):
223                 logger.info("Enabling slices %s" % slice)
224                 try:
225                         if not debug:
226                                 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
227                                 if len(slice_list) == 0:
228                                         return
229                                 slice_id = slice_list[0]['slice_id']
230                                 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
231                                 for attr in l_attr:
232                                         if "enabled" == attr['name'] and attr['value'] == "0":
233                                                 logger.info("Deleted enable=0 attribute from slice %s" % slice)
234                                                 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
235                 except Exception, exc:
236                         logger.info("enableSlices: %s" % exc)
237                         print "exception: %s" % exc
238
239 #I'm commenting this because this really should be a manual process.  
240 #'''
241 #Enable suspended site slices.
242 #'''
243 #def enableSlices(nodename, slicelist):
244 #       api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
245 #       for slice in  slices(siteId(nodename)):
246 #               logger.info("Suspending slice %s" % slice)
247 #               api.SliceAttributeAdd(auth.auth, slice, "plc_slice_state", {"state" : "suspended"})
248 #
249 def enableSliceCreation(nodename):
250         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none=True)
251         try:
252                 loginbase = siteId(nodename)
253                 logger.info("Enabling slice creation for site %s" % loginbase)
254                 if not debug:
255                         logger.info("\tcalling UpdateSite(%s, enabled=True)" % loginbase)
256                         api.UpdateSite(auth.auth, loginbase, {'enabled': True})
257         except Exception, exc:
258                 print "ERROR: enableSliceCreation:  %s" % exc
259                 logger.info("ERROR: enableSliceCreation:  %s" % exc)
260
261 '''
262 Removes ability to create slices. Returns previous max_slices
263 '''
264 def removeSliceCreation(nodename):
265         print "removeSliceCreation(%s)" % nodename
266         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
267         try:
268                 loginbase = siteId(nodename)
269                 #numslices = api.GetSites(auth.auth, {"login_base": loginbase}, 
270                 #               ["max_slices"])[0]['max_slices']
271                 logger.info("Removing slice creation for site %s" % loginbase)
272                 if not debug:
273                         #api.UpdateSite(auth.auth, loginbase, {'max_slices': 0})
274                         api.UpdateSite(auth.auth, loginbase, {'enabled': False})
275         except Exception, exc:
276                 logger.info("removeSliceCreation:  %s" % exc)
277
278 '''
279 QED
280 '''
281 #def enableSliceCreation(nodename, maxslices):
282 #       api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
283 #       anon = {'AuthMethod': "anonymous"}
284 #       siteid = api.AnonAdmQuerySite (anon, {"node_hostname": nodename})
285 #       if len(siteid) == 1:
286 #               logger.info("Enabling slice creation for site %s" % siteId(nodename))
287 #               try:
288 #                       if not debug:
289 #                               api.AdmUpdateSite(auth.auth, siteid[0], {"max_slices" : maxslices})
290 #               except Exception, exc:
291 #                       logger.info("API:  %s" % exc)
292 #       else:
293 #               logger.debug("Cant find site for %s.  Cannot enable creation." % nodename)
294
295 def main():
296         logger.setLevel(logging.DEBUG)
297         ch = logging.StreamHandler()
298         ch.setLevel(logging.DEBUG)
299         formatter = logging.Formatter('logger - %(message)s')
300         ch.setFormatter(formatter)
301         logger.addHandler(ch)
302         #print getpcu("kupl2.ittc.ku.edu")
303         #print getpcu("planetlab1.cse.msu.edu")
304         #print getpcu("alice.cs.princeton.edu")
305         #print nodesDbg()
306         #nodeBootState("alice.cs.princeton.edu", "boot")
307         #freezeSite("alice.cs.princeton.edu")
308         print removeSliceCreation("alice.cs.princeton.edu")
309         #enableSliceCreation("alice.cs.princeton.edu", 1024)
310         #print getSiteNodes("princeton")
311         #print siteId("alice.cs.princeton.edu")
312         #print nodePOD("alice.cs.princeton.edu")
313         #print slices("princeton")
314
315 if __name__=="__main__":
316         import reboot
317         main()