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)
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__()
87 api = PLC(auth.auth, auth.server)
91 def _param_to_str(self, name, *params):
94 retstr += "%s-" % name
99 def __getattr__(self, name):
100 method = getattr(self.api, name)
102 raise AssertionError("method does not exist")
104 def run_or_returncached(*params):
105 cachename = self._param_to_str(name, *params)
106 #print "cachename is %s" % cachename
107 if hasattr(config, 'refresh'):
108 refresh = config.refresh
113 if not database.cachedRecently(cachename):
114 load_old_cache = False
116 values = method(self.auth, *params)
118 print "Call %s FAILED: Using old cached data" % cachename
119 load_old_cache = True
122 values = database.dbLoad(cachename)
124 database.dbDump(cachename, values)
128 values = database.dbLoad(cachename)
131 return method(self.auth, *params)
133 return run_or_returncached
137 return xmlrpclib.Server(url, verbose=False, allow_none=True)
139 def getNodeAPI(session):
140 nodeauth = Auth(session=session)
141 return PLC(nodeauth.auth, auth.server)
144 return PLC(auth.auth, auth.server)
146 def getCachedAuthAPI():
147 return CachedPLC(auth.auth, auth.server)
149 def getTechEmails(loginbase):
151 For the given site, return all user email addresses that have the 'tech' role.
155 s = api.GetSites(loginbase)[0]
157 p = api.GetPersons(s['person_ids'])
158 # pull out those with the right role.
159 emails = [ person['email'] for person in filter(lambda x: 'tech' in x['roles'], p) ]
162 def getPIEmails(loginbase):
164 For the given site, return all user email addresses that have the 'tech' role.
168 s = api.GetSites(loginbase)[0]
170 p = api.GetPersons(s['person_ids'])
171 # pull out those with the right role.
172 emails = [ person['email'] for person in filter(lambda x: 'pi' in x['roles'], p) ]
175 def getSliceUserEmails(loginbase):
177 For the given site, return all user email addresses that have the 'tech' role.
181 s = api.GetSites(loginbase)[0]
183 slices = api.GetSlices(s['slice_ids'])
186 people += api.GetPersons(slice['person_ids'])
187 # pull out those with the right role.
188 emails = [ person['email'] for person in filter(lambda x: 'pi' in x['roles'], people) ]
189 unique_emails = [ x for x in set(emails) ]
193 Returns list of nodes in dbg as reported by PLC
197 api = xmlrpclib.Server(auth.server, verbose=False)
198 anon = {'AuthMethod': "anonymous"}
199 for node in api.GetNodes(anon, {"boot_state":"dbg"},["hostname"]):
200 dbgNodes.append(node['hostname'])
201 logger.info("%s nodes in debug according to PLC." %len(dbgNodes))
206 Returns loginbase for given nodename
208 def siteId(nodename):
209 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
210 site_id = api.GetNodes (auth.auth, {"hostname": nodename}, ['site_id'])
211 if len(site_id) == 1:
212 loginbase = api.GetSites (auth.auth, site_id[0], ["login_base"])
213 return loginbase[0]['login_base']
215 print "Not nodes returned!!!!"
218 Returns list of slices for a site.
220 def slices(loginbase):
222 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
223 sliceids = api.GetSites (auth.auth, {"login_base" : loginbase}, ["slice_ids"])[0]['slice_ids']
224 for slice in api.GetSlices(auth.auth, {"slice_id" : sliceids}, ["name"]):
225 siteslices.append(slice['name'])
229 Returns dict of PCU info of a given node.
231 def getpcu(nodename):
232 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
233 anon = {'AuthMethod': "anonymous"}
234 nodeinfo = api.GetNodes(auth.auth, {"hostname": nodename}, ["pcu_ids", "ports"])[0]
235 if nodeinfo['pcu_ids']:
237 sitepcu = api.GetPCUs(auth.auth, nodeinfo['pcu_ids'])[0]
239 print nodeinfo["ports"]
240 sitepcu[nodename] = nodeinfo["ports"][0]
243 logger.info("%s doesn't have PCU" % nodename)
246 def GetPCUs(filter=None, fields=None):
247 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
248 pcu_list = api.GetPCUs(auth.auth, filter, fields)
252 Returns all site nodes for site id (loginbase).
254 def getSiteNodes(loginbase, fields=None):
255 api = xmlrpclib.Server(auth.server, verbose=False)
257 anon = {'AuthMethod': "anonymous"}
259 nodeids = api.GetSites(anon, {"login_base": loginbase}, fields)[0]['node_ids']
260 for node in api.GetNodes(anon, {"node_id": nodeids}, ['hostname']):
261 nodelist.append(node['hostname'])
262 except Exception, exc:
263 logger.info("getSiteNodes: %s" % exc)
264 print "getSiteNodes: %s" % exc
268 def getPersons(filter=None, fields=None):
269 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
272 persons = api.GetPersons(auth.auth, filter, fields)
273 except Exception, exc:
274 print "getPersons: %s" % exc
275 logger.info("getPersons: %s" % exc)
278 def getSites(filter=None, fields=None):
279 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
281 anon = {'AuthMethod': "anonymous"}
283 #sites = api.GetSites(anon, filter, fields)
284 sites = api.GetSites(auth.auth, filter, fields)
285 except Exception, exc:
286 traceback.print_exc()
287 print "getSites: %s" % exc
288 logger.info("getSites: %s" % exc)
291 def getSiteNodes2(loginbase):
292 api = xmlrpclib.Server(auth.server, verbose=False)
294 anon = {'AuthMethod': "anonymous"}
296 nodeids = api.GetSites(anon, {"login_base": loginbase})[0]['node_ids']
297 nodelist += getNodes({'node_id':nodeids})
298 except Exception, exc:
299 logger.info("getSiteNodes2: %s" % exc)
302 def getNodeNetworks(filter=None):
303 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
304 nodenetworks = api.GetNodeNetworks(auth.auth, filter, None)
307 def getNodes(filter=None, fields=None):
308 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
309 nodes = api.GetNodes(auth.auth, filter, fields)
310 #['boot_state', 'hostname',
311 #'site_id', 'date_created', 'node_id', 'version', 'nodenetwork_ids',
312 #'last_updated', 'peer_node_id', 'ssh_rsa_key' ])
316 Sets boot state of a node.
318 def nodeBootState(nodename, state):
319 api = xmlrpclib.Server(auth.server, verbose=False)
321 return api.UpdateNode(auth.auth, nodename, {'boot_state': state})
322 except Exception, exc:
323 logger.info("nodeBootState: %s" % exc)
325 def updateNodeKey(nodename, key):
326 api = xmlrpclib.Server(auth.server, verbose=False)
328 return api.UpdateNode(auth.auth, nodename, {'key': key})
329 except Exception, exc:
330 logger.info("updateNodeKey: %s" % exc)
333 Sends Ping Of Death to node.
335 def nodePOD(nodename):
336 api = xmlrpclib.Server(auth.server, verbose=False)
337 logger.info("Sending POD to %s" % nodename)
340 return api.RebootNode(auth.auth, nodename)
341 except Exception, exc:
342 logger.info("nodePOD: %s" % exc)
345 Freeze all site slices.
347 def suspendSiteSlices(loginbase):
348 api = xmlrpclib.Server(auth.server, verbose=False)
349 for slice in slices(loginbase):
350 logger.info("Suspending slice %s" % slice)
353 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
354 except Exception, exc:
355 logger.info("suspendSlices: %s" % exc)
358 Freeze all site slices.
360 def suspendSlices(nodename):
361 api = xmlrpclib.Server(auth.server, verbose=False)
362 for slice in slices(siteId(nodename)):
363 logger.info("Suspending slice %s" % slice)
366 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
367 except Exception, exc:
368 logger.info("suspendSlices: %s" % exc)
370 def enableSiteSlices(loginbase):
371 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
372 for slice in slices(loginbase):
373 logger.info("Enabling slices %s" % slice)
376 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
377 if len(slice_list) == 0:
379 slice_id = slice_list[0]['slice_id']
380 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
382 if "enabled" == attr['name'] and attr['value'] == "0":
383 logger.info("Deleted enable=0 attribute from slice %s" % slice)
384 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
385 except Exception, exc:
386 logger.info("enableSiteSlices: %s" % exc)
387 print "exception: %s" % exc
389 def enableSlices(nodename):
390 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
391 for slice in slices(siteId(nodename)):
392 logger.info("Enabling slices %s" % slice)
395 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
396 if len(slice_list) == 0:
398 slice_id = slice_list[0]['slice_id']
399 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
401 if "enabled" == attr['name'] and attr['value'] == "0":
402 logger.info("Deleted enable=0 attribute from slice %s" % slice)
403 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
404 except Exception, exc:
405 logger.info("enableSlices: %s" % exc)
406 print "exception: %s" % exc
408 #I'm commenting this because this really should be a manual process.
410 #Enable suspended site slices.
412 #def enableSlices(nodename, slicelist):
413 # api = xmlrpclib.Server(auth.server, verbose=False)
414 # for slice in slices(siteId(nodename)):
415 # logger.info("Suspending slice %s" % slice)
416 # api.SliceAttributeAdd(auth.auth, slice, "plc_slice_state", {"state" : "suspended"})
418 def enableSiteSliceCreation(loginbase):
419 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
421 logger.info("Enabling slice creation for site %s" % loginbase)
423 logger.info("\tcalling UpdateSite(%s, enabled=True)" % loginbase)
424 api.UpdateSite(auth.auth, loginbase, {'enabled': True})
425 except Exception, exc:
426 print "ERROR: enableSiteSliceCreation: %s" % exc
427 logger.info("ERROR: enableSiteSliceCreation: %s" % exc)
429 def enableSliceCreation(nodename):
430 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
432 loginbase = siteId(nodename)
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: enableSliceCreation: %s" % exc
439 logger.info("ERROR: enableSliceCreation: %s" % exc)
442 Removes site's ability to create slices. Returns previous max_slices
444 def removeSiteSliceCreation(sitename):
445 print "removeSiteSliceCreation(%s)" % sitename
446 api = xmlrpclib.Server(auth.server, verbose=False)
448 logger.info("Removing slice creation for site %s" % sitename)
450 api.UpdateSite(auth.auth, sitename, {'enabled': False})
451 except Exception, exc:
452 logger.info("removeSiteSliceCreation: %s" % exc)
455 Removes ability to create slices. Returns previous max_slices
457 def removeSliceCreation(nodename):
458 print "removeSliceCreation(%s)" % nodename
459 api = xmlrpclib.Server(auth.server, verbose=False)
461 loginbase = siteId(nodename)
462 #numslices = api.GetSites(auth.auth, {"login_base": loginbase},
463 # ["max_slices"])[0]['max_slices']
464 logger.info("Removing slice creation for site %s" % loginbase)
466 #api.UpdateSite(auth.auth, loginbase, {'max_slices': 0})
467 api.UpdateSite(auth.auth, loginbase, {'enabled': False})
468 except Exception, exc:
469 logger.info("removeSliceCreation: %s" % exc)
474 #def enableSliceCreation(nodename, maxslices):
475 # api = xmlrpclib.Server(auth.server, verbose=False)
476 # anon = {'AuthMethod': "anonymous"}
477 # siteid = api.AnonAdmQuerySite (anon, {"node_hostname": nodename})
478 # if len(siteid) == 1:
479 # logger.info("Enabling slice creation for site %s" % siteId(nodename))
482 # api.AdmUpdateSite(auth.auth, siteid[0], {"max_slices" : maxslices})
483 # except Exception, exc:
484 # logger.info("API: %s" % exc)
486 # logger.debug("Cant find site for %s. Cannot enable creation." % nodename)
489 logger.setLevel(logging.DEBUG)
490 ch = logging.StreamHandler()
491 ch.setLevel(logging.DEBUG)
492 formatter = logging.Formatter('logger - %(message)s')
493 ch.setFormatter(formatter)
494 logger.addHandler(ch)
495 #print getpcu("kupl2.ittc.ku.edu")
496 #print getpcu("planetlab1.cse.msu.edu")
497 #print getpcu("alice.cs.princeton.edu")
499 #nodeBootState("alice.cs.princeton.edu", "boot")
500 #freezeSite("alice.cs.princeton.edu")
501 print removeSliceCreation("alice.cs.princeton.edu")
502 #enableSliceCreation("alice.cs.princeton.edu", 1024)
503 #print getSiteNodes("princeton")
504 #print siteId("alice.cs.princeton.edu")
505 #print nodePOD("alice.cs.princeton.edu")
506 #print slices("princeton")
508 if __name__=="__main__":