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)
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__()
89 def _param_to_str(self, name, *params):
92 retstr += "%s-" % name
97 def __getattr__(self, name):
98 method = getattr(self.api, name)
100 raise AssertionError("method does not exist")
102 def run_or_returncached(*params):
103 cachename = self._param_to_str(name, *params)
104 #print "cachename is %s" % cachename
105 if hasattr(config, 'refresh'):
106 refresh = config.refresh
111 if not database.cachedRecently(cachename):
112 load_old_cache = False
114 values = method(self.auth, *params)
116 print "Call %s FAILED: Using old cached data" % cachename
117 load_old_cache = True
120 values = database.dbLoad(cachename)
122 database.dbDump(cachename, values)
126 values = database.dbLoad(cachename)
129 return method(self.auth, *params)
131 return run_or_returncached
135 return xmlrpclib.Server(url, verbose=False, allow_none=True)
137 def getNodeAPI(session):
138 nodeauth = Auth(session=session)
139 return PLC(nodeauth.auth, auth.server)
142 return PLC(auth.auth, auth.server)
144 def getCachedAuthAPI():
145 return CachedPLC(auth.auth, auth.server)
147 def getTechEmails(loginbase):
149 For the given site, return all user email addresses that have the 'tech' role.
153 s = api.GetSites(loginbase)[0]
155 p = api.GetPersons(s['person_ids'])
156 # pull out those with the right role.
157 emails = [ person['email'] for person in filter(lambda x: 'tech' in x['roles'], p) ]
160 def getPIEmails(loginbase):
162 For the given site, return all user email addresses that have the 'tech' role.
166 s = api.GetSites(loginbase)[0]
168 p = api.GetPersons(s['person_ids'])
169 # pull out those with the right role.
170 emails = [ person['email'] for person in filter(lambda x: 'pi' in x['roles'], p) ]
173 def getSliceUserEmails(loginbase):
175 For the given site, return all user email addresses that have the 'tech' role.
179 s = api.GetSites(loginbase)[0]
181 slices = api.GetSlices(s['slice_ids'])
184 people += api.GetPersons(slice['person_ids'])
185 # pull out those with the right role.
186 emails = [ person['email'] for person in filter(lambda x: 'pi' in x['roles'], people) ]
187 unique_emails = [ x for x in set(emails) ]
191 Returns list of nodes in dbg as reported by PLC
195 api = xmlrpclib.Server(auth.server, verbose=False)
196 anon = {'AuthMethod': "anonymous"}
197 for node in api.GetNodes(anon, {"boot_state":"dbg"},["hostname"]):
198 dbgNodes.append(node['hostname'])
199 logger.info("%s nodes in debug according to PLC." %len(dbgNodes))
204 Returns loginbase for given nodename
206 def siteId(nodename):
207 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
208 site_id = api.GetNodes (auth.auth, {"hostname": nodename}, ['site_id'])
209 if len(site_id) == 1:
210 loginbase = api.GetSites (auth.auth, site_id[0], ["login_base"])
211 return loginbase[0]['login_base']
213 print "Not nodes returned!!!!"
216 Returns list of slices for a site.
218 def slices(loginbase):
220 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
221 sliceids = api.GetSites (auth.auth, {"login_base" : loginbase}, ["slice_ids"])[0]['slice_ids']
222 for slice in api.GetSlices(auth.auth, {"slice_id" : sliceids}, ["name"]):
223 siteslices.append(slice['name'])
227 Returns dict of PCU info of a given node.
229 def getpcu(nodename):
230 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
231 anon = {'AuthMethod': "anonymous"}
232 nodeinfo = api.GetNodes(auth.auth, {"hostname": nodename}, ["pcu_ids", "ports"])[0]
233 if nodeinfo['pcu_ids']:
235 sitepcu = api.GetPCUs(auth.auth, nodeinfo['pcu_ids'])[0]
237 print nodeinfo["ports"]
238 sitepcu[nodename] = nodeinfo["ports"][0]
241 logger.info("%s doesn't have PCU" % nodename)
244 def GetPCUs(filter=None, fields=None):
245 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
246 pcu_list = api.GetPCUs(auth.auth, filter, fields)
250 Returns all site nodes for site id (loginbase).
252 def getSiteNodes(loginbase, fields=None):
253 api = xmlrpclib.Server(auth.server, verbose=False)
255 anon = {'AuthMethod': "anonymous"}
257 nodeids = api.GetSites(anon, {"login_base": loginbase}, fields)[0]['node_ids']
258 for node in api.GetNodes(anon, {"node_id": nodeids}, ['hostname']):
259 nodelist.append(node['hostname'])
260 except Exception, exc:
261 logger.info("getSiteNodes: %s" % exc)
262 print "getSiteNodes: %s" % exc
266 def getPersons(filter=None, fields=None):
267 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
270 persons = api.GetPersons(auth.auth, filter, fields)
271 except Exception, exc:
272 print "getPersons: %s" % exc
273 logger.info("getPersons: %s" % exc)
276 def getSites(filter=None, fields=None):
277 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
279 anon = {'AuthMethod': "anonymous"}
281 #sites = api.GetSites(anon, filter, fields)
282 sites = api.GetSites(auth.auth, filter, fields)
283 except Exception, exc:
284 traceback.print_exc()
285 print "getSites: %s" % exc
286 logger.info("getSites: %s" % exc)
289 def getSiteNodes2(loginbase):
290 api = xmlrpclib.Server(auth.server, verbose=False)
292 anon = {'AuthMethod': "anonymous"}
294 nodeids = api.GetSites(anon, {"login_base": loginbase})[0]['node_ids']
295 nodelist += getNodes({'node_id':nodeids})
296 except Exception, exc:
297 logger.info("getSiteNodes2: %s" % exc)
300 def getNodeNetworks(filter=None):
301 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
302 nodenetworks = api.GetNodeNetworks(auth.auth, filter, None)
305 def getNodes(filter=None, fields=None):
306 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
307 nodes = api.GetNodes(auth.auth, filter, fields)
308 #['boot_state', 'hostname',
309 #'site_id', 'date_created', 'node_id', 'version', 'nodenetwork_ids',
310 #'last_updated', 'peer_node_id', 'ssh_rsa_key' ])
314 Sets boot state of a node.
316 def nodeBootState(nodename, state):
317 api = xmlrpclib.Server(auth.server, verbose=False)
319 return api.UpdateNode(auth.auth, nodename, {'boot_state': state})
320 except Exception, exc:
321 logger.info("nodeBootState: %s" % exc)
323 def updateNodeKey(nodename, key):
324 api = xmlrpclib.Server(auth.server, verbose=False)
326 return api.UpdateNode(auth.auth, nodename, {'key': key})
327 except Exception, exc:
328 logger.info("updateNodeKey: %s" % exc)
331 Sends Ping Of Death to node.
333 def nodePOD(nodename):
334 api = xmlrpclib.Server(auth.server, verbose=False)
335 logger.info("Sending POD to %s" % nodename)
338 return api.RebootNode(auth.auth, nodename)
339 except Exception, exc:
340 logger.info("nodePOD: %s" % exc)
343 Freeze all site slices.
345 def suspendSiteSlices(loginbase):
346 api = xmlrpclib.Server(auth.server, verbose=False)
347 for slice in slices(loginbase):
348 logger.info("Suspending slice %s" % slice)
351 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
352 except Exception, exc:
353 logger.info("suspendSlices: %s" % exc)
356 Freeze all site slices.
358 def suspendSlices(nodename):
359 api = xmlrpclib.Server(auth.server, verbose=False)
360 for slice in slices(siteId(nodename)):
361 logger.info("Suspending slice %s" % slice)
364 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
365 except Exception, exc:
366 logger.info("suspendSlices: %s" % exc)
368 def enableSiteSlices(loginbase):
369 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
370 for slice in slices(loginbase):
371 logger.info("Enabling slices %s" % slice)
374 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
375 if len(slice_list) == 0:
377 slice_id = slice_list[0]['slice_id']
378 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
380 if "enabled" == attr['name'] and attr['value'] == "0":
381 logger.info("Deleted enable=0 attribute from slice %s" % slice)
382 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
383 except Exception, exc:
384 logger.info("enableSiteSlices: %s" % exc)
385 print "exception: %s" % exc
387 def enableSlices(nodename):
388 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
389 for slice in slices(siteId(nodename)):
390 logger.info("Enabling slices %s" % slice)
393 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
394 if len(slice_list) == 0:
396 slice_id = slice_list[0]['slice_id']
397 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
399 if "enabled" == attr['name'] and attr['value'] == "0":
400 logger.info("Deleted enable=0 attribute from slice %s" % slice)
401 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
402 except Exception, exc:
403 logger.info("enableSlices: %s" % exc)
404 print "exception: %s" % exc
406 #I'm commenting this because this really should be a manual process.
408 #Enable suspended site slices.
410 #def enableSlices(nodename, slicelist):
411 # api = xmlrpclib.Server(auth.server, verbose=False)
412 # for slice in slices(siteId(nodename)):
413 # logger.info("Suspending slice %s" % slice)
414 # api.SliceAttributeAdd(auth.auth, slice, "plc_slice_state", {"state" : "suspended"})
416 def enableSiteSliceCreation(loginbase):
417 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
419 logger.info("Enabling slice creation for site %s" % loginbase)
421 logger.info("\tcalling UpdateSite(%s, enabled=True)" % loginbase)
422 api.UpdateSite(auth.auth, loginbase, {'enabled': True})
423 except Exception, exc:
424 print "ERROR: enableSiteSliceCreation: %s" % exc
425 logger.info("ERROR: enableSiteSliceCreation: %s" % exc)
427 def enableSliceCreation(nodename):
428 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
430 loginbase = siteId(nodename)
431 logger.info("Enabling slice creation for site %s" % loginbase)
433 logger.info("\tcalling UpdateSite(%s, enabled=True)" % loginbase)
434 api.UpdateSite(auth.auth, loginbase, {'enabled': True})
435 except Exception, exc:
436 print "ERROR: enableSliceCreation: %s" % exc
437 logger.info("ERROR: enableSliceCreation: %s" % exc)
440 Removes site's ability to create slices. Returns previous max_slices
442 def removeSiteSliceCreation(sitename):
443 print "removeSiteSliceCreation(%s)" % sitename
444 api = xmlrpclib.Server(auth.server, verbose=False)
446 logger.info("Removing slice creation for site %s" % sitename)
448 api.UpdateSite(auth.auth, sitename, {'enabled': False})
449 except Exception, exc:
450 logger.info("removeSiteSliceCreation: %s" % exc)
453 Removes ability to create slices. Returns previous max_slices
455 def removeSliceCreation(nodename):
456 print "removeSliceCreation(%s)" % nodename
457 api = xmlrpclib.Server(auth.server, verbose=False)
459 loginbase = siteId(nodename)
460 #numslices = api.GetSites(auth.auth, {"login_base": loginbase},
461 # ["max_slices"])[0]['max_slices']
462 logger.info("Removing slice creation for site %s" % loginbase)
464 #api.UpdateSite(auth.auth, loginbase, {'max_slices': 0})
465 api.UpdateSite(auth.auth, loginbase, {'enabled': False})
466 except Exception, exc:
467 logger.info("removeSliceCreation: %s" % exc)
472 #def enableSliceCreation(nodename, maxslices):
473 # api = xmlrpclib.Server(auth.server, verbose=False)
474 # anon = {'AuthMethod': "anonymous"}
475 # siteid = api.AnonAdmQuerySite (anon, {"node_hostname": nodename})
476 # if len(siteid) == 1:
477 # logger.info("Enabling slice creation for site %s" % siteId(nodename))
480 # api.AdmUpdateSite(auth.auth, siteid[0], {"max_slices" : maxslices})
481 # except Exception, exc:
482 # logger.info("API: %s" % exc)
484 # logger.debug("Cant find site for %s. Cannot enable creation." % nodename)
487 logger.setLevel(logging.DEBUG)
488 ch = logging.StreamHandler()
489 ch.setLevel(logging.DEBUG)
490 formatter = logging.Formatter('logger - %(message)s')
491 ch.setFormatter(formatter)
492 logger.addHandler(ch)
493 #print getpcu("kupl2.ittc.ku.edu")
494 #print getpcu("planetlab1.cse.msu.edu")
495 #print getpcu("alice.cs.princeton.edu")
497 #nodeBootState("alice.cs.princeton.edu", "boot")
498 #freezeSite("alice.cs.princeton.edu")
499 print removeSliceCreation("alice.cs.princeton.edu")
500 #enableSliceCreation("alice.cs.princeton.edu", 1024)
501 #print getSiteNodes("princeton")
502 #print siteId("alice.cs.princeton.edu")
503 #print nodePOD("alice.cs.princeton.edu")
504 #print slices("princeton")
506 if __name__=="__main__":