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
20 XMLRPC_SERVER=config.API_SERVER
23 # NOTE: this host is used by default when there are no auth files.
24 XMLRPC_SERVER="https://boot.planet-lab.org/PLCAPI/"
26 logger = logging.getLogger("monitor")
29 def __init__(self, username=None, password=None, **kwargs):
30 if 'session' in kwargs:
31 self.auth= { 'AuthMethod' : 'session',
32 'session' : kwargs['session'] }
34 if username==None and password==None:
35 self.auth = {'AuthMethod': "anonymous"}
37 self.auth = {'Username' : username,
38 'AuthMethod' : 'password',
39 'AuthString' : password}
42 # NOTE: by default, use anonymous access, but if auth files are
43 # configured, use them, with their auth definitions.
46 from monitor import config
47 auth.auth = {'Username' : config.API_AUTH_USER,
48 'AuthMethod' : 'password',
49 'AuthString' : config.API_AUTH_PASSWORD}
50 auth.server = config.API_SERVER
54 auth.server = auth.plc
57 auth.server = XMLRPC_SERVER
59 global_error_count = 0
62 def __init__(self, auth, url):
65 self.api = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
67 def __getattr__(self, name):
68 method = getattr(self.api, name)
70 raise AssertionError("method does not exist")
73 return lambda *params : method(self.auth, *params)
74 except xmlrpclib.ProtocolError:
76 global_error_count += 1
77 if global_error_count >= 10:
78 print "maximum error count exceeded; exiting..."
81 print "%s errors have occurred" % global_error_count
82 raise Exception("ProtocolError continuing")
85 return self.api.__repr__()
90 def _param_to_str(self, name, *params):
93 retstr += "%s-" % name
98 def __getattr__(self, name):
99 method = getattr(self.api, name)
101 raise AssertionError("method does not exist")
103 def run_or_returncached(*params):
104 cachename = self._param_to_str(name, *params)
105 #print "cachename is %s" % cachename
106 if hasattr(config, 'refresh'):
107 refresh = config.refresh
112 if not database.cachedRecently(cachename):
113 load_old_cache = False
115 values = method(self.auth, *params)
117 print "Call %s FAILED: Using old cached data" % cachename
118 load_old_cache = True
121 values = database.dbLoad(cachename)
123 database.dbDump(cachename, values)
127 values = database.dbLoad(cachename)
130 return method(self.auth, *params)
132 return run_or_returncached
134 api = PLC(auth.auth, auth.server)
135 cacheapi = CachedPLC(auth.auth, auth.server)
139 return xmlrpclib.Server(url, verbose=False, allow_none=True)
141 def getNodeAPI(session):
142 nodeauth = Auth(session=session)
143 return PLC(nodeauth.auth, auth.server)
145 def getAuthAPI(url=None):
147 return PLC(auth.auth, url)
149 return PLC(auth.auth, auth.server)
151 def getCachedAuthAPI():
152 return CachedPLC(auth.auth, auth.server)
154 def getSessionAPI(session, server):
155 nodeauth = Auth(session=session)
156 return PLC(nodeauth.auth, server)
157 def getUserAPI(username, password, server):
158 auth = Auth(username,password)
159 return PLC(auth.auth, server)
161 def getTechEmails(loginbase):
163 For the given site, return all user email addresses that have the 'tech' role.
167 s = api.GetSites(loginbase)[0]
169 p = api.GetPersons(s['person_ids'])
170 # pull out those with the right role.
171 emails = [ person['email'] for person in filter(lambda x: 'tech' in x['roles'], p) ]
174 def getPIEmails(loginbase):
176 For the given site, return all user email addresses that have the 'tech' role.
180 s = api.GetSites(loginbase)[0]
182 p = api.GetPersons(s['person_ids'])
183 # pull out those with the right role.
184 emails = [ person['email'] for person in filter(lambda x: 'pi' in x['roles'], p) ]
187 def getSliceUserEmails(loginbase):
189 For the given site, return all user email addresses that have the 'tech' role.
193 s = api.GetSites(loginbase)[0]
195 slices = api.GetSlices(s['slice_ids'])
198 people += api.GetPersons(slice['person_ids'])
199 # pull out those with the right role.
200 emails = [ person['email'] for person in filter(lambda x: 'pi' in x['roles'], people) ]
201 unique_emails = [ x for x in set(emails) ]
205 Returns list of nodes in dbg as reported by PLC
209 api = xmlrpclib.Server(auth.server, verbose=False)
210 anon = {'AuthMethod': "anonymous"}
211 for node in api.GetNodes(anon, {"boot_state":"dbg"},["hostname"]):
212 dbgNodes.append(node['hostname'])
213 logger.info("%s nodes in debug according to PLC." %len(dbgNodes))
218 Returns loginbase for given nodename
220 def siteId(nodename):
221 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
222 site_id = api.GetNodes (auth.auth, {"hostname": nodename}, ['site_id'])
223 if len(site_id) == 1:
224 loginbase = api.GetSites (auth.auth, site_id[0], ["login_base"])
225 return loginbase[0]['login_base']
227 print "Not nodes returned!!!!"
230 Returns list of slices for a site.
232 def slices(loginbase):
234 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
235 sliceids = api.GetSites (auth.auth, {"login_base" : loginbase}, ["slice_ids"])[0]['slice_ids']
236 for slice in api.GetSlices(auth.auth, {"slice_id" : sliceids}, ["name"]):
237 siteslices.append(slice['name'])
241 Returns dict of PCU info of a given node.
243 def getpcu(nodename):
244 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
245 anon = {'AuthMethod': "anonymous"}
246 nodeinfo = api.GetNodes(auth.auth, {"hostname": nodename}, ["pcu_ids", "ports"])[0]
247 if nodeinfo['pcu_ids']:
249 sitepcu = api.GetPCUs(auth.auth, nodeinfo['pcu_ids'])[0]
251 print nodeinfo["ports"]
252 sitepcu[nodename] = nodeinfo["ports"][0]
255 logger.info("%s doesn't have PCU" % nodename)
258 def GetPCUs(filter=None, fields=None):
259 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
260 pcu_list = api.GetPCUs(auth.auth, filter, fields)
264 Returns all site nodes for site id (loginbase).
266 def getSiteNodes(loginbase, fields=None):
267 api = xmlrpclib.Server(auth.server, verbose=False)
269 anon = {'AuthMethod': "anonymous"}
271 nodeids = api.GetSites(anon, {"login_base": loginbase}, fields)[0]['node_ids']
272 for node in api.GetNodes(anon, {"node_id": nodeids}, ['hostname']):
273 nodelist.append(node['hostname'])
274 except Exception, exc:
275 logger.info("getSiteNodes: %s" % exc)
276 print "getSiteNodes: %s" % exc
280 def getPersons(filter=None, fields=None):
281 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
284 persons = api.GetPersons(auth.auth, filter, fields)
285 except Exception, exc:
286 print "getPersons: %s" % exc
287 logger.info("getPersons: %s" % exc)
290 def getSites(filter=None, fields=None):
291 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
293 anon = {'AuthMethod': "anonymous"}
295 #sites = api.GetSites(anon, filter, fields)
296 sites = api.GetSites(auth.auth, filter, fields)
297 except Exception, exc:
298 traceback.print_exc()
299 print "getSites: %s" % exc
300 logger.info("getSites: %s" % exc)
303 def getSiteNodes2(loginbase):
304 api = xmlrpclib.Server(auth.server, verbose=False)
306 anon = {'AuthMethod': "anonymous"}
308 nodeids = api.GetSites(anon, {"login_base": loginbase})[0]['node_ids']
309 nodelist += getNodes({'node_id':nodeids})
310 except Exception, exc:
311 logger.info("getSiteNodes2: %s" % exc)
314 def getNodeNetworks(filter=None):
315 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
316 nodenetworks = api.GetInterfaces(auth.auth, filter, None)
319 def getNodes(filter=None, fields=None):
320 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
321 nodes = api.GetNodes(auth.auth, filter, fields)
322 #['boot_state', 'hostname',
323 #'site_id', 'date_created', 'node_id', 'version', 'interface_ids',
324 #'last_updated', 'peer_node_id', 'ssh_rsa_key' ])
328 Sets boot state of a node.
330 def nodeBootState(nodename, state):
331 api = xmlrpclib.Server(auth.server, verbose=False)
333 return api.UpdateNode(auth.auth, nodename, {'boot_state': state})
334 except Exception, exc:
335 logger.info("nodeBootState: %s" % exc)
337 def updateNodeKey(nodename, key):
338 api = xmlrpclib.Server(auth.server, verbose=False)
340 return api.UpdateNode(auth.auth, nodename, {'key': key})
341 except Exception, exc:
342 logger.info("updateNodeKey: %s" % exc)
345 Sends Ping Of Death to node.
347 def nodePOD(nodename):
348 api = xmlrpclib.Server(auth.server, verbose=False)
349 logger.info("Sending POD to %s" % nodename)
352 return api.RebootNode(auth.auth, nodename)
353 except Exception, exc:
354 logger.info("nodePOD: %s" % exc)
357 Freeze all site slices.
359 def suspendSiteSlices(loginbase):
360 api = xmlrpclib.Server(auth.server, verbose=False)
361 for slice in slices(loginbase):
362 logger.info("Suspending slice %s" % slice)
365 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
366 except Exception, exc:
367 logger.info("suspendSlices: %s" % exc)
370 Freeze all site slices.
372 def suspendSlices(nodename):
373 api = xmlrpclib.Server(auth.server, verbose=False)
374 for slice in slices(siteId(nodename)):
375 logger.info("Suspending slice %s" % slice)
378 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
379 except Exception, exc:
380 logger.info("suspendSlices: %s" % exc)
382 def enableSiteSlices(loginbase):
383 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
384 for slice in slices(loginbase):
385 logger.info("Enabling slices %s" % slice)
388 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
389 if len(slice_list) == 0:
391 slice_id = slice_list[0]['slice_id']
392 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
394 if "enabled" == attr['name'] and attr['value'] == "0":
395 logger.info("Deleted enable=0 attribute from slice %s" % slice)
396 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
397 except Exception, exc:
398 logger.info("enableSiteSlices: %s" % exc)
399 print "exception: %s" % exc
401 def enableSlices(nodename):
402 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
403 for slice in slices(siteId(nodename)):
404 logger.info("Enabling slices %s" % slice)
407 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
408 if len(slice_list) == 0:
410 slice_id = slice_list[0]['slice_id']
411 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
413 if "enabled" == attr['name'] and attr['value'] == "0":
414 logger.info("Deleted enable=0 attribute from slice %s" % slice)
415 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
416 except Exception, exc:
417 logger.info("enableSlices: %s" % exc)
418 print "exception: %s" % exc
420 #I'm commenting this because this really should be a manual process.
422 #Enable suspended site slices.
424 #def enableSlices(nodename, slicelist):
425 # api = xmlrpclib.Server(auth.server, verbose=False)
426 # for slice in slices(siteId(nodename)):
427 # logger.info("Suspending slice %s" % slice)
428 # api.SliceAttributeAdd(auth.auth, slice, "plc_slice_state", {"state" : "suspended"})
430 def enableSiteSliceCreation(loginbase):
431 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
433 logger.info("Enabling slice creation for site %s" % loginbase)
435 logger.info("\tcalling UpdateSite(%s, enabled=True)" % loginbase)
436 api.UpdateSite(auth.auth, loginbase, {'enabled': True})
437 except Exception, exc:
438 print "ERROR: enableSiteSliceCreation: %s" % exc
439 logger.info("ERROR: enableSiteSliceCreation: %s" % exc)
441 def enableSliceCreation(nodename):
442 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
444 loginbase = siteId(nodename)
445 logger.info("Enabling slice creation for site %s" % loginbase)
447 logger.info("\tcalling UpdateSite(%s, enabled=True)" % loginbase)
448 api.UpdateSite(auth.auth, loginbase, {'enabled': True})
449 except Exception, exc:
450 print "ERROR: enableSliceCreation: %s" % exc
451 logger.info("ERROR: enableSliceCreation: %s" % exc)
454 Removes site's ability to create slices. Returns previous max_slices
456 def removeSiteSliceCreation(sitename):
457 print "removeSiteSliceCreation(%s)" % sitename
458 api = xmlrpclib.Server(auth.server, verbose=False)
460 logger.info("Removing slice creation for site %s" % sitename)
462 api.UpdateSite(auth.auth, sitename, {'enabled': False})
463 except Exception, exc:
464 logger.info("removeSiteSliceCreation: %s" % exc)
467 Removes ability to create slices. Returns previous max_slices
469 def removeSliceCreation(nodename):
470 print "removeSliceCreation(%s)" % nodename
471 api = xmlrpclib.Server(auth.server, verbose=False)
473 loginbase = siteId(nodename)
474 #numslices = api.GetSites(auth.auth, {"login_base": loginbase},
475 # ["max_slices"])[0]['max_slices']
476 logger.info("Removing slice creation for site %s" % loginbase)
478 #api.UpdateSite(auth.auth, loginbase, {'max_slices': 0})
479 api.UpdateSite(auth.auth, loginbase, {'enabled': False})
480 except Exception, exc:
481 logger.info("removeSliceCreation: %s" % exc)
486 #def enableSliceCreation(nodename, maxslices):
487 # api = xmlrpclib.Server(auth.server, verbose=False)
488 # anon = {'AuthMethod': "anonymous"}
489 # siteid = api.AnonAdmQuerySite (anon, {"node_hostname": nodename})
490 # if len(siteid) == 1:
491 # logger.info("Enabling slice creation for site %s" % siteId(nodename))
494 # api.AdmUpdateSite(auth.auth, siteid[0], {"max_slices" : maxslices})
495 # except Exception, exc:
496 # logger.info("API: %s" % exc)
498 # logger.debug("Cant find site for %s. Cannot enable creation." % nodename)
501 logger.setLevel(logging.DEBUG)
502 ch = logging.StreamHandler()
503 ch.setLevel(logging.DEBUG)
504 formatter = logging.Formatter('logger - %(message)s')
505 ch.setFormatter(formatter)
506 logger.addHandler(ch)
507 #print getpcu("kupl2.ittc.ku.edu")
508 #print getpcu("planetlab1.cse.msu.edu")
509 #print getpcu("alice.cs.princeton.edu")
511 #nodeBootState("alice.cs.princeton.edu", "boot")
512 #freezeSite("alice.cs.princeton.edu")
513 print removeSliceCreation("alice.cs.princeton.edu")
514 #enableSliceCreation("alice.cs.princeton.edu", 1024)
515 #print getSiteNodes("princeton")
516 #print siteId("alice.cs.princeton.edu")
517 #print nodePOD("alice.cs.princeton.edu")
518 #print slices("princeton")
520 if __name__=="__main__":