4 # Helper functions that minipulate the PLC api.
6 # Faiyaz Ahmed <faiyaza@cs.princeton.edu
8 # $Id: plc.py,v 1.18 2007/08/29 17:26:50 soltesz Exp $
15 from monitor import database
18 from monitor import config
22 logger = logging.getLogger("monitor")
25 def __init__(self, username=None, password=None, **kwargs):
26 if 'session' in kwargs:
27 self.auth= { 'AuthMethod' : 'session',
28 'session' : kwargs['session'] }
30 if username==None and password==None:
31 self.auth = {'AuthMethod': "anonymous"}
33 self.auth = {'Username' : username,
34 'AuthMethod' : 'password',
35 'AuthString' : password}
37 # NOTE: this host is used by default when there are no auth files.
38 XMLRPC_SERVER="https://boot.planet-lab.org/PLCAPI/"
40 # NOTE: by default, use anonymous access, but if auth files are
41 # configured, use them, with their auth definitions.
44 from monitor import config
45 auth.auth = {'Username' : config.API_AUTH_USER,
46 'AuthMethod' : 'password',
47 'AuthString' : config.API_AUTH_PASSWORD}
48 auth.server = config.API_SERVER
52 auth.server = auth.plc
55 auth.server = XMLRPC_SERVER
57 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
60 def __init__(self, auth, url):
63 self.api = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
65 def __getattr__(self, name):
66 method = getattr(self.api, name)
68 raise AssertionError("method does not exist")
70 return lambda *params : method(self.auth, *params)
73 return self.api.__repr__()
77 def _param_to_str(self, name, *params):
80 retstr += "%s-" % name
85 def __getattr__(self, name):
86 method = getattr(self.api, name)
88 raise AssertionError("method does not exist")
90 def run_or_returncached(*params):
91 cachename = self._param_to_str(name, *params)
92 #print "cachename is %s" % cachename
93 if hasattr(config, 'refresh'):
94 refresh = config.refresh
99 if not database.cachedRecently(cachename):
100 load_old_cache = False
102 values = method(self.auth, *params)
104 print "Call %s FAILED: Using old cached data" % cachename
105 load_old_cache = True
108 values = database.dbLoad(cachename)
110 database.dbDump(cachename, values)
114 values = database.dbLoad(cachename)
117 return method(self.auth, *params)
119 return run_or_returncached
123 return xmlrpclib.Server(url, verbose=False, allow_none=True)
125 def getNodeAPI(session):
126 nodeauth = Auth(session=session)
127 return PLC(nodeauth.auth, auth.server)
130 return PLC(auth.auth, auth.server)
132 def getCachedAuthAPI():
133 return CachedPLC(auth.auth, auth.server)
135 def getTechEmails(loginbase):
137 For the given site, return all user email addresses that have the 'tech' role.
141 s = api.GetSites(loginbase)[0]
143 p = api.GetPersons(s['person_ids'])
144 # pull out those with the right role.
145 emails = [ person['email'] for person in filter(lambda x: 'tech' in x['roles'], p) ]
148 def getPIEmails(loginbase):
150 For the given site, return all user email addresses that have the 'tech' role.
154 s = api.GetSites(loginbase)[0]
156 p = api.GetPersons(s['person_ids'])
157 # pull out those with the right role.
158 emails = [ person['email'] for person in filter(lambda x: 'pi' in x['roles'], p) ]
161 def getSliceUserEmails(loginbase):
163 For the given site, return all user email addresses that have the 'tech' role.
167 s = api.GetSites(loginbase)[0]
169 slices = api.GetSlices(s['slice_ids'])
172 people += api.GetPersons(slice['person_ids'])
173 # pull out those with the right role.
174 emails = [ person['email'] for person in filter(lambda x: 'pi' in x['roles'], people) ]
175 unique_emails = [ x for x in set(emails) ]
179 Returns list of nodes in dbg as reported by PLC
183 api = xmlrpclib.Server(auth.server, verbose=False)
184 anon = {'AuthMethod': "anonymous"}
185 for node in api.GetNodes(anon, {"boot_state":"dbg"},["hostname"]):
186 dbgNodes.append(node['hostname'])
187 logger.info("%s nodes in debug according to PLC." %len(dbgNodes))
192 Returns loginbase for given nodename
194 def siteId(nodename):
195 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
196 site_id = api.GetNodes (auth.auth, {"hostname": nodename}, ['site_id'])
197 if len(site_id) == 1:
198 loginbase = api.GetSites (auth.auth, site_id[0], ["login_base"])
199 return loginbase[0]['login_base']
201 print "Not nodes returned!!!!"
204 Returns list of slices for a site.
206 def slices(loginbase):
208 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
209 sliceids = api.GetSites (auth.auth, {"login_base" : loginbase}, ["slice_ids"])[0]['slice_ids']
210 for slice in api.GetSlices(auth.auth, {"slice_id" : sliceids}, ["name"]):
211 siteslices.append(slice['name'])
215 Returns dict of PCU info of a given node.
217 def getpcu(nodename):
218 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
219 anon = {'AuthMethod': "anonymous"}
220 nodeinfo = api.GetNodes(auth.auth, {"hostname": nodename}, ["pcu_ids", "ports"])[0]
221 if nodeinfo['pcu_ids']:
223 sitepcu = api.GetPCUs(auth.auth, nodeinfo['pcu_ids'])[0]
225 print nodeinfo["ports"]
226 sitepcu[nodename] = nodeinfo["ports"][0]
229 logger.info("%s doesn't have PCU" % nodename)
232 def GetPCUs(filter=None, fields=None):
233 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
234 pcu_list = api.GetPCUs(auth.auth, filter, fields)
238 Returns all site nodes for site id (loginbase).
240 def getSiteNodes(loginbase, fields=None):
241 api = xmlrpclib.Server(auth.server, verbose=False)
243 anon = {'AuthMethod': "anonymous"}
245 nodeids = api.GetSites(anon, {"login_base": loginbase}, fields)[0]['node_ids']
246 for node in api.GetNodes(anon, {"node_id": nodeids}, ['hostname']):
247 nodelist.append(node['hostname'])
248 except Exception, exc:
249 logger.info("getSiteNodes: %s" % exc)
250 print "getSiteNodes: %s" % exc
254 def getPersons(filter=None, fields=None):
255 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
258 persons = api.GetPersons(auth.auth, filter, fields)
259 except Exception, exc:
260 print "getPersons: %s" % exc
261 logger.info("getPersons: %s" % exc)
264 def getSites(filter=None, fields=None):
265 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
267 anon = {'AuthMethod': "anonymous"}
269 #sites = api.GetSites(anon, filter, fields)
270 sites = api.GetSites(auth.auth, filter, fields)
271 except Exception, exc:
272 traceback.print_exc()
273 print "getSites: %s" % exc
274 logger.info("getSites: %s" % exc)
277 def getSiteNodes2(loginbase):
278 api = xmlrpclib.Server(auth.server, verbose=False)
280 anon = {'AuthMethod': "anonymous"}
282 nodeids = api.GetSites(anon, {"login_base": loginbase})[0]['node_ids']
283 nodelist += getNodes({'node_id':nodeids})
284 except Exception, exc:
285 logger.info("getSiteNodes2: %s" % exc)
288 def getNodeNetworks(filter=None):
289 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
290 nodenetworks = api.GetNodeNetworks(auth.auth, filter, None)
293 def getNodes(filter=None, fields=None):
294 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
295 nodes = api.GetNodes(auth.auth, filter, fields)
296 #['boot_state', 'hostname',
297 #'site_id', 'date_created', 'node_id', 'version', 'nodenetwork_ids',
298 #'last_updated', 'peer_node_id', 'ssh_rsa_key' ])
302 Sets boot state of a node.
304 def nodeBootState(nodename, state):
305 api = xmlrpclib.Server(auth.server, verbose=False)
307 return api.UpdateNode(auth.auth, nodename, {'boot_state': state})
308 except Exception, exc:
309 logger.info("nodeBootState: %s" % exc)
311 def updateNodeKey(nodename, key):
312 api = xmlrpclib.Server(auth.server, verbose=False)
314 return api.UpdateNode(auth.auth, nodename, {'key': key})
315 except Exception, exc:
316 logger.info("updateNodeKey: %s" % exc)
319 Sends Ping Of Death to node.
321 def nodePOD(nodename):
322 api = xmlrpclib.Server(auth.server, verbose=False)
323 logger.info("Sending POD to %s" % nodename)
326 return api.RebootNode(auth.auth, nodename)
327 except Exception, exc:
328 logger.info("nodePOD: %s" % exc)
331 Freeze all site slices.
333 def suspendSlices(nodename):
334 api = xmlrpclib.Server(auth.server, verbose=False)
335 for slice in slices(siteId(nodename)):
336 logger.info("Suspending slice %s" % slice)
339 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
340 except Exception, exc:
341 logger.info("suspendSlices: %s" % exc)
343 def enableSlices(nodename):
344 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
345 for slice in slices(siteId(nodename)):
346 logger.info("Enabling slices %s" % slice)
349 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
350 if len(slice_list) == 0:
352 slice_id = slice_list[0]['slice_id']
353 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
355 if "enabled" == attr['name'] and attr['value'] == "0":
356 logger.info("Deleted enable=0 attribute from slice %s" % slice)
357 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
358 except Exception, exc:
359 logger.info("enableSlices: %s" % exc)
360 print "exception: %s" % exc
362 #I'm commenting this because this really should be a manual process.
364 #Enable suspended site slices.
366 #def enableSlices(nodename, slicelist):
367 # api = xmlrpclib.Server(auth.server, verbose=False)
368 # for slice in slices(siteId(nodename)):
369 # logger.info("Suspending slice %s" % slice)
370 # api.SliceAttributeAdd(auth.auth, slice, "plc_slice_state", {"state" : "suspended"})
372 def enableSliceCreation(nodename):
373 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
375 loginbase = siteId(nodename)
376 logger.info("Enabling slice creation for site %s" % loginbase)
378 logger.info("\tcalling UpdateSite(%s, enabled=True)" % loginbase)
379 api.UpdateSite(auth.auth, loginbase, {'enabled': True})
380 except Exception, exc:
381 print "ERROR: enableSliceCreation: %s" % exc
382 logger.info("ERROR: enableSliceCreation: %s" % exc)
385 Removes ability to create slices. Returns previous max_slices
387 def removeSliceCreation(nodename):
388 print "removeSliceCreation(%s)" % nodename
389 api = xmlrpclib.Server(auth.server, verbose=False)
391 loginbase = siteId(nodename)
392 #numslices = api.GetSites(auth.auth, {"login_base": loginbase},
393 # ["max_slices"])[0]['max_slices']
394 logger.info("Removing slice creation for site %s" % loginbase)
396 #api.UpdateSite(auth.auth, loginbase, {'max_slices': 0})
397 api.UpdateSite(auth.auth, loginbase, {'enabled': False})
398 except Exception, exc:
399 logger.info("removeSliceCreation: %s" % exc)
404 #def enableSliceCreation(nodename, maxslices):
405 # api = xmlrpclib.Server(auth.server, verbose=False)
406 # anon = {'AuthMethod': "anonymous"}
407 # siteid = api.AnonAdmQuerySite (anon, {"node_hostname": nodename})
408 # if len(siteid) == 1:
409 # logger.info("Enabling slice creation for site %s" % siteId(nodename))
412 # api.AdmUpdateSite(auth.auth, siteid[0], {"max_slices" : maxslices})
413 # except Exception, exc:
414 # logger.info("API: %s" % exc)
416 # logger.debug("Cant find site for %s. Cannot enable creation." % nodename)
419 logger.setLevel(logging.DEBUG)
420 ch = logging.StreamHandler()
421 ch.setLevel(logging.DEBUG)
422 formatter = logging.Formatter('logger - %(message)s')
423 ch.setFormatter(formatter)
424 logger.addHandler(ch)
425 #print getpcu("kupl2.ittc.ku.edu")
426 #print getpcu("planetlab1.cse.msu.edu")
427 #print getpcu("alice.cs.princeton.edu")
429 #nodeBootState("alice.cs.princeton.edu", "boot")
430 #freezeSite("alice.cs.princeton.edu")
431 print removeSliceCreation("alice.cs.princeton.edu")
432 #enableSliceCreation("alice.cs.princeton.edu", 1024)
433 #print getSiteNodes("princeton")
434 #print siteId("alice.cs.princeton.edu")
435 #print nodePOD("alice.cs.princeton.edu")
436 #print slices("princeton")
438 if __name__=="__main__":