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 $
20 logger = logging.getLogger("monitor")
24 self.auth = {'AuthMethod': "anonymous"}
26 # NOTE: this host is used by default when there are no auth files.
27 XMLRPC_SERVER="https://boot.planet-lab.org/PLCAPI/"
29 # NOTE: by default, use anonymous access, but if auth files are
30 # configured, use them, with their auth definitions.
33 from monitor import config
34 auth.auth = {'Username' : config.API_AUTH_USER,
35 'AuthMethod' : 'password',
36 'AuthString' : config.API_AUTH_PASSWORD}
37 auth.server = config.API_SERVER
41 auth.server = auth.plc
44 auth.server = XMLRPC_SERVER
46 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
49 def __init__(self, auth, url):
52 self.api = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
54 def __getattr__(self, name):
55 method = getattr(self.api, name)
57 raise AssertionError("method does not exist")
59 return lambda *params : method(self.auth, *params)
62 return self.api.__repr__()
65 return xmlrpclib.Server(url, verbose=False, allow_none=True)
68 return PLC(auth.auth, auth.server)
71 Returns list of nodes in dbg as reported by PLC
75 api = xmlrpclib.Server(auth.server, verbose=False)
76 anon = {'AuthMethod': "anonymous"}
77 for node in api.GetNodes(anon, {"boot_state":"dbg"},["hostname"]):
78 dbgNodes.append(node['hostname'])
79 logger.info("%s nodes in debug according to PLC." %len(dbgNodes))
84 Returns loginbase for given nodename
87 api = xmlrpclib.Server(auth.server, verbose=False)
88 anon = {'AuthMethod': "anonymous"}
89 site_id = api.GetNodes (anon, {"hostname": nodename}, ['site_id'])
91 loginbase = api.GetSites (anon, site_id[0], ["login_base"])
92 return loginbase[0]['login_base']
95 Returns list of slices for a site.
97 def slices(loginbase):
99 api = xmlrpclib.Server(auth.server, verbose=False)
100 sliceids = api.GetSites (auth.auth, {"login_base" : loginbase}, ["slice_ids"])[0]['slice_ids']
101 for slice in api.GetSlices(auth.auth, {"slice_id" : sliceids}, ["name"]):
102 siteslices.append(slice['name'])
106 Returns dict of PCU info of a given node.
108 def getpcu(nodename):
109 api = xmlrpclib.Server(auth.server, verbose=False)
110 anon = {'AuthMethod': "anonymous"}
111 nodeinfo = api.GetNodes(auth.auth, {"hostname": nodename}, ["pcu_ids", "ports"])[0]
112 if nodeinfo['pcu_ids']:
113 sitepcu = api.GetPCUs(auth.auth, nodeinfo['pcu_ids'])[0]
114 sitepcu[nodename] = nodeinfo["ports"][0]
117 logger.info("%s doesn't have PCU" % nodename)
120 def GetPCUs(filter=None, fields=None):
121 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
122 pcu_list = api.GetPCUs(auth.auth, filter, fields)
126 Returns all site nodes for site id (loginbase).
128 def getSiteNodes(loginbase, fields=None):
129 api = xmlrpclib.Server(auth.server, verbose=False)
131 anon = {'AuthMethod': "anonymous"}
133 nodeids = api.GetSites(anon, {"login_base": loginbase}, fields)[0]['node_ids']
134 for node in api.GetNodes(anon, {"node_id": nodeids}, ['hostname']):
135 nodelist.append(node['hostname'])
136 except Exception, exc:
137 logger.info("getSiteNodes: %s" % exc)
138 print "getSiteNodes: %s" % exc
141 def getPersons(filter=None, fields=None):
142 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
145 persons = api.GetPersons(auth.auth, filter, fields)
146 except Exception, exc:
147 print "getPersons: %s" % exc
148 logger.info("getPersons: %s" % exc)
151 def getSites(filter=None, fields=None):
152 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
154 anon = {'AuthMethod': "anonymous"}
156 #sites = api.GetSites(anon, filter, fields)
157 sites = api.GetSites(auth.auth, filter, fields)
158 except Exception, exc:
159 traceback.print_exc()
160 print "getSites: %s" % exc
161 logger.info("getSites: %s" % exc)
164 def getSiteNodes2(loginbase):
165 api = xmlrpclib.Server(auth.server, verbose=False)
167 anon = {'AuthMethod': "anonymous"}
169 nodeids = api.GetSites(anon, {"login_base": loginbase})[0]['node_ids']
170 nodelist += getNodes({'node_id':nodeids})
171 except Exception, exc:
172 logger.info("getSiteNodes2: %s" % exc)
175 def getNodeNetworks(filter=None):
176 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
177 nodenetworks = api.GetNodeNetworks(auth.auth, filter, None)
180 def getNodes(filter=None, fields=None):
181 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
182 nodes = api.GetNodes(auth.auth, filter, fields)
183 #['boot_state', 'hostname',
184 #'site_id', 'date_created', 'node_id', 'version', 'nodenetwork_ids',
185 #'last_updated', 'peer_node_id', 'ssh_rsa_key' ])
189 Sets boot state of a node.
191 def nodeBootState(nodename, state):
192 api = xmlrpclib.Server(auth.server, verbose=False)
194 return api.UpdateNode(auth.auth, nodename, {'boot_state': state})
195 except Exception, exc:
196 logger.info("nodeBootState: %s" % exc)
198 def updateNodeKey(nodename, key):
199 api = xmlrpclib.Server(auth.server, verbose=False)
201 return api.UpdateNode(auth.auth, nodename, {'key': key})
202 except Exception, exc:
203 logger.info("updateNodeKey: %s" % exc)
206 Sends Ping Of Death to node.
208 def nodePOD(nodename):
209 api = xmlrpclib.Server(auth.server, verbose=False)
210 logger.info("Sending POD to %s" % nodename)
213 return api.RebootNode(auth.auth, nodename)
214 except Exception, exc:
215 logger.info("nodePOD: %s" % exc)
218 Freeze all site slices.
220 def suspendSlices(nodename):
221 api = xmlrpclib.Server(auth.server, verbose=False)
222 for slice in slices(siteId(nodename)):
223 logger.info("Suspending slice %s" % slice)
226 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
227 except Exception, exc:
228 logger.info("suspendSlices: %s" % exc)
230 def enableSlices(nodename):
231 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
232 for slice in slices(siteId(nodename)):
233 logger.info("Enabling slices %s" % slice)
236 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
237 if len(slice_list) == 0:
239 slice_id = slice_list[0]['slice_id']
240 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
242 if "enabled" == attr['name'] and attr['value'] == "0":
243 logger.info("Deleted enable=0 attribute from slice %s" % slice)
244 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
245 except Exception, exc:
246 logger.info("enableSlices: %s" % exc)
247 print "exception: %s" % exc
249 #I'm commenting this because this really should be a manual process.
251 #Enable suspended site slices.
253 #def enableSlices(nodename, slicelist):
254 # api = xmlrpclib.Server(auth.server, verbose=False)
255 # for slice in slices(siteId(nodename)):
256 # logger.info("Suspending slice %s" % slice)
257 # api.SliceAttributeAdd(auth.auth, slice, "plc_slice_state", {"state" : "suspended"})
259 def enableSliceCreation(nodename):
260 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
262 loginbase = siteId(nodename)
263 logger.info("Enabling slice creation for site %s" % loginbase)
265 logger.info("\tcalling UpdateSite(%s, enabled=True)" % loginbase)
266 api.UpdateSite(auth.auth, loginbase, {'enabled': True})
267 except Exception, exc:
268 print "ERROR: enableSliceCreation: %s" % exc
269 logger.info("ERROR: enableSliceCreation: %s" % exc)
272 Removes ability to create slices. Returns previous max_slices
274 def removeSliceCreation(nodename):
275 print "removeSliceCreation(%s)" % nodename
276 api = xmlrpclib.Server(auth.server, verbose=False)
278 loginbase = siteId(nodename)
279 #numslices = api.GetSites(auth.auth, {"login_base": loginbase},
280 # ["max_slices"])[0]['max_slices']
281 logger.info("Removing slice creation for site %s" % loginbase)
283 #api.UpdateSite(auth.auth, loginbase, {'max_slices': 0})
284 api.UpdateSite(auth.auth, loginbase, {'enabled': False})
285 except Exception, exc:
286 logger.info("removeSliceCreation: %s" % exc)
291 #def enableSliceCreation(nodename, maxslices):
292 # api = xmlrpclib.Server(auth.server, verbose=False)
293 # anon = {'AuthMethod': "anonymous"}
294 # siteid = api.AnonAdmQuerySite (anon, {"node_hostname": nodename})
295 # if len(siteid) == 1:
296 # logger.info("Enabling slice creation for site %s" % siteId(nodename))
299 # api.AdmUpdateSite(auth.auth, siteid[0], {"max_slices" : maxslices})
300 # except Exception, exc:
301 # logger.info("API: %s" % exc)
303 # logger.debug("Cant find site for %s. Cannot enable creation." % nodename)
306 logger.setLevel(logging.DEBUG)
307 ch = logging.StreamHandler()
308 ch.setLevel(logging.DEBUG)
309 formatter = logging.Formatter('logger - %(message)s')
310 ch.setFormatter(formatter)
311 logger.addHandler(ch)
312 #print getpcu("kupl2.ittc.ku.edu")
313 #print getpcu("planetlab1.cse.msu.edu")
314 #print getpcu("alice.cs.princeton.edu")
316 #nodeBootState("alice.cs.princeton.edu", "boot")
317 #freezeSite("alice.cs.princeton.edu")
318 print removeSliceCreation("alice.cs.princeton.edu")
319 #enableSliceCreation("alice.cs.princeton.edu", 1024)
320 #print getSiteNodes("princeton")
321 #print siteId("alice.cs.princeton.edu")
322 #print nodePOD("alice.cs.princeton.edu")
323 #print slices("princeton")
325 if __name__=="__main__":